* add logging if auth-basic session connecting fails with weird conditions
[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("iconbar"), NULL, &NoCtx);*/
213                         page_popup();
214                 }
215
216                 if (do_room_banner == 1) {
217                         wprintf("<div id=\"banner\">\n");
218                         embed_room_banner(NULL, navbar_default);
219                         wprintf("</div>\n");
220                 }
221         }
222
223         if (do_room_banner == 1) {
224                 wprintf("<div id=\"content\">\n");
225         }
226 }
227
228 void output_custom_content_header(const char *ctype) {
229   hprintf("HTTP/1.1 200 OK\r\n");
230   hprintf("Content-type: %s; charset=utf-8\r\n",ctype);
231   hprintf("Server: %s / %s\r\n", PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software));
232   hprintf("Connection: close\r\n");
233 }
234
235
236 /*
237  * Generic function to do an HTTP redirect.  Easy and fun.
238  */
239 void http_redirect(const char *whichpage) {
240         hprintf("HTTP/1.1 302 Moved Temporarily\n");
241         hprintf("Location: %s\r\n", whichpage);
242         hprintf("URI: %s\r\n", whichpage);
243         hprintf("Content-type: text/html; charset=utf-8\r\n");
244         begin_burst();
245         wprintf("<html><body>");
246         wprintf("Go <a href=\"%s\">here</A>.", whichpage);
247         wprintf("</body></html>\n");
248         end_burst();
249 }
250
251
252
253 /*
254  * Output a piece of content to the web browser using conformant HTTP and MIME semantics
255  */
256 void http_transmit_thing(const char *content_type,
257                          int is_static) {
258
259 #ifndef TECH_PREVIEW
260         lprintf(9, "http_transmit_thing(%s)%s\n",
261                 content_type,
262                 ((is_static > 0) ? " (static)" : "")
263         );
264 #endif
265         output_headers(0, 0, 0, 0, 0, is_static);
266
267         hprintf("Content-type: %s\r\n"
268                 "Server: %s\r\n"
269                 "Connection: close\r\n",
270                 content_type,
271                 PACKAGE_STRING);
272
273         end_burst();
274 }
275
276 /*
277  * print menu box like used in the floor view or admin interface.
278  * This function takes pair of strings as va_args, 
279  * Title        Title string of the box
280  * Class        CSS Class for the box
281  * nLines       How many string pairs should we print? (URL, UrlText)
282  * ...          Pairs of URL Strings and their Names
283  */
284 void print_menu_box(char* Title, char *Class, int nLines, ...)
285 {
286         va_list arg_list;
287         long i;
288         
289         svput("BOXTITLE", WCS_STRING, Title);
290         do_template("beginboxx", NULL);
291         
292         wprintf("<ul class=\"%s\">", Class);
293         
294         va_start(arg_list, nLines);
295         for (i = 0; i < nLines; ++i)
296         { 
297                 wprintf("<li><a href=\"%s\">", va_arg(arg_list, char *));
298                 wprintf((char *) va_arg(arg_list, char *));
299                 wprintf("</a></li>\n");
300         }
301         va_end (arg_list);
302         
303         wprintf("</a></li>\n");
304         
305         wprintf("</ul>");
306         
307         do_template("endbox", NULL);
308 }
309
310
311
312 /*
313  * Convenience functions to display a page containing only a string
314  *
315  * titlebarcolor        color of the titlebar of the frame
316  * titlebarmsg          text to display in the title bar
317  * messagetext          body of the box
318  */
319 void convenience_page(const char *titlebarcolor, const char *titlebarmsg, const char *messagetext)
320 {
321         hprintf("HTTP/1.1 200 OK\n");
322         output_headers(1, 1, 2, 0, 0, 0);
323         wprintf("<div id=\"banner\">\n");
324         wprintf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
325         wprintf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
326         wprintf("</td></tr></table>\n");
327         wprintf("</div>\n<div id=\"content\">\n");
328         escputs(messagetext);
329
330         wprintf("<hr />\n");
331         wDumpContent(1);
332 }
333
334
335 /*
336  * Display a blank page.
337  */
338 void blank_page(void) {
339         output_headers(1, 1, 0, 0, 0, 0);
340         wDumpContent(2);
341 }
342
343
344 /*
345  * A template has been requested
346  */
347 void url_do_template(void) {
348         const StrBuf *MimeType;
349         const StrBuf *Tmpl = sbstr("template");
350         begin_burst();
351         MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
352         http_transmit_thing(ChrPtr(MimeType), 0);
353 }
354
355
356
357 /*
358  * convenience function to indicate success
359  */
360 void display_success(char *successmessage)
361 {
362         convenience_page("007700", "OK", successmessage);
363 }
364
365
366 /*
367  * Authorization required page 
368  * This is probably temporary and should be revisited 
369  */
370 void authorization_required(void)
371 {
372         wcsession *WCC = WC;
373         const char *message = "";
374
375         hprintf("HTTP/1.1 401 Authorization Required\r\n");
376         hprintf(
377                 "Server: %s / %s\r\n"
378                 "Connection: close\r\n",
379                 PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software)
380         );
381         hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", ChrPtr(WC->serv_info->serv_humannode));
382         hprintf("Content-Type: text/html\r\n");
383         begin_burst();
384         wprintf("<h1>");
385         wprintf(_("Authorization Required"));
386         wprintf("</h1>\r\n");
387         
388
389         if (WCC->ImportantMsg != NULL)
390                 message = ChrPtr(WCC->ImportantMsg);
391         else if (WCC->ImportantMessage != NULL)
392                 message = WCC->ImportantMessage;
393
394         wprintf(_("The resource you requested requires a valid username and password. "
395                 "You could not be logged in: %s\n"), message);
396         wDumpContent(0);
397         end_webcit_session();
398 }
399
400 /*
401  * Convenience functions to wrap around asynchronous ajax responses
402  */
403 void begin_ajax_response(void) {
404         wcsession *WCC = WC;
405
406         FlushStrBuf(WCC->HBuf);
407         output_headers(0, 0, 0, 0, 0, 0);
408
409         hprintf("Content-type: text/html; charset=UTF-8\r\n"
410                 "Server: %s\r\n"
411                 "Connection: close\r\n"
412                 ,
413                 PACKAGE_STRING);
414         begin_burst();
415 }
416
417 /*
418  * print ajax response footer 
419  */
420 void end_ajax_response(void) {
421         wDumpContent(0);
422 }
423
424
425
426 /*
427  * Wraps a Citadel server command in an AJAX transaction.
428  */
429 void ajax_servcmd(void)
430 {
431         wcsession *WCC = WC;
432         int Done = 0;
433         StrBuf *Buf;
434         char *junk;
435         size_t len;
436
437         begin_ajax_response();
438         Buf = NewStrBuf();
439         serv_puts(bstr("g_cmd"));
440         StrBuf_ServGetln(Buf);
441         StrBufAppendBuf(WCC->WBuf, Buf, 0);
442         StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
443         
444         switch (GetServerStatus(Buf, NULL)) {
445         case 8:
446                 serv_puts("\n\n000");
447                 if ( (StrLength(Buf)==3) && 
448                      !strcmp(ChrPtr(Buf), "000")) {
449                         StrBufAppendBufPlain(WCC->WBuf, HKEY("\000"), 0);
450                         break;
451                 }
452         case 1:
453                 while (!Done) {
454                         StrBuf_ServGetln(Buf);
455                         if ( (StrLength(Buf)==3) && 
456                              !strcmp(ChrPtr(Buf), "000")) {
457                                 Done = 1;
458                         }
459                         StrBufAppendBuf(WCC->WBuf, Buf, 0);
460                         StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
461                 }
462                 break;
463         case 4:
464                 text_to_server(bstr("g_input"));
465                 serv_puts("000");
466                 break;
467         case 6:
468                 len = atol(&ChrPtr(Buf)[4]);
469                 StrBuf_ServGetBLOBBuffered(Buf, len);
470                 break;
471         case 7:
472                 len = atol(&ChrPtr(Buf)[4]);
473                 junk = malloc(len);
474                 memset(junk, 0, len);
475                 serv_write(junk, len);
476                 free(junk);
477         }
478         
479         end_ajax_response();
480         
481         /*
482          * This is kind of an ugly hack, but this is the only place it can go.
483          * If the command was GEXP, then the instant messenger window must be
484          * running, so reset the "last_pager_check" watchdog timer so
485          * that page_popup() doesn't try to open it a second time.
486          */
487         if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
488                 WCC->last_pager_check = time(NULL);
489         }
490         FreeStrBuf(&Buf);
491 }
492
493
494 /*
495  * Helper function for the asynchronous check to see if we need
496  * to open the instant messenger window.
497  */
498 void seconds_since_last_gexp(void)
499 {
500         char buf[256];
501
502         if ( (time(NULL) - WC->last_pager_check) < 30) {
503                 wprintf("NO\n");
504         }
505         else {
506                 memset(buf, 0, 5);
507                 serv_puts("NOOP");
508                 serv_getln(buf, sizeof buf);
509                 if (buf[3] == '*') {
510                         wprintf("YES");
511                 }
512                 else {
513                         wprintf("NO");
514                 }
515         }
516 }
517
518
519
520 void ReadPostData(void)
521 {
522         const char *content_end = NULL;
523         int body_start = 0;
524         wcsession *WCC = WC;
525         StrBuf *content = NULL;
526         
527         content = NewStrBufPlain(NULL, WCC->Hdr->HR.ContentLength + 256);
528
529         StrBufPrintf(content, 
530                      "Content-type: %s\n"
531                      "Content-length: %ld\n\n",
532                      ChrPtr(WCC->Hdr->HR.ContentType), 
533                              WCC->Hdr->HR.ContentLength);
534 /*
535   hprintf("Content-type: %s\n"
536   "Content-length: %d\n\n",
537   ContentType, ContentLength);
538 */
539         body_start = StrLength(content);
540
541         /** Read the entire input data at once. */
542         client_read_to(WCC->Hdr, content, 
543                        WCC->Hdr->HR.ContentLength,
544                        SLEEPING);
545         
546         if (!strncasecmp(ChrPtr(WCC->Hdr->HR.ContentType), "application/x-www-form-urlencoded", 33)) {
547                 StrBufCutLeft(content, body_start);
548                 ParseURLParams(content);
549         } else if (!strncasecmp(ChrPtr(WCC->Hdr->HR.ContentType), "multipart", 9)) {
550                 content_end = ChrPtr(content) + 
551                         WCC->Hdr->HR.ContentLength + 
552                         body_start;
553                 mime_parser(ChrPtr(content), content_end, *upload_handler, NULL, NULL, NULL, 0);
554         } else if (WCC->Hdr->HR.ContentLength > 0) {
555                 WCC->upload = content;
556                 content = NULL;
557         }
558         FreeStrBuf(&content);
559 }
560
561
562 /*
563  * Entry point for WebCit transaction
564  */
565 void session_loop(void)
566 {
567         int Flags = 0;
568         int xhttp;
569         StrBuf *Buf;
570         
571         /*
572          * We stuff these with the values coming from the client cookies,
573          * so we can use them to reconnect a timed out session if we have to.
574          */
575         wcsession *WCC;
576
577         
578         Buf = NewStrBuf();
579
580         WCC= WC;
581
582         WCC->upload_length = 0;
583         WCC->upload = NULL;
584         WCC->is_mobile = 0;
585         WCC->trailing_javascript = NewStrBuf();
586         WCC->Hdr->nWildfireHeaders = 0;
587         if (WCC->Hdr->HR.Handler != NULL)
588                 Flags = WCC->Hdr->HR.Handler->Flags; /* so we can temporarily add our own... */
589
590         if (WCC->Hdr->HR.ContentLength > 0) {
591                 ReadPostData();
592         }
593
594         /* If there are variables in the URL, we must grab them now */
595         if (WCC->Hdr->PlainArgs != NULL)
596                 ParseURLParams(WCC->Hdr->PlainArgs);
597
598         /* If the client sent a nonce that is incorrect, kill the request. */
599         if (havebstr("nonce")) {
600                 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n", 
601                         bstr("nonce"), WCC->nonce);
602                 if (ibstr("nonce") != WCC->nonce) {
603                         lprintf(9, "Ignoring request with mismatched nonce.\n");
604                         hprintf("HTTP/1.1 404 Security check failed\r\n");
605                         hprintf("Content-Type: text/plain\r\n\r\n");
606                         begin_burst();
607                         wprintf("Security check failed.\r\n");
608                         end_burst();
609                         goto SKIP_ALL_THIS_CRAP;
610                 }
611         }
612
613         /*
614          * If we're not connected to a Citadel server, try to hook up the
615          * connection now.
616          */
617         if (!WCC->connected) {
618                 if (GetConnected ())
619                         goto SKIP_ALL_THIS_CRAP;
620         }
621
622
623         /*
624          * If we're not logged in, but we have authentication data (either from
625          * a cookie or from http-auth), try logging in to Citadel using that.
626          */
627         if ((!WCC->logged_in)
628             && (StrLength(WCC->Hdr->c_username) > 0)
629             && (StrLength(WCC->Hdr->c_password) > 0))
630         {
631                 FlushStrBuf(Buf);
632                 serv_printf("USER %s", ChrPtr(WCC->Hdr->c_username));
633                 StrBuf_ServGetln(Buf);
634                 if (GetServerStatus(Buf, NULL) == 3) {
635                         serv_printf("PASS %s", ChrPtr(WCC->Hdr->c_password));
636                         StrBuf_ServGetln(Buf);
637                         if (GetServerStatus(Buf, NULL) == 2) {
638                                 become_logged_in(WCC->Hdr->c_username,
639                                                  WCC->Hdr->c_password, Buf);
640                         } else {
641                                 /* Should only display when password is wrong */
642                                 WCC->ImportantMsg = NewStrBufPlain(ChrPtr(Buf) + 4, StrLength(Buf) - 4);
643                                 authorization_required();
644                                 FreeStrBuf(&Buf);
645                                 goto SKIP_ALL_THIS_CRAP;
646                         }
647                 }
648         }
649
650         xhttp = (WCC->Hdr->HR.eReqType != eGET) &&
651                 (WCC->Hdr->HR.eReqType != ePOST) &&
652                 (WCC->Hdr->HR.eReqType != eHEAD);
653
654         /*
655          * If a 'gotofirst' parameter has been specified, attempt to goto that room
656          * prior to doing anything else.
657          */
658         if (havebstr("gotofirst")) {
659                 int ret;
660                 ret = gotoroom(sbstr("gotofirst"));     /* do quietly to avoid session output! */
661                 if ((ret/100) != 2) {
662                         lprintf(1, "GOTOFIRST: Unable to change to [%s]; Reason: %d\n",
663                                 bstr("gotofirst"), ret);
664                 }
665         }
666
667         /*
668          * If we aren't in any room yet, but we have cookie data telling us where we're
669          * supposed to be, and 'gotofirst' was not specified, then go there.
670          */
671         else if ( (StrLength(WCC->wc_roomname) == 0) && ( (StrLength(WCC->Hdr->c_roomname) > 0) )) {
672                 int ret;
673
674                 lprintf(9, "We are in '%s' but cookie indicates '%s', going there...\n",
675                         ChrPtr(WCC->wc_roomname),
676                         ChrPtr(WCC->Hdr->c_roomname)
677                 );
678                 ret = gotoroom(WCC->Hdr->c_roomname);   /* do quietly to avoid session output! */
679                 if ((ret/100) != 2) {
680                         lprintf(1, "COOKIEGOTO: Unable to change to [%s]; Reason: %d\n",
681                                 ChrPtr(WCC->Hdr->c_roomname), ret);
682                 }
683         }
684
685         if (WCC->Hdr->HR.Handler != NULL) {
686                 if (!WCC->logged_in && ((WCC->Hdr->HR.Handler->Flags & ANONYMOUS) == 0)) {
687                         display_login(NULL);
688                 }
689                 else {
690                         if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
691                                 begin_ajax_response();
692                         WCC->Hdr->HR.Handler->F();
693                         if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
694                                 end_ajax_response();
695                 }
696         }
697         /* When all else fais, display the main menu. */
698         else {
699                 /* 
700                  * ordinary browser users get a nice login screen, DAV etc. requsets
701                  * are given a 401 so they can handle it appropriate.
702                  */
703                 if (!WCC->logged_in)  {
704                         if (xhttp)
705                                 authorization_required();
706                         else 
707                                 display_login(NULL);
708                 }
709                 /*
710                  * Toplevel dav requests? or just a flat browser request? 
711                  */
712                 else {
713                         if (xhttp)
714                                 groupdav_main();
715                         else
716                                 display_main_menu();
717                 }
718         }
719
720 SKIP_ALL_THIS_CRAP:
721         FreeStrBuf(&Buf);
722         fflush(stdout);
723 }
724
725
726 /*
727  * Replacement for sleep() that uses select() in order to avoid SIGALRM
728  */
729 void sleeeeeeeeeep(int seconds)
730 {
731         struct timeval tv;
732
733         tv.tv_sec = seconds;
734         tv.tv_usec = 0;
735         select(0, NULL, NULL, NULL, &tv);
736 }
737
738
739 int ConditionalImportantMesage(StrBuf *Target, WCTemplputParams *TP)
740 {
741         wcsession *WCC = WC;
742         if (WCC != NULL)
743                 return ((!IsEmptyStr(WCC->ImportantMessage)) || 
744                         (StrLength(WCC->ImportantMsg) > 0));
745         else
746                 return 0;
747 }
748
749 void tmplput_importantmessage(StrBuf *Target, WCTemplputParams *TP)
750 {
751         wcsession *WCC = WC;
752         
753         if (WCC != NULL) {
754                 if (!IsEmptyStr(WCC->ImportantMessage)) {
755                         StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
756                         WCC->ImportantMessage[0] = '\0';
757                 }
758                 else if (StrLength(WCC->ImportantMsg) > 0) {
759                         StrEscAppend(Target, WCC->ImportantMsg, NULL, 0, 0);
760                         FlushStrBuf(WCC->ImportantMsg);
761                 }
762         }
763 }
764
765 void tmplput_trailing_javascript(StrBuf *Target, WCTemplputParams *TP)
766 {
767         wcsession *WCC = WC;
768
769         if (WCC != NULL)
770                 StrBufAppendTemplate(Target, TP, WCC->trailing_javascript, 0);
771 }
772
773 void tmplput_csslocal(StrBuf *Target, WCTemplputParams *TP)
774 {
775         StrBufAppendBuf(Target, 
776                         csslocal, 0);
777 }
778
779 extern char static_local_dir[PATH_MAX];
780
781
782 void 
783 InitModule_WEBCIT
784 (void)
785 {
786         char dir[SIZ];
787         WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS|COOKIEUNNEEDED|ISSTATIC);
788         WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
789         WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX|LOGCHATTY);
790         WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
791         WebcitAddUrlHandler(HKEY("webcit"), blank_page, URLNAMESPACE);
792
793         WebcitAddUrlHandler(HKEY("401"), authorization_required, ANONYMOUS|COOKIEUNNEEDED);
794         RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage, CTX_NONE);
795         RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, CTX_NONE);
796         RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, CTX_NONE);
797         RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, CTX_NONE);
798
799         snprintf(dir, SIZ, "%s/webcit.css", static_local_dir);
800         if (!access(dir, R_OK)) {
801                 lprintf(9, "Using local Stylesheet [%s]\n", dir);
802                 csslocal = NewStrBufPlain(HKEY("<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\">"));
803         }
804         else
805                 lprintf(9, "No Site-local Stylesheet [%s] installed. \n", dir);
806
807 }
808
809 void
810 ServerStartModule_WEBCIT
811 (void)
812 {
813         HandlerHash = NewHash(1, NULL);
814 }
815
816
817 void 
818 ServerShutdownModule_WEBCIT
819 (void)
820 {
821         FreeStrBuf(&csslocal);
822         DeleteHash(&HandlerHash);
823 }
824
825
826
827 void
828 SessionNewModule_WEBCIT
829 (wcsession *sess)
830 {
831         sess->ImportantMsg = NewStrBuf();
832         sess->WBuf = NewStrBufPlain(NULL, SIZ * 4);
833         sess->HBuf = NewStrBufPlain(NULL, SIZ / 4);
834 }
835
836 void
837 SessionDetachModule_WEBCIT
838 (wcsession *sess)
839 {
840         DeleteHash(&sess->Hdr->urlstrings);// TODO?
841         if (sess->upload_length > 0) {
842                 FreeStrBuf(&sess->upload);
843                 sess->upload_length = 0;
844         }
845         FreeStrBuf(&sess->trailing_javascript);
846
847         if (StrLength(sess->WBuf) > SIZ * 30) /* Bigger than 120K? release. */
848         {
849                 FreeStrBuf(&sess->WBuf);
850                 sess->WBuf = NewStrBuf();
851         }
852         else
853                 FlushStrBuf(sess->WBuf);
854         FlushStrBuf(sess->HBuf);
855 }
856
857 void 
858 SessionDestroyModule_WEBCIT
859 (wcsession *sess)
860 {
861         FreeStrBuf(&sess->WBuf);
862         FreeStrBuf(&sess->HBuf);
863         FreeStrBuf(&sess->ImportantMsg);
864 }
865