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