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