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