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