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