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