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