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