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