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