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