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