* fix groupdav handling
[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         }
553         FreeStrBuf(&content);
554 }
555
556
557 /*
558  * Entry point for WebCit transaction
559  */
560 void session_loop(void)
561 {
562         int Flags = 0;
563         int xhttp;
564         StrBuf *Buf;
565         
566         /*
567          * We stuff these with the values coming from the client cookies,
568          * so we can use them to reconnect a timed out session if we have to.
569          */
570         wcsession *WCC;
571
572         
573         Buf = NewStrBuf();
574
575         WCC= WC;
576
577         WCC->upload_length = 0;
578         WCC->upload = NULL;
579         WCC->is_mobile = 0;
580         WCC->trailing_javascript = NewStrBuf();
581         WCC->Hdr->nWildfireHeaders = 0;
582         if (WCC->Hdr->HR.Handler != NULL)
583                 Flags = WCC->Hdr->HR.Handler->Flags; /* so we can temporarily add our own... */
584
585         if (WCC->Hdr->HR.ContentLength > 0) {
586                 ReadPostData();
587         }
588
589         /* If there are variables in the URL, we must grab them now */
590         if (WCC->Hdr->PlainArgs != NULL)
591                 ParseURLParams(WCC->Hdr->PlainArgs);
592
593         /* If the client sent a nonce that is incorrect, kill the request. */
594         if (havebstr("nonce")) {
595                 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n", 
596                         bstr("nonce"), WCC->nonce);
597                 if (ibstr("nonce") != WCC->nonce) {
598                         lprintf(9, "Ignoring request with mismatched nonce.\n");
599                         hprintf("HTTP/1.1 404 Security check failed\r\n");
600                         hprintf("Content-Type: text/plain\r\n\r\n");
601                         wprintf("Security check failed.\r\n");
602                         end_burst();
603                         goto SKIP_ALL_THIS_CRAP;
604                 }
605         }
606
607         /*
608          * If we're not connected to a Citadel server, try to hook up the
609          * connection now.
610          */
611         if (!WCC->connected) {
612                 if (GetConnected ())
613                         goto SKIP_ALL_THIS_CRAP;
614         }
615
616
617         /*
618          * If we're not logged in, but we have authentication data (either from
619          * a cookie or from http-auth), try logging in to Citadel using that.
620          */
621         if ((!WCC->logged_in)
622             && (StrLength(WCC->Hdr->c_username) > 0)
623             && (StrLength(WCC->Hdr->c_password) > 0))
624         {
625                 FlushStrBuf(Buf);
626                 serv_printf("USER %s", ChrPtr(WCC->Hdr->c_username));
627                 StrBuf_ServGetln(Buf);
628                 if (GetServerStatus(Buf, NULL) == 3) {
629                         serv_printf("PASS %s", ChrPtr(WCC->Hdr->c_password));
630                         StrBuf_ServGetln(Buf);
631                         if (GetServerStatus(Buf, NULL) == 2) {
632                                 become_logged_in(WCC->Hdr->c_username,
633                                                  WCC->Hdr->c_password, Buf);
634                         } else {
635                                 /* Should only display when password is wrong */
636                                 WCC->ImportantMsg = NewStrBufPlain(ChrPtr(Buf) + 4, StrLength(Buf) - 4);
637                                 authorization_required();
638                                 FreeStrBuf(&Buf);
639                                 goto SKIP_ALL_THIS_CRAP;
640                         }
641                 }
642         }
643
644         xhttp = (WCC->Hdr->HR.eReqType != eGET) &&
645                 (WCC->Hdr->HR.eReqType != ePOST) &&
646                 (WCC->Hdr->HR.eReqType != eHEAD);
647
648         /*
649          * If a 'gotofirst' parameter has been specified, attempt to goto that room
650          * prior to doing anything else.
651          */
652         if (havebstr("gotofirst")) {
653                 int ret;
654                 ret = gotoroom(sbstr("gotofirst"));     /* do quietly to avoid session output! */
655                 if ((ret/100) != 2) {
656                         lprintf(1, "GOTOFIRST: Unable to change to [%s]; Reason: %d\n",
657                                 bstr("gotofirst"), ret);
658                 }
659         }
660
661         /*
662          * If we aren't in any room yet, but we have cookie data telling us where we're
663          * supposed to be, and 'gotofirst' was not specified, then go there.
664          */
665         else if ( (StrLength(WCC->wc_roomname) == 0) && ( (StrLength(WCC->Hdr->c_roomname) > 0) )) {
666                 int ret;
667
668                 lprintf(9, "We are in '%s' but cookie indicates '%s', going there...\n",
669                         ChrPtr(WCC->wc_roomname),
670                         ChrPtr(WCC->Hdr->c_roomname)
671                 );
672                 ret = gotoroom(WCC->Hdr->c_roomname);   /* do quietly to avoid session output! */
673                 if ((ret/100) != 2) {
674                         lprintf(1, "COOKIEGOTO: Unable to change to [%s]; Reason: %d\n",
675                                 ChrPtr(WCC->Hdr->c_roomname), ret);
676                 }
677         }
678
679         if (WCC->Hdr->HR.Handler != NULL) {
680                 if (!WCC->logged_in && ((WCC->Hdr->HR.Handler->Flags & ANONYMOUS) == 0)) {
681                         display_login(NULL);
682                 }
683                 else {
684                         if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
685                                 begin_ajax_response();
686                         WCC->Hdr->HR.Handler->F();
687                         if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
688                                 end_ajax_response();
689                 }
690         }
691         /* When all else fais, display the main menu. */
692         else {
693                 /* 
694                  * ordinary browser users get a nice login screen, DAV etc. requsets
695                  * are given a 401 so they can handle it appropriate.
696                  */
697                 if (!WCC->logged_in)  {
698                         if (xhttp)
699                                 authorization_required();
700                         else 
701                                 display_login(NULL);
702                 }
703                 /*
704                  * Toplevel dav requests? or just a flat browser request? 
705                  */
706                 else {
707                         if (xhttp)
708                                 groupdav_main();
709                         else
710                                 display_main_menu();
711                 }
712         }
713
714 SKIP_ALL_THIS_CRAP:
715         FreeStrBuf(&Buf);
716         fflush(stdout);
717 }
718
719
720 /*
721  * Replacement for sleep() that uses select() in order to avoid SIGALRM
722  */
723 void sleeeeeeeeeep(int seconds)
724 {
725         struct timeval tv;
726
727         tv.tv_sec = seconds;
728         tv.tv_usec = 0;
729         select(0, NULL, NULL, NULL, &tv);
730 }
731
732
733 int ConditionalImportantMesage(StrBuf *Target, WCTemplputParams *TP)
734 {
735         wcsession *WCC = WC;
736         if (WCC != NULL)
737                 return ((!IsEmptyStr(WCC->ImportantMessage)) || 
738                         (StrLength(WCC->ImportantMsg) > 0));
739         else
740                 return 0;
741 }
742
743 void tmplput_importantmessage(StrBuf *Target, WCTemplputParams *TP)
744 {
745         wcsession *WCC = WC;
746         
747         if (WCC != NULL) {
748                 if (!IsEmptyStr(WCC->ImportantMessage)) {
749                         StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
750                         WCC->ImportantMessage[0] = '\0';
751                 }
752                 else if (StrLength(WCC->ImportantMsg) > 0) {
753                         StrEscAppend(Target, WCC->ImportantMsg, NULL, 0, 0);
754                         FlushStrBuf(WCC->ImportantMsg);
755                 }
756         }
757 }
758
759 void tmplput_trailing_javascript(StrBuf *Target, WCTemplputParams *TP)
760 {
761         wcsession *WCC = WC;
762
763         if (WCC != NULL)
764                 StrBufAppendTemplate(Target, TP, WCC->trailing_javascript, 0);
765 }
766
767 void tmplput_csslocal(StrBuf *Target, WCTemplputParams *TP)
768 {
769         StrBufAppendBuf(Target, 
770                         csslocal, 0);
771 }
772
773 extern char static_local_dir[PATH_MAX];
774
775
776 void 
777 InitModule_WEBCIT
778 (void)
779 {
780         char dir[SIZ];
781         WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS|COOKIEUNNEEDED|ISSTATIC);
782         WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
783         WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX|LOGCHATTY);
784         WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
785         WebcitAddUrlHandler(HKEY("webcit"), blank_page, URLNAMESPACE);
786
787         WebcitAddUrlHandler(HKEY("401"), authorization_required, ANONYMOUS|COOKIEUNNEEDED);
788         RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage, CTX_NONE);
789         RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, CTX_NONE);
790         RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, CTX_NONE);
791         RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, CTX_NONE);
792
793         snprintf(dir, SIZ, "%s/static.local/webcit.css", static_local_dir);
794         if (!access(dir, R_OK)) {
795                 lprintf(9, "Using local Stylesheet [%s]\n", dir);
796                 csslocal = NewStrBufPlain(HKEY("<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\">"));
797         }
798         else
799                 lprintf(9, "Didn't find site local Stylesheet [%s]\n", dir);
800
801 }
802
803 void
804 ServerStartModule_WEBCIT
805 (void)
806 {
807         HandlerHash = NewHash(1, NULL);
808 }
809
810
811 void 
812 ServerShutdownModule_WEBCIT
813 (void)
814 {
815         FreeStrBuf(&csslocal);
816         DeleteHash(&HandlerHash);
817 }
818
819
820
821 void
822 SessionNewModule_WEBCIT
823 (wcsession *sess)
824 {
825         sess->ImportantMsg = NewStrBuf();
826         sess->WBuf = NewStrBufPlain(NULL, SIZ * 4);
827         sess->HBuf = NewStrBufPlain(NULL, SIZ / 4);
828 }
829
830 void
831 SessionDetachModule_WEBCIT
832 (wcsession *sess)
833 {
834         DeleteHash(&sess->Hdr->urlstrings);// TODO?
835         if (sess->upload_length > 0) {
836                 free(sess->upload);
837                 sess->upload_length = 0;
838         }
839         FreeStrBuf(&sess->trailing_javascript);
840
841         if (StrLength(sess->WBuf) > SIZ * 30) /* Bigger than 120K? release. */
842         {
843                 FreeStrBuf(&sess->WBuf);
844                 sess->WBuf = NewStrBuf();
845         }
846         else
847                 FlushStrBuf(sess->WBuf);
848         FlushStrBuf(sess->HBuf);
849 }
850
851 void 
852 SessionDestroyModule_WEBCIT
853 (wcsession *sess)
854 {
855         FreeStrBuf(&sess->WBuf);
856         FreeStrBuf(&sess->HBuf);
857         FreeStrBuf(&sess->ImportantMsg);
858 }
859