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