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