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