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