]> code.citadel.org Git - citadel.git/blob - webcit/webcit.c
* shuffled members of wcsession -> do a make clean or everything will burst in your...
[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 *Tmpl = sbstr("template");
372         begin_burst();
373         output_headers(1, 0, 0, 0, 1, 0);
374         DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
375         end_burst();
376 }
377
378
379
380 /*
381  * convenience function to indicate success
382  */
383 void display_success(char *successmessage)
384 {
385         convenience_page("007700", "OK", successmessage);
386 }
387
388
389 /*
390  * Authorization required page 
391  * This is probably temporary and should be revisited 
392  */
393 void authorization_required(const char *message)
394 {
395         hprintf("HTTP/1.1 401 Authorization Required\r\n");
396         hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", ChrPtr(serv_info.serv_humannode));
397         hprintf("Content-Type: text/html\r\n");
398         wprintf("<h1>");
399         wprintf(_("Authorization Required"));
400         wprintf("</h1>\r\n");
401         wprintf(_("The resource you requested requires a valid username and password. "
402                 "You could not be logged in: %s\n"), message);
403         wDumpContent(0);
404         
405 }
406
407 /*
408  * Convenience functions to wrap around asynchronous ajax responses
409  */
410 void begin_ajax_response(void) {
411         wcsession *WCC = WC;
412
413         FlushStrBuf(WCC->HBuf);
414         output_headers(0, 0, 0, 0, 0, 0);
415
416         hprintf("Content-type: text/html; charset=UTF-8\r\n"
417                 "Server: %s\r\n"
418                 "Connection: close\r\n"
419                 ,
420                 PACKAGE_STRING);
421         begin_burst();
422 }
423
424 /*
425  * print ajax response footer 
426  */
427 void end_ajax_response(void) {
428         wDumpContent(0);
429 }
430
431 /*
432  * Wraps a Citadel server command in an AJAX transaction.
433  */
434 void ajax_servcmd(void)
435 {
436         char buf[1024];
437         char gcontent[1024];
438         char *junk;
439         size_t len;
440
441         begin_ajax_response();
442
443         serv_printf("%s", bstr("g_cmd"));
444         serv_getln(buf, sizeof buf);
445         wprintf("%s\n", buf);
446
447         if (buf[0] == '8') {
448                 serv_printf("\n\n000");
449         }
450         if ((buf[0] == '1') || (buf[0] == '8')) {
451                 while (serv_getln(gcontent, sizeof gcontent), strcmp(gcontent, "000")) {
452                         wprintf("%s\n", gcontent);
453                 }
454                 wprintf("000");
455         }
456         if (buf[0] == '4') {
457                 text_to_server(bstr("g_input"));
458                 serv_puts("000");
459         }
460         if (buf[0] == '6') {
461                 len = atol(&buf[4]);
462                 junk = malloc(len);
463                 serv_read(junk, len);
464                 free(junk);
465         }
466         if (buf[0] == '7') {
467                 len = atol(&buf[4]);
468                 junk = malloc(len);
469                 memset(junk, 0, len);
470                 serv_write(junk, len);
471                 free(junk);
472         }
473
474         end_ajax_response();
475         
476         /*
477          * This is kind of an ugly hack, but this is the only place it can go.
478          * If the command was GEXP, then the instant messenger window must be
479          * running, so reset the "last_pager_check" watchdog timer so
480          * that page_popup() doesn't try to open it a second time.
481          */
482         if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
483                 WC->last_pager_check = time(NULL);
484         }
485 }
486
487
488 /*
489  * Helper function for the asynchronous check to see if we need
490  * to open the instant messenger window.
491  */
492 void seconds_since_last_gexp(void)
493 {
494         char buf[256];
495
496         if ( (time(NULL) - WC->last_pager_check) < 30) {
497                 wprintf("NO\n");
498         }
499         else {
500                 memset(buf, 0, 5);
501                 serv_puts("NOOP");
502                 serv_getln(buf, sizeof buf);
503                 if (buf[3] == '*') {
504                         wprintf("YES");
505                 }
506                 else {
507                         wprintf("NO");
508                 }
509         }
510 }
511
512 /**
513  * \brief Detects a 'mobile' user agent 
514  */
515 int is_mobile_ua(char *user_agent) {
516       if (strstr(user_agent,"iPhone OS") != NULL) {
517         return 1;
518       } else if (strstr(user_agent,"Windows CE") != NULL) {
519         return 1;
520       } else if (strstr(user_agent,"SymbianOS") != NULL) {
521         return 1;
522       } else if (strstr(user_agent, "Opera Mobi") != NULL) {
523         return 1;
524       } else if (strstr(user_agent, "Firefox/2.0.0 Opera 9.51 Beta") != NULL) {
525               /*  For some reason a new install of Opera 9.51beta decided to spoof. */
526           return 1;
527           }
528       return 0;
529 }
530
531
532 /*
533  * Entry point for WebCit transaction
534  */
535 void session_loop(HashList *HTTPHeaders, StrBuf *ReqLine, StrBuf *request_method, StrBuf *ReadBuf)
536 {
537         StrBuf *Buf;
538         const char *pch, *pchs, *pche;
539         void *vLine;
540         char action[1024];
541         char arg[8][128];
542         size_t sizes[10];
543         char *index[10];
544         char buf[SIZ];
545         int a, nBackDots, nEmpty;
546         int ContentLength = 0;
547         StrBuf *ContentType = NULL;
548         StrBuf *UrlLine = NULL;
549         StrBuf *content = NULL;
550         const char *content_end = NULL;
551         StrBuf *browser_host = NULL;
552         char user_agent[256];
553         int body_start = 0;
554         int is_static = 0;
555         int n_static = 0;
556         int len = 0;
557         void *vHandler;
558         WebcitHandler *Handler;
559
560         /*
561          * We stuff these with the values coming from the client cookies,
562          * so we can use them to reconnect a timed out session if we have to.
563          */
564         StrBuf *c_username;
565         StrBuf *c_password;
566         StrBuf *c_roomname;
567         char c_httpauth_string[SIZ];
568         StrBuf *c_httpauth_user;
569         StrBuf *c_httpauth_pass;
570         wcsession *WCC;
571         
572         Buf = NewStrBuf();
573         c_username = NewStrBuf();
574         c_password = NewStrBuf();
575         c_roomname = NewStrBuf();
576         safestrncpy(c_httpauth_string, "", sizeof c_httpauth_string);
577         c_httpauth_user = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_USER));
578         c_httpauth_pass = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_PASS));
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                 WCC->http_host = (StrBuf*)vLine;
658         }
659         if ((StrLength(WCC->http_host) == 0) && 
660             GetHash(HTTPHeaders, HKEY("HOST"), &vLine) &&
661             (vLine!=NULL)) {
662                 WCC->http_host = (StrBuf*)vLine;
663         }
664
665         if (GetHash(HTTPHeaders, HKEY("X-FORWARDED-FOR"), &vLine) &&
666             (vLine!=NULL)) {
667                 browser_host = (StrBuf*) vLine;
668
669                 while (StrBufNum_tokens(browser_host, ',') > 1) {
670                         StrBufRemove_token(browser_host, 0, ',');
671                 }
672                 StrBufTrim(browser_host);
673         }
674
675         if (ContentLength > 0) {
676                 content = NewStrBuf();
677                 StrBufPrintf(content, "Content-type: %s\n"
678                          "Content-length: %d\n\n",
679                          ChrPtr(ContentType), ContentLength);
680 /*
681                 hprintf("Content-type: %s\n"
682                         "Content-length: %d\n\n",
683                         ContentType, ContentLength);
684 */
685                 body_start = StrLength(content);
686
687                 /** Read the entire input data at once. */
688                 client_read(&WCC->http_sock, content, ReadBuf, ContentLength + body_start);
689
690                 if (!strncasecmp(ChrPtr(ContentType), "application/x-www-form-urlencoded", 33)) {
691                         StrBufCutLeft(content, body_start);
692                         ParseURLParams(content);
693                 } else if (!strncasecmp(ChrPtr(ContentType), "multipart", 9)) {
694                         content_end = ChrPtr(content) + ContentLength + body_start;
695                         mime_parser(ChrPtr(content), content_end, *upload_handler, NULL, NULL, NULL, 0);
696                 }
697         } else {
698                 content = NULL;
699         }
700
701         /* make a note of where we are in case the user wants to save it */
702         WCC->this_page = NewStrBufDup(ReqLine);
703         StrBufRemove_token(WCC->this_page, 2, ' ');
704         StrBufRemove_token(WCC->this_page, 0, ' ');
705
706         /* If there are variables in the URL, we must grab them now */
707         UrlLine = NewStrBufDup(ReqLine);
708         len = StrLength(UrlLine);
709         pch = pchs = ChrPtr(UrlLine);
710         pche = pchs + len;
711         while (pch < pche) {
712                 if ((*pch == '?') || (*pch == '&')) {
713                         StrBufCutLeft(UrlLine, pch - pchs + 1);
714                         ParseURLParams(UrlLine);
715                         break;
716                 }
717                 pch ++;
718         }
719         FreeStrBuf(&UrlLine);
720
721         /* If it's a "force 404" situation then display the error and bail. */
722         if (!strcmp(action, "404")) {
723                 hprintf("HTTP/1.1 404 Not found\r\n");
724                 hprintf("Content-Type: text/plain\r\n");
725                 wprintf("Not found\r\n");
726                 end_burst();
727                 goto SKIP_ALL_THIS_CRAP;
728         }
729
730         /* Static content can be sent without connecting to Citadel. */
731         is_static = 0;
732         for (a=0; a<ndirs && ! is_static; ++a) {
733                 if (!strcasecmp(action, (char*)static_content_dirs[a])) { /* map web to disk location */
734                         is_static = 1;
735                         n_static = a;
736                 }
737         }
738         if (is_static) {
739                 if (nBackDots < 2)
740                 {
741                         snprintf(buf, sizeof buf, "%s/%s/%s/%s/%s/%s/%s/%s",
742                                  static_dirs[n_static], 
743                                  index[1], index[2], index[3], index[4], index[5], index[6], index[7]);
744                         for (a=0; a<8; ++a) {
745                                 if (buf[strlen(buf)-1] == '/') {
746                                         buf[strlen(buf)-1] = 0;
747                                 }
748                         }
749                         for (a = 0; a < strlen(buf); ++a) {
750                                 if (isspace(buf[a])) {
751                                         buf[a] = 0;
752                                 }
753                         }
754                         output_static(buf);
755                 }
756                 else 
757                 {
758                         lprintf(9, "Suspicious request. Ignoring.");
759                         hprintf("HTTP/1.1 404 Security check failed\r\n");
760                         hprintf("Content-Type: text/plain\r\n\r\n");
761                         wprintf("You have sent a malformed or invalid request.\r\n");
762                         end_burst();
763                 }
764                 goto SKIP_ALL_THIS_CRAP;        /* Don't try to connect */
765         }
766
767         /* If the client sent a nonce that is incorrect, kill the request. */
768         if (strlen(bstr("nonce")) > 0) {
769                 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n", 
770                         bstr("nonce"), WCC->nonce);
771                 if (ibstr("nonce") != WCC->nonce) {
772                         lprintf(9, "Ignoring request with mismatched nonce.\n");
773                         hprintf("HTTP/1.1 404 Security check failed\r\n");
774                         hprintf("Content-Type: text/plain\r\n\r\n");
775                         wprintf("Security check failed.\r\n");
776                         end_burst();
777                         goto SKIP_ALL_THIS_CRAP;
778                 }
779         }
780
781         /*
782          * If we're not connected to a Citadel server, try to hook up the
783          * connection now.
784          */
785         if (!WCC->connected) {
786                 if (!strcasecmp(ctdlhost, "uds")) {
787                         /* unix domain socket */
788                         snprintf(buf, SIZ, "%s/citadel.socket", ctdlport);
789                         WCC->serv_sock = uds_connectsock(buf);
790                 }
791                 else {
792                         /* tcp socket */
793                         WCC->serv_sock = tcp_connectsock(ctdlhost, ctdlport);
794                 }
795
796                 if (WCC->serv_sock < 0) {
797                         do_logout();
798                         goto SKIP_ALL_THIS_CRAP;
799                 }
800                 else {
801                         WCC->connected = 1;
802                         serv_getln(buf, sizeof buf);    /* get the server greeting */
803
804                         /* Are there too many users already logged in? */
805                         if (!strncmp(buf, "571", 3)) {
806                                 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."));
807                                 end_burst();
808                                 end_webcit_session();
809                                 goto SKIP_ALL_THIS_CRAP;
810                         }
811
812                         /*
813                          * From what host is our user connecting?  Go with
814                          * the host at the other end of the HTTP socket,
815                          * unless we are following X-Forwarded-For: headers
816                          * and such a header has already turned up something.
817                          */
818                         if ( (!follow_xff) || (StrLength(browser_host) == 0) ) {
819                                 if (browser_host == NULL) {
820                                         browser_host = NewStrBuf();
821                                         Put(HTTPHeaders, HKEY("FreeMeWithTheOtherHeaders"), 
822                                             browser_host, HFreeStrBuf);
823                                 }
824                                 locate_host(browser_host, WCC->http_sock);
825                         }
826
827                         get_serv_info(browser_host, user_agent);
828                         if (serv_info.serv_rev_level < MINIMUM_CIT_VERSION) {
829                                 begin_burst();
830                                 wprintf(_("You are connected to a Citadel "
831                                         "server running Citadel %d.%02d. \n"
832                                         "In order to run this version of WebCit "
833                                         "you must also have Citadel %d.%02d or"
834                                         " newer.\n\n\n"),
835                                                 serv_info.serv_rev_level / 100,
836                                                 serv_info.serv_rev_level % 100,
837                                                 MINIMUM_CIT_VERSION / 100,
838                                                 MINIMUM_CIT_VERSION % 100
839                                         );
840                                 end_burst();
841                                 end_webcit_session();
842                                 goto SKIP_ALL_THIS_CRAP;
843                         }
844                 }
845         }
846 /*///////todo: restore language in this case */
847         /*
848          * Functions which can be performed without logging in
849          */
850         if (!strcasecmp(action, "listsub")) {
851                 do_listsub();
852                 goto SKIP_ALL_THIS_CRAP;
853         }
854         if (!strcasecmp(action, "freebusy")) {
855                 do_freebusy(ChrPtr(ReqLine));
856                 goto SKIP_ALL_THIS_CRAP;
857         }
858
859         /*
860          * If we're not logged in, but we have HTTP Authentication data,
861          * try logging in to Citadel using that.
862          */
863         if ((!WCC->logged_in)
864             && (StrLength(c_httpauth_user) > 0)
865             && (StrLength(c_httpauth_pass) > 0))
866         {
867                 FlushStrBuf(Buf);
868                 serv_printf("USER %s", ChrPtr(c_httpauth_user));
869                 StrBuf_ServGetln(Buf);
870                 if (GetServerStatus(Buf, NULL) == 3) {
871                         serv_printf("PASS %s", ChrPtr(c_httpauth_pass));
872                         StrBuf_ServGetln(Buf);
873                         if (GetServerStatus(Buf, NULL) == 2) {
874                                 become_logged_in(c_httpauth_user,
875                                                 c_httpauth_pass, Buf);
876                                 if (WCC->httpauth_user == NULL)
877                                         WCC->httpauth_user = NewStrBufDup(c_httpauth_user);
878                                 else {
879                                         FlushStrBuf(WCC->httpauth_user);
880                                         StrBufAppendBuf(WCC->httpauth_user, c_httpauth_user, 0);
881                                 }
882                                 if (WCC->httpauth_pass == NULL)
883                                         WCC->httpauth_pass = NewStrBufDup(c_httpauth_pass);
884                                 else {
885                                         FlushStrBuf(WCC->httpauth_pass);
886                                         StrBufAppendBuf(WCC->httpauth_pass, c_httpauth_pass, 0);
887                                 }
888                         } else {
889                                 /* Should only display when password is wrong */
890                                 authorization_required(&buf[4]);
891                                 FreeStrBuf(&Buf);
892                                 goto SKIP_ALL_THIS_CRAP;
893                         }
894                 }
895         }
896
897         /* This needs to run early */
898 #ifdef TECH_PREVIEW
899         if (!strcasecmp(action, "rss")) {
900                 display_rss(sbstr("room"), request_method);
901                 goto SKIP_ALL_THIS_CRAP;
902         }
903 #endif
904
905         /* 
906          * The GroupDAV stuff relies on HTTP authentication instead of
907          * our session's authentication.
908          */
909         if (!strncasecmp(action, "groupdav", 8)) {
910                 groupdav_main(HTTPHeaders, 
911                               ReqLine, request_method,
912                               ContentType, /* do GroupDAV methods */
913                               ContentLength, content, body_start);
914                 if (!WCC->logged_in) {
915                         WCC->killthis = 1;      /* If not logged in, don't */
916                 }                               /* keep the session active */
917                 goto SKIP_ALL_THIS_CRAP;
918         }
919
920
921         /*
922          * Automatically send requests with any method other than GET or
923          * POST to the GroupDAV code as well.
924          */
925         if ((strcasecmp(ChrPtr(request_method), "GET")) && (strcasecmp(ChrPtr(request_method), "POST"))) {
926                 groupdav_main(HTTPHeaders, ReqLine, 
927                               request_method, ContentType, /** do GroupDAV methods */
928                               ContentLength, content, body_start);
929                 if (!WCC->logged_in) {
930                         WCC->killthis = 1;      /** If not logged in, don't */
931                 }                               /** keep the session active */
932                 goto SKIP_ALL_THIS_CRAP;
933         }
934
935         /*
936          * If we're not logged in, but we have username and password cookies
937          * supplied by the browser, try using them to log in.
938          */
939         if ((!WCC->logged_in)
940            && (StrLength(c_username)>0)
941            && (StrLength(c_password)>0)) {
942                 serv_printf("USER %s", ChrPtr(c_username));
943                 StrBuf_ServGetln(Buf);
944                 if (GetServerStatus(Buf, NULL) == 3) {
945                         serv_printf("PASS %s", ChrPtr(c_password));
946                         StrBuf_ServGetln(Buf);
947                         if (GetServerStatus(Buf, NULL) == 2) {
948                                 StrBuf *Lang;
949                                 become_logged_in(c_username, c_password, Buf);
950                                 if (get_preference("language", &Lang)) {
951                                         set_selected_language(ChrPtr(Lang));
952                                         go_selected_language();         /* set locale */
953                                 }
954                                 get_preference("default_header_charset", &WCC->DefaultCharset);
955                         }
956                 }
957         }
958
959         /*
960          * If a 'gotofirst' parameter has been specified, attempt to goto that room
961          * prior to doing anything else.
962          */
963         if (havebstr("gotofirst")) {
964                 gotoroom(sbstr("gotofirst"));   /* do this quietly to avoid session output! */
965         }
966
967         /*
968          * If we don't have a current room, but a cookie specifying the
969          * current room is supplied, make an effort to go there.
970          */
971         if ((StrLength(WCC->wc_roomname) == 0) && (StrLength(c_roomname) > 0)) {
972                 serv_printf("GOTO %s", ChrPtr(c_roomname));
973                 StrBuf_ServGetln(Buf);
974                 if (GetServerStatus(Buf, NULL) == 2) {
975                         if (WCC->wc_roomname == NULL) {
976                                 WCC->wc_roomname = NewStrBufDup(c_roomname);
977                         }
978                         else {
979                                 FlushStrBuf(WCC->wc_roomname);
980                                 StrBufAppendBuf(WCC->wc_roomname, c_roomname, 0);
981                         }
982                 }
983         }
984         
985         GetHash(HandlerHash, action, strlen(action) /* TODO*/, &vHandler),
986                 Handler = (WebcitHandler*) vHandler;
987         if (Handler != NULL) {
988                 if (!WCC->logged_in && ((Handler->Flags & ANONYMOUS) == 0)) {
989                         display_login(NULL);
990                 }
991                 else {
992                         if((Handler->Flags & NEED_URL)) {
993                                 if (WCC->UrlFragment1 == NULL)
994                                         WCC->UrlFragment1 = NewStrBuf();
995                                 if (WCC->UrlFragment2 == NULL)
996                                         WCC->UrlFragment2 = NewStrBuf();
997                                 if (WCC->UrlFragment3 == NULL)
998                                         WCC->UrlFragment3 = NewStrBuf();
999                                 StrBufPrintf(WCC->UrlFragment1, "%s", index[0]);
1000                                 StrBufPrintf(WCC->UrlFragment2, "%s", index[1]);
1001                                 StrBufPrintf(WCC->UrlFragment3, "%s", index[2]);
1002                         }
1003                         if ((Handler->Flags & AJAX) != 0)
1004                                 begin_ajax_response();
1005                         Handler->F();
1006                         if ((Handler->Flags & AJAX) != 0)
1007                                 end_ajax_response();
1008                 }
1009         }
1010         /* When all else fais, display the main menu. */
1011         else {
1012                 if (!WCC->logged_in) 
1013                         display_login(NULL);
1014                 else
1015                         display_main_menu();
1016         }
1017
1018 SKIP_ALL_THIS_CRAP:
1019         if (WCC->SavePrefsToServer) {
1020                 save_preferences();
1021                 WCC->SavePrefsToServer = 0;
1022         }
1023         FreeStrBuf(&Buf);
1024         FreeStrBuf(&c_username);
1025         FreeStrBuf(&c_password);
1026         FreeStrBuf(&c_roomname);
1027         FreeStrBuf(&c_httpauth_user);
1028         FreeStrBuf(&c_httpauth_pass);
1029         FreeStrBuf(&WCC->this_page);
1030         fflush(stdout);
1031         if (content != NULL) {
1032                 FreeStrBuf(&content);
1033                 content = NULL;
1034         }
1035         DeleteHash(&WCC->urlstrings);
1036         if (WCC->upload_length > 0) {
1037                 free(WCC->upload);
1038                 WCC->upload_length = 0;
1039         }
1040         FreeStrBuf(&WCC->trailing_javascript);
1041 }
1042
1043
1044 /*
1045  * Replacement for sleep() that uses select() in order to avoid SIGALRM
1046  */
1047 void sleeeeeeeeeep(int seconds)
1048 {
1049         struct timeval tv;
1050
1051         tv.tv_sec = seconds;
1052         tv.tv_usec = 0;
1053         select(0, NULL, NULL, NULL, &tv);
1054 }
1055
1056
1057 int ConditionalImportantMesage(StrBuf *Target, WCTemplputParams *TP)
1058 {
1059         wcsession *WCC = WC;
1060         if (WCC != NULL)
1061                 return (!IsEmptyStr(WCC->ImportantMessage));
1062         else
1063                 return 0;
1064 }
1065
1066 void tmplput_importantmessage(StrBuf *Target, WCTemplputParams *TP)
1067 {
1068         wcsession *WCC = WC;
1069         
1070         if (WCC != NULL) {
1071 /*
1072                 StrBufAppendTemplate(Target, nArgs, Tokens, Context, ContextType,
1073                                      WCC->ImportantMessage, 0);
1074 */
1075                 StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
1076                 WCC->ImportantMessage[0] = '\0';
1077         }
1078 }
1079
1080 void tmplput_trailing_javascript(StrBuf *Target, WCTemplputParams *TP)
1081 {
1082         wcsession *WCC = WC;
1083
1084         if (WCC != NULL)
1085                 StrBufAppendTemplate(Target, TP, WCC->trailing_javascript, 0);
1086 }
1087
1088 void tmplput_csslocal(StrBuf *Target, WCTemplputParams *TP)
1089 {
1090         extern StrBuf *csslocal;
1091         StrBufAppendBuf(Target, 
1092                         csslocal, 0);
1093 }
1094
1095
1096
1097
1098 void 
1099 InitModule_WEBCIT
1100 (void)
1101 {
1102         WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS);
1103         WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
1104         WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX);
1105         WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
1106
1107         RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage, CTX_NONE);
1108         RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, CTX_NONE);
1109         RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, CTX_NONE);
1110         RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, CTX_NONE);
1111 }