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