Added the ability to handle Base64-encoded URL's. We will use these, along with...
[citadel.git] / webcit / webcit.c
1 /*
2  * This is the main transaction loop of the web service.  It maintains a
3  * persistent session to the Citadel server, handling HTTP WebCit requests as
4  * they arrive and presenting a user interface.
5  */
6 #define SHOW_ME_VAPPEND_PRINTF
7 #include <stdio.h>
8 #include <stdarg.h>
9 #include "webcit.h"
10 #include "groupdav.h"
11 #include "webserver.h"
12
13
14 StrBuf *csslocal = NULL;
15 HashList *HandlerHash = NULL;
16
17
18 void DeleteWebcitHandler(void *vHandler)
19 {
20         WebcitHandler *Handler = (WebcitHandler*) vHandler;
21         FreeStrBuf(&Handler->Name);
22         FreeStrBuf(&Handler->DisplayName);
23         free (Handler);
24 }
25
26 void WebcitAddUrlHandler(const char * UrlString, long UrlSLen, 
27                          const char *DisplayName, long dslen,
28                          WebcitHandlerFunc F, 
29                          long Flags)
30 {
31         WebcitHandler *NewHandler;      
32         NewHandler = (WebcitHandler*) malloc(sizeof(WebcitHandler));
33         NewHandler->F = F;
34         NewHandler->Flags = Flags;
35         NewHandler->Name = NewStrBufPlain(UrlString, UrlSLen);
36         StrBufShrinkToFit(NewHandler->Name, 1);
37         NewHandler->DisplayName = NewStrBufPlain(DisplayName, dslen);
38         StrBufShrinkToFit(NewHandler->DisplayName, 1);
39         Put(HandlerHash, UrlString, UrlSLen, NewHandler, DeleteWebcitHandler);
40 }
41
42 void tmplput_HANDLER_DISPLAYNAME(StrBuf *Target, WCTemplputParams *TP) 
43 {
44         wcsession *WCC = WC;
45         if (WCC->Hdr->HR.Handler != NULL)
46                 StrBufAppendTemplate(Target, TP, WCC->Hdr->HR.Handler->DisplayName, 0);
47 }
48
49 void tmplput_HOST_DISPLAYNAME(StrBuf *Target, WCTemplputParams *TP) 
50 {
51         wcsession *WCC = WC;
52         StrBufAppendTemplate(Target, TP, WCC->Hdr->HR.http_host, 0);
53 }
54
55 /*
56  * web-printing funcion. uses our vsnprintf wrapper
57  */
58 #ifdef UBER_VERBOSE_DEBUGGING
59 void wcc_printf(const char *FILE, const char *FUNCTION, long LINE, const char *format,...)
60 #else
61 void wc_printf(const char *format,...)
62 #endif
63 {
64         wcsession *WCC = WC;
65         va_list arg_ptr;
66
67         if (WCC->WBuf == NULL)
68                 WCC->WBuf = NewStrBuf();
69 #ifdef UBER_VERBOSE_DEBUGGING
70         StrBufAppendPrintf(WCC->WBuf, "\n%s:%s:%d[", FILE, FUNCTION, LINE);
71 #endif
72
73         va_start(arg_ptr, format);
74         StrBufVAppendPrintf(WCC->WBuf, format, arg_ptr);
75         va_end(arg_ptr);
76 #ifdef UBER_VERBOSE_DEBUGGING
77         StrBufAppendPrintf(WCC->WBuf, "]\n");
78 #endif
79 }
80
81 /*
82  * http-header-printing funcion. uses our vsnprintf wrapper
83  */
84 void hprintf(const char *format,...)
85 {
86         wcsession *WCC = WC;
87         va_list arg_ptr;
88
89         va_start(arg_ptr, format);
90         StrBufVAppendPrintf(WCC->HBuf, format, arg_ptr);
91         va_end(arg_ptr);
92 }
93
94
95
96 /*
97  * wrap up an HTTP session, closes tags, etc.
98  *
99  * print_standard_html_footer should be set to:
100  * 0            - to transmit only,
101  * nonzero      - to append the closing tags
102  */
103 void wDumpContent(int print_standard_html_footer)
104 {
105         if (print_standard_html_footer) {
106                 wc_printf("</div> <!-- end of 'content' div -->\n");
107                 do_template("trailing", NULL);
108         }
109
110         /* If we've been saving it all up for one big output burst,
111          * go ahead and do that now.
112          */
113         end_burst();
114 }
115
116
117  
118
119 /*
120  * Output HTTP headers and leading HTML for a page
121  */
122 void output_headers(    int do_httpheaders,     /* 1 = output HTTP headers                        */
123                         int do_htmlhead,        /* 1 = output HTML <head> section and <body> opener */
124
125                         int do_room_banner,     /* 0=no, 1=yes,                              
126                                                  * 2 = I'm going to embed my own, so don't open the 
127                                                  *     <div id="content"> either.                  
128                                                  */
129
130                         int unset_cookies,      /* 1 = session is terminating, so unset the cookies */
131                         int suppress_check,     /* 1 = suppress check for instant messages        */
132                         int cache               /* 1 = allow browser to cache this page      */
133 ) {
134         wcsession *WCC = WC;
135         char httpnow[128];
136
137         hprintf("HTTP/1.1 200 OK\n");
138         http_datestring(httpnow, sizeof httpnow, time(NULL));
139
140         if (do_httpheaders) {
141                 if (WCC->serv_info != NULL)
142                         hprintf("Content-type: text/html; charset=utf-8\r\n"
143                                 "Server: %s / %s\n"
144                                 "Connection: close\r\n",
145                                 PACKAGE_STRING, 
146                                 ChrPtr(WCC->serv_info->serv_software));
147                 else
148                         hprintf("Content-type: text/html; charset=utf-8\r\n"
149                                 "Server: %s / [n/a]\n"
150                                 "Connection: close\r\n",
151                                 PACKAGE_STRING);
152         }
153
154         if (cache > 0) {
155                 char httpTomorow[128];
156
157                 http_datestring(httpTomorow, sizeof httpTomorow, 
158                                 time(NULL) + 60 * 60 * 24 * 2);
159
160                 hprintf("Pragma: public\r\n"
161                         "Cache-Control: max-age=3600, must-revalidate\r\n"
162                         "Last-modified: %s\r\n"
163                         "Expires: %s\r\n",
164                         httpnow,
165                         httpTomorow
166                 );
167         }
168         else {
169                 hprintf("Pragma: no-cache\r\n"
170                         "Cache-Control: no-store\r\n"
171                         "Expires: -1\r\n"
172                 );
173         }
174
175         if (cache < 2) stuff_to_cookie(unset_cookies);
176
177         if (do_htmlhead) {
178                 begin_burst();
179                 do_template("head", NULL);
180
181                 /* check for ImportantMessages (these display in a div overlaying the main screen) */
182                 if (!IsEmptyStr(WCC->ImportantMessage)) {
183                         wc_printf("<div id=\"important_message\">\n"
184                                 "<span class=\"imsg\">");
185                         StrEscAppend(WCC->WBuf, NULL, WCC->ImportantMessage, 0, 0);
186                         wc_printf("</span><br />\n"
187                                 "</div>\n"
188                         );
189                         StrBufAppendBufPlain(WCC->trailing_javascript,
190                                              HKEY("setTimeout('hide_imsg_popup()', 5000);       \n"), 
191                                              0
192                         );
193                         WCC->ImportantMessage[0] = 0;
194                 }
195                 else if (StrLength(WCC->ImportantMsg) > 0) {
196                         wc_printf("<div id=\"important_message\">\n"
197                                 "<span class=\"imsg\">");
198                         StrEscAppend(WCC->WBuf, WCC->ImportantMsg, NULL, 0, 0);
199                         wc_printf("</span><br />\n"
200                                 "</div>\n"
201                         );
202                         StrBufAppendBufPlain(WCC->trailing_javascript,
203                                              HKEY("setTimeout('hide_imsg_popup()', 5000);       \n"),
204                                              0
205                         );
206                         FlushStrBuf(WCC->ImportantMsg);
207                 }
208                 if ( (WCC->logged_in) && (!unset_cookies) ) {
209                         DoTemplate(HKEY("paging"), NULL, &NoCtx);
210                 }
211
212                 if (do_room_banner == 1) {
213                         tmplput_roombanner(NULL, NULL);
214                 }
215         }
216
217         if (do_room_banner == 1) {
218                 wc_printf("<div id=\"content\">\n");
219         }
220 }
221
222 void output_custom_content_header(const char *ctype) {
223   hprintf("HTTP/1.1 200 OK\r\n");
224   hprintf("Content-type: %s; charset=utf-8\r\n",ctype);
225   hprintf("Server: %s / %s\r\n", PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software));
226   hprintf("Connection: close\r\n");
227 }
228
229
230 /*
231  * Generic function to do an HTTP redirect.  Easy and fun.
232  */
233 void http_redirect(const char *whichpage) {
234         hprintf("HTTP/1.1 302 Moved Temporarily\n");
235         hprintf("Location: %s\r\n", whichpage);
236         hprintf("URI: %s\r\n", whichpage);
237         hprintf("Content-type: text/html; charset=utf-8\r\n");
238         begin_burst();
239         wc_printf("<html><body>");
240         wc_printf("Go <a href=\"%s\">here</A>.", whichpage);
241         wc_printf("</body></html>\n");
242         end_burst();
243 }
244
245
246
247 /*
248  * Output a piece of content to the web browser using conformant HTTP and MIME semantics
249  */
250 void http_transmit_thing(const char *content_type,
251                          int is_static) {
252
253 #ifndef TECH_PREVIEW
254         lprintf(9, "http_transmit_thing(%s)%s\n",
255                 content_type,
256                 ((is_static > 0) ? " (static)" : "")
257         );
258 #endif
259         output_headers(0, 0, 0, 0, 0, is_static);
260
261         hprintf("Content-type: %s\r\n"
262                 "Server: %s\r\n"
263                 "Connection: close\r\n",
264                 content_type,
265                 PACKAGE_STRING);
266
267         end_burst();
268 }
269
270
271 /*
272  * Convenience functions to display a page containing only a string
273  *
274  * titlebarcolor        color of the titlebar of the frame
275  * titlebarmsg          text to display in the title bar
276  * messagetext          body of the box
277  */
278 void convenience_page(const char *titlebarcolor, const char *titlebarmsg, const char *messagetext)
279 {
280         hprintf("HTTP/1.1 200 OK\n");
281         output_headers(1, 1, 2, 0, 0, 0);
282         wc_printf("<div id=\"banner\">\n");
283         wc_printf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
284         wc_printf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
285         wc_printf("</td></tr></table>\n");
286         wc_printf("</div>\n<div id=\"content\">\n");
287         escputs(messagetext);
288
289         wc_printf("<hr />\n");
290         wDumpContent(1);
291 }
292
293
294 /*
295  * Display a blank page.
296  */
297 void blank_page(void) {
298         output_headers(1, 1, 0, 0, 0, 0);
299         wDumpContent(2);
300 }
301
302
303 /*
304  * A template has been requested
305  */
306 void url_do_template(void) {
307         const StrBuf *MimeType;
308         const StrBuf *Tmpl = sbstr("template");
309         begin_burst();
310         MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
311         http_transmit_thing(ChrPtr(MimeType), 0);
312 }
313
314
315
316 /*
317  * convenience function to indicate success
318  */
319 void display_success(char *successmessage)
320 {
321         convenience_page("007700", "OK", successmessage);
322 }
323
324
325 /*
326  * Authorization required page 
327  * This is probably temporary and should be revisited 
328  */
329 void authorization_required(void)
330 {
331         wcsession *WCC = WC;
332         const char *message = "";
333
334         hprintf("HTTP/1.1 401 Authorization Required\r\n");
335         hprintf(
336                 "Server: %s / %s\r\n"
337                 "Connection: close\r\n",
338                 PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software)
339         );
340         hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", ChrPtr(WC->serv_info->serv_humannode));
341         hprintf("Content-Type: text/html\r\n");
342         begin_burst();
343         wc_printf("<h1>");
344         wc_printf(_("Authorization Required"));
345         wc_printf("</h1>\r\n");
346         
347
348         if (WCC->ImportantMsg != NULL)
349                 message = ChrPtr(WCC->ImportantMsg);
350         else if (WCC->ImportantMessage != NULL)
351                 message = WCC->ImportantMessage;
352
353         wc_printf(_("The resource you requested requires a valid username and password. "
354                 "You could not be logged in: %s\n"), message);
355         wDumpContent(0);
356         end_webcit_session();
357 }
358
359 /*
360  * Convenience functions to wrap around asynchronous ajax responses
361  */
362 void begin_ajax_response(void) {
363         wcsession *WCC = WC;
364
365         FlushStrBuf(WCC->HBuf);
366         output_headers(0, 0, 0, 0, 0, 0);
367
368         hprintf("Content-type: text/html; charset=UTF-8\r\n"
369                 "Server: %s\r\n"
370                 "Connection: close\r\n"
371                 ,
372                 PACKAGE_STRING);
373         begin_burst();
374 }
375
376 /*
377  * print ajax response footer 
378  */
379 void end_ajax_response(void) {
380         wDumpContent(0);
381 }
382
383
384
385 /*
386  * Wraps a Citadel server command in an AJAX transaction.
387  */
388 void ajax_servcmd(void)
389 {
390         wcsession *WCC = WC;
391         int Done = 0;
392         StrBuf *Buf;
393         char *junk;
394         size_t len;
395
396         begin_ajax_response();
397         Buf = NewStrBuf();
398         serv_puts(bstr("g_cmd"));
399         StrBuf_ServGetln(Buf);
400         StrBufAppendBuf(WCC->WBuf, Buf, 0);
401         StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
402         
403         switch (GetServerStatus(Buf, NULL)) {
404         case 8:
405                 serv_puts("\n\n000");
406                 if ( (StrLength(Buf)==3) && 
407                      !strcmp(ChrPtr(Buf), "000")) {
408                         StrBufAppendBufPlain(WCC->WBuf, HKEY("\000"), 0);
409                         break;
410                 }
411         case 1:
412                 while (!Done) {
413                         StrBuf_ServGetln(Buf);
414                         if ( (StrLength(Buf)==3) && 
415                              !strcmp(ChrPtr(Buf), "000")) {
416                                 Done = 1;
417                         }
418                         StrBufAppendBuf(WCC->WBuf, Buf, 0);
419                         StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
420                 }
421                 break;
422         case 4:
423                 text_to_server(bstr("g_input"));
424                 serv_puts("000");
425                 break;
426         case 6:
427                 len = atol(&ChrPtr(Buf)[4]);
428                 StrBuf_ServGetBLOBBuffered(Buf, len);
429                 break;
430         case 7:
431                 len = atol(&ChrPtr(Buf)[4]);
432                 junk = malloc(len);
433                 memset(junk, 0, len);
434                 serv_write(junk, len);
435                 free(junk);
436         }
437         
438         end_ajax_response();
439         
440         /*
441          * This is kind of an ugly hack, but this is the only place it can go.
442          * If the command was GEXP, then the instant messenger window must be
443          * running, so reset the "last_pager_check" watchdog timer so
444          * that page_popup() doesn't try to open it a second time.
445          */
446         if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
447                 WCC->last_pager_check = time(NULL);
448         }
449         FreeStrBuf(&Buf);
450 }
451
452
453 /*
454  * Helper function for the asynchronous check to see if we need
455  * to open the instant messenger window.
456  */
457 void seconds_since_last_gexp(void)
458 {
459         char buf[256];
460
461         if ( (time(NULL) - WC->last_pager_check) < 30) {
462                 wc_printf("NO\n");
463         }
464         else {
465                 memset(buf, 0, 5);
466                 serv_puts("NOOP");
467                 serv_getln(buf, sizeof buf);
468                 if (buf[3] == '*') {
469                         wc_printf("YES");
470                 }
471                 else {
472                         wc_printf("NO");
473                 }
474         }
475 }
476
477
478
479 int ReadPostData(void)
480 {
481         int rc;
482         int body_start = 0;
483         wcsession *WCC = WC;
484         StrBuf *content = NULL;
485         
486         content = NewStrBufPlain(NULL, WCC->Hdr->HR.ContentLength + 256);
487
488         StrBufPrintf(content, 
489                      "Content-type: %s\n"
490                      "Content-length: %ld\n\n",
491                      ChrPtr(WCC->Hdr->HR.ContentType), 
492                              WCC->Hdr->HR.ContentLength);
493 /*
494   hprintf("Content-type: %s\n"
495   "Content-length: %d\n\n",
496   ContentType, ContentLength);
497 */
498         body_start = StrLength(content);
499
500         /** Read the entire input data at once. */
501         rc = client_read_to(WCC->Hdr, content, 
502                             WCC->Hdr->HR.ContentLength,
503                             SLEEPING);
504         if (rc < 0)
505                 return rc;
506                 
507         
508         if (!strncasecmp(ChrPtr(WCC->Hdr->HR.ContentType), "application/x-www-form-urlencoded", 33)) {
509                 StrBufCutLeft(content, body_start);
510                 ParseURLParams(content);
511         } else if (!strncasecmp(ChrPtr(WCC->Hdr->HR.ContentType), "multipart", 9)) {
512                 char *Buf;
513                 char *BufEnd;
514                 long len;
515
516                 len = StrLength(content);
517                 Buf = SmashStrBuf(&content);
518                 BufEnd = Buf + len;
519                 mime_parser(Buf, BufEnd, *upload_handler, NULL, NULL, NULL, 0);
520                 free(Buf);
521         } else if (WCC->Hdr->HR.ContentLength > 0) {
522                 WCC->upload = content;
523                 WCC->upload_length = StrLength(WCC->upload);
524                 content = NULL;
525         }
526         FreeStrBuf(&content);
527         return 1;
528 }
529
530
531 void ParseREST_URL(void)
532 {
533         StrBuf *Buf;
534         StrBuf *pFloor = NULL;
535         wcsession *WCC = WC;
536         long i = 0;
537         const char *pCh = NULL;
538         HashList *Floors;
539         void *vFloor;
540
541         lprintf(1, "parsing rest URL: %s\n", ChrPtr(WCC->Hdr->HR.ReqLine));
542
543         WCC->Directory = NewHash(1, Flathash);
544         WCC->CurrentFloor = NULL;
545
546         Buf = NewStrBuf();
547         while (StrBufExtract_NextToken(Buf, WCC->Hdr->HR.ReqLine, &pCh,  '/') >= 0)
548         {
549                 if (StrLength(Buf) != 0) {
550                         /* ignore empty path segments */
551                         StrBufUnescape(Buf, 1);
552                         Put(WCC->Directory, IKEY(i), Buf, HFreeStrBuf);
553                         if (i==0)
554                                 pFloor = Buf;
555                         Buf = NewStrBuf();
556                 }
557                 i++;
558         }
559
560         FreeStrBuf(&Buf);
561         if (pFloor != NULL)
562         {
563                 Floors = GetFloorListHash(NULL, NULL);
564                 
565                 if (Floors != NULL)
566                 {
567                         if (GetHash(WCC->FloorsByName, SKEY(pFloor), &vFloor))
568                                 WCC->CurrentFloor = (Floor*) vFloor;
569                 }
570         }
571 }
572
573 int Conditional_REST_DEPTH(StrBuf *Target, WCTemplputParams *TP)
574 {
575         long Depth, IsDepth;
576         long offset = 0;
577         wcsession *WCC = WC;
578
579         if (WCC->Hdr->HR.Handler != NULL)
580                 offset ++;
581         Depth = GetTemplateTokenNumber(Target, TP, 2, 0);
582         IsDepth = GetCount(WCC->Directory) + offset;
583
584 //      LogTemplateError(Target, "bla", 1, TP, "REST_DEPTH: %ld : %ld\n", Depth, IsDepth);
585         if (Depth < 0) {
586                 Depth = -Depth;
587                 return IsDepth > Depth;
588         }
589         else 
590                 return Depth == IsDepth;
591 }
592
593
594
595 /*
596  * Entry point for WebCit transaction
597  */
598 void session_loop(void)
599 {
600         int Flags = 0;
601         int xhttp;
602         StrBuf *Buf;
603         
604         /*
605          * We stuff these with the values coming from the client cookies,
606          * so we can use them to reconnect a timed out session if we have to.
607          */
608         wcsession *WCC;
609       
610         WCC= WC;
611         WCC->upload_length = 0;
612         WCC->upload = NULL;
613         WCC->is_mobile = 0;
614         WCC->Hdr->nWildfireHeaders = 0;
615         if (WCC->Hdr->HR.Handler != NULL)
616                 Flags = WCC->Hdr->HR.Handler->Flags; /* so we can temporarily add our own... */
617
618         if (WCC->Hdr->HR.ContentLength > 0) {
619                 if (ReadPostData() < 0) {
620                         return;
621                 }
622         }
623
624         Buf = NewStrBuf();
625         WCC->trailing_javascript = NewStrBuf();
626
627         /* Convert base64-encoded URL's back to plain text */
628         if (!strncmp(ChrPtr(WCC->Hdr->this_page), "/B64", 4)) {
629                 StrBufCutLeft(WCC->Hdr->this_page, 4);
630                 StrBufDecodeBase64(WCC->Hdr->this_page);
631                 http_redirect(ChrPtr(WCC->Hdr->this_page));
632                 goto SKIP_ALL_THIS_CRAP;
633         }
634
635         /* If there are variables in the URL, we must grab them now */
636         if (WCC->Hdr->PlainArgs != NULL)
637                 ParseURLParams(WCC->Hdr->PlainArgs);
638
639         /* If the client sent a nonce that is incorrect, kill the request. */
640         if (havebstr("nonce")) {
641                 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n", 
642                         bstr("nonce"), WCC->nonce);
643                 if (ibstr("nonce") != WCC->nonce) {
644                         lprintf(9, "Ignoring request with mismatched nonce.\n");
645                         hprintf("HTTP/1.1 404 Security check failed\r\n");
646                         hprintf("Content-Type: text/plain\r\n");
647                         begin_burst();
648                         wc_printf("Security check failed.\r\n");
649                         end_burst();
650                         goto SKIP_ALL_THIS_CRAP;
651                 }
652         }
653
654         /*
655          * If we're not connected to a Citadel server, try to hook up the
656          * connection now.
657          */
658         if (!WCC->connected) {
659                 if (GetConnected ())
660                         goto SKIP_ALL_THIS_CRAP;
661         }
662
663
664         /*
665          * If we're not logged in, but we have authentication data (either from
666          * a cookie or from http-auth), try logging in to Citadel using that.
667          */
668         if ((!WCC->logged_in)
669             && (StrLength(WCC->Hdr->c_username) > 0)
670             && (StrLength(WCC->Hdr->c_password) > 0))
671         {
672                 long Status;
673
674                 FlushStrBuf(Buf);
675                 serv_printf("USER %s", ChrPtr(WCC->Hdr->c_username));
676                 StrBuf_ServGetln(Buf);
677                 if (GetServerStatus(Buf, &Status) == 3) {
678                         serv_printf("PASS %s", ChrPtr(WCC->Hdr->c_password));
679                         StrBuf_ServGetln(Buf);
680                         if (GetServerStatus(Buf, NULL) == 2) {
681                                 become_logged_in(WCC->Hdr->c_username,
682                                                  WCC->Hdr->c_password, Buf);
683                         } else {
684                                 /* Should only display when password is wrong */
685                                 WCC->ImportantMsg = NewStrBufPlain(ChrPtr(Buf) + 4, StrLength(Buf) - 4);
686                                 authorization_required();
687                                 FreeStrBuf(&Buf);
688                                 goto SKIP_ALL_THIS_CRAP;
689                         }
690                 }
691                 else if (Status == 541) {
692                         WCC->logged_in = 1;
693                 }
694         }
695
696         xhttp = (WCC->Hdr->HR.eReqType != eGET) &&
697                 (WCC->Hdr->HR.eReqType != ePOST) &&
698                 (WCC->Hdr->HR.eReqType != eHEAD);
699
700         /*
701          * If a 'gotofirst' parameter has been specified, attempt to goto that room
702          * prior to doing anything else.
703          */
704         if (havebstr("gotofirst")) {
705                 int ret;
706                 ret = gotoroom(sbstr("gotofirst"));     /* do quietly to avoid session output! */
707                 if ((ret/100) != 2) {
708                         lprintf(1, "GOTOFIRST: Unable to change to [%s]; Reason: %d\n",
709                                 bstr("gotofirst"), ret);
710                 }
711         }
712
713         /*
714          * If we aren't in any room yet, but we have cookie data telling us where we're
715          * supposed to be, and 'gotofirst' was not specified, then go there.
716          */
717         else if ( (StrLength(WCC->CurRoom.name) == 0) && ( (StrLength(WCC->Hdr->c_roomname) > 0) )) {
718                 int ret;
719
720                 lprintf(9, "We are in '%s' but cookie indicates '%s', going there...\n",
721                         ChrPtr(WCC->CurRoom.name),
722                         ChrPtr(WCC->Hdr->c_roomname)
723                 );
724                 ret = gotoroom(WCC->Hdr->c_roomname);   /* do quietly to avoid session output! */
725                 if ((ret/100) != 2) {
726                         lprintf(1, "COOKIEGOTO: Unable to change to [%s]; Reason: %d\n",
727                                 ChrPtr(WCC->Hdr->c_roomname), ret);
728                 }
729         }
730
731         if (WCC->Hdr->HR.Handler != NULL) {
732                 if (!WCC->logged_in && ((WCC->Hdr->HR.Handler->Flags & ANONYMOUS) == 0)) {
733                         display_login();
734                 }
735                 else {
736 /*
737                         if ((WCC->Hdr->HR.Handler->Flags & PARSE_REST_URL) != 0)
738                                 ParseREST_URL();
739 */
740                         if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
741                                 begin_ajax_response();
742                         WCC->Hdr->HR.Handler->F();
743                         if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
744                                 end_ajax_response();
745                 }
746         }
747         /* When all else fais, display the main menu. */
748         else {
749                 /* 
750                  * ordinary browser users get a nice login screen, DAV etc. requsets
751                  * are given a 401 so they can handle it appropriate.
752                  */
753                 if (!WCC->logged_in)  {
754                         if (xhttp)
755                                 authorization_required();
756                         else 
757                                 display_login();
758                 }
759                 /*
760                  * Toplevel dav requests? or just a flat browser request? 
761                  */
762                 else {
763                         if (xhttp)
764                                 groupdav_main();
765                         else
766                                 display_main_menu();
767                 }
768         }
769
770 SKIP_ALL_THIS_CRAP:
771         FreeStrBuf(&Buf);
772         fflush(stdout);
773 }
774
775
776 /*
777  * Replacement for sleep() that uses select() in order to avoid SIGALRM
778  */
779 void sleeeeeeeeeep(int seconds)
780 {
781         struct timeval tv;
782
783         tv.tv_sec = seconds;
784         tv.tv_usec = 0;
785         select(0, NULL, NULL, NULL, &tv);
786 }
787
788 int Conditional_IS_HTTPS(StrBuf *Target, WCTemplputParams *TP)
789 {
790         return is_https != 0;
791 }
792
793 void AppendImportantMessage(const char *pch, long len)
794 {
795         wcsession *WCC = WC;
796
797         if (StrLength(WCC->ImportantMsg) > 0) {
798                 StrBufAppendBufPlain(WCC->ImportantMsg, HKEY("\n"), 0);
799         }
800                 
801         StrBufAppendBufPlain(WCC->ImportantMsg, pch, len, 0);
802 }
803
804 int ConditionalImportantMesage(StrBuf *Target, WCTemplputParams *TP)
805 {
806         wcsession *WCC = WC;
807         if (WCC != NULL)
808                 return ((!IsEmptyStr(WCC->ImportantMessage)) || 
809                         (StrLength(WCC->ImportantMsg) > 0));
810         else
811                 return 0;
812 }
813
814 void tmplput_importantmessage(StrBuf *Target, WCTemplputParams *TP)
815 {
816         wcsession *WCC = WC;
817         
818         if (WCC != NULL) {
819                 if (!IsEmptyStr(WCC->ImportantMessage)) {
820                         StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
821                         WCC->ImportantMessage[0] = '\0';
822                 }
823                 else if (StrLength(WCC->ImportantMsg) > 0) {
824                         StrEscAppend(Target, WCC->ImportantMsg, NULL, 0, 0);
825                         FlushStrBuf(WCC->ImportantMsg);
826                 }
827         }
828 }
829
830 void tmplput_trailing_javascript(StrBuf *Target, WCTemplputParams *TP)
831 {
832         wcsession *WCC = WC;
833
834         if (WCC != NULL)
835                 StrBufAppendTemplate(Target, TP, WCC->trailing_javascript, 0);
836 }
837
838 void tmplput_csslocal(StrBuf *Target, WCTemplputParams *TP)
839 {
840         StrBufAppendBuf(Target, 
841                         csslocal, 0);
842 }
843
844 extern char static_local_dir[PATH_MAX];
845
846
847 void 
848 InitModule_WEBCIT
849 (void)
850 {
851         char dir[SIZ];
852         WebcitAddUrlHandler(HKEY("blank"), "", 0, blank_page, ANONYMOUS|COOKIEUNNEEDED|ISSTATIC);
853         WebcitAddUrlHandler(HKEY("do_template"), "", 0, url_do_template, ANONYMOUS);
854         WebcitAddUrlHandler(HKEY("sslg"), "", 0, seconds_since_last_gexp, AJAX|LOGCHATTY);
855         WebcitAddUrlHandler(HKEY("ajax_servcmd"), "", 0, ajax_servcmd, 0);
856         WebcitAddUrlHandler(HKEY("webcit"), "", 0, blank_page, URLNAMESPACE);
857
858         WebcitAddUrlHandler(HKEY("401"), "", 0, authorization_required, ANONYMOUS|COOKIEUNNEEDED);
859         RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage, CTX_NONE);
860         RegisterConditional(HKEY("COND:REST:DEPTH"), 0, Conditional_REST_DEPTH, CTX_NONE);
861         RegisterConditional(HKEY("COND:IS_HTTPS"), 0, Conditional_IS_HTTPS, CTX_NONE);
862
863         RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, NULL, CTX_NONE);
864         RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, NULL, CTX_NONE);
865         RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, NULL, CTX_NONE);
866         RegisterNamespace("URL:DISPLAYNAME", 0, 1, tmplput_HANDLER_DISPLAYNAME, NULL, CTX_NONE);
867         RegisterNamespace("URL:HOSTNAME", 0, 1, tmplput_HOST_DISPLAYNAME, NULL, CTX_NONE);
868
869         
870         snprintf(dir, SIZ, "%s/webcit.css", static_local_dir);
871         if (!access(dir, R_OK)) {
872                 lprintf(9, "Using local Stylesheet [%s]\n", dir);
873                 csslocal = NewStrBufPlain(HKEY("<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\" />"));
874         }
875         else
876                 lprintf(9, "No Site-local Stylesheet [%s] installed. \n", dir);
877
878 }
879
880 void
881 ServerStartModule_WEBCIT
882 (void)
883 {
884         HandlerHash = NewHash(1, NULL);
885 }
886
887
888 void 
889 ServerShutdownModule_WEBCIT
890 (void)
891 {
892         FreeStrBuf(&csslocal);
893         DeleteHash(&HandlerHash);
894 }
895
896
897
898 void
899 SessionNewModule_WEBCIT
900 (wcsession *sess)
901 {
902         sess->ImportantMsg = NewStrBuf();
903         sess->WBuf = NewStrBufPlain(NULL, SIZ * 4);
904         sess->HBuf = NewStrBufPlain(NULL, SIZ / 4);
905 }
906
907 void
908 SessionDetachModule_WEBCIT
909 (wcsession *sess)
910 {
911         DeleteHash(&sess->Directory);
912
913         FreeStrBuf(&sess->upload);
914         sess->upload_length = 0;
915         
916         FreeStrBuf(&sess->trailing_javascript);
917
918         if (StrLength(sess->WBuf) > SIZ * 30) /* Bigger than 120K? release. */
919         {
920                 FreeStrBuf(&sess->WBuf);
921                 sess->WBuf = NewStrBuf();
922         }
923         else
924                 FlushStrBuf(sess->WBuf);
925         FlushStrBuf(sess->HBuf);
926 }
927
928 void 
929 SessionDestroyModule_WEBCIT
930 (wcsession *sess)
931 {
932         FreeStrBuf(&sess->WBuf);
933         FreeStrBuf(&sess->HBuf);
934         FreeStrBuf(&sess->ImportantMsg);
935 }
936