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