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