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