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