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