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