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