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