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