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