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