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