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