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