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