a7069f14d5a8b30cf55d1abdfc218f1125fe84ab
[citadel.git] / webcit / webcit.c
1 /*
2  * $Id$
3  *
4  * This is the main transaction loop of the web service.  It maintains a
5  * persistent session to the Citadel server, handling HTTP WebCit requests as
6  * they arrive and presenting a user interface.
7  */
8 #define SHOW_ME_VAPPEND_PRINTF
9 #include <stdio.h>
10 #include <stdarg.h>
11 #include "webcit.h"
12 #include "groupdav.h"
13 #include "webserver.h"
14
15
16 /*
17  * String to unset the cookie.
18  * Any date "in the past" will work, so I chose my birthday, right down to
19  * the exact minute.  :)
20  */
21 static char *unset = "; expires=28-May-1971 18:10:00 GMT";
22
23 HashList *HandlerHash = NULL;
24
25 void WebcitAddUrlHandler(const char * UrlString, 
26                          long UrlSLen, 
27                          WebcitHandlerFunc F, 
28                          long Flags)
29 {
30         WebcitHandler *NewHandler;
31
32         if (HandlerHash == NULL)
33                 HandlerHash = NewHash(1, NULL);
34         
35         NewHandler = (WebcitHandler*) malloc(sizeof(WebcitHandler));
36         NewHandler->F = F;
37         NewHandler->Flags = Flags;
38         Put(HandlerHash, UrlString, UrlSLen, NewHandler, NULL);
39 }
40
41
42 /*
43  * web-printing funcion. uses our vsnprintf wrapper
44  */
45 void wprintf(const char *format,...)
46 {
47         wcsession *WCC = WC;
48         va_list arg_ptr;
49
50         if (WCC->WBuf == NULL)
51                 WCC->WBuf = NewStrBuf();
52
53         va_start(arg_ptr, format);
54         StrBufVAppendPrintf(WCC->WBuf, format, arg_ptr);
55         va_end(arg_ptr);
56 }
57
58 /*
59  * http-header-printing funcion. uses our vsnprintf wrapper
60  */
61 void hprintf(const char *format,...)
62 {
63         wcsession *WCC = WC;
64         va_list arg_ptr;
65
66         va_start(arg_ptr, format);
67         StrBufVAppendPrintf(WCC->HBuf, format, arg_ptr);
68         va_end(arg_ptr);
69 }
70
71
72
73 /*
74  * wrap up an HTTP session, closes tags, etc.
75  *
76  * print_standard_html_footer should be set to:
77  * 0            - to transmit only,
78  * nonzero      - to append the closing tags
79  */
80 void wDumpContent(int print_standard_html_footer)
81 {
82         if (print_standard_html_footer) {
83                 wprintf("</div> <!-- end of 'content' div -->\n");
84                 do_template("trailing", NULL);
85         }
86
87         /* If we've been saving it all up for one big output burst,
88          * go ahead and do that now.
89          */
90         end_burst();
91 }
92
93
94  
95
96 /*
97  * Output HTTP headers and leading HTML for a page
98  */
99 void output_headers(    int do_httpheaders,     /* 1 = output HTTP headers                          */
100                         int do_htmlhead,        /* 1 = output HTML <head> section and <body> opener */
101
102                         int do_room_banner,     /* 0=no, 1=yes,                                     
103                                                  * 2 = I'm going to embed my own, so don't open the 
104                                                  *     <div id="content"> either.                   
105                                                  */
106
107                         int unset_cookies,      /* 1 = session is terminating, so unset the cookies */
108                         int suppress_check,     /* 1 = suppress check for instant messages          */
109                         int cache               /* 1 = allow browser to cache this page             */
110 ) {
111         char cookie[1024];
112         char httpnow[128];
113
114         hprintf("HTTP/1.1 200 OK\n");
115         http_datestring(httpnow, sizeof httpnow, time(NULL));
116
117         if (do_httpheaders) {
118                 hprintf("Content-type: text/html; charset=utf-8\r\n"
119                         "Server: %s / %s\n"
120                         "Connection: close\r\n",
121                         PACKAGE_STRING, serv_info.serv_software
122                 );
123         }
124
125         if (cache) {
126                 char httpTomorow[128];
127
128                 http_datestring(httpTomorow, sizeof httpTomorow, 
129                                 time(NULL) + 60 * 60 * 24 * 2);
130
131                 hprintf("Pragma: public\r\n"
132                         "Cache-Control: max-age=3600, must-revalidate\r\n"
133                         "Last-modified: %s\r\n"
134                         "Expires: %s\r\n",
135                         httpnow,
136                         httpTomorow
137                 );
138         }
139         else {
140                 hprintf("Pragma: no-cache\r\n"
141                         "Cache-Control: no-store\r\n"
142                         "Expires: -1\r\n"
143                 );
144         }
145
146         stuff_to_cookie(cookie, 1024, WC->wc_session, WC->wc_username,
147                         WC->wc_password, WC->wc_roomname);
148
149         if (unset_cookies) {
150                 hprintf("Set-cookie: webcit=%s; path=/\r\n", unset);
151         } else {
152                 hprintf("Set-cookie: webcit=%s; path=/\r\n", cookie);
153                 if (server_cookie != NULL) {
154                         hprintf("%s\n", server_cookie);
155                 }
156         }
157
158         if (do_htmlhead) {
159                 begin_burst();
160                 do_template("head", NULL);
161
162                 /* check for ImportantMessages (these display in a div overlaying the main screen) */
163                 if (!IsEmptyStr(WC->ImportantMessage)) {
164                         wprintf("<div id=\"important_message\">\n"
165                                 "<span class=\"imsg\">");
166                         escputs(WC->ImportantMessage);
167                         wprintf("</span><br />\n"
168                                 "</div>\n"
169                                 "<script type=\"text/javascript\">\n"
170                                 "        setTimeout('hide_imsg_popup()', 5000); \n"
171                                 "</script>\n");
172                         WC->ImportantMessage[0] = 0;
173                 }
174
175                 if ( (WC->logged_in) && (!unset_cookies) ) {
176                         wprintf("<div id=\"iconbar\">");
177                         do_selected_iconbar();
178                         /** check for instant messages (these display in a new window) */
179                         page_popup();
180                         wprintf("</div>");
181                 }
182
183                 if (do_room_banner == 1) {
184                         wprintf("<div id=\"banner\">\n");
185                         embed_room_banner(NULL, navbar_default);
186                         wprintf("</div>\n");
187                 }
188         }
189
190         if (do_room_banner == 1) {
191                 wprintf("<div id=\"content\">\n");
192         }
193 }
194
195
196 /*
197  * Generic function to do an HTTP redirect.  Easy and fun.
198  */
199 void http_redirect(const char *whichpage) {
200         hprintf("HTTP/1.1 302 Moved Temporarily\n");
201         hprintf("Location: %s\r\n", whichpage);
202         hprintf("URI: %s\r\n", whichpage);
203         hprintf("Content-type: text/html; charset=utf-8\r\n");
204         wprintf("<html><body>");
205         wprintf("Go <a href=\"%s\">here</A>.", whichpage);
206         wprintf("</body></html>\n");
207         end_burst();
208 }
209
210
211
212 /*
213  * Output a piece of content to the web browser using conformant HTTP and MIME semantics
214  */
215 void http_transmit_thing(const char *content_type,
216                          int is_static) {
217
218 #ifndef TECH_PREVIEW
219         lprintf(9, "http_transmit_thing(%s)%s\n",
220                 content_type,
221                 (is_static ? " (static)" : "")
222         );
223 #endif
224         output_headers(0, 0, 0, 0, 0, is_static);
225
226         hprintf("Content-type: %s\r\n"
227                 "Server: %s\r\n"
228                 "Connection: close\r\n",
229                 content_type,
230                 PACKAGE_STRING);
231
232         end_burst();
233 }
234
235 /*
236  * print menu box like used in the floor view or admin interface.
237  * This function takes pair of strings as va_args, 
238  * Title        Title string of the box
239  * Class        CSS Class for the box
240  * nLines       How many string pairs should we print? (URL, UrlText)
241  * ...          Pairs of URL Strings and their Names
242  */
243 void print_menu_box(char* Title, char *Class, int nLines, ...)
244 {
245         va_list arg_list;
246         long i;
247         
248         svput("BOXTITLE", WCS_STRING, Title);
249         do_template("beginboxx", NULL);
250         
251         wprintf("<ul class=\"%s\">", Class);
252         
253         va_start(arg_list, nLines);
254         for (i = 0; i < nLines; ++i)
255         { 
256                 wprintf("<li><a href=\"%s\">", va_arg(arg_list, char *));
257                 wprintf((char *) va_arg(arg_list, char *));
258                 wprintf("</a></li>\n");
259         }
260         va_end (arg_list);
261         
262         wprintf("</a></li>\n");
263         
264         wprintf("</ul>");
265         
266         do_template("endbox", NULL);
267 }
268
269
270 /*
271  * dump out static pages from disk
272  */
273 void output_static(char *what)
274 {
275         int fd;
276         struct stat statbuf;
277         off_t bytes;
278         off_t count = 0;
279         const char *content_type;
280         int len;
281         const char *Err;
282
283         fd = open(what, O_RDONLY);
284         if (fd <= 0) {
285                 lprintf(9, "output_static('%s')  -- NOT FOUND --\n", what);
286                 hprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
287                 hprintf("Content-Type: text/plain\r\n");
288                 wprintf("Cannot open %s: %s\r\n", what, strerror(errno));
289                 end_burst();
290         } else {
291                 len = strlen (what);
292                 content_type = GuessMimeByFilename(what, len);
293
294                 if (fstat(fd, &statbuf) == -1) {
295                         lprintf(9, "output_static('%s')  -- FSTAT FAILED --\n", what);
296                         hprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
297                         hprintf("Content-Type: text/plain\r\n");
298                         wprintf("Cannot fstat %s: %s\n", what, strerror(errno));
299                         end_burst();
300                         return;
301                 }
302
303                 count = 0;
304                 bytes = statbuf.st_size;
305
306                 if (StrBufReadBLOB(WC->WBuf, &fd, 1, bytes, &Err) < 0)
307                 {
308                         if (fd > 0) close(fd);
309                         lprintf(9, "output_static('%s')  -- FREAD FAILED (%s) --\n", what, strerror(errno));
310                                 hprintf("HTTP/1.1 500 internal server error \r\n");
311                                 hprintf("Content-Type: text/plain\r\n");
312                                 end_burst();
313                                 return;
314                 }
315
316
317                 close(fd);
318 #ifndef TECH_PREVIEW
319                 lprintf(9, "output_static('%s')  %s\n", what, content_type);
320 #endif
321                 http_transmit_thing(content_type, 1);
322         }
323         if (yesbstr("force_close_session")) {
324                 end_webcit_session();
325         }
326 }
327
328
329 /*
330  * Convenience functions to display a page containing only a string
331  *
332  * titlebarcolor        color of the titlebar of the frame
333  * titlebarmsg          text to display in the title bar
334  * messagetext          body of the box
335  */
336 void convenience_page(char *titlebarcolor, char *titlebarmsg, char *messagetext)
337 {
338         hprintf("HTTP/1.1 200 OK\n");
339         output_headers(1, 1, 2, 0, 0, 0);
340         wprintf("<div id=\"banner\">\n");
341         wprintf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
342         wprintf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
343         wprintf("</td></tr></table>\n");
344         wprintf("</div>\n<div id=\"content\">\n");
345         escputs(messagetext);
346
347         wprintf("<hr />\n");
348         wDumpContent(1);
349 }
350
351
352 /*
353  * Display a blank page.
354  */
355 void blank_page(void) {
356         output_headers(1, 1, 0, 0, 0, 0);
357         wDumpContent(2);
358 }
359
360
361 /*
362  * A template has been requested
363  */
364 void url_do_template(void) {
365         const StrBuf *Tmpl = sbstr("template");
366         begin_burst();
367         output_headers(1, 0, 0, 0, 1, 0);
368         DoTemplate(ChrPtr(Tmpl), StrLength(Tmpl), NULL, NULL, 0);
369         end_burst();
370 }
371
372
373
374 /*
375  * convenience function to indicate success
376  */
377 void display_success(char *successmessage)
378 {
379         convenience_page("007700", "OK", successmessage);
380 }
381
382
383 /*
384  * Authorization required page 
385  * This is probably temporary and should be revisited 
386  */
387 void authorization_required(const char *message)
388 {
389         hprintf("HTTP/1.1 401 Authorization Required\r\n");
390         hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", serv_info.serv_humannode);
391         hprintf("Content-Type: text/html\r\n");
392         wprintf("<h1>");
393         wprintf(_("Authorization Required"));
394         wprintf("</h1>\r\n");
395         wprintf(_("The resource you requested requires a valid username and password. "
396                 "You could not be logged in: %s\n"), message);
397         wDumpContent(0);
398         
399 }
400
401 /*
402  * Convenience functions to wrap around asynchronous ajax responses
403  */
404 void begin_ajax_response(void) {
405         wcsession *WCC = WC;
406
407         FlushStrBuf(WCC->HBuf);
408         output_headers(0, 0, 0, 0, 0, 0);
409
410         hprintf("Content-type: text/html; charset=UTF-8\r\n"
411                 "Server: %s\r\n"
412                 "Connection: close\r\n"
413                 ,
414                 PACKAGE_STRING);
415         begin_burst();
416 }
417
418 /*
419  * print ajax response footer 
420  */
421 void end_ajax_response(void) {
422         wDumpContent(0);
423 }
424
425 /*
426  * Wraps a Citadel server command in an AJAX transaction.
427  */
428 void ajax_servcmd(void)
429 {
430         char buf[1024];
431         char gcontent[1024];
432         char *junk;
433         size_t len;
434
435         begin_ajax_response();
436
437         serv_printf("%s", bstr("g_cmd"));
438         serv_getln(buf, sizeof buf);
439         wprintf("%s\n", buf);
440
441         if (buf[0] == '8') {
442                 serv_printf("\n\n000");
443         }
444         if ((buf[0] == '1') || (buf[0] == '8')) {
445                 while (serv_getln(gcontent, sizeof gcontent), strcmp(gcontent, "000")) {
446                         wprintf("%s\n", gcontent);
447                 }
448                 wprintf("000");
449         }
450         if (buf[0] == '4') {
451                 text_to_server(bstr("g_input"));
452                 serv_puts("000");
453         }
454         if (buf[0] == '6') {
455                 len = atol(&buf[4]);
456                 junk = malloc(len);
457                 serv_read(junk, len);
458                 free(junk);
459         }
460         if (buf[0] == '7') {
461                 len = atol(&buf[4]);
462                 junk = malloc(len);
463                 memset(junk, 0, len);
464                 serv_write(junk, len);
465                 free(junk);
466         }
467
468         end_ajax_response();
469         
470         /*
471          * This is kind of an ugly hack, but this is the only place it can go.
472          * If the command was GEXP, then the instant messenger window must be
473          * running, so reset the "last_pager_check" watchdog timer so
474          * that page_popup() doesn't try to open it a second time.
475          */
476         if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
477                 WC->last_pager_check = time(NULL);
478         }
479 }
480
481
482 /*
483  * Helper function for the asynchronous check to see if we need
484  * to open the instant messenger window.
485  */
486 void seconds_since_last_gexp(void)
487 {
488         char buf[256];
489
490         if ( (time(NULL) - WC->last_pager_check) < 30) {
491                 wprintf("NO\n");
492         }
493         else {
494                 memset(buf, 5, 0);
495                 serv_puts("NOOP");
496                 serv_getln(buf, sizeof buf);
497                 if (buf[3] == '*') {
498                         wprintf("YES");
499                 }
500                 else {
501                         wprintf("NO");
502                 }
503         }
504 }
505
506 /**
507  * \brief Detects a 'mobile' user agent 
508  */
509 int is_mobile_ua(char *user_agent) {
510       if (strstr(user_agent,"iPhone OS") != NULL) {
511         return 1;
512       } else if (strstr(user_agent,"Windows CE") != NULL) {
513         return 1;
514       } else if (strstr(user_agent,"SymbianOS") != NULL) {
515         return 1;
516       } else if (strstr(user_agent, "Opera Mobi") != NULL) {
517         return 1;
518       } else if (strstr(user_agent, "Firefox/2.0.0 Opera 9.51 Beta") != NULL) {
519               /*  For some reason a new install of Opera 9.51beta decided to spoof. */
520           return 1;
521           }
522       return 0;
523 }
524
525
526 /*
527  * Entry point for WebCit transaction
528  */
529 void session_loop(HashList *HTTPHeaders, StrBuf *ReqLine, StrBuf *request_method, StrBuf *ReadBuf)
530 {
531         const char *pch, *pchs, *pche;
532         void *vLine;
533         char action[1024];
534         char arg[8][128];
535         size_t sizes[10];
536         char *index[10];
537         char buf[SIZ];
538         int a, nBackDots, nEmpty;
539         int ContentLength = 0;
540         StrBuf *ContentType = NULL;
541         StrBuf *UrlLine = NULL;
542         StrBuf *content = NULL;
543         const char *content_end = NULL;
544         char browser_host[256];
545         char user_agent[256];
546         int body_start = 0;
547         int is_static = 0;
548         int n_static = 0;
549         int len = 0;
550         void *vHandler;
551         WebcitHandler *Handler;
552
553         /*
554          * We stuff these with the values coming from the client cookies,
555          * so we can use them to reconnect a timed out session if we have to.
556          */
557         char c_username[SIZ];
558         char c_password[SIZ];
559         char c_roomname[SIZ];
560         char c_httpauth_string[SIZ];
561         char c_httpauth_user[SIZ];
562         char c_httpauth_pass[SIZ];
563         wcsession *WCC;
564         
565         safestrncpy(c_username, "", sizeof c_username);
566         safestrncpy(c_password, "", sizeof c_password);
567         safestrncpy(c_roomname, "", sizeof c_roomname);
568         safestrncpy(c_httpauth_string, "", sizeof c_httpauth_string);
569         safestrncpy(c_httpauth_user, DEFAULT_HTTPAUTH_USER, sizeof c_httpauth_user);
570         safestrncpy(c_httpauth_pass, DEFAULT_HTTPAUTH_PASS, sizeof c_httpauth_pass);
571         strcpy(browser_host, "");
572
573         WCC= WC;
574         if (WCC->WBuf == NULL)
575                 WC->WBuf = NewStrBufPlain(NULL, 32768);
576         FlushStrBuf(WCC->WBuf);
577
578         if (WCC->HBuf == NULL)
579                 WCC->HBuf = NewStrBuf();
580         FlushStrBuf(WCC->HBuf);
581
582         WCC->upload_length = 0;
583         WCC->upload = NULL;
584         WCC->is_mobile = 0;
585         WCC->trailing_javascript = NewStrBuf();
586
587         /** Figure out the action */
588         index[0] = action;
589         sizes[0] = sizeof action;
590         for (a=1; a<9; a++)
591         {
592                 index[a] = arg[a-1];
593                 sizes[a] = sizeof arg[a-1];
594         }
595 /*///   index[9] = &foo; todo */
596         nBackDots = 0;
597         nEmpty = 0;
598         for ( a = 0; a < 9; ++a)
599         {
600                 extract_token(index[a], ChrPtr(ReqLine), a + 1, '/', sizes[a]);
601                 if (strstr(index[a], "?")) *strstr(index[a], "?") = 0;
602                 if (strstr(index[a], "&")) *strstr(index[a], "&") = 0;
603                 if (strstr(index[a], " ")) *strstr(index[a], " ") = 0;
604                 if ((index[a][0] == '.') && (index[a][1] == '.'))
605                         nBackDots++;
606                 if (index[a][0] == '\0')
607                         nEmpty++;
608         }
609
610
611         if (GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) && 
612             (vLine != NULL)){
613                 cookie_to_stuff((StrBuf *)vLine, NULL,
614                                 c_username, sizeof c_username,
615                                 c_password, sizeof c_password,
616                                 c_roomname, sizeof c_roomname);
617         }
618         if (GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) &&
619             (vLine!=NULL)) {
620                 CtdlDecodeBase64(c_httpauth_string, ChrPtr((StrBuf*)vLine), StrLength((StrBuf*)vLine));
621                 extract_token(c_httpauth_user, c_httpauth_string, 0, ':', sizeof c_httpauth_user);
622                 extract_token(c_httpauth_pass, c_httpauth_string, 1, ':', sizeof c_httpauth_pass);
623         }
624         if (GetHash(HTTPHeaders, HKEY("CONTENT-LENGTH"), &vLine) &&
625             (vLine!=NULL)) {
626                 ContentLength = StrToi((StrBuf*)vLine);
627         }
628         if (GetHash(HTTPHeaders, HKEY("CONTENT-TYPE"), &vLine) &&
629             (vLine!=NULL)) {
630                 ContentType = (StrBuf*)vLine;
631         }
632         if (GetHash(HTTPHeaders, HKEY("USER-AGENT"), &vLine) &&
633             (vLine!=NULL)) {
634                 safestrncpy(user_agent, ChrPtr((StrBuf*)vLine), sizeof user_agent);
635 #ifdef TECH_PREVIEW
636                 if ((WCC->is_mobile < 0) && is_mobile_ua(&buf[12])) {                   
637                         WCC->is_mobile = 1;
638                 }
639                 else {
640                         WCC->is_mobile = 0;
641                 }
642 #endif
643         }
644         if ((follow_xff) &&
645             GetHash(HTTPHeaders, HKEY("X-FORWARDED-HOST"), &vLine) &&
646             (vLine != NULL)) {
647                 safestrncpy(WCC->http_host, 
648                             ChrPtr((StrBuf*)vLine), 
649                             sizeof WCC->http_host);
650         }
651         if (IsEmptyStr(WCC->http_host) && 
652             GetHash(HTTPHeaders, HKEY("HOST"), &vLine) &&
653             (vLine!=NULL)) {
654                 safestrncpy(WCC->http_host, 
655                             ChrPtr((StrBuf*)vLine), 
656                             sizeof WCC->http_host);
657                 
658         }
659         if (GetHash(HTTPHeaders, HKEY("X-FORWARDED-FOR"), &vLine) &&
660             (vLine!=NULL)) {
661                 safestrncpy(browser_host, 
662                             ChrPtr((StrBuf*) vLine), 
663                             sizeof browser_host);
664                 while (num_tokens(browser_host, ',') > 1) {
665                         remove_token(browser_host, 0, ',');
666                 }
667                 striplt(browser_host);
668         }
669
670         if (ContentLength > 0) {
671                 content = NewStrBuf();
672                 StrBufPrintf(content, "Content-type: %s\n"
673                          "Content-length: %d\n\n",
674                          ChrPtr(ContentType), ContentLength);
675 /*
676                 hprintf("Content-type: %s\n"
677                         "Content-length: %d\n\n",
678                         ContentType, ContentLength);
679 */
680                 body_start = StrLength(content);
681
682                 /** Read the entire input data at once. */
683                 client_read(&WCC->http_sock, content, ReadBuf, ContentLength + body_start);
684
685                 if (!strncasecmp(ChrPtr(ContentType), "application/x-www-form-urlencoded", 33)) {
686                         StrBufCutLeft(content, body_start);
687                         ParseURLParams(content);
688                 } else if (!strncasecmp(ChrPtr(ContentType), "multipart", 9)) {
689                         content_end = ChrPtr(content) + ContentLength + body_start;
690                         mime_parser(ChrPtr(content), content_end, *upload_handler, NULL, NULL, NULL, 0);
691                 }
692         } else {
693                 content = NULL;
694         }
695
696         /* make a note of where we are in case the user wants to save it */
697         safestrncpy(WCC->this_page, ChrPtr(ReqLine), sizeof(WCC->this_page));
698         remove_token(WCC->this_page, 2, ' ');
699         remove_token(WCC->this_page, 0, ' ');
700
701         /* If there are variables in the URL, we must grab them now */
702         UrlLine = NewStrBufDup(ReqLine);
703         len = StrLength(UrlLine);
704         pch = pchs = ChrPtr(UrlLine);
705         pche = pchs + len;
706         while (pch < pche) {
707                 if ((*pch == '?') || (*pch == '&')) {
708                         StrBufCutLeft(UrlLine, pch - pchs + 1);
709                         ParseURLParams(UrlLine);
710                         break;
711                 }
712                 pch ++;
713         }
714         FreeStrBuf(&UrlLine);
715
716         /* If it's a "force 404" situation then display the error and bail. */
717         if (!strcmp(action, "404")) {
718                 hprintf("HTTP/1.1 404 Not found\r\n");
719                 hprintf("Content-Type: text/plain\r\n");
720                 wprintf("Not found\r\n");
721                 end_burst();
722                 goto SKIP_ALL_THIS_CRAP;
723         }
724
725         /* Static content can be sent without connecting to Citadel. */
726         is_static = 0;
727         for (a=0; a<ndirs && ! is_static; ++a) {
728                 if (!strcasecmp(action, (char*)static_content_dirs[a])) { /* map web to disk location */
729                         is_static = 1;
730                         n_static = a;
731                 }
732         }
733         if (is_static) {
734                 if (nBackDots < 2)
735                 {
736                         snprintf(buf, sizeof buf, "%s/%s/%s/%s/%s/%s/%s/%s",
737                                  static_dirs[n_static], 
738                                  index[1], index[2], index[3], index[4], index[5], index[6], index[7]);
739                         for (a=0; a<8; ++a) {
740                                 if (buf[strlen(buf)-1] == '/') {
741                                         buf[strlen(buf)-1] = 0;
742                                 }
743                         }
744                         for (a = 0; a < strlen(buf); ++a) {
745                                 if (isspace(buf[a])) {
746                                         buf[a] = 0;
747                                 }
748                         }
749                         output_static(buf);
750                 }
751                 else 
752                 {
753                         lprintf(9, "Suspicious request. Ignoring.");
754                         hprintf("HTTP/1.1 404 Security check failed\r\n");
755                         hprintf("Content-Type: text/plain\r\n\r\n");
756                         wprintf("You have sent a malformed or invalid request.\r\n");
757                         end_burst();
758                 }
759                 goto SKIP_ALL_THIS_CRAP;        /* Don't try to connect */
760         }
761
762         /* If the client sent a nonce that is incorrect, kill the request. */
763         if (strlen(bstr("nonce")) > 0) {
764                 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n", 
765                         bstr("nonce"), WCC->nonce);
766                 if (ibstr("nonce") != WCC->nonce) {
767                         lprintf(9, "Ignoring request with mismatched nonce.\n");
768                         hprintf("HTTP/1.1 404 Security check failed\r\n");
769                         hprintf("Content-Type: text/plain\r\n\r\n");
770                         wprintf("Security check failed.\r\n");
771                         end_burst();
772                         goto SKIP_ALL_THIS_CRAP;
773                 }
774         }
775
776         /*
777          * If we're not connected to a Citadel server, try to hook up the
778          * connection now.
779          */
780         if (!WCC->connected) {
781                 if (!strcasecmp(ctdlhost, "uds")) {
782                         /* unix domain socket */
783                         snprintf(buf, SIZ, "%s/citadel.socket", ctdlport);
784                         WCC->serv_sock = uds_connectsock(buf);
785                 }
786                 else {
787                         /* tcp socket */
788                         WCC->serv_sock = tcp_connectsock(ctdlhost, ctdlport);
789                 }
790
791                 if (WCC->serv_sock < 0) {
792                         do_logout();
793                         goto SKIP_ALL_THIS_CRAP;
794                 }
795                 else {
796                         WCC->connected = 1;
797                         serv_getln(buf, sizeof buf);    /** get the server welcome message */
798
799                         /**
800                          * From what host is our user connecting?  Go with
801                          * the host at the other end of the HTTP socket,
802                          * unless we are following X-Forwarded-For: headers
803                          * and such a header has already turned up something.
804                          */
805                         if ( (!follow_xff) || (strlen(browser_host) == 0) ) {
806                                 locate_host(browser_host, WCC->http_sock);
807                         }
808
809                         get_serv_info(browser_host, user_agent);
810                         if (serv_info.serv_rev_level < MINIMUM_CIT_VERSION) {
811                                 begin_burst();
812                                 wprintf(_("You are connected to a Citadel "
813                                         "server running Citadel %d.%02d. \n"
814                                         "In order to run this version of WebCit "
815                                         "you must also have Citadel %d.%02d or"
816                                         " newer.\n\n\n"),
817                                                 serv_info.serv_rev_level / 100,
818                                                 serv_info.serv_rev_level % 100,
819                                                 MINIMUM_CIT_VERSION / 100,
820                                                 MINIMUM_CIT_VERSION % 100
821                                         );
822                                 end_burst();
823                                 end_webcit_session();
824                                 goto SKIP_ALL_THIS_CRAP;
825                         }
826                 }
827         }
828 /*///////todo: restore language in this case */
829         /*
830          * Functions which can be performed without logging in
831          */
832         if (!strcasecmp(action, "listsub")) {
833                 do_listsub();
834                 goto SKIP_ALL_THIS_CRAP;
835         }
836         if (!strcasecmp(action, "freebusy")) {
837                 do_freebusy(ChrPtr(ReqLine));
838                 goto SKIP_ALL_THIS_CRAP;
839         }
840
841         /*
842          * If we're not logged in, but we have HTTP Authentication data,
843          * try logging in to Citadel using that.
844          */
845         if ((!WCC->logged_in)
846            && (strlen(c_httpauth_user) > 0)
847            && (strlen(c_httpauth_pass) > 0)) {
848                 serv_printf("USER %s", c_httpauth_user);
849                 serv_getln(buf, sizeof buf);
850                 if (buf[0] == '3') {
851                         serv_printf("PASS %s", c_httpauth_pass);
852                         serv_getln(buf, sizeof buf);
853                         if (buf[0] == '2') {
854                                 become_logged_in(c_httpauth_user,
855                                                 c_httpauth_pass, buf);
856                                 safestrncpy(WCC->httpauth_user, c_httpauth_user, sizeof WCC->httpauth_user);
857                                 safestrncpy(WCC->httpauth_pass, c_httpauth_pass, sizeof WCC->httpauth_pass);
858                         } else {
859                                 /* Should only display when password is wrong */
860                                 authorization_required(&buf[4]);
861                                 goto SKIP_ALL_THIS_CRAP;
862                         }
863                 }
864         }
865
866         /* This needs to run early */
867 #ifdef TECH_PREVIEW
868         if (!strcasecmp(action, "rss")) {
869                 display_rss(bstr("room"), request_method);
870                 goto SKIP_ALL_THIS_CRAP;
871         }
872 #endif
873
874         /* 
875          * The GroupDAV stuff relies on HTTP authentication instead of
876          * our session's authentication.
877          */
878         if (!strncasecmp(action, "groupdav", 8)) {
879                 groupdav_main(HTTPHeaders, 
880                               ReqLine, request_method,
881                               ContentType, /* do GroupDAV methods */
882                               ContentLength, content, body_start);
883                 if (!WCC->logged_in) {
884                         WCC->killthis = 1;      /* If not logged in, don't */
885                 }                               /* keep the session active */
886                 goto SKIP_ALL_THIS_CRAP;
887         }
888
889
890         /*
891          * Automatically send requests with any method other than GET or
892          * POST to the GroupDAV code as well.
893          */
894         if ((strcasecmp(ChrPtr(request_method), "GET")) && (strcasecmp(ChrPtr(request_method), "POST"))) {
895                 groupdav_main(HTTPHeaders, ReqLine, 
896                               request_method, ContentType, /** do GroupDAV methods */
897                               ContentLength, content, body_start);
898                 if (!WCC->logged_in) {
899                         WCC->killthis = 1;      /** If not logged in, don't */
900                 }                               /** keep the session active */
901                 goto SKIP_ALL_THIS_CRAP;
902         }
903
904         /*
905          * If we're not logged in, but we have username and password cookies
906          * supplied by the browser, try using them to log in.
907          */
908         if ((!WCC->logged_in)
909            && (!IsEmptyStr(c_username))
910            && (!IsEmptyStr(c_password))) {
911                 serv_printf("USER %s", c_username);
912                 serv_getln(buf, sizeof buf);
913                 if (buf[0] == '3') {
914                         serv_printf("PASS %s", c_password);
915                         serv_getln(buf, sizeof buf);
916                         if (buf[0] == '2') {
917                                 StrBuf *Lang;
918                                 become_logged_in(c_username, c_password, buf);
919                                 if (get_preference("language", &Lang)) {
920                                         set_selected_language(ChrPtr(Lang));
921                                         go_selected_language();         /* set locale */
922                                 }
923                                 get_preference("default_header_charset", &WCC->DefaultCharset);
924                         }
925                 }
926         }
927
928         /*
929          * If a 'gotofirst' parameter has been specified, attempt to goto that room
930          * prior to doing anything else.
931          */
932         if (havebstr("gotofirst")) {
933                 gotoroom(bstr("gotofirst"));    /* do this quietly to avoid session output! */
934         }
935
936         /*
937          * If we don't have a current room, but a cookie specifying the
938          * current room is supplied, make an effort to go there.
939          */
940         if ((IsEmptyStr(WCC->wc_roomname)) && (!IsEmptyStr(c_roomname))) {
941                 serv_printf("GOTO %s", c_roomname);
942                 serv_getln(buf, sizeof buf);
943                 if (buf[0] == '2') {
944                         safestrncpy(WCC->wc_roomname, c_roomname, sizeof WCC->wc_roomname);
945                 }
946         }
947         
948         GetHash(HandlerHash, action, strlen(action) /* TODO*/, &vHandler),
949                 Handler = (WebcitHandler*) vHandler;
950         if (Handler != NULL) {
951                 if (!WCC->logged_in && ((Handler->Flags & ANONYMOUS) == 0)) {
952                         display_login(NULL);
953                 }
954                 else {
955                         if((Handler->Flags & NEED_URL)) {
956                                 if (WCC->UrlFragment1 == NULL)
957                                         WCC->UrlFragment1 = NewStrBuf();
958                                 if (WCC->UrlFragment2 == NULL)
959                                         WCC->UrlFragment2 = NewStrBuf();
960                                 if (WCC->UrlFragment3 == NULL)
961                                         WCC->UrlFragment3 = NewStrBuf();
962                                 StrBufPrintf(WCC->UrlFragment1, "%s", index[0]);
963                                 StrBufPrintf(WCC->UrlFragment2, "%s", index[1]);
964                                 StrBufPrintf(WCC->UrlFragment3, "%s", index[2]);
965                         }
966                         if ((Handler->Flags & AJAX) != 0)
967                                 begin_ajax_response();
968                         Handler->F();
969                         if ((Handler->Flags & AJAX) != 0)
970                                 end_ajax_response();
971                 }
972         }
973         /* When all else fais, display the main menu. */
974         else {
975                 if (!WCC->logged_in) 
976                         display_login(NULL);
977                 else
978                         display_main_menu();
979         }
980
981 SKIP_ALL_THIS_CRAP:
982         fflush(stdout);
983         if (content != NULL) {
984                 FreeStrBuf(&content);
985                 content = NULL;
986         }
987         DeleteHash(&WCC->urlstrings);
988         if (WCC->upload_length > 0) {
989                 free(WCC->upload);
990                 WCC->upload_length = 0;
991         }
992         FreeStrBuf(&WCC->trailing_javascript);
993 }
994
995
996 /*
997  * Replacement for sleep() that uses select() in order to avoid SIGALRM
998  */
999 void sleeeeeeeeeep(int seconds)
1000 {
1001         struct timeval tv;
1002
1003         tv.tv_sec = seconds;
1004         tv.tv_usec = 0;
1005         select(0, NULL, NULL, NULL, &tv);
1006 }
1007
1008
1009 int ConditionalImportantMesage(WCTemplateToken *Tokens, void *Context, int ContextType)
1010 {
1011         wcsession *WCC = WC;
1012         if (WCC != NULL)
1013                 return (!IsEmptyStr(WCC->ImportantMessage));
1014         else
1015                 return 0;
1016 }
1017
1018 void tmplput_importantmessage(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1019 {
1020         wcsession *WCC = WC;
1021         
1022         if (WCC != NULL) {
1023 /*
1024                 StrBufAppendTemplate(Target, nArgs, Tokens, Context, ContextType,
1025                                      WCC->ImportantMessage, 0);
1026 */
1027                 StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
1028                 WCC->ImportantMessage[0] = '\0';
1029         }
1030 }
1031
1032 void tmplput_trailing_javascript(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *vContext, int ContextType)
1033 {
1034         wcsession *WCC = WC;
1035
1036         if (WCC != NULL)
1037                 StrBufAppendTemplate(Target, nArgs, Tokens, vContext, ContextType,
1038                                      WCC->trailing_javascript, 0);
1039 }
1040
1041 void tmplput_csslocal(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1042 {
1043         extern StrBuf *csslocal;
1044         StrBufAppendBuf(Target, 
1045                         csslocal, 0);
1046 }
1047
1048
1049
1050
1051 void 
1052 InitModule_WEBCIT
1053 (void)
1054 {
1055         WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS);
1056         WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
1057         WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX);
1058         WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
1059
1060         RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage, CTX_NONE);
1061         RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, CTX_NONE);
1062         RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, CTX_NONE);
1063         RegisterNamespace("OFFERSTARTPAGE", 0, 0, offer_start_page, CTX_NONE);
1064         RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, CTX_NONE);
1065 }