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