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