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