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