8892ece71d52a95408daf39fdc9fd91b27705bcf
[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
9 #include "webcit.h"
10 #include "groupdav.h"
11 #include "webserver.h"
12
13 #include <stdio.h>
14 #include <stdarg.h>
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
26 void WebcitAddUrlHandler(const char * UrlString, long UrlSLen, WebcitHandlerFunc F, int IsAjax)
27 {
28         WebcitHandler *NewHandler;
29
30         if (HandlerHash == NULL)
31                 HandlerHash = NewHash(1, NULL);
32         
33         NewHandler = (WebcitHandler*) malloc(sizeof(WebcitHandler));
34         NewHandler->F = F;
35         NewHandler->IsAjax = IsAjax;
36
37         Put(HandlerHash, UrlString, UrlSLen, NewHandler, NULL);
38 }
39
40 /*   
41  * remove escaped strings from i.e. the url string (like %20 for blanks)
42  */
43 long unescape_input(char *buf)
44 {
45         int a, b;
46         char hex[3];
47         long buflen;
48         long len;
49
50         buflen = strlen(buf);
51
52         while ((buflen > 0) && (isspace(buf[buflen - 1]))){
53                 buf[buflen - 1] = 0;
54                 buflen --;
55         }
56
57         a = 0; 
58         while (a < buflen) {
59                 if (buf[a] == '+')
60                         buf[a] = ' ';
61                 if (buf[a] == '%') {
62                         /* don't let % chars through, rather truncate the input. */
63                         if (a + 2 > buflen) {
64                                 buf[a] = '\0';
65                                 buflen = a;
66                         }
67                         else {                  
68                                 hex[0] = buf[a + 1];
69                                 hex[1] = buf[a + 2];
70                                 hex[2] = 0;
71                                 b = 0;
72                                 sscanf(hex, "%02x", &b);
73                                 buf[a] = (char) b;
74                                 len = buflen - a - 2;
75                                 if (len > 0)
76                                         memmove(&buf[a + 1], &buf[a + 3], len);
77                         
78                                 buflen -=2;
79                         }
80                 }
81                 a++;
82         }
83         return a;
84 }
85
86 void free_url(void *U)
87 {
88         urlcontent *u = (urlcontent*) U;
89         free(u->url_data);
90         free(u);
91 }
92
93 /*
94  * Extract variables from the URL.
95  */
96 void addurls(char *url, long ulen)
97 {
98         char *aptr, *bptr, *eptr;
99         char *up;
100         char *buf;
101         int len, keylen;
102         urlcontent *u;
103         struct wcsession *WCC = WC;
104
105         if (WCC->urlstrings == NULL)
106                 WCC->urlstrings = NewHash(1, NULL);
107         buf = (char*) malloc (ulen + 1);
108         memcpy(buf, url, ulen);
109         buf[ulen] = '\0';
110         eptr = buf + ulen;
111         up = buf;
112         while ((up < eptr) && (!IsEmptyStr(up))) {
113                 aptr = up;
114                 while ((aptr < eptr) && (*aptr != '\0') && (*aptr != '='))
115                         aptr++;
116                 if (*aptr != '=')
117                         return;
118                 *aptr = '\0';
119                 aptr++;
120                 bptr = aptr;
121                 while ((bptr < eptr) && (*bptr != '\0')
122                       && (*bptr != '&') && (*bptr != '?') && (*bptr != ' ')) {
123                         bptr++;
124                 }
125                 *bptr = '\0';
126                 u = (urlcontent *) malloc(sizeof(urlcontent));
127
128                 keylen = safestrncpy(u->url_key, up, sizeof u->url_key);
129                 if (keylen < 0){
130                         lprintf(1, "URLkey to long! [%s]", up);
131                         continue;
132                 }
133
134                 Put(WCC->urlstrings, u->url_key, keylen, u, free_url);
135                 len = bptr - aptr;
136                 u->url_data = malloc(len + 2);
137                 safestrncpy(u->url_data, aptr, len + 2);
138                 u->url_data_size = unescape_input(u->url_data);
139                 u->url_data[u->url_data_size] = '\0';
140                 up = bptr;
141                 ++up;
142 #ifdef DEBUG_URLSTRINGS
143                 lprintf(9, "%s = [%ld]  %s\n", u->url_key, u->url_data_size, u->url_data); 
144 #endif
145         }
146         free(buf);
147 }
148
149 /*
150  * free urlstring memory
151  */
152 void free_urls(void)
153 {
154         DeleteHash(&WC->urlstrings);
155 }
156
157 /*
158  * Diagnostic function to display the contents of all variables
159  */
160
161 void dump_vars(void)
162 {
163         struct wcsession *WCC = WC;
164         urlcontent *u;
165         void *U;
166         long HKLen;
167         char *HKey;
168         HashPos *Cursor;
169         
170         Cursor = GetNewHashPos ();
171         while (GetNextHashPos(WCC->urlstrings, Cursor, &HKLen, &HKey, &U)) {
172                 u = (urlcontent*) U;
173                 wprintf("%38s = %s\n", u->url_key, u->url_data);
174         }
175 }
176
177 /*
178  * Return the value of a variable supplied to the current web page (from the url or a form)
179  */
180
181 const char *XBstr(char *key, size_t keylen, size_t *len)
182 {
183         void *U;
184
185         if ((WC->urlstrings != NULL) && 
186             GetHash(WC->urlstrings, key, keylen, &U)) {
187                 *len = ((urlcontent *)U)->url_data_size;
188                 return ((urlcontent *)U)->url_data;
189         }
190         else {
191                 *len = 0;
192                 return ("");
193         }
194 }
195
196 const char *XBSTR(char *key, size_t *len)
197 {
198         void *U;
199
200         if ((WC->urlstrings != NULL) &&
201             GetHash(WC->urlstrings, key, strlen (key), &U)){
202                 *len = ((urlcontent *)U)->url_data_size;
203                 return ((urlcontent *)U)->url_data;
204         }
205         else {
206                 *len = 0;
207                 return ("");
208         }
209 }
210
211
212 const char *BSTR(char *key)
213 {
214         void *U;
215
216         if ((WC->urlstrings != NULL) &&
217             GetHash(WC->urlstrings, key, strlen (key), &U))
218                 return ((urlcontent *)U)->url_data;
219         else    
220                 return ("");
221 }
222
223 const char *Bstr(char *key, size_t keylen)
224 {
225         void *U;
226
227         if ((WC->urlstrings != NULL) && 
228             GetHash(WC->urlstrings, key, keylen, &U))
229                 return ((urlcontent *)U)->url_data;
230         else    
231                 return ("");
232 }
233
234 long LBstr(char *key, size_t keylen)
235 {
236         void *U;
237
238         if ((WC->urlstrings != NULL) && 
239             GetHash(WC->urlstrings, key, keylen, &U))
240                 return atol(((urlcontent *)U)->url_data);
241         else    
242                 return (0);
243 }
244
245 long LBSTR(char *key)
246 {
247         void *U;
248
249         if ((WC->urlstrings != NULL) && 
250             GetHash(WC->urlstrings, key, strlen(key), &U))
251                 return atol(((urlcontent *)U)->url_data);
252         else    
253                 return (0);
254 }
255
256 int IBstr(char *key, size_t keylen)
257 {
258         void *U;
259
260         if ((WC->urlstrings != NULL) && 
261             GetHash(WC->urlstrings, key, keylen, &U))
262                 return atoi(((urlcontent *)U)->url_data);
263         else    
264                 return (0);
265 }
266
267 int IBSTR(char *key)
268 {
269         void *U;
270
271         if ((WC->urlstrings != NULL) && 
272             GetHash(WC->urlstrings, key, strlen(key), &U))
273                 return atoi(((urlcontent *)U)->url_data);
274         else    
275                 return (0);
276 }
277
278 int HaveBstr(char *key, size_t keylen)
279 {
280         void *U;
281
282         if ((WC->urlstrings != NULL) && 
283             GetHash(WC->urlstrings, key, keylen, &U))
284                 return ((urlcontent *)U)->url_data_size != 0;
285         else    
286                 return (0);
287 }
288
289 int HAVEBSTR(char *key)
290 {
291         void *U;
292
293         if ((WC->urlstrings != NULL) && 
294             GetHash(WC->urlstrings, key, strlen(key), &U))
295                 return ((urlcontent *)U)->url_data_size != 0;
296         else    
297                 return (0);
298 }
299
300
301 int YesBstr(char *key, size_t keylen)
302 {
303         void *U;
304
305         if ((WC->urlstrings != NULL) && 
306             GetHash(WC->urlstrings, key, keylen, &U))
307                 return strcmp( ((urlcontent *)U)->url_data, "yes") == 0;
308         else    
309                 return (0);
310 }
311
312 int YESBSTR(char *key)
313 {
314         void *U;
315
316         if ((WC->urlstrings != NULL) && 
317             GetHash(WC->urlstrings, key, strlen(key), &U))
318                 return strcmp( ((urlcontent *)U)->url_data, "yes") == 0;
319         else    
320                 return (0);
321 }
322
323 /*
324  * web-printing funcion. uses our vsnprintf wrapper
325  */
326 void wprintf(const char *format,...)
327 {
328         va_list arg_ptr;
329         char wbuf[4096];
330
331         va_start(arg_ptr, format);
332         vsnprintf(wbuf, sizeof wbuf, format, arg_ptr);
333         va_end(arg_ptr);
334
335         client_write(wbuf, strlen(wbuf));
336 }
337
338
339 /*
340  * wrap up an HTTP session, closes tags, etc.
341  *
342  * print_standard_html_footer should be set to:
343  * 0 to transmit only,
344  * 1 to append the main menu and closing tags,
345  * 2 to append the closing tags only.
346  */
347 void wDumpContent(int print_standard_html_footer)
348 {
349         if (print_standard_html_footer) {
350                 wprintf("</div>\n");    /* end of "text" div */
351                 do_template("trailing");
352         }
353
354         /* If we've been saving it all up for one big output burst,
355          * go ahead and do that now.
356          */
357         end_burst();
358 }
359
360
361 /*
362  * Copy a string, escaping characters which have meaning in HTML.  
363  *
364  * target               target buffer
365  * strbuf               source buffer
366  * nbsp                 If nonzero, spaces are converted to non-breaking spaces.
367  * nolinebreaks         if set, linebreaks are removed from the string.
368  */
369 long stresc(char *target, long tSize, char *strbuf, int nbsp, int nolinebreaks)
370 {
371         char *aptr, *bptr, *eptr;
372
373         *target = '\0';
374         aptr = strbuf;
375         bptr = target;
376         eptr = target + tSize - 6; // our biggest unit to put in... 
377
378         while ((bptr < eptr) && !IsEmptyStr(aptr) ){
379                 if (*aptr == '<') {
380                         memcpy(bptr, "&lt;", 4);
381                         bptr += 4;
382                 }
383                 else if (*aptr == '>') {
384                         memcpy(bptr, "&gt;", 4);
385                         bptr += 4;
386                 }
387                 else if (*aptr == '&') {
388                         memcpy(bptr, "&amp;", 5);
389                         bptr += 5;
390                 }
391                 else if (*aptr == '\"') {
392                         memcpy(bptr, "&quot;", 6);
393                         bptr += 6;
394                 }
395                 else if (*aptr == '\'') {
396                         memcpy(bptr, "&#39;", 5);
397                         bptr += 5;
398                 }
399                 else if (*aptr == LB) {
400                         *bptr = '<';
401                         bptr ++;
402                 }
403                 else if (*aptr == RB) {
404                         *bptr = '>';
405                         bptr ++;
406                 }
407                 else if (*aptr == QU) {
408                         *bptr ='"';
409                         bptr ++;
410                 }
411                 else if ((*aptr == 32) && (nbsp == 1)) {
412                         memcpy(bptr, "&nbsp;", 6);
413                         bptr += 6;
414                 }
415                 else if ((*aptr == '\n') && (nolinebreaks)) {
416                         *bptr='\0';     /* nothing */
417                 }
418                 else if ((*aptr == '\r') && (nolinebreaks)) {
419                         *bptr='\0';     /* nothing */
420                 }
421                 else{
422                         *bptr = *aptr;
423                         bptr++;
424                 }
425                 aptr ++;
426         }
427         *bptr = '\0';
428         if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
429                 return -1;
430         return (bptr - target);
431 }
432
433 void escputs1(char *strbuf, int nbsp, int nolinebreaks)
434 {
435         char *buf;
436         long Siz;
437
438         if (strbuf == NULL) return;
439         Siz = (3 * strlen(strbuf)) + SIZ ;
440         buf = malloc(Siz);
441         stresc(buf, Siz, strbuf, nbsp, nolinebreaks);
442         wprintf("%s", buf);
443         free(buf);
444 }
445
446 /* 
447  * static wrapper for ecsputs1
448  */
449 void escputs(char *strbuf)
450 {
451         escputs1(strbuf, 0, 0);
452 }
453
454
455 /*
456  * urlescape buffer and print it to the client
457  */
458 void urlescputs(char *strbuf)
459 {
460         char outbuf[SIZ];
461         
462         urlesc(outbuf, SIZ, strbuf);
463         wprintf("%s", outbuf);
464 }
465
466
467 /*
468  * Copy a string, escaping characters for JavaScript strings.
469  */
470 void jsesc(char *target, size_t tlen, char *strbuf)
471 {
472         int len;
473         char *tend;
474         char *send;
475         char *tptr;
476         char *sptr;
477
478         target[0]='\0';
479         len = strlen (strbuf);
480         send = strbuf + len;
481         tend = target + tlen;
482         sptr = strbuf;
483         tptr = target;
484         
485         while (!IsEmptyStr(sptr) && 
486                (sptr < send) &&
487                (tptr < tend)) {
488                
489                 if (*sptr == '<')
490                         *tptr = '[';
491                 else if (*sptr == '>')
492                         *tptr = ']';
493                 else if (*sptr == '\'') {
494                         if (tend - tptr < 3)
495                                 return;
496                         *(tptr++) = '\\';
497                         *tptr = '\'';
498                 }
499                 else if (*sptr == '"') {
500                         if (tend - tptr < 8)
501                                 return;
502                         *(tptr++) = '&';
503                         *(tptr++) = 'q';
504                         *(tptr++) = 'u';
505                         *(tptr++) = 'o';
506                         *(tptr++) = 't';
507                         *tptr = ';';
508                 }
509                 else if (*sptr == '&') {
510                         if (tend - tptr < 7)
511                                 return;
512                         *(tptr++) = '&';
513                         *(tptr++) = 'a';
514                         *(tptr++) = 'm';
515                         *(tptr++) = 'p';
516                         *tptr = ';';
517                 } else {
518                         *tptr = *sptr;
519                 }
520                 tptr++; sptr++;
521         }
522         *tptr = '\0';
523 }
524
525 /*
526  * escape and print javascript
527  */
528 void jsescputs(char *strbuf)
529 {
530         char outbuf[SIZ];
531         
532         jsesc(outbuf, SIZ, strbuf);
533         wprintf("%s", outbuf);
534 }
535
536 /*
537  * Copy a string, escaping characters for message text hold
538  */
539 void msgesc(char *target, size_t tlen, char *strbuf)
540 {
541         int len;
542         char *tend;
543         char *send;
544         char *tptr;
545         char *sptr;
546
547         target[0]='\0';
548         len = strlen (strbuf);
549         send = strbuf + len;
550         tend = target + tlen;
551         sptr = strbuf;
552         tptr = target;
553
554         while (!IsEmptyStr(sptr) && 
555                (sptr < send) &&
556                (tptr < tend)) {
557                
558                 if (*sptr == '\n')
559                         *tptr = ' ';
560                 else if (*sptr == '\r')
561                         *tptr = ' ';
562                 else if (*sptr == '\'') {
563                         if (tend - tptr < 8)
564                                 return;
565                         *(tptr++) = '&';
566                         *(tptr++) = '#';
567                         *(tptr++) = '3';
568                         *(tptr++) = '9';
569                         *tptr = ';';
570                 } else {
571                         *tptr = *sptr;
572                 }
573                 tptr++; sptr++;
574         }
575         *tptr = '\0';
576 }
577
578 /*
579  * print a string to the client after cleaning it with msgesc() and stresc()
580  */
581 void msgescputs1( char *strbuf)
582 {
583         char *outbuf;
584         char *outbuf2;
585         int buflen;
586
587         if (strbuf == NULL) return;
588         buflen = 3 * strlen(strbuf) + SIZ;
589         outbuf = malloc( buflen);
590         outbuf2 = malloc( buflen);
591         msgesc(outbuf, buflen, strbuf);
592         stresc(outbuf2, buflen, outbuf, 0, 0);
593         wprintf("%s", outbuf2);
594         free(outbuf);
595         free(outbuf2);
596 }
597
598 /*
599  * print a string to the client after cleaning it with msgesc()
600  */
601 void msgescputs(char *strbuf) {
602         char *outbuf;
603         size_t len;
604
605         if (strbuf == NULL) return;
606         len =  (3 * strlen(strbuf)) + SIZ;
607         outbuf = malloc(len);
608         msgesc(outbuf, len, strbuf);
609         wprintf("%s", outbuf);
610         free(outbuf);
611 }
612
613
614
615
616 /*
617  * Output HTTP headers and leading HTML for a page
618  */
619 void output_headers(    int do_httpheaders,     /* 1 = output HTTP headers                          */
620                         int do_htmlhead,        /* 1 = output HTML <head> section and <body> opener */
621
622                         int do_room_banner,     /* 0=no, 1=yes,                                     
623                                                  * 2 = I'm going to embed my own, so don't open the 
624                                                  *     <div id="content"> either.                   
625                                                  */
626
627                         int unset_cookies,      /* 1 = session is terminating, so unset the cookies */
628                         int suppress_check,     /* 1 = suppress check for instant messages          */
629                         int cache               /* 1 = allow browser to cache this page             */
630 ) {
631         char cookie[1024];
632         char httpnow[128];
633
634         wprintf("HTTP/1.1 200 OK\n");
635         http_datestring(httpnow, sizeof httpnow, time(NULL));
636
637         if (do_httpheaders) {
638                 wprintf("Content-type: text/html; charset=utf-8\r\n"
639                         "Server: %s / %s\n"
640                         "Connection: close\r\n",
641                         PACKAGE_STRING, serv_info.serv_software
642                 );
643         }
644
645         if (cache) {
646                 char httpTomorow[128];
647
648                 http_datestring(httpTomorow, sizeof httpTomorow, 
649                                 time(NULL) + 60 * 60 * 24 * 2);
650
651                 wprintf("Pragma: public\r\n"
652                         "Cache-Control: max-age=3600, must-revalidate\r\n"
653                         "Last-modified: %s\r\n"
654                         "Expires: %s\r\n",
655                         httpnow,
656                         httpTomorow
657                 );
658         }
659         else {
660                 wprintf("Pragma: no-cache\r\n"
661                         "Cache-Control: no-store\r\n"
662                         "Expires: -1\r\n"
663                 );
664         }
665
666         stuff_to_cookie(cookie, 1024, WC->wc_session, WC->wc_username,
667                         WC->wc_password, WC->wc_roomname);
668
669         if (unset_cookies) {
670                 wprintf("Set-cookie: webcit=%s; path=/\r\n", unset);
671         } else {
672                 wprintf("Set-cookie: webcit=%s; path=/\r\n", cookie);
673                 if (server_cookie != NULL) {
674                         wprintf("%s\n", server_cookie);
675                 }
676         }
677
678         if (do_htmlhead) {
679                 begin_burst();
680                 if (!access("static.local/webcit.css", R_OK)) {
681                         svprintf(HKEY("CSSLOCAL"), WCS_STRING,
682                            "<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\">"
683                         );
684                 }
685                 do_template("head");
686         }
687
688         /* ICONBAR */
689         if (do_htmlhead) {
690
691
692                 /* check for ImportantMessages (these display in a div overlaying the main screen) */
693                 if (!IsEmptyStr(WC->ImportantMessage)) {
694                         wprintf("<div id=\"important_message\">\n"
695                                 "<span class=\"imsg\">");
696                         escputs(WC->ImportantMessage);
697                         wprintf("</span><br />\n"
698                                 "</div>\n"
699                                 "<script type=\"text/javascript\">\n"
700                                 "        setTimeout('hide_imsg_popup()', 5000); \n"
701                                 "</script>\n");
702                         WC->ImportantMessage[0] = 0;
703                 }
704
705                 if ( (WC->logged_in) && (!unset_cookies) ) {
706                         wprintf("<div id=\"iconbar\">");
707                         do_selected_iconbar();
708                         /** check for instant messages (these display in a new window) */
709                         page_popup();
710                         wprintf("</div>");
711                 }
712
713                 if (do_room_banner == 1) {
714                         wprintf("<div id=\"banner\">\n");
715                         embed_room_banner(NULL, navbar_default);
716                         wprintf("</div>\n");
717                 }
718         }
719
720         if (do_room_banner == 1) {
721                 wprintf("<div id=\"content\">\n");
722         }
723 }
724
725
726 /*
727  * Generic function to do an HTTP redirect.  Easy and fun.
728  */
729 void http_redirect(const char *whichpage) {
730         wprintf("HTTP/1.1 302 Moved Temporarily\n");
731         wprintf("Location: %s\r\n", whichpage);
732         wprintf("URI: %s\r\n", whichpage);
733         wprintf("Content-type: text/html; charset=utf-8\r\n\r\n");
734         wprintf("<html><body>");
735         wprintf("Go <a href=\"%s\">here</A>.", whichpage);
736         wprintf("</body></html>\n");
737 }
738
739
740
741 /*
742  * Output a piece of content to the web browser using conformant HTTP and MIME semantics
743  */
744 void http_transmit_thing(char *thing, size_t length, const char *content_type,
745                          int is_static) {
746
747         output_headers(0, 0, 0, 0, 0, is_static);
748
749         wprintf("Content-type: %s\r\n"
750                 "Server: %s\r\n"
751                 "Connection: close\r\n",
752                 content_type,
753                 PACKAGE_STRING);
754
755 #ifdef HAVE_ZLIB
756         /* If we can send the data out compressed, please do so. */
757         if (WC->gzip_ok) {
758                 char *compressed_data = NULL;
759                 size_t compressed_len;
760
761                 compressed_len =  ((length * 101) / 100) + 100;
762                 compressed_data = malloc(compressed_len);
763
764                 if (compress_gzip((Bytef *) compressed_data,
765                                   &compressed_len,
766                                   (Bytef *) thing,
767                                   (uLongf) length, Z_BEST_SPEED) == Z_OK) {
768                         wprintf("Content-encoding: gzip\r\n"
769                                 "Content-length: %ld\r\n"
770                                 "\r\n",
771                                 (long) compressed_len
772                         );
773                         client_write(compressed_data, (size_t)compressed_len);
774                         free(compressed_data);
775                         return;
776                 }
777         }
778 #endif
779
780         /* No compression ... just send it out as-is */
781         wprintf("Content-length: %ld\r\n"
782                 "\r\n",
783                 (long) length
784         );
785         client_write(thing, (size_t)length);
786 }
787
788 /*
789  * print menu box like used in the floor view or admin interface.
790  * This function takes pair of strings as va_args, 
791  * Title        Title string of the box
792  * Class        CSS Class for the box
793  * nLines       How many string pairs should we print? (URL, UrlText)
794  * ...          Pairs of URL Strings and their Names
795  */
796 void print_menu_box(char* Title, char *Class, int nLines, ...)
797 {
798         va_list arg_list;
799         long i;
800         
801         svput("BOXTITLE", WCS_STRING, Title);
802         do_template("beginbox");
803         
804         wprintf("<ul class=\"%s\">", Class);
805         
806         va_start(arg_list, nLines);
807         for (i = 0; i < nLines; ++i)
808         { 
809                 wprintf("<li><a href=\"%s\">", va_arg(arg_list, char *));
810                 wprintf((char *) va_arg(arg_list, char *));
811                 wprintf("</a></li>\n");
812         }
813         va_end (arg_list);
814         
815         wprintf("</a></li>\n");
816         
817         wprintf("</ul>");
818         
819         do_template("endbox");
820 }
821
822
823 /*
824  * dump out static pages from disk
825  */
826 void output_static(char *what)
827 {
828         FILE *fp;
829         struct stat statbuf;
830         off_t bytes;
831         off_t count = 0;
832         size_t res;
833         char *bigbuffer;
834         const char *content_type;
835         int len;
836
837         fp = fopen(what, "rb");
838         if (fp == NULL) {
839                 lprintf(9, "output_static('%s')  -- NOT FOUND --\n", what);
840                 wprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
841                 wprintf("Content-Type: text/plain\r\n");
842                 wprintf("\r\n");
843                 wprintf("Cannot open %s: %s\r\n", what, strerror(errno));
844         } else {
845                 len = strlen (what);
846                 content_type = GuessMimeByFilename(what, len);
847
848                 if (fstat(fileno(fp), &statbuf) == -1) {
849                         lprintf(9, "output_static('%s')  -- FSTAT FAILED --\n", what);
850                         wprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
851                         wprintf("Content-Type: text/plain\r\n");
852                         wprintf("\r\n");
853                         wprintf("Cannot fstat %s: %s\n", what, strerror(errno));
854                         return;
855                 }
856
857                 count = 0;
858                 bytes = statbuf.st_size;
859                 if ((bigbuffer = malloc(bytes + 2)) == NULL) {
860                         lprintf(9, "output_static('%s')  -- MALLOC FAILED (%s) --\n", what, strerror(errno));
861                         wprintf("HTTP/1.1 500 internal server error\r\n");
862                         wprintf("Content-Type: text/plain\r\n");
863                         wprintf("\r\n");
864                         return;
865                 }
866                 while (count < bytes) {
867                         if ((res = fread(bigbuffer + count, 1, bytes - count, fp)) == 0) {
868                                 lprintf(9, "output_static('%s')  -- FREAD FAILED (%s) %zu bytes of %zu --\n", what, strerror(errno), bytes - count, bytes);
869                                 wprintf("HTTP/1.1 500 internal server error \r\n");
870                                 wprintf("Content-Type: text/plain\r\n");
871                                 wprintf("\r\n");
872                                 return;
873                         }
874                         count += res;
875                 }
876
877                 fclose(fp);
878
879                 lprintf(9, "output_static('%s')  %s\n", what, content_type);
880                 http_transmit_thing(bigbuffer, (size_t)bytes, content_type, 1);
881                 free(bigbuffer);
882         }
883         if (yesbstr("force_close_session")) {
884                 end_webcit_session();
885         }
886 }
887
888 /*
889  * When the browser requests an image file from the Citadel server,
890  * this function is called to transmit it.
891  */
892 void output_image()
893 {
894         char buf[SIZ];
895         char *xferbuf = NULL;
896         off_t bytes;
897         const char *MimeType;
898
899         serv_printf("OIMG %s|%s", bstr("name"), bstr("parm"));
900         serv_getln(buf, sizeof buf);
901         if (buf[0] == '2') {
902                 bytes = extract_long(&buf[4], 0);
903                 xferbuf = malloc(bytes + 2);
904
905                 /** Read it from the server */
906                 read_server_binary(xferbuf, bytes);
907                 serv_puts("CLOS");
908                 serv_getln(buf, sizeof buf);
909
910                 MimeType = GuessMimeType (xferbuf, bytes);
911                 /** Write it to the browser */
912                 if (!IsEmptyStr(MimeType))
913                 {
914                         http_transmit_thing(xferbuf, 
915                                             (size_t)bytes, 
916                                             MimeType, 
917                                             0);
918                         free(xferbuf);
919                         return;
920                 }
921                 /* hm... unknown mimetype? fallback to blank gif */
922                 free(xferbuf);
923         } 
924
925         
926         /*
927          * Instead of an ugly 404, send a 1x1 transparent GIF
928          * when there's no such image on the server.
929          */
930         char blank_gif[SIZ];
931         snprintf (blank_gif, SIZ, "%s%s", static_dirs[0], "/blank.gif");
932         output_static(blank_gif);
933 }
934
935 /*
936  * Extract an embedded photo from a vCard for display on the client
937  */
938 void display_vcard_photo_img(char *msgnum_as_string)
939 {
940         long msgnum = 0L;
941         char *vcard;
942         struct vCard *v;
943         char *xferbuf;
944     char *photosrc;
945         int decoded;
946         const char *contentType;
947
948         msgnum = atol(msgnum_as_string);
949         
950         vcard = load_mimepart(msgnum,"1");
951         v = vcard_load(vcard);
952         
953         photosrc = vcard_get_prop(v, "PHOTO", 1,0,0);
954         xferbuf = malloc(strlen(photosrc));
955         if (xferbuf == NULL) {
956                 lprintf(5, "xferbuf malloc failed\n");
957                 return;
958         }
959         memset(xferbuf, 1, SIZ);
960         decoded = CtdlDecodeBase64(
961                 xferbuf,
962                 photosrc,
963                 strlen(photosrc));
964         contentType = GuessMimeType(xferbuf, decoded);
965         http_transmit_thing(xferbuf, decoded, contentType, 0);
966         free(v);
967         free(photosrc);
968         free(xferbuf);
969 }
970
971 /*
972  * Generic function to output an arbitrary MIME part from an arbitrary
973  * message number on the server.
974  *
975  * msgnum               Number of the item on the citadel server
976  * partnum              The MIME part to be output
977  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
978  */
979 void mimepart(char *msgnum, char *partnum, int force_download)
980 {
981         char buf[256];
982         off_t bytes;
983         char content_type[256];
984         char *content = NULL;
985         
986         serv_printf("OPNA %s|%s", msgnum, partnum);
987         serv_getln(buf, sizeof buf);
988         if (buf[0] == '2') {
989                 bytes = extract_long(&buf[4], 0);
990                 content = malloc(bytes + 2);
991                 if (force_download) {
992                         strcpy(content_type, "application/octet-stream");
993                 }
994                 else {
995                         extract_token(content_type, &buf[4], 3, '|', sizeof content_type);
996                 }
997                 output_headers(0, 0, 0, 0, 0, 0);
998                 read_server_binary(content, bytes);
999                 serv_puts("CLOS");
1000                 serv_getln(buf, sizeof buf);
1001                 http_transmit_thing(content, bytes, content_type, 0);
1002                 free(content);
1003         } else {
1004                 wprintf("HTTP/1.1 404 %s\n", &buf[4]);
1005                 output_headers(0, 0, 0, 0, 0, 0);
1006                 wprintf("Content-Type: text/plain\r\n");
1007                 wprintf("\r\n");
1008                 wprintf(_("An error occurred while retrieving this part: %s\n"), &buf[4]);
1009         }
1010
1011 }
1012
1013
1014 /*
1015  * Read any MIME part of a message, from the server, into memory.
1016  */
1017 char *load_mimepart(long msgnum, char *partnum)
1018 {
1019         char buf[SIZ];
1020         off_t bytes;
1021         char content_type[SIZ];
1022         char *content;
1023         
1024         serv_printf("DLAT %ld|%s", msgnum, partnum);
1025         serv_getln(buf, sizeof buf);
1026         if (buf[0] == '6') {
1027                 bytes = extract_long(&buf[4], 0);
1028                 extract_token(content_type, &buf[4], 3, '|', sizeof content_type);
1029
1030                 content = malloc(bytes + 2);
1031                 serv_read(content, bytes);
1032
1033                 content[bytes] = 0;     /* null terminate for good measure */
1034                 return(content);
1035         }
1036         else {
1037                 return(NULL);
1038         }
1039
1040 }
1041
1042
1043 /*
1044  * Convenience functions to display a page containing only a string
1045  *
1046  * titlebarcolor        color of the titlebar of the frame
1047  * titlebarmsg          text to display in the title bar
1048  * messagetext          body of the box
1049  */
1050 void convenience_page(char *titlebarcolor, char *titlebarmsg, char *messagetext)
1051 {
1052         wprintf("HTTP/1.1 200 OK\n");
1053         output_headers(1, 1, 2, 0, 0, 0);
1054         wprintf("<div id=\"banner\">\n");
1055         wprintf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
1056         wprintf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
1057         wprintf("</td></tr></table>\n");
1058         wprintf("</div>\n<div id=\"content\">\n");
1059         escputs(messagetext);
1060
1061         wprintf("<hr />\n");
1062         wDumpContent(1);
1063 }
1064
1065
1066 /*
1067  * Display a blank page.
1068  */
1069 void blank_page(void) {
1070         output_headers(1, 1, 0, 0, 0, 0);
1071         wDumpContent(2);
1072 }
1073
1074
1075 /*
1076  * A template has been requested
1077  */
1078 void url_do_template(void) {
1079         do_template(bstr("template"));
1080 }
1081
1082
1083
1084 /*
1085  * Offer to make any page the user's "start page."
1086  */
1087 void offer_start_page(void) {
1088         wprintf("<a href=\"change_start_page?startpage=");
1089         urlescputs(WC->this_page);
1090         wprintf("\">");
1091         wprintf(_("Make this my start page"));
1092         wprintf("</a>");
1093 #ifdef TECH_PREVIEW
1094         wprintf("<br/><a href=\"rss?room=");
1095         urlescputs(WC->wc_roomname);
1096         wprintf("\" title=\"RSS 2.0 feed for ");
1097         escputs(WC->wc_roomname);
1098         wprintf("\"><img alt=\"RSS\" border=\"0\" src=\"static/xml_button.gif\"/></a>\n");
1099 #endif
1100 }
1101
1102
1103 /*
1104  * Change the user's start page
1105  */
1106 void change_start_page(void) {
1107
1108         if (bstr("startpage") == NULL) {
1109                 safestrncpy(WC->ImportantMessage,
1110                         _("You no longer have a start page selected."),
1111                         sizeof WC->ImportantMessage);
1112                 display_main_menu();
1113                 return;
1114         }
1115
1116         set_preference("startpage", NewStrBufPlain(bstr("startpage"), -1), 1);
1117
1118         output_headers(1, 1, 0, 0, 0, 0);
1119         do_template("newstartpage");
1120         wDumpContent(1);
1121 }
1122
1123
1124
1125 /*
1126  * convenience function to indicate success
1127  */
1128 void display_success(char *successmessage)
1129 {
1130         convenience_page("007700", "OK", successmessage);
1131 }
1132
1133
1134 /*
1135  * Authorization required page 
1136  * This is probably temporary and should be revisited 
1137  */
1138 void authorization_required(const char *message)
1139 {
1140         wprintf("HTTP/1.1 401 Authorization Required\r\n");
1141         wprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", serv_info.serv_humannode);
1142         wprintf("Content-Type: text/html\r\n\r\n");
1143         wprintf("<h1>");
1144         wprintf(_("Authorization Required"));
1145         wprintf("</h1>\r\n");
1146         wprintf(_("The resource you requested requires a valid username and password. "
1147                 "You could not be logged in: %s\n"), message);
1148         wDumpContent(0);
1149 }
1150
1151 /*
1152  * This function is called by the MIME parser to handle data uploaded by
1153  * the browser.  Form data, uploaded files, and the data from HTTP PUT
1154  * operations (such as those found in GroupDAV) all arrive this way.
1155  *
1156  * name         Name of the item being uploaded
1157  * filename     Filename of the item being uploaded
1158  * partnum      MIME part identifier (not needed)
1159  * disp         MIME content disposition (not needed)
1160  * content      The actual data
1161  * cbtype       MIME content-type
1162  * cbcharset    Character set
1163  * length       Content length
1164  * encoding     MIME encoding type (not needed)
1165  * userdata     Not used here
1166  */
1167 void upload_handler(char *name, char *filename, char *partnum, char *disp,
1168                         void *content, char *cbtype, char *cbcharset,
1169                         size_t length, char *encoding, void *userdata)
1170 {
1171         urlcontent *u;
1172 #ifdef DEBUG_URLSTRINGS
1173         lprintf(9, "upload_handler() name=%s, type=%s, len=%d\n", name, cbtype, length);
1174 #endif
1175         if (WC->urlstrings == NULL)
1176                 WC->urlstrings = NewHash(1, NULL);
1177
1178         /* Form fields */
1179         if ( (length > 0) && (IsEmptyStr(cbtype)) ) {
1180                 u = (urlcontent *) malloc(sizeof(urlcontent));
1181                 
1182                 safestrncpy(u->url_key, name, sizeof(u->url_key));
1183                 u->url_data = malloc(length + 1);
1184                 u->url_data_size = length;
1185                 memcpy(u->url_data, content, length);
1186                 u->url_data[length] = 0;
1187                 Put(WC->urlstrings, u->url_key, strlen(u->url_key), u, free_url);
1188 #ifdef DEBUG_URLSTRINGS
1189                 lprintf(9, "Key: <%s> len: [%ld] Data: <%s>\n", u->url_key, u->url_data_size, u->url_data);
1190 #endif
1191         }
1192
1193         /** Uploaded files */
1194         if ( (length > 0) && (!IsEmptyStr(cbtype)) ) {
1195                 WC->upload = malloc(length);
1196                 if (WC->upload != NULL) {
1197                         WC->upload_length = length;
1198                         safestrncpy(WC->upload_filename, filename,
1199                                         sizeof(WC->upload_filename));
1200                         safestrncpy(WC->upload_content_type, cbtype,
1201                                         sizeof(WC->upload_content_type));
1202                         memcpy(WC->upload, content, length);
1203                 }
1204                 else {
1205                         lprintf(3, "malloc() failed: %s\n", strerror(errno));
1206                 }
1207         }
1208
1209 }
1210
1211 /*
1212  * Convenience functions to wrap around asynchronous ajax responses
1213  */
1214 void begin_ajax_response(void) {
1215         output_headers(0, 0, 0, 0, 0, 0);
1216
1217         wprintf("Content-type: text/html; charset=UTF-8\r\n"
1218                 "Server: %s\r\n"
1219                 "Connection: close\r\n"
1220                 "Pragma: no-cache\r\n"
1221                 "Cache-Control: no-cache\r\n"
1222                 "Expires: -1\r\n"
1223                 ,
1224                 PACKAGE_STRING);
1225         begin_burst();
1226 }
1227
1228 /*
1229  * print ajax response footer 
1230  */
1231 void end_ajax_response(void) {
1232         wprintf("\r\n");
1233         wDumpContent(0);
1234 }
1235
1236 /*
1237  * Wraps a Citadel server command in an AJAX transaction.
1238  */
1239 void ajax_servcmd(void)
1240 {
1241         char buf[1024];
1242         char gcontent[1024];
1243         char *junk;
1244         size_t len;
1245
1246         begin_ajax_response();
1247
1248         serv_printf("%s", bstr("g_cmd"));
1249         serv_getln(buf, sizeof buf);
1250         wprintf("%s\n", buf);
1251
1252         if (buf[0] == '8') {
1253                 serv_printf("\n\n000");
1254         }
1255         if ((buf[0] == '1') || (buf[0] == '8')) {
1256                 while (serv_getln(gcontent, sizeof gcontent), strcmp(gcontent, "000")) {
1257                         wprintf("%s\n", gcontent);
1258                 }
1259                 wprintf("000");
1260         }
1261         if (buf[0] == '4') {
1262                 text_to_server(bstr("g_input"));
1263                 serv_puts("000");
1264         }
1265         if (buf[0] == '6') {
1266                 len = atol(&buf[4]);
1267                 junk = malloc(len);
1268                 serv_read(junk, len);
1269                 free(junk);
1270         }
1271         if (buf[0] == '7') {
1272                 len = atol(&buf[4]);
1273                 junk = malloc(len);
1274                 memset(junk, 0, len);
1275                 serv_write(junk, len);
1276                 free(junk);
1277         }
1278
1279         end_ajax_response();
1280         
1281         /*
1282          * This is kind of an ugly hack, but this is the only place it can go.
1283          * If the command was GEXP, then the instant messenger window must be
1284          * running, so reset the "last_pager_check" watchdog timer so
1285          * that page_popup() doesn't try to open it a second time.
1286          */
1287         if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
1288                 WC->last_pager_check = time(NULL);
1289         }
1290 }
1291
1292
1293 /*
1294  * Helper function for the asynchronous check to see if we need
1295  * to open the instant messenger window.
1296  */
1297 void seconds_since_last_gexp(void)
1298 {
1299         char buf[256];
1300
1301         begin_ajax_response();
1302         if ( (time(NULL) - WC->last_pager_check) < 30) {
1303                 wprintf("NO\n");
1304         }
1305         else {
1306                 serv_puts("NOOP");
1307                 serv_getln(buf, sizeof buf);
1308                 if (buf[3] == '*') {
1309                         wprintf("YES");
1310                 }
1311                 else {
1312                         wprintf("NO");
1313                 }
1314         }
1315         end_ajax_response();
1316 }
1317
1318 /**
1319  * \brief Detects a 'mobile' user agent 
1320  */
1321 int is_mobile_ua(char *user_agent) {
1322         if (strstr(user_agent,"iPhone OS") != NULL) {
1323                 return 1;
1324         } else if (strstr(user_agent,"Windows CE") != NULL) {
1325                 return 1;
1326         } else if (strstr(user_agent,"SymbianOS") != NULL) {
1327                 return 1;
1328         }
1329         return 0;
1330 }
1331
1332
1333 /*
1334  * Entry point for WebCit transaction
1335  */
1336 void session_loop(struct httprequest *req)
1337 {
1338         char cmd[1024];
1339         char action[1024];
1340         char arg[8][128];
1341         size_t sizes[10];
1342         char *index[10];
1343         char buf[SIZ];
1344         char request_method[128];
1345         char pathname[1024];
1346         int a, b, nBackDots, nEmpty;
1347         int ContentLength = 0;
1348         char ContentType[512];
1349         char *content = NULL;
1350         char *content_end = NULL;
1351         struct httprequest *hptr;
1352         char browser_host[256];
1353         char user_agent[256];
1354         int body_start = 0;
1355         int is_static = 0;
1356         int n_static = 0;
1357         int len = 0;
1358         /*
1359          * We stuff these with the values coming from the client cookies,
1360          * so we can use them to reconnect a timed out session if we have to.
1361          */
1362         char c_username[SIZ];
1363         char c_password[SIZ];
1364         char c_roomname[SIZ];
1365         char c_httpauth_string[SIZ];
1366         char c_httpauth_user[SIZ];
1367         char c_httpauth_pass[SIZ];
1368         char cookie[SIZ];
1369
1370         safestrncpy(c_username, "", sizeof c_username);
1371         safestrncpy(c_password, "", sizeof c_password);
1372         safestrncpy(c_roomname, "", sizeof c_roomname);
1373         safestrncpy(c_httpauth_string, "", sizeof c_httpauth_string);
1374         safestrncpy(c_httpauth_user, DEFAULT_HTTPAUTH_USER, sizeof c_httpauth_user);
1375         safestrncpy(c_httpauth_pass, DEFAULT_HTTPAUTH_PASS, sizeof c_httpauth_pass);
1376         strcpy(browser_host, "");
1377
1378         WC->upload_length = 0;
1379         WC->upload = NULL;
1380         WC->is_mobile = 0;
1381
1382         hptr = req;
1383         if (hptr == NULL) return;
1384
1385         safestrncpy(cmd, hptr->line, sizeof cmd);
1386         hptr = hptr->next;
1387         extract_token(request_method, cmd, 0, ' ', sizeof request_method);
1388         extract_token(pathname, cmd, 1, ' ', sizeof pathname);
1389
1390         /** Figure out the action */
1391         index[0] = action;
1392         sizes[0] = sizeof action;
1393         for (a=1; a<9; a++)
1394         {
1395                 index[a] = arg[a-1];
1396                 sizes[a] = sizeof arg[a-1];
1397         }
1398 ////    index[9] = &foo; todo
1399         nBackDots = 0;
1400         nEmpty = 0;
1401         for ( a = 0; a < 9; ++a)
1402         {
1403                 extract_token(index[a], pathname, a + 1, '/', sizes[a]);
1404                 if (strstr(index[a], "?")) *strstr(index[a], "?") = 0;
1405                 if (strstr(index[a], "&")) *strstr(index[a], "&") = 0;
1406                 if (strstr(index[a], " ")) *strstr(index[a], " ") = 0;
1407                 if ((index[a][0] == '.') && (index[a][1] == '.'))
1408                         nBackDots++;
1409                 if (index[a][0] == '\0')
1410                         nEmpty++;
1411         }
1412
1413         while (hptr != NULL) {
1414                 safestrncpy(buf, hptr->line, sizeof buf);
1415                 /* lprintf(9, "HTTP HEADER: %s\n", buf); */
1416                 hptr = hptr->next;
1417
1418                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
1419                         safestrncpy(cookie, &buf[15], sizeof cookie);
1420                         cookie_to_stuff(cookie, NULL,
1421                                         c_username, sizeof c_username,
1422                                         c_password, sizeof c_password,
1423                                         c_roomname, sizeof c_roomname);
1424                 }
1425                 else if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
1426                         CtdlDecodeBase64(c_httpauth_string, &buf[21], strlen(&buf[21]));
1427                         extract_token(c_httpauth_user, c_httpauth_string, 0, ':', sizeof c_httpauth_user);
1428                         extract_token(c_httpauth_pass, c_httpauth_string, 1, ':', sizeof c_httpauth_pass);
1429                 }
1430                 else if (!strncasecmp(buf, "Content-length: ", 16)) {
1431                         ContentLength = atoi(&buf[16]);
1432                 }
1433                 else if (!strncasecmp(buf, "Content-type: ", 14)) {
1434                         safestrncpy(ContentType, &buf[14], sizeof ContentType);
1435                 }
1436                 else if (!strncasecmp(buf, "User-agent: ", 12)) {
1437                         safestrncpy(user_agent, &buf[12], sizeof user_agent);
1438                         if (is_mobile_ua(&buf[12])) {
1439                                 WC->is_mobile = 1;
1440                         }
1441                 }
1442                 else if (!strncasecmp(buf, "X-Forwarded-Host: ", 18)) {
1443                         if (follow_xff) {
1444                                 safestrncpy(WC->http_host, &buf[18], sizeof WC->http_host);
1445                         }
1446                 }
1447                 else if (!strncasecmp(buf, "Host: ", 6)) {
1448                         if (IsEmptyStr(WC->http_host)) {
1449                                 safestrncpy(WC->http_host, &buf[6], sizeof WC->http_host);
1450                         }
1451                 }
1452                 else if (!strncasecmp(buf, "X-Forwarded-For: ", 17)) {
1453                         safestrncpy(browser_host, &buf[17], sizeof browser_host);
1454                         while (num_tokens(browser_host, ',') > 1) {
1455                                 remove_token(browser_host, 0, ',');
1456                         }
1457                         striplt(browser_host);
1458                 }
1459         }
1460
1461         if (ContentLength > 0) {
1462                 int BuffSize;
1463
1464                 BuffSize = ContentLength + SIZ;
1465                 content = malloc(BuffSize);
1466                 memset(content, 0, BuffSize);
1467                 snprintf(content,  BuffSize, "Content-type: %s\n"
1468                                 "Content-length: %d\n\n",
1469                                 ContentType, ContentLength);
1470                 body_start = strlen(content);
1471
1472                 /** Read the entire input data at once. */
1473                 client_read(WC->http_sock, &content[body_start], ContentLength);
1474
1475                 if (!strncasecmp(ContentType, "application/x-www-form-urlencoded", 33)) {
1476                         addurls(&content[body_start], ContentLength);
1477                 } else if (!strncasecmp(ContentType, "multipart", 9)) {
1478                         content_end = content + ContentLength + body_start;
1479                         mime_parser(content, content_end, *upload_handler, NULL, NULL, NULL, 0);
1480                 }
1481         } else {
1482                 content = NULL;
1483         }
1484
1485         /* make a note of where we are in case the user wants to save it */
1486         safestrncpy(WC->this_page, cmd, sizeof(WC->this_page));
1487         remove_token(WC->this_page, 2, ' ');
1488         remove_token(WC->this_page, 0, ' ');
1489
1490         /* If there are variables in the URL, we must grab them now */
1491         len = strlen(cmd);
1492         for (a = 0; a < len; ++a) {
1493                 if ((cmd[a] == '?') || (cmd[a] == '&')) {
1494                         for (b = a; b < len; ++b) {
1495                                 if (isspace(cmd[b])){
1496                                         cmd[b] = 0;
1497                                         len = b - 1;
1498                                 }
1499                         }
1500                         addurls(&cmd[a + 1], len - a);
1501                         cmd[a] = 0;
1502                         len = a - 1;
1503                 }
1504         }
1505
1506         /* If it's a "force 404" situation then display the error and bail. */
1507         if (!strcmp(action, "404")) {
1508                 wprintf("HTTP/1.1 404 Not found\r\n");
1509                 wprintf("Content-Type: text/plain\r\n");
1510                 wprintf("\r\n");
1511                 wprintf("Not found\r\n");
1512                 goto SKIP_ALL_THIS_CRAP;
1513         }
1514
1515         /* Static content can be sent without connecting to Citadel. */
1516         is_static = 0;
1517         for (a=0; a<ndirs; ++a) {
1518                 if (!strcasecmp(action, (char*)static_content_dirs[a])) { /* map web to disk location */
1519                         is_static = 1;
1520                         n_static = a;
1521                 }
1522         }
1523         if (is_static) {
1524                 if (nBackDots < 2)
1525                 {
1526                         snprintf(buf, sizeof buf, "%s/%s/%s/%s/%s/%s/%s/%s",
1527                                  static_dirs[n_static], 
1528                                  index[1], index[2], index[3], index[4], index[5], index[6], index[7]);
1529                         for (a=0; a<8; ++a) {
1530                                 if (buf[strlen(buf)-1] == '/') {
1531                                         buf[strlen(buf)-1] = 0;
1532                                 }
1533                         }
1534                         for (a = 0; a < strlen(buf); ++a) {
1535                                 if (isspace(buf[a])) {
1536                                         buf[a] = 0;
1537                                 }
1538                         }
1539                         output_static(buf);
1540                 }
1541                 else 
1542                 {
1543                         lprintf(9, "Suspicious request. Ignoring.");
1544                         wprintf("HTTP/1.1 404 Security check failed\r\n");
1545                         wprintf("Content-Type: text/plain\r\n");
1546                         wprintf("\r\n");
1547                         wprintf("You have sent a malformed or invalid request.\r\n");
1548                 }
1549                 goto SKIP_ALL_THIS_CRAP;        /* Don't try to connect */
1550         }
1551
1552         /* If the client sent a nonce that is incorrect, kill the request. */
1553         if (strlen(bstr("nonce")) > 0) {
1554                 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n", 
1555                         bstr("nonce"), WC->nonce);
1556                 if (ibstr("nonce") != WC->nonce) {
1557                         lprintf(9, "Ignoring request with mismatched nonce.\n");
1558                         wprintf("HTTP/1.1 404 Security check failed\r\n");
1559                         wprintf("Content-Type: text/plain\r\n");
1560                         wprintf("\r\n");
1561                         wprintf("Security check failed.\r\n");
1562                         goto SKIP_ALL_THIS_CRAP;
1563                 }
1564         }
1565
1566         /*
1567          * If we're not connected to a Citadel server, try to hook up the
1568          * connection now.
1569          */
1570         if (!WC->connected) {
1571                 if (!strcasecmp(ctdlhost, "uds")) {
1572                         /* unix domain socket */
1573                         snprintf(buf, SIZ, "%s/citadel.socket", ctdlport);
1574                         WC->serv_sock = uds_connectsock(buf);
1575                 }
1576                 else {
1577                         /* tcp socket */
1578                         WC->serv_sock = tcp_connectsock(ctdlhost, ctdlport);
1579                 }
1580
1581                 if (WC->serv_sock < 0) {
1582                         do_logout();
1583                         goto SKIP_ALL_THIS_CRAP;
1584                 }
1585                 else {
1586                         WC->connected = 1;
1587                         serv_getln(buf, sizeof buf);    /** get the server welcome message */
1588
1589                         /**
1590                          * From what host is our user connecting?  Go with
1591                          * the host at the other end of the HTTP socket,
1592                          * unless we are following X-Forwarded-For: headers
1593                          * and such a header has already turned up something.
1594                          */
1595                         if ( (!follow_xff) || (strlen(browser_host) == 0) ) {
1596                                 locate_host(browser_host, WC->http_sock);
1597                         }
1598
1599                         get_serv_info(browser_host, user_agent);
1600                         if (serv_info.serv_rev_level < MINIMUM_CIT_VERSION) {
1601                                 wprintf(_("You are connected to a Citadel "
1602                                         "server running Citadel %d.%02d. \n"
1603                                         "In order to run this version of WebCit "
1604                                         "you must also have Citadel %d.%02d or"
1605                                         " newer.\n\n\n"),
1606                                                 serv_info.serv_rev_level / 100,
1607                                                 serv_info.serv_rev_level % 100,
1608                                                 MINIMUM_CIT_VERSION / 100,
1609                                                 MINIMUM_CIT_VERSION % 100
1610                                         );
1611                                 end_webcit_session();
1612                                 goto SKIP_ALL_THIS_CRAP;
1613                         }
1614                 }
1615         }
1616
1617         /*
1618          * Functions which can be performed without logging in
1619          */
1620         if (!strcasecmp(action, "listsub")) {
1621                 do_listsub();
1622                 goto SKIP_ALL_THIS_CRAP;
1623         }
1624         if (!strcasecmp(action, "freebusy")) {
1625                 do_freebusy(cmd);
1626                 goto SKIP_ALL_THIS_CRAP;
1627         }
1628
1629         /*
1630          * If we're not logged in, but we have HTTP Authentication data,
1631          * try logging in to Citadel using that.
1632          */
1633         if ((!WC->logged_in)
1634            && (strlen(c_httpauth_user) > 0)
1635            && (strlen(c_httpauth_pass) > 0)) {
1636                 serv_printf("USER %s", c_httpauth_user);
1637                 serv_getln(buf, sizeof buf);
1638                 if (buf[0] == '3') {
1639                         serv_printf("PASS %s", c_httpauth_pass);
1640                         serv_getln(buf, sizeof buf);
1641                         if (buf[0] == '2') {
1642                                 become_logged_in(c_httpauth_user,
1643                                                 c_httpauth_pass, buf);
1644                                 safestrncpy(WC->httpauth_user, c_httpauth_user, sizeof WC->httpauth_user);
1645                                 safestrncpy(WC->httpauth_pass, c_httpauth_pass, sizeof WC->httpauth_pass);
1646                         } else {
1647                                 /* Should only display when password is wrong */
1648                                 authorization_required(&buf[4]);
1649                                 goto SKIP_ALL_THIS_CRAP;
1650                         }
1651                 }
1652         }
1653
1654         /* This needs to run early */
1655 #ifdef TECH_PREVIEW
1656         if (!strcasecmp(action, "rss")) {
1657                 display_rss(bstr("room"), request_method);
1658                 goto SKIP_ALL_THIS_CRAP;
1659         }
1660 #endif
1661
1662         /* 
1663          * The GroupDAV stuff relies on HTTP authentication instead of
1664          * our session's authentication.
1665          */
1666         if (!strncasecmp(action, "groupdav", 8)) {
1667                 groupdav_main(req, ContentType, /* do GroupDAV methods */
1668                         ContentLength, content+body_start);
1669                 if (!WC->logged_in) {
1670                         WC->killthis = 1;       /* If not logged in, don't */
1671                 }                               /* keep the session active */
1672                 goto SKIP_ALL_THIS_CRAP;
1673         }
1674
1675
1676         /*
1677          * Automatically send requests with any method other than GET or
1678          * POST to the GroupDAV code as well.
1679          */
1680         if ((strcasecmp(request_method, "GET")) && (strcasecmp(request_method, "POST"))) {
1681                 groupdav_main(req, ContentType, /** do GroupDAV methods */
1682                         ContentLength, content+body_start);
1683                 if (!WC->logged_in) {
1684                         WC->killthis = 1;       /** If not logged in, don't */
1685                 }                               /** keep the session active */
1686                 goto SKIP_ALL_THIS_CRAP;
1687         }
1688
1689         /*
1690          * If we're not logged in, but we have username and password cookies
1691          * supplied by the browser, try using them to log in.
1692          */
1693         if ((!WC->logged_in)
1694            && (!IsEmptyStr(c_username))
1695            && (!IsEmptyStr(c_password))) {
1696                 serv_printf("USER %s", c_username);
1697                 serv_getln(buf, sizeof buf);
1698                 if (buf[0] == '3') {
1699                         serv_printf("PASS %s", c_password);
1700                         serv_getln(buf, sizeof buf);
1701                         if (buf[0] == '2') {
1702                                 become_logged_in(c_username, c_password, buf);
1703                         }
1704                 }
1705         }
1706         /*
1707          * If we don't have a current room, but a cookie specifying the
1708          * current room is supplied, make an effort to go there.
1709          */
1710         if ((IsEmptyStr(WC->wc_roomname)) && (!IsEmptyStr(c_roomname))) {
1711                 serv_printf("GOTO %s", c_roomname);
1712                 serv_getln(buf, sizeof buf);
1713                 if (buf[0] == '2') {
1714                         safestrncpy(WC->wc_roomname, c_roomname, sizeof WC->wc_roomname);
1715                 }
1716         }
1717
1718         if (!strcasecmp(action, "image")) {
1719                 output_image();
1720         } else if (!strcasecmp(action, "display_mime_icon")) {
1721                 display_mime_icon();
1722
1723         /*
1724          * All functions handled below this point ... make sure we log in
1725          * before doing anything else!
1726          */
1727         } else if ((!WC->logged_in) && (!strcasecmp(action, "login"))) {
1728                 do_login();
1729         } else if ((!WC->logged_in) && (!strcasecmp(action, "display_openid_login"))) {
1730                 display_openid_login(NULL);
1731         } else if ((!WC->logged_in) && (!strcasecmp(action, "openid_login"))) {
1732                 do_openid_login();
1733         } else if (!strcasecmp(action, "finalize_openid_login")) {
1734                 finalize_openid_login();
1735         } else if (!strcasecmp(action, "openid_manual_create")) {
1736                 openid_manual_create();
1737         } else if (!WC->logged_in) {
1738                 display_login(NULL);
1739         }
1740
1741         /*
1742          * Various commands...
1743          */
1744
1745         else {
1746                 void *vHandler;
1747                 WebcitHandler *Handler;
1748
1749                 GetHash(HandlerHash, action, strlen(action) /* TODO*/, &vHandler),
1750                         Handler = (WebcitHandler*) vHandler;
1751                 if (Handler != NULL) {
1752                         if (Handler->IsAjax)
1753                                 begin_ajax_response();
1754                         Handler->F();
1755                         if (Handler->IsAjax)
1756                                 end_ajax_response();
1757                 }
1758                 
1759
1760         else if (!strcasecmp(action, "do_welcome")) {
1761                 do_welcome();
1762         } else if (!strcasecmp(action, "blank")) {
1763                 blank_page();
1764         } else if (!strcasecmp(action, "do_template")) {
1765                 url_do_template();
1766         } else if (!strcasecmp(action, "display_aide_menu")) {
1767                 display_aide_menu();
1768         } else if (!strcasecmp(action, "server_shutdown")) {
1769                 display_shutdown();
1770         } else if (!strcasecmp(action, "display_main_menu")) {
1771                 display_main_menu();
1772         } else if (!strcasecmp(action, "who")) {
1773                 who();
1774         } else if (!strcasecmp(action, "sslg")) {
1775                 seconds_since_last_gexp();
1776         } else if (!strcasecmp(action, "who_inner_html")) {
1777                 begin_ajax_response();
1778                 who_inner_div();
1779                 end_ajax_response();
1780         } else if (!strcasecmp(action, "wholist_section")) {
1781                 begin_ajax_response();
1782                 wholist_section();
1783                 end_ajax_response();
1784         } else if (!strcasecmp(action, "new_messages_html")) {
1785                 begin_ajax_response();
1786                 new_messages_section();
1787                 end_ajax_response();
1788         } else if (!strcasecmp(action, "tasks_inner_html")) {
1789                 begin_ajax_response();
1790                 tasks_section();
1791                 end_ajax_response();
1792         } else if (!strcasecmp(action, "calendar_inner_html")) {
1793                 begin_ajax_response();
1794                 calendar_section();
1795                 end_ajax_response();
1796         } else if (!strcasecmp(action, "mini_calendar")) {
1797                 begin_ajax_response();
1798                 ajax_mini_calendar();
1799                 end_ajax_response();
1800         } else if (!strcasecmp(action, "iconbar_ajax_menu")) {
1801                 begin_ajax_response();
1802                 do_iconbar();
1803                 end_ajax_response();
1804         } else if (!strcasecmp(action, "iconbar_ajax_rooms")) {
1805                 begin_ajax_response();
1806                 do_iconbar_roomlist();
1807                 end_ajax_response();
1808         } else if (!strcasecmp(action, "knrooms")) {
1809                 knrooms();
1810         } else if (!strcasecmp(action, "gotonext")) {
1811                 slrp_highest();
1812                 gotonext();
1813         } else if (!strcasecmp(action, "skip")) {
1814                 gotonext();
1815         } else if (!strcasecmp(action, "ungoto")) {
1816                 ungoto();
1817         } else if (!strcasecmp(action, "dotgoto")) {
1818                 if (WC->wc_view != VIEW_MAILBOX) {      /* dotgoto acts like dotskip when we're in a mailbox view */
1819                         slrp_highest();
1820                 }
1821                 smart_goto(bstr("room"));
1822         } else if (!strcasecmp(action, "dotskip")) {
1823                 smart_goto(bstr("room"));
1824         } else if (!strcasecmp(action, "termquit")) {
1825                 do_logout();
1826         } else if (!strcasecmp(action, "readnew")) {
1827                 readloop("readnew");
1828         } else if (!strcasecmp(action, "readold")) {
1829                 readloop("readold");
1830         } else if (!strcasecmp(action, "readfwd")) {
1831                 readloop("readfwd");
1832         } else if (!strcasecmp(action, "headers")) {
1833                 readloop("headers");
1834         } else if (!strcasecmp(action, "do_search")) {
1835                 readloop("do_search");
1836         } else if (!strcasecmp(action, "msg")) {
1837                 embed_message(index[1]);
1838         } else if (!strcasecmp(action, "printmsg")) {
1839                 print_message(index[1]);
1840         } else if (!strcasecmp(action, "msgheaders")) {
1841                 display_headers(index[1]);
1842         } else if (!strcasecmp(action, "vcardphoto")) {
1843                 display_vcard_photo_img(index[1]);      
1844         } else if (!strcasecmp(action, "wiki")) {
1845                 display_wiki_page();
1846         } else if (!strcasecmp(action, "display_enter")) {
1847                 display_enter();
1848         } else if (!strcasecmp(action, "post")) {
1849                 post_message();
1850         } else if (!strcasecmp(action, "move_msg")) {
1851                 move_msg();
1852         } else if (!strcasecmp(action, "delete_msg")) {
1853                 delete_msg();
1854         } else if (!strcasecmp(action, "userlist")) {
1855                 userlist();
1856         } else if (!strcasecmp(action, "showuser")) {
1857                 showuser();
1858         } else if (!strcasecmp(action, "display_page")) {
1859                 display_page();
1860         } else if (!strcasecmp(action, "page_user")) {
1861                 page_user();
1862         } else if (!strcasecmp(action, "chat")) {
1863                 do_chat();
1864         } else if (!strcasecmp(action, "display_private")) {
1865                 display_private("", 0);
1866         } else if (!strcasecmp(action, "goto_private")) {
1867                 goto_private();
1868         } else if (!strcasecmp(action, "zapped_list")) {
1869                 zapped_list();
1870         } else if (!strcasecmp(action, "display_zap")) {
1871                 display_zap();
1872         } else if (!strcasecmp(action, "zap")) {
1873                 zap();
1874         } else if (!strcasecmp(action, "display_entroom")) {
1875                 display_entroom();
1876         } else if (!strcasecmp(action, "entroom")) {
1877                 entroom();
1878         } else if (!strcasecmp(action, "display_whok")) {
1879                 display_whok();
1880         } else if (!strcasecmp(action, "do_invt_kick")) {
1881                 do_invt_kick();
1882         } else if (!strcasecmp(action, "display_editroom")) {
1883                 display_editroom();
1884         } else if (!strcasecmp(action, "netedit")) {
1885                 netedit();
1886         } else if (!strcasecmp(action, "editroom")) {
1887                 editroom();
1888         } else if (!strcasecmp(action, "display_editinfo")) {
1889                 display_edit(_("Room info"), "EINF 0", "RINF", "editinfo", 1);
1890         } else if (!strcasecmp(action, "editinfo")) {
1891                 save_edit(_("Room info"), "EINF 1", 1);
1892         } else if (!strcasecmp(action, "display_editbio")) {
1893                 snprintf(buf, SIZ, "RBIO %s", WC->wc_fullname);
1894                 display_edit(_("Your bio"), "NOOP", buf, "editbio", 3);
1895         } else if (!strcasecmp(action, "editbio")) {
1896                 save_edit(_("Your bio"), "EBIO", 0);
1897         } else if (!strcasecmp(action, "confirm_move_msg")) {
1898                 confirm_move_msg();
1899         } else if (!strcasecmp(action, "delete_room")) {
1900                 delete_room();
1901         } else if (!strcasecmp(action, "validate")) {
1902                 validate();
1903                 /* The users photo display / upload facility */
1904         } else if (!strcasecmp(action, "display_editpic")) {
1905                 display_graphics_upload(_("your photo"),
1906                                         "_userpic_",
1907                                         "editpic");
1908         } else if (!strcasecmp(action, "editpic")) {
1909                 do_graphics_upload("_userpic_");
1910                 /* room picture dispay / upload facility */
1911         } else if (!strcasecmp(action, "display_editroompic")) {
1912                 display_graphics_upload(_("the icon for this room"),
1913                                         "_roompic_",
1914                                         "editroompic");
1915         } else if (!strcasecmp(action, "editroompic")) {
1916                 do_graphics_upload("_roompic_");
1917                 /* the greetingpage hello pic */
1918         } else if (!strcasecmp(action, "display_edithello")) {
1919                 display_graphics_upload(_("the Greetingpicture for the login prompt"),
1920                                         "hello",
1921                                         "edithellopic");
1922         } else if (!strcasecmp(action, "edithellopic")) {
1923                 do_graphics_upload("hello");
1924                 /* the logoff banner */
1925         } else if (!strcasecmp(action, "display_editgoodbyepic")) {
1926                 display_graphics_upload(_("the Logoff banner picture"),
1927                                         "UIMG 0|%s|goodbuye",
1928                                         "editgoodbuyepic");
1929         } else if (!strcasecmp(action, "editgoodbuyepic")) {
1930                 do_graphics_upload("UIMG 1|%s|goodbuye");
1931
1932         } else if (!strcasecmp(action, "delete_floor")) {
1933                 delete_floor();
1934         } else if (!strcasecmp(action, "rename_floor")) {
1935                 rename_floor();
1936         } else if (!strcasecmp(action, "create_floor")) {
1937                 create_floor();
1938         } else if (!strcasecmp(action, "display_editfloorpic")) {
1939                 snprintf(buf, SIZ, "UIMG 0|_floorpic_|%s",
1940                         bstr("which_floor"));
1941                 display_graphics_upload(_("the icon for this floor"),
1942                                         buf,
1943                                         "editfloorpic");
1944         } else if (!strcasecmp(action, "editfloorpic")) {
1945                 snprintf(buf, SIZ, "UIMG 1|_floorpic_|%s",
1946                         bstr("which_floor"));
1947                 do_graphics_upload(buf);
1948         } else if (!strcasecmp(action, "display_reg")) {
1949                 display_reg(0);
1950         } else if (!strcasecmp(action, "display_changepw")) {
1951                 display_changepw();
1952         } else if (!strcasecmp(action, "changepw")) {
1953                 changepw();
1954         } else if (!strcasecmp(action, "display_edit_node")) {
1955                 display_edit_node();
1956         } else if (!strcasecmp(action, "edit_node")) {
1957                 edit_node();
1958         } else if (!strcasecmp(action, "display_netconf")) {
1959                 display_netconf();
1960         } else if (!strcasecmp(action, "display_confirm_delete_node")) {
1961                 display_confirm_delete_node();
1962         } else if (!strcasecmp(action, "delete_node")) {
1963                 delete_node();
1964         } else if (!strcasecmp(action, "display_add_node")) {
1965                 display_add_node();
1966         } else if (!strcasecmp(action, "terminate_session")) {
1967                 slrp_highest();
1968                 terminate_session();
1969         } else if (!strcasecmp(action, "edit_me")) {
1970                 edit_me();
1971         } else if (!strcasecmp(action, "display_siteconfig")) {
1972                 display_siteconfig();
1973         } else if (!strcasecmp(action, "chat_recv")) {
1974                 chat_recv();
1975         } else if (!strcasecmp(action, "chat_send")) {
1976                 chat_send();
1977         } else if (!strcasecmp(action, "siteconfig")) {
1978                 siteconfig();
1979         } else if (!strcasecmp(action, "display_generic")) {
1980                 display_generic();
1981         } else if (!strcasecmp(action, "do_generic")) {
1982                 do_generic();
1983         } else if (!strcasecmp(action, "ajax_servcmd")) {
1984                 ajax_servcmd();
1985         } else if (!strcasecmp(action, "display_menubar")) {
1986                 display_menubar(1);
1987         } else if (!strcasecmp(action, "mimepart")) {
1988                 mimepart(index[1], index[2], 0);
1989         } else if (!strcasecmp(action, "mimepart_download")) {
1990                 mimepart(index[1], index[2], 1);
1991         } else if (!strcasecmp(action, "edit_vcard")) {
1992                 edit_vcard();
1993         } else if (!strcasecmp(action, "submit_vcard")) {
1994                 submit_vcard();
1995         } else if (!strcasecmp(action, "select_user_to_edit")) {
1996                 select_user_to_edit(NULL, NULL);
1997         } else if (!strcasecmp(action, "display_edituser")) {
1998                 display_edituser(NULL, 0);
1999         } else if (!strcasecmp(action, "edituser")) {
2000                 edituser();
2001         } else if (!strcasecmp(action, "create_user")) {
2002                 create_user();
2003         } else if (!strcasecmp(action, "changeview")) {
2004                 change_view();
2005         } else if (!strcasecmp(action, "change_start_page")) {
2006                 change_start_page();
2007         } else if (!strcasecmp(action, "display_floorconfig")) {
2008                 display_floorconfig(NULL);
2009         } else if (!strcasecmp(action, "toggle_self_service")) {
2010                 toggle_self_service();
2011         } else if (!strcasecmp(action, "display_edit_task")) {
2012                 display_edit_task();
2013         } else if (!strcasecmp(action, "save_task")) {
2014                 save_task();
2015         } else if (!strcasecmp(action, "display_edit_event")) {
2016                 display_edit_event();
2017         } else if (!strcasecmp(action, "save_event")) {
2018                 save_event();
2019         } else if (!strcasecmp(action, "respond_to_request")) {
2020                 respond_to_request();
2021         } else if (!strcasecmp(action, "handle_rsvp")) {
2022                 handle_rsvp();
2023         } else if (!strcasecmp(action, "summary")) {
2024                 summary();
2025         } else if (!strcasecmp(action, "summary_inner_div")) {
2026                 begin_ajax_response();
2027                 summary_inner_div();
2028                 end_ajax_response();
2029         } else if (!strcasecmp(action, "display_customize_iconbar")) {
2030                 display_customize_iconbar();
2031         } else if (!strcasecmp(action, "commit_iconbar")) {
2032                 commit_iconbar();
2033         } else if (!strcasecmp(action, "set_room_policy")) {
2034                 set_room_policy();
2035         } else if (!strcasecmp(action, "display_inetconf")) {
2036                 display_inetconf();
2037         } else if (!strcasecmp(action, "save_inetconf")) {
2038                 save_inetconf();
2039         } else if (!strcasecmp(action, "display_smtpqueue")) {
2040                 display_smtpqueue();
2041         } else if (!strcasecmp(action, "display_smtpqueue_inner_div")) {
2042                 display_smtpqueue_inner_div();
2043         } else if (!strcasecmp(action, "display_sieve")) {
2044                 display_sieve();
2045         } else if (!strcasecmp(action, "save_sieve")) {
2046                 save_sieve();
2047         } else if (!strcasecmp(action, "display_pushemail")) {
2048                 display_pushemail();
2049         } else if (!strcasecmp(action, "save_pushemail")) {
2050                 save_pushemail();
2051         } else if (!strcasecmp(action, "display_add_remove_scripts")) {
2052                 display_add_remove_scripts(NULL);
2053         } else if (!strcasecmp(action, "create_script")) {
2054                 create_script();
2055         } else if (!strcasecmp(action, "delete_script")) {
2056                 delete_script();
2057         } else if (!strcasecmp(action, "setup_wizard")) {
2058                 do_setup_wizard();
2059         } else if (!strcasecmp(action, "display_preferences")) {
2060                 display_preferences();
2061         } else if (!strcasecmp(action, "set_preferences")) {
2062                 set_preferences();
2063         } else if (!strcasecmp(action, "recp_autocomplete")) {
2064                 recp_autocomplete(bstr("recp"));
2065         } else if (!strcasecmp(action, "cc_autocomplete")) {
2066                 recp_autocomplete(bstr("cc"));
2067         } else if (!strcasecmp(action, "bcc_autocomplete")) {
2068                 recp_autocomplete(bstr("bcc"));
2069         } else if (!strcasecmp(action, "display_address_book_middle_div")) {
2070                 display_address_book_middle_div();
2071         } else if (!strcasecmp(action, "display_address_book_inner_div")) {
2072                 display_address_book_inner_div();
2073         } else if (!strcasecmp(action, "set_floordiv_expanded")) {
2074                 set_floordiv_expanded(index[1]);
2075         } else if (!strcasecmp(action, "diagnostics")) {
2076                 output_headers(1, 1, 1, 0, 0, 0);
2077                 wprintf("Session: %d<hr />\n", WC->wc_session);
2078                 wprintf("Command: <br /><PRE>\n");
2079                 escputs(cmd);
2080                 wprintf("</PRE><hr />\n");
2081                 wprintf("Variables: <br /><PRE>\n");
2082                 dump_vars();
2083                 wprintf("</PRE><hr />\n");
2084                 wDumpContent(1);
2085         } else if (!strcasecmp(action, "add_new_note")) {
2086                 add_new_note();
2087         } else if (!strcasecmp(action, "ajax_update_note")) {
2088                 ajax_update_note();
2089         } else if (!strcasecmp(action, "display_room_directory")) {
2090                 display_room_directory();
2091         } else if (!strcasecmp(action, "display_pictureview")) {
2092                 display_pictureview();
2093         } else if (!strcasecmp(action, "download_file")) {
2094                 download_file(index[1]);
2095         } else if (!strcasecmp(action, "upload_file")) {
2096                 upload_file();
2097         } else if (!strcasecmp(action, "display_openids")) {
2098                 display_openids();
2099         } else if (!strcasecmp(action, "openid_attach")) {
2100                 openid_attach();
2101         } else if (!strcasecmp(action, "openid_detach")) {
2102                 openid_detach();
2103         }
2104
2105         /* When all else fais, display the main menu. */
2106         else {
2107                 display_main_menu();
2108         }
2109 }
2110 SKIP_ALL_THIS_CRAP:
2111         fflush(stdout);
2112         if (content != NULL) {
2113                 free(content);
2114                 content = NULL;
2115         }
2116         free_urls();
2117         if (WC->upload_length > 0) {
2118                 free(WC->upload);
2119                 WC->upload_length = 0;
2120         }
2121 }
2122
2123
2124 /*
2125  * Replacement for sleep() that uses select() in order to avoid SIGALRM
2126  */
2127 void sleeeeeeeeeep(int seconds)
2128 {
2129         struct timeval tv;
2130
2131         tv.tv_sec = seconds;
2132         tv.tv_usec = 0;
2133         select(0, NULL, NULL, NULL, &tv);
2134 }
2135
2136