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