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