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