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