* Restored the instant messenger popup
[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         char browser_host[256];
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         strcpy(browser_host, "");
580
581         WCC= WC;
582         if (WCC->WBuf == NULL)
583                 WC->WBuf = NewStrBufPlain(NULL, 32768);
584         FlushStrBuf(WCC->WBuf);
585
586         if (WCC->HBuf == NULL)
587                 WCC->HBuf = NewStrBuf();
588         FlushStrBuf(WCC->HBuf);
589
590         WCC->upload_length = 0;
591         WCC->upload = NULL;
592         WCC->is_mobile = 0;
593         WCC->trailing_javascript = NewStrBuf();
594
595         /** Figure out the action */
596         index[0] = action;
597         sizes[0] = sizeof action;
598         for (a=1; a<9; a++)
599         {
600                 index[a] = arg[a-1];
601                 sizes[a] = sizeof arg[a-1];
602         }
603 /*///   index[9] = &foo; todo */
604         nBackDots = 0;
605         nEmpty = 0;
606         for ( a = 0; a < 9; ++a)
607         {
608                 extract_token(index[a], ChrPtr(ReqLine), a + 1, '/', sizes[a]);
609                 if (strstr(index[a], "?")) *strstr(index[a], "?") = 0;
610                 if (strstr(index[a], "&")) *strstr(index[a], "&") = 0;
611                 if (strstr(index[a], " ")) *strstr(index[a], " ") = 0;
612                 if ((index[a][0] == '.') && (index[a][1] == '.'))
613                         nBackDots++;
614                 if (index[a][0] == '\0')
615                         nEmpty++;
616         }
617
618
619         if (GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) && 
620             (vLine != NULL)){
621                 cookie_to_stuff((StrBuf *)vLine, NULL,
622                                 c_username,
623                                 c_password,
624                                 c_roomname);
625         }
626         if (GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) &&
627             (vLine!=NULL)) {
628 /* TODO: wrap base64 in strbuf */
629                 CtdlDecodeBase64(c_httpauth_string, ChrPtr((StrBuf*)vLine), StrLength((StrBuf*)vLine));
630                 FlushStrBuf(Buf);
631                 StrBufAppendBufPlain(Buf, c_httpauth_string, -1, 0);
632                 StrBufExtract_token(c_httpauth_user, Buf, 0, ':');
633                 StrBufExtract_token(c_httpauth_pass, Buf, 1, ':');
634         }
635         if (GetHash(HTTPHeaders, HKEY("CONTENT-LENGTH"), &vLine) &&
636             (vLine!=NULL)) {
637                 ContentLength = StrToi((StrBuf*)vLine);
638         }
639         if (GetHash(HTTPHeaders, HKEY("CONTENT-TYPE"), &vLine) &&
640             (vLine!=NULL)) {
641                 ContentType = (StrBuf*)vLine;
642         }
643         if (GetHash(HTTPHeaders, HKEY("USER-AGENT"), &vLine) &&
644             (vLine!=NULL)) {
645                 safestrncpy(user_agent, ChrPtr((StrBuf*)vLine), sizeof user_agent);
646 #ifdef TECH_PREVIEW
647                 if ((WCC->is_mobile < 0) && is_mobile_ua(&buf[12])) {                   
648                         WCC->is_mobile = 1;
649                 }
650                 else {
651                         WCC->is_mobile = 0;
652                 }
653 #endif
654         }
655         if ((follow_xff) &&
656             GetHash(HTTPHeaders, HKEY("X-FORWARDED-HOST"), &vLine) &&
657             (vLine != NULL)) {
658                 safestrncpy(WCC->http_host, 
659                             ChrPtr((StrBuf*)vLine), 
660                             sizeof WCC->http_host);
661         }
662         if (IsEmptyStr(WCC->http_host) && 
663             GetHash(HTTPHeaders, HKEY("HOST"), &vLine) &&
664             (vLine!=NULL)) {
665                 safestrncpy(WCC->http_host, 
666                             ChrPtr((StrBuf*)vLine), 
667                             sizeof WCC->http_host);
668                 
669         }
670         if (GetHash(HTTPHeaders, HKEY("X-FORWARDED-FOR"), &vLine) &&
671             (vLine!=NULL)) {
672                 safestrncpy(browser_host, 
673                             ChrPtr((StrBuf*) vLine), 
674                             sizeof browser_host);
675                 while (num_tokens(browser_host, ',') > 1) {
676                         remove_token(browser_host, 0, ',');
677                 }
678                 striplt(browser_host);
679         }
680
681         if (ContentLength > 0) {
682                 content = NewStrBuf();
683                 StrBufPrintf(content, "Content-type: %s\n"
684                          "Content-length: %d\n\n",
685                          ChrPtr(ContentType), ContentLength);
686 /*
687                 hprintf("Content-type: %s\n"
688                         "Content-length: %d\n\n",
689                         ContentType, ContentLength);
690 */
691                 body_start = StrLength(content);
692
693                 /** Read the entire input data at once. */
694                 client_read(&WCC->http_sock, content, ReadBuf, ContentLength + body_start);
695
696                 if (!strncasecmp(ChrPtr(ContentType), "application/x-www-form-urlencoded", 33)) {
697                         StrBufCutLeft(content, body_start);
698                         ParseURLParams(content);
699                 } else if (!strncasecmp(ChrPtr(ContentType), "multipart", 9)) {
700                         content_end = ChrPtr(content) + ContentLength + body_start;
701                         mime_parser(ChrPtr(content), content_end, *upload_handler, NULL, NULL, NULL, 0);
702                 }
703         } else {
704                 content = NULL;
705         }
706
707         /* make a note of where we are in case the user wants to save it */
708         safestrncpy(WCC->this_page, ChrPtr(ReqLine), sizeof(WCC->this_page));
709         remove_token(WCC->this_page, 2, ' ');
710         remove_token(WCC->this_page, 0, ' ');
711
712         /* If there are variables in the URL, we must grab them now */
713         UrlLine = NewStrBufDup(ReqLine);
714         len = StrLength(UrlLine);
715         pch = pchs = ChrPtr(UrlLine);
716         pche = pchs + len;
717         while (pch < pche) {
718                 if ((*pch == '?') || (*pch == '&')) {
719                         StrBufCutLeft(UrlLine, pch - pchs + 1);
720                         ParseURLParams(UrlLine);
721                         break;
722                 }
723                 pch ++;
724         }
725         FreeStrBuf(&UrlLine);
726
727         /* If it's a "force 404" situation then display the error and bail. */
728         if (!strcmp(action, "404")) {
729                 hprintf("HTTP/1.1 404 Not found\r\n");
730                 hprintf("Content-Type: text/plain\r\n");
731                 wprintf("Not found\r\n");
732                 end_burst();
733                 goto SKIP_ALL_THIS_CRAP;
734         }
735
736         /* Static content can be sent without connecting to Citadel. */
737         is_static = 0;
738         for (a=0; a<ndirs && ! is_static; ++a) {
739                 if (!strcasecmp(action, (char*)static_content_dirs[a])) { /* map web to disk location */
740                         is_static = 1;
741                         n_static = a;
742                 }
743         }
744         if (is_static) {
745                 if (nBackDots < 2)
746                 {
747                         snprintf(buf, sizeof buf, "%s/%s/%s/%s/%s/%s/%s/%s",
748                                  static_dirs[n_static], 
749                                  index[1], index[2], index[3], index[4], index[5], index[6], index[7]);
750                         for (a=0; a<8; ++a) {
751                                 if (buf[strlen(buf)-1] == '/') {
752                                         buf[strlen(buf)-1] = 0;
753                                 }
754                         }
755                         for (a = 0; a < strlen(buf); ++a) {
756                                 if (isspace(buf[a])) {
757                                         buf[a] = 0;
758                                 }
759                         }
760                         output_static(buf);
761                 }
762                 else 
763                 {
764                         lprintf(9, "Suspicious request. Ignoring.");
765                         hprintf("HTTP/1.1 404 Security check failed\r\n");
766                         hprintf("Content-Type: text/plain\r\n\r\n");
767                         wprintf("You have sent a malformed or invalid request.\r\n");
768                         end_burst();
769                 }
770                 goto SKIP_ALL_THIS_CRAP;        /* Don't try to connect */
771         }
772
773         /* If the client sent a nonce that is incorrect, kill the request. */
774         if (strlen(bstr("nonce")) > 0) {
775                 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n", 
776                         bstr("nonce"), WCC->nonce);
777                 if (ibstr("nonce") != WCC->nonce) {
778                         lprintf(9, "Ignoring request with mismatched nonce.\n");
779                         hprintf("HTTP/1.1 404 Security check failed\r\n");
780                         hprintf("Content-Type: text/plain\r\n\r\n");
781                         wprintf("Security check failed.\r\n");
782                         end_burst();
783                         goto SKIP_ALL_THIS_CRAP;
784                 }
785         }
786
787         /*
788          * If we're not connected to a Citadel server, try to hook up the
789          * connection now.
790          */
791         if (!WCC->connected) {
792                 if (!strcasecmp(ctdlhost, "uds")) {
793                         /* unix domain socket */
794                         snprintf(buf, SIZ, "%s/citadel.socket", ctdlport);
795                         WCC->serv_sock = uds_connectsock(buf);
796                 }
797                 else {
798                         /* tcp socket */
799                         WCC->serv_sock = tcp_connectsock(ctdlhost, ctdlport);
800                 }
801
802                 if (WCC->serv_sock < 0) {
803                         do_logout();
804                         goto SKIP_ALL_THIS_CRAP;
805                 }
806                 else {
807                         WCC->connected = 1;
808                         serv_getln(buf, sizeof buf);    /* get the server greeting */
809
810                         /* Are there too many users already logged in? */
811                         if (!strncmp(buf, "571", 3)) {
812                                 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."));
813                                 end_burst();
814                                 end_webcit_session();
815                                 goto SKIP_ALL_THIS_CRAP;
816                         }
817
818                         /*
819                          * From what host is our user connecting?  Go with
820                          * the host at the other end of the HTTP socket,
821                          * unless we are following X-Forwarded-For: headers
822                          * and such a header has already turned up something.
823                          */
824                         if ( (!follow_xff) || (strlen(browser_host) == 0) ) {
825                                 locate_host(browser_host, WCC->http_sock);
826                         }
827
828                         get_serv_info(browser_host, user_agent);
829                         if (serv_info.serv_rev_level < MINIMUM_CIT_VERSION) {
830                                 begin_burst();
831                                 wprintf(_("You are connected to a Citadel "
832                                         "server running Citadel %d.%02d. \n"
833                                         "In order to run this version of WebCit "
834                                         "you must also have Citadel %d.%02d or"
835                                         " newer.\n\n\n"),
836                                                 serv_info.serv_rev_level / 100,
837                                                 serv_info.serv_rev_level % 100,
838                                                 MINIMUM_CIT_VERSION / 100,
839                                                 MINIMUM_CIT_VERSION % 100
840                                         );
841                                 end_burst();
842                                 end_webcit_session();
843                                 goto SKIP_ALL_THIS_CRAP;
844                         }
845                 }
846         }
847 /*///////todo: restore language in this case */
848         /*
849          * Functions which can be performed without logging in
850          */
851         if (!strcasecmp(action, "listsub")) {
852                 do_listsub();
853                 goto SKIP_ALL_THIS_CRAP;
854         }
855         if (!strcasecmp(action, "freebusy")) {
856                 do_freebusy(ChrPtr(ReqLine));
857                 goto SKIP_ALL_THIS_CRAP;
858         }
859
860         /*
861          * If we're not logged in, but we have HTTP Authentication data,
862          * try logging in to Citadel using that.
863          */
864         if ((!WCC->logged_in)
865             && (StrLength(c_httpauth_user) > 0)
866             && (StrLength(c_httpauth_pass) > 0))
867         {
868                 FlushStrBuf(Buf);
869                 serv_printf("USER %s", ChrPtr(c_httpauth_user));
870                 StrBuf_ServGetln(Buf);
871                 if (GetServerStatus(Buf, NULL) == 3) {
872                         serv_printf("PASS %s", ChrPtr(c_httpauth_pass));
873                         StrBuf_ServGetln(Buf);
874                         if (GetServerStatus(Buf, NULL) == 2) {
875                                 become_logged_in(c_httpauth_user,
876                                                 c_httpauth_pass, Buf);
877                                 if (WCC->httpauth_user == NULL)
878                                         WCC->httpauth_user = NewStrBufDup(c_httpauth_user);
879                                 else {
880                                         FlushStrBuf(WCC->httpauth_user);
881                                         StrBufAppendBuf(WCC->httpauth_user, c_httpauth_user, 0);
882                                 }
883                                 if (WCC->httpauth_pass == NULL)
884                                         WCC->httpauth_pass = NewStrBufDup(c_httpauth_pass);
885                                 else {
886                                         FlushStrBuf(WCC->httpauth_pass);
887                                         StrBufAppendBuf(WCC->httpauth_pass, c_httpauth_pass, 0);
888                                 }
889                         } else {
890                                 /* Should only display when password is wrong */
891                                 authorization_required(&buf[4]);
892                                 FreeStrBuf(&Buf);
893                                 goto SKIP_ALL_THIS_CRAP;
894                         }
895                 }
896         }
897
898         /* This needs to run early */
899 #ifdef TECH_PREVIEW
900         if (!strcasecmp(action, "rss")) {
901                 display_rss(sbstr("room"), request_method);
902                 goto SKIP_ALL_THIS_CRAP;
903         }
904 #endif
905
906         /* 
907          * The GroupDAV stuff relies on HTTP authentication instead of
908          * our session's authentication.
909          */
910         if (!strncasecmp(action, "groupdav", 8)) {
911                 groupdav_main(HTTPHeaders, 
912                               ReqLine, request_method,
913                               ContentType, /* do GroupDAV methods */
914                               ContentLength, content, body_start);
915                 if (!WCC->logged_in) {
916                         WCC->killthis = 1;      /* If not logged in, don't */
917                 }                               /* keep the session active */
918                 goto SKIP_ALL_THIS_CRAP;
919         }
920
921
922         /*
923          * Automatically send requests with any method other than GET or
924          * POST to the GroupDAV code as well.
925          */
926         if ((strcasecmp(ChrPtr(request_method), "GET")) && (strcasecmp(ChrPtr(request_method), "POST"))) {
927                 groupdav_main(HTTPHeaders, ReqLine, 
928                               request_method, ContentType, /** do GroupDAV methods */
929                               ContentLength, content, body_start);
930                 if (!WCC->logged_in) {
931                         WCC->killthis = 1;      /** If not logged in, don't */
932                 }                               /** keep the session active */
933                 goto SKIP_ALL_THIS_CRAP;
934         }
935
936         /*
937          * If we're not logged in, but we have username and password cookies
938          * supplied by the browser, try using them to log in.
939          */
940         if ((!WCC->logged_in)
941            && (StrLength(c_username)>0)
942            && (StrLength(c_password)>0)) {
943                 serv_printf("USER %s", ChrPtr(c_username));
944                 StrBuf_ServGetln(Buf);
945                 if (GetServerStatus(Buf, NULL) == 3) {
946                         serv_printf("PASS %s", ChrPtr(c_password));
947                         StrBuf_ServGetln(Buf);
948                         if (GetServerStatus(Buf, NULL) == 2) {
949                                 StrBuf *Lang;
950                                 become_logged_in(c_username, c_password, Buf);
951                                 if (get_preference("language", &Lang)) {
952                                         set_selected_language(ChrPtr(Lang));
953                                         go_selected_language();         /* set locale */
954                                 }
955                                 get_preference("default_header_charset", &WCC->DefaultCharset);
956                         }
957                 }
958         }
959
960         /*
961          * If a 'gotofirst' parameter has been specified, attempt to goto that room
962          * prior to doing anything else.
963          */
964         if (havebstr("gotofirst")) {
965                 gotoroom(sbstr("gotofirst"));   /* do this quietly to avoid session output! */
966         }
967
968         /*
969          * If we don't have a current room, but a cookie specifying the
970          * current room is supplied, make an effort to go there.
971          */
972         if ((StrLength(WCC->wc_roomname) == 0) && (StrLength(c_roomname) > 0)) {
973                 serv_printf("GOTO %s", ChrPtr(c_roomname));
974                 StrBuf_ServGetln(Buf);
975                 if (GetServerStatus(Buf, NULL) == 2) {
976                         if (WCC->wc_roomname == NULL) {
977                                 WCC->wc_roomname = NewStrBufDup(c_roomname);
978                         }
979                         else {
980                                 FlushStrBuf(WCC->wc_roomname);
981                                 StrBufAppendBuf(WCC->wc_roomname, c_roomname, 0);
982                         }
983                 }
984         }
985         
986         GetHash(HandlerHash, action, strlen(action) /* TODO*/, &vHandler),
987                 Handler = (WebcitHandler*) vHandler;
988         if (Handler != NULL) {
989                 if (!WCC->logged_in && ((Handler->Flags & ANONYMOUS) == 0)) {
990                         display_login(NULL);
991                 }
992                 else {
993                         if((Handler->Flags & NEED_URL)) {
994                                 if (WCC->UrlFragment1 == NULL)
995                                         WCC->UrlFragment1 = NewStrBuf();
996                                 if (WCC->UrlFragment2 == NULL)
997                                         WCC->UrlFragment2 = NewStrBuf();
998                                 if (WCC->UrlFragment3 == NULL)
999                                         WCC->UrlFragment3 = NewStrBuf();
1000                                 StrBufPrintf(WCC->UrlFragment1, "%s", index[0]);
1001                                 StrBufPrintf(WCC->UrlFragment2, "%s", index[1]);
1002                                 StrBufPrintf(WCC->UrlFragment3, "%s", index[2]);
1003                         }
1004                         if ((Handler->Flags & AJAX) != 0)
1005                                 begin_ajax_response();
1006                         Handler->F();
1007                         if ((Handler->Flags & AJAX) != 0)
1008                                 end_ajax_response();
1009                 }
1010         }
1011         /* When all else fais, display the main menu. */
1012         else {
1013                 if (!WCC->logged_in) 
1014                         display_login(NULL);
1015                 else
1016                         display_main_menu();
1017         }
1018
1019 SKIP_ALL_THIS_CRAP:
1020         if (WCC->SavePrefsToServer) {
1021                 save_preferences();
1022                 WCC->SavePrefsToServer = 0;
1023         }
1024         FreeStrBuf(&Buf);
1025         FreeStrBuf(&c_username);
1026         FreeStrBuf(&c_password);
1027         FreeStrBuf(&c_roomname);
1028         FreeStrBuf(&c_httpauth_user);
1029         FreeStrBuf(&c_httpauth_pass);
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 }