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