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