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