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