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