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