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