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