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