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