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