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