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