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