0c8d142c6932fdfd55f0bfd101236c06674068e9
[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 (WCC->urlstrings, 0);
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 tmplput_trailing_javascript(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *vContext, int ContextType)
386 {
387         struct wcsession *WCC = WC;
388
389         if (WCC != NULL)
390                 StrBufAppendTemplate(Target, nArgs, Tokens, vContext, ContextType,
391                                      WCC->trailing_javascript, 0);
392 }
393
394 /*
395  * wrap up an HTTP session, closes tags, etc.
396  *
397  * print_standard_html_footer should be set to:
398  * 0            - to transmit only,
399  * nonzero      - to append the closing tags
400  */
401 void wDumpContent(int print_standard_html_footer)
402 {
403         if (print_standard_html_footer) {
404                 wprintf("</div> <!-- end of 'content' div -->\n");
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                 do_template("head", NULL);
703         }
704
705         /* ICONBAR */
706         if (do_htmlhead) {
707                 begin_burst();
708
709                 /* check for ImportantMessages (these display in a div overlaying the main screen) */
710                 if (!IsEmptyStr(WC->ImportantMessage)) {
711                         wprintf("<div id=\"important_message\">\n"
712                                 "<span class=\"imsg\">");
713                         escputs(WC->ImportantMessage);
714                         wprintf("</span><br />\n"
715                                 "</div>\n"
716                                 "<script type=\"text/javascript\">\n"
717                                 "        setTimeout('hide_imsg_popup()', 5000); \n"
718                                 "</script>\n");
719                         WC->ImportantMessage[0] = 0;
720                 }
721
722                 if ( (WC->logged_in) && (!unset_cookies) ) {
723                         wprintf("<div id=\"iconbar\">");
724                         do_selected_iconbar();
725                         /** check for instant messages (these display in a new window) */
726                         page_popup();
727                         wprintf("</div>");
728                 }
729
730                 if (do_room_banner == 1) {
731                         wprintf("<div id=\"banner\">\n");
732                         embed_room_banner(NULL, navbar_default);
733                         wprintf("</div>\n");
734                 }
735         }
736
737         if (do_room_banner == 1) {
738                 wprintf("<div id=\"content\">\n");
739         }
740 }
741
742
743 /*
744  * Generic function to do an HTTP redirect.  Easy and fun.
745  */
746 void http_redirect(const char *whichpage) {
747         hprintf("HTTP/1.1 302 Moved Temporarily\n");
748         hprintf("Location: %s\r\n", whichpage);
749         hprintf("URI: %s\r\n", whichpage);
750         hprintf("Content-type: text/html; charset=utf-8\r\n");
751         wprintf("<html><body>");
752         wprintf("Go <a href=\"%s\">here</A>.", whichpage);
753         wprintf("</body></html>\n");
754         end_burst();
755 }
756
757
758
759 /*
760  * Output a piece of content to the web browser using conformant HTTP and MIME semantics
761  */
762 void http_transmit_thing(const char *content_type,
763                          int is_static) {
764
765 #ifndef TECH_PREVIEW
766         lprintf(9, "http_transmit_thing(%s)%s\n",
767                 content_type,
768                 (is_static ? " (static)" : "")
769         );
770 #endif
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("beginboxx", 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 #ifndef TECH_PREVIEW
866                 lprintf(9, "output_static('%s')  %s\n", what, content_type);
867 #endif
868                 http_transmit_thing(content_type, 1);
869         }
870         if (yesbstr("force_close_session")) {
871                 end_webcit_session();
872         }
873 }
874
875 /*
876  * When the browser requests an image file from the Citadel server,
877  * this function is called to transmit it.
878  */
879 void output_image()
880 {
881         struct wcsession *WCC = WC;
882         char buf[SIZ];
883         off_t bytes;
884         const char *MimeType;
885         
886         serv_printf("OIMG %s|%s", bstr("name"), bstr("parm"));
887         serv_getln(buf, sizeof buf);
888         if (buf[0] == '2') {
889                 bytes = extract_long(&buf[4], 0);
890
891                 /** Read it from the server */
892                 
893                 if (read_server_binary(WCC->WBuf, bytes) > 0) {
894                         serv_puts("CLOS");
895                         serv_getln(buf, sizeof buf);
896                 
897                         MimeType = GuessMimeType (ChrPtr(WCC->WBuf), StrLength(WCC->WBuf));
898                         /** Write it to the browser */
899                         if (!IsEmptyStr(MimeType))
900                         {
901                                 http_transmit_thing(MimeType, 0);
902                                 return;
903                         }
904                 }
905                 /* hm... unknown mimetype? fallback to blank gif */
906         } 
907
908         
909         /*
910          * Instead of an ugly 404, send a 1x1 transparent GIF
911          * when there's no such image on the server.
912          */
913         char blank_gif[SIZ];
914         snprintf (blank_gif, SIZ, "%s%s", static_dirs[0], "/blank.gif");
915         output_static(blank_gif);
916 }
917
918 /*
919  * Extract an embedded photo from a vCard for display on the client
920  */
921 void display_vcard_photo_img(void)
922 {
923         long msgnum = 0L;
924         char *vcard;
925         struct vCard *v;
926         char *photosrc;
927         const char *contentType;
928         struct wcsession *WCC = WC;
929
930         msgnum = StrTol(WCC->UrlFragment2);
931         
932         vcard = load_mimepart(msgnum,"1");
933         v = vcard_load(vcard);
934         
935         photosrc = vcard_get_prop(v, "PHOTO", 1,0,0);
936         FlushStrBuf(WCC->WBuf);
937         StrBufAppendBufPlain(WCC->WBuf, photosrc, -1, 0);
938         if (StrBufDecodeBase64(WCC->WBuf) <= 0) {
939                 FlushStrBuf(WCC->WBuf);
940                 
941                 hprintf("HTTP/1.1 500 %s\n","Unable to get photo");
942                 output_headers(0, 0, 0, 0, 0, 0);
943                 hprintf("Content-Type: text/plain\r\n");
944                 wprintf(_("Could Not decode vcard photo\n"));
945                 end_burst();
946                 return;
947         }
948         contentType = GuessMimeType(ChrPtr(WCC->WBuf), StrLength(WCC->WBuf));
949         http_transmit_thing(contentType, 0);
950         free(v);
951         free(photosrc);
952 }
953
954 /*
955  * Generic function to output an arbitrary MIME attachment from
956  * message being composed
957  *
958  * partnum              The MIME part to be output
959  * filename             Fake filename to give
960  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
961  */
962 void postpart(StrBuf *partnum, StrBuf *filename, int force_download)
963 {
964         void *vPart;
965         StrBuf *content_type;
966         wc_mime_attachment *part;
967         
968         if (GetHash(WC->attachments, SKEY(partnum), &vPart) &&
969             (vPart != NULL)) {
970                 part = (wc_mime_attachment*) vPart;
971                 if (force_download) {
972                         content_type = NewStrBufPlain(HKEY("application/octet-stream"));
973                 }
974                 else {
975                         content_type = NewStrBufDup(part->ContentType);
976                 }
977                 output_headers(0, 0, 0, 0, 0, 0);
978                 StrBufAppendBuf(WC->WBuf, part->Data, 0);
979                 http_transmit_thing(ChrPtr(content_type), 0);
980         } else {
981                 hprintf("HTTP/1.1 404 %s\n", ChrPtr(partnum));
982                 output_headers(0, 0, 0, 0, 0, 0);
983                 hprintf("Content-Type: text/plain\r\n");
984                 wprintf(_("An error occurred while retrieving this part: %s/%s\n"), 
985                         ChrPtr(partnum), ChrPtr(filename));
986                 end_burst();
987         }
988         FreeStrBuf(&content_type);
989 }
990
991
992 /*
993  * Generic function to output an arbitrary MIME part from an arbitrary
994  * message number on the server.
995  *
996  * msgnum               Number of the item on the citadel server
997  * partnum              The MIME part to be output
998  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
999  */
1000 void mimepart(const char *msgnum, const char *partnum, int force_download)
1001 {
1002         char buf[256];
1003         off_t bytes;
1004         char content_type[256];
1005         
1006         serv_printf("OPNA %s|%s", msgnum, partnum);
1007         serv_getln(buf, sizeof buf);
1008         if (buf[0] == '2') {
1009                 bytes = extract_long(&buf[4], 0);
1010                 if (force_download) {
1011                         strcpy(content_type, "application/octet-stream");
1012                 }
1013                 else {
1014                         extract_token(content_type, &buf[4], 3, '|', sizeof content_type);
1015                 }
1016                 output_headers(0, 0, 0, 0, 0, 0);
1017
1018                 read_server_binary(WC->WBuf, bytes);
1019                 serv_puts("CLOS");
1020                 serv_getln(buf, sizeof buf);
1021                 http_transmit_thing(content_type, 0);
1022         } else {
1023                 hprintf("HTTP/1.1 404 %s\n", &buf[4]);
1024                 output_headers(0, 0, 0, 0, 0, 0);
1025                 hprintf("Content-Type: text/plain\r\n");
1026                 wprintf(_("An error occurred while retrieving this part: %s\n"), &buf[4]);
1027                 end_burst();
1028         }
1029 }
1030
1031
1032 /*
1033  * Read any MIME part of a message, from the server, into memory.
1034  */
1035 char *load_mimepart(long msgnum, char *partnum)
1036 {
1037         char buf[SIZ];
1038         off_t bytes;
1039         char content_type[SIZ];
1040         char *content;
1041         
1042         serv_printf("DLAT %ld|%s", msgnum, partnum);
1043         serv_getln(buf, sizeof buf);
1044         if (buf[0] == '6') {
1045                 bytes = extract_long(&buf[4], 0);
1046                 extract_token(content_type, &buf[4], 3, '|', sizeof content_type);
1047
1048                 content = malloc(bytes + 2);
1049                 serv_read(content, bytes);
1050
1051                 content[bytes] = 0;     /* null terminate for good measure */
1052                 return(content);
1053         }
1054         else {
1055                 return(NULL);
1056         }
1057 }
1058
1059 /*
1060  * Read any MIME part of a message, from the server, into memory.
1061  */
1062 void MimeLoadData(wc_mime_attachment *Mime)
1063 {
1064         char buf[SIZ];
1065         off_t bytes;
1066 //// TODO: is there a chance the contenttype is different  to the one we know?  
1067         serv_printf("DLAT %ld|%s", Mime->msgnum, ChrPtr(Mime->PartNum));
1068         serv_getln(buf, sizeof buf);
1069         if (buf[0] == '6') {
1070                 bytes = extract_long(&buf[4], 0);
1071
1072                 if (Mime->Data == NULL)
1073                         Mime->Data = NewStrBufPlain(NULL, bytes);
1074                 StrBuf_ServGetBLOB(Mime->Data, bytes);
1075
1076         }
1077         else {
1078                 FlushStrBuf(Mime->Data);
1079                 /// TODO XImportant message
1080         }
1081 }
1082
1083
1084 /*
1085  * Convenience functions to display a page containing only a string
1086  *
1087  * titlebarcolor        color of the titlebar of the frame
1088  * titlebarmsg          text to display in the title bar
1089  * messagetext          body of the box
1090  */
1091 void convenience_page(char *titlebarcolor, char *titlebarmsg, char *messagetext)
1092 {
1093         hprintf("HTTP/1.1 200 OK\n");
1094         output_headers(1, 1, 2, 0, 0, 0);
1095         wprintf("<div id=\"banner\">\n");
1096         wprintf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
1097         wprintf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
1098         wprintf("</td></tr></table>\n");
1099         wprintf("</div>\n<div id=\"content\">\n");
1100         escputs(messagetext);
1101
1102         wprintf("<hr />\n");
1103         wDumpContent(1);
1104 }
1105
1106
1107 /*
1108  * Display a blank page.
1109  */
1110 void blank_page(void) {
1111         output_headers(1, 1, 0, 0, 0, 0);
1112         wDumpContent(2);
1113 }
1114
1115
1116 /*
1117  * A template has been requested
1118  */
1119 void url_do_template(void) {
1120         const StrBuf *Tmpl = sbstr("template");
1121         begin_burst();
1122         output_headers(1, 0, 0, 0, 1, 0);
1123         DoTemplate(ChrPtr(Tmpl), StrLength(Tmpl), NULL, NULL, 0);
1124         end_burst();
1125 }
1126
1127
1128
1129 /*
1130  * Offer to make any page the user's "start page."
1131  */
1132 void offer_start_page(StrBuf *Target, int nArgs, WCTemplateToken *Token, void *Context, int ContextType) {
1133         wprintf("<a href=\"change_start_page?startpage=");
1134         urlescputs(WC->this_page);
1135         wprintf("\">");
1136         wprintf(_("Make this my start page"));
1137         wprintf("</a>");
1138 #ifdef TECH_PREVIEW
1139         wprintf("<br/><a href=\"rss?room=");
1140         urlescputs(WC->wc_roomname);
1141         wprintf("\" title=\"RSS 2.0 feed for ");
1142         escputs(WC->wc_roomname);
1143         wprintf("\"><img alt=\"RSS\" border=\"0\" src=\"static/xml_button.gif\"/></a>\n");
1144 #endif
1145 }
1146
1147
1148 /*
1149  * Change the user's start page
1150  */
1151 void change_start_page(void) {
1152
1153         if (bstr("startpage") == NULL) {
1154                 safestrncpy(WC->ImportantMessage,
1155                         _("You no longer have a start page selected."),
1156                         sizeof WC->ImportantMessage);
1157                 display_main_menu();
1158                 return;
1159         }
1160
1161         set_preference("startpage", NewStrBufPlain(bstr("startpage"), -1), 1);
1162
1163         output_headers(1, 1, 0, 0, 0, 0);
1164         do_template("newstartpage", NULL);
1165         wDumpContent(1);
1166 }
1167
1168
1169
1170 /*
1171  * convenience function to indicate success
1172  */
1173 void display_success(char *successmessage)
1174 {
1175         convenience_page("007700", "OK", successmessage);
1176 }
1177
1178
1179 /*
1180  * Authorization required page 
1181  * This is probably temporary and should be revisited 
1182  */
1183 void authorization_required(const char *message)
1184 {
1185         hprintf("HTTP/1.1 401 Authorization Required\r\n");
1186         hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", serv_info.serv_humannode);
1187         hprintf("Content-Type: text/html\r\n");
1188         wprintf("<h1>");
1189         wprintf(_("Authorization Required"));
1190         wprintf("</h1>\r\n");
1191         wprintf(_("The resource you requested requires a valid username and password. "
1192                 "You could not be logged in: %s\n"), message);
1193         wDumpContent(0);
1194         
1195 }
1196
1197 /*
1198  * This function is called by the MIME parser to handle data uploaded by
1199  * the browser.  Form data, uploaded files, and the data from HTTP PUT
1200  * operations (such as those found in GroupDAV) all arrive this way.
1201  *
1202  * name         Name of the item being uploaded
1203  * filename     Filename of the item being uploaded
1204  * partnum      MIME part identifier (not needed)
1205  * disp         MIME content disposition (not needed)
1206  * content      The actual data
1207  * cbtype       MIME content-type
1208  * cbcharset    Character set
1209  * length       Content length
1210  * encoding     MIME encoding type (not needed)
1211  * cbid         Content ID (not needed)
1212  * userdata     Not used here
1213  */
1214 void upload_handler(char *name, char *filename, char *partnum, char *disp,
1215                         void *content, char *cbtype, char *cbcharset,
1216                         size_t length, char *encoding, char *cbid, void *userdata)
1217 {
1218         urlcontent *u;
1219 #ifdef DEBUG_URLSTRINGS
1220         lprintf(9, "upload_handler() name=%s, type=%s, len=%d\n", name, cbtype, length);
1221 #endif
1222         if (WC->urlstrings == NULL)
1223                 WC->urlstrings = NewHash(1, NULL);
1224
1225         /* Form fields */
1226         if ( (length > 0) && (IsEmptyStr(cbtype)) ) {
1227                 u = (urlcontent *) malloc(sizeof(urlcontent));
1228                 
1229                 safestrncpy(u->url_key, name, sizeof(u->url_key));
1230                 u->url_data = NewStrBufPlain(content, length);
1231                 
1232                 Put(WC->urlstrings, u->url_key, strlen(u->url_key), u, free_url);
1233 #ifdef DEBUG_URLSTRINGS
1234                 lprintf(9, "Key: <%s> len: [%ld] Data: <%s>\n", 
1235                         u->url_key, 
1236                         StrLength(u->url_data), 
1237                         ChrPtr(u->url_data));
1238 #endif
1239         }
1240
1241         /** Uploaded files */
1242         if ( (length > 0) && (!IsEmptyStr(cbtype)) ) {
1243                 WC->upload = malloc(length);
1244                 if (WC->upload != NULL) {
1245                         WC->upload_length = length;
1246                         safestrncpy(WC->upload_filename, filename,
1247                                         sizeof(WC->upload_filename));
1248                         safestrncpy(WC->upload_content_type, cbtype,
1249                                         sizeof(WC->upload_content_type));
1250                         memcpy(WC->upload, content, length);
1251                 }
1252                 else {
1253                         lprintf(3, "malloc() failed: %s\n", strerror(errno));
1254                 }
1255         }
1256
1257 }
1258
1259 /*
1260  * Convenience functions to wrap around asynchronous ajax responses
1261  */
1262 void begin_ajax_response(void) {
1263         struct wcsession *WCC = WC;
1264
1265         FlushStrBuf(WCC->HBuf);
1266         output_headers(0, 0, 0, 0, 0, 0);
1267
1268         hprintf("Content-type: text/html; charset=UTF-8\r\n"
1269                 "Server: %s\r\n"
1270                 "Connection: close\r\n"
1271                 ,
1272                 PACKAGE_STRING);
1273         begin_burst();
1274 }
1275
1276 /*
1277  * print ajax response footer 
1278  */
1279 void end_ajax_response(void) {
1280         wDumpContent(0);
1281 }
1282
1283 /*
1284  * Wraps a Citadel server command in an AJAX transaction.
1285  */
1286 void ajax_servcmd(void)
1287 {
1288         char buf[1024];
1289         char gcontent[1024];
1290         char *junk;
1291         size_t len;
1292
1293         begin_ajax_response();
1294
1295         serv_printf("%s", bstr("g_cmd"));
1296         serv_getln(buf, sizeof buf);
1297         wprintf("%s\n", buf);
1298
1299         if (buf[0] == '8') {
1300                 serv_printf("\n\n000");
1301         }
1302         if ((buf[0] == '1') || (buf[0] == '8')) {
1303                 while (serv_getln(gcontent, sizeof gcontent), strcmp(gcontent, "000")) {
1304                         wprintf("%s\n", gcontent);
1305                 }
1306                 wprintf("000");
1307         }
1308         if (buf[0] == '4') {
1309                 text_to_server(bstr("g_input"));
1310                 serv_puts("000");
1311         }
1312         if (buf[0] == '6') {
1313                 len = atol(&buf[4]);
1314                 junk = malloc(len);
1315                 serv_read(junk, len);
1316                 free(junk);
1317         }
1318         if (buf[0] == '7') {
1319                 len = atol(&buf[4]);
1320                 junk = malloc(len);
1321                 memset(junk, 0, len);
1322                 serv_write(junk, len);
1323                 free(junk);
1324         }
1325
1326         end_ajax_response();
1327         
1328         /*
1329          * This is kind of an ugly hack, but this is the only place it can go.
1330          * If the command was GEXP, then the instant messenger window must be
1331          * running, so reset the "last_pager_check" watchdog timer so
1332          * that page_popup() doesn't try to open it a second time.
1333          */
1334         if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
1335                 WC->last_pager_check = time(NULL);
1336         }
1337 }
1338
1339
1340 /*
1341  * Helper function for the asynchronous check to see if we need
1342  * to open the instant messenger window.
1343  */
1344 void seconds_since_last_gexp(void)
1345 {
1346         char buf[256];
1347
1348         if ( (time(NULL) - WC->last_pager_check) < 30) {
1349                 wprintf("NO\n");
1350         }
1351         else {
1352                 memset(buf, 5, 0);
1353                 serv_puts("NOOP");
1354                 serv_getln(buf, sizeof buf);
1355                 if (buf[3] == '*') {
1356                         wprintf("YES");
1357                 }
1358                 else {
1359                         wprintf("NO");
1360                 }
1361         }
1362 }
1363
1364 /**
1365  * \brief Detects a 'mobile' user agent 
1366  */
1367 int is_mobile_ua(char *user_agent) {
1368       if (strstr(user_agent,"iPhone OS") != NULL) {
1369         return 1;
1370       } else if (strstr(user_agent,"Windows CE") != NULL) {
1371         return 1;
1372       } else if (strstr(user_agent,"SymbianOS") != NULL) {
1373         return 1;
1374       } else if (strstr(user_agent, "Opera Mobi") != NULL) {
1375         return 1;
1376       } else if (strstr(user_agent, "Firefox/2.0.0 Opera 9.51 Beta") != NULL) {
1377                  // For some reason a new install of Opera 9.51beta decided to spoof.
1378           return 1;
1379           }
1380       return 0;
1381 }
1382
1383
1384 /*
1385  * Entry point for WebCit transaction
1386  */
1387 void session_loop(HashList *HTTPHeaders, StrBuf *ReqLine, StrBuf *request_method, StrBuf *ReadBuf)
1388 {
1389         const char *pch, *pchs, *pche;
1390         void *vLine;
1391         char action[1024];
1392         char arg[8][128];
1393         size_t sizes[10];
1394         char *index[10];
1395         char buf[SIZ];
1396         int a, nBackDots, nEmpty;
1397         int ContentLength = 0;
1398         StrBuf *ContentType = NULL;
1399         StrBuf *UrlLine = NULL;
1400         StrBuf *content = NULL;
1401         const char *content_end = NULL;
1402         char browser_host[256];
1403         char user_agent[256];
1404         int body_start = 0;
1405         int is_static = 0;
1406         int n_static = 0;
1407         int len = 0;
1408         /*
1409          * We stuff these with the values coming from the client cookies,
1410          * so we can use them to reconnect a timed out session if we have to.
1411          */
1412         char c_username[SIZ];
1413         char c_password[SIZ];
1414         char c_roomname[SIZ];
1415         char c_httpauth_string[SIZ];
1416         char c_httpauth_user[SIZ];
1417         char c_httpauth_pass[SIZ];
1418         struct wcsession *WCC;
1419         
1420         safestrncpy(c_username, "", sizeof c_username);
1421         safestrncpy(c_password, "", sizeof c_password);
1422         safestrncpy(c_roomname, "", sizeof c_roomname);
1423         safestrncpy(c_httpauth_string, "", sizeof c_httpauth_string);
1424         safestrncpy(c_httpauth_user, DEFAULT_HTTPAUTH_USER, sizeof c_httpauth_user);
1425         safestrncpy(c_httpauth_pass, DEFAULT_HTTPAUTH_PASS, sizeof c_httpauth_pass);
1426         strcpy(browser_host, "");
1427
1428         WCC= WC;
1429         if (WCC->WBuf == NULL)
1430                 WC->WBuf = NewStrBufPlain(NULL, 32768);
1431         FlushStrBuf(WCC->WBuf);
1432
1433         if (WCC->HBuf == NULL)
1434                 WCC->HBuf = NewStrBuf();
1435         FlushStrBuf(WCC->HBuf);
1436
1437         WCC->upload_length = 0;
1438         WCC->upload = NULL;
1439         WCC->is_mobile = 0;
1440         WCC->trailing_javascript = NewStrBuf();
1441
1442         /** Figure out the action */
1443         index[0] = action;
1444         sizes[0] = sizeof action;
1445         for (a=1; a<9; a++)
1446         {
1447                 index[a] = arg[a-1];
1448                 sizes[a] = sizeof arg[a-1];
1449         }
1450 ////    index[9] = &foo; todo
1451         nBackDots = 0;
1452         nEmpty = 0;
1453         for ( a = 0; a < 9; ++a)
1454         {
1455                 extract_token(index[a], ChrPtr(ReqLine), a + 1, '/', sizes[a]);
1456                 if (strstr(index[a], "?")) *strstr(index[a], "?") = 0;
1457                 if (strstr(index[a], "&")) *strstr(index[a], "&") = 0;
1458                 if (strstr(index[a], " ")) *strstr(index[a], " ") = 0;
1459                 if ((index[a][0] == '.') && (index[a][1] == '.'))
1460                         nBackDots++;
1461                 if (index[a][0] == '\0')
1462                         nEmpty++;
1463         }
1464
1465
1466         if (GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) && 
1467             (vLine != NULL)){
1468                 cookie_to_stuff((StrBuf *)vLine, NULL,
1469                                 c_username, sizeof c_username,
1470                                 c_password, sizeof c_password,
1471                                 c_roomname, sizeof c_roomname);
1472         }
1473         if (GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) &&
1474             (vLine!=NULL)) {
1475                 CtdlDecodeBase64(c_httpauth_string, ChrPtr((StrBuf*)vLine), StrLength((StrBuf*)vLine));
1476                 extract_token(c_httpauth_user, c_httpauth_string, 0, ':', sizeof c_httpauth_user);
1477                 extract_token(c_httpauth_pass, c_httpauth_string, 1, ':', sizeof c_httpauth_pass);
1478         }
1479         if (GetHash(HTTPHeaders, HKEY("CONTENT-LENGTH"), &vLine) &&
1480             (vLine!=NULL)) {
1481                 ContentLength = StrToi((StrBuf*)vLine);
1482         }
1483         if (GetHash(HTTPHeaders, HKEY("CONTENT-TYPE"), &vLine) &&
1484             (vLine!=NULL)) {
1485                 ContentType = (StrBuf*)vLine;
1486         }
1487         if (GetHash(HTTPHeaders, HKEY("USER-AGENT"), &vLine) &&
1488             (vLine!=NULL)) {
1489                 safestrncpy(user_agent, ChrPtr((StrBuf*)vLine), sizeof user_agent);
1490 #ifdef TECH_PREVIEW
1491                 if ((WCC->is_mobile < 0) && is_mobile_ua(&buf[12])) {                   
1492                         WCC->is_mobile = 1;
1493                 }
1494                 else {
1495                         WCC->is_mobile = 0;
1496                 }
1497 #endif
1498         }
1499         if ((follow_xff) &&
1500             GetHash(HTTPHeaders, HKEY("X-FORWARDED-HOST"), &vLine) &&
1501             (vLine != NULL)) {
1502                 safestrncpy(WCC->http_host, 
1503                             ChrPtr((StrBuf*)vLine), 
1504                             sizeof WCC->http_host);
1505         }
1506         if (IsEmptyStr(WCC->http_host) && 
1507             GetHash(HTTPHeaders, HKEY("HOST"), &vLine) &&
1508             (vLine!=NULL)) {
1509                 safestrncpy(WCC->http_host, 
1510                             ChrPtr((StrBuf*)vLine), 
1511                             sizeof WCC->http_host);
1512                 
1513         }
1514         if (GetHash(HTTPHeaders, HKEY("X-FORWARDED-FOR"), &vLine) &&
1515             (vLine!=NULL)) {
1516                 safestrncpy(browser_host, 
1517                             ChrPtr((StrBuf*) vLine), 
1518                             sizeof browser_host);
1519                 while (num_tokens(browser_host, ',') > 1) {
1520                         remove_token(browser_host, 0, ',');
1521                 }
1522                 striplt(browser_host);
1523         }
1524
1525         if (ContentLength > 0) {
1526                 content = NewStrBuf();
1527                 StrBufPrintf(content, "Content-type: %s\n"
1528                          "Content-length: %d\n\n",
1529                          ChrPtr(ContentType), ContentLength);
1530 /*
1531                 hprintf("Content-type: %s\n"
1532                         "Content-length: %d\n\n",
1533                         ContentType, ContentLength);
1534 */
1535                 body_start = StrLength(content);
1536
1537                 /** Read the entire input data at once. */
1538                 client_read(&WCC->http_sock, content, ReadBuf, ContentLength + body_start);
1539
1540                 if (!strncasecmp(ChrPtr(ContentType), "application/x-www-form-urlencoded", 33)) {
1541                         StrBufCutLeft(content, body_start);
1542                         ParseURLParams(content);
1543                 } else if (!strncasecmp(ChrPtr(ContentType), "multipart", 9)) {
1544                         content_end = ChrPtr(content) + ContentLength + body_start;
1545                         mime_parser(ChrPtr(content), content_end, *upload_handler, NULL, NULL, NULL, 0);
1546                 }
1547         } else {
1548                 content = NULL;
1549         }
1550
1551         /* make a note of where we are in case the user wants to save it */
1552         safestrncpy(WCC->this_page, ChrPtr(ReqLine), sizeof(WCC->this_page));
1553         remove_token(WCC->this_page, 2, ' ');
1554         remove_token(WCC->this_page, 0, ' ');
1555
1556         /* If there are variables in the URL, we must grab them now */
1557         UrlLine = NewStrBufDup(ReqLine);
1558         len = StrLength(UrlLine);
1559         pch = pchs = ChrPtr(UrlLine);
1560         pche = pchs + len;
1561         while (pch < pche) {
1562                 if ((*pch == '?') || (*pch == '&')) {
1563                         StrBufCutLeft(UrlLine, pch - pchs + 1);
1564                         ParseURLParams(UrlLine);
1565                         break;
1566                 }
1567                 pch ++;
1568         }
1569         FreeStrBuf(&UrlLine);
1570
1571         /* If it's a "force 404" situation then display the error and bail. */
1572         if (!strcmp(action, "404")) {
1573                 hprintf("HTTP/1.1 404 Not found\r\n");
1574                 hprintf("Content-Type: text/plain\r\n");
1575                 wprintf("Not found\r\n");
1576                 end_burst();
1577                 goto SKIP_ALL_THIS_CRAP;
1578         }
1579
1580         /* Static content can be sent without connecting to Citadel. */
1581         is_static = 0;
1582         for (a=0; a<ndirs && ! is_static; ++a) {
1583                 if (!strcasecmp(action, (char*)static_content_dirs[a])) { /* map web to disk location */
1584                         is_static = 1;
1585                         n_static = a;
1586                 }
1587         }
1588         if (is_static) {
1589                 if (nBackDots < 2)
1590                 {
1591                         snprintf(buf, sizeof buf, "%s/%s/%s/%s/%s/%s/%s/%s",
1592                                  static_dirs[n_static], 
1593                                  index[1], index[2], index[3], index[4], index[5], index[6], index[7]);
1594                         for (a=0; a<8; ++a) {
1595                                 if (buf[strlen(buf)-1] == '/') {
1596                                         buf[strlen(buf)-1] = 0;
1597                                 }
1598                         }
1599                         for (a = 0; a < strlen(buf); ++a) {
1600                                 if (isspace(buf[a])) {
1601                                         buf[a] = 0;
1602                                 }
1603                         }
1604                         output_static(buf);
1605                 }
1606                 else 
1607                 {
1608                         lprintf(9, "Suspicious request. Ignoring.");
1609                         hprintf("HTTP/1.1 404 Security check failed\r\n");
1610                         hprintf("Content-Type: text/plain\r\n");
1611                         wprintf("You have sent a malformed or invalid request.\r\n");
1612                         end_burst();
1613                 }
1614                 goto SKIP_ALL_THIS_CRAP;        /* Don't try to connect */
1615         }
1616
1617         /* If the client sent a nonce that is incorrect, kill the request. */
1618         if (strlen(bstr("nonce")) > 0) {
1619                 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n", 
1620                         bstr("nonce"), WCC->nonce);
1621                 if (ibstr("nonce") != WCC->nonce) {
1622                         lprintf(9, "Ignoring request with mismatched nonce.\n");
1623                         hprintf("HTTP/1.1 404 Security check failed\r\n");
1624                         hprintf("Content-Type: text/plain\r\n");
1625                         wprintf("Security check failed.\r\n");
1626                         end_burst();
1627                         goto SKIP_ALL_THIS_CRAP;
1628                 }
1629         }
1630
1631         /*
1632          * If we're not connected to a Citadel server, try to hook up the
1633          * connection now.
1634          */
1635         if (!WCC->connected) {
1636                 if (!strcasecmp(ctdlhost, "uds")) {
1637                         /* unix domain socket */
1638                         snprintf(buf, SIZ, "%s/citadel.socket", ctdlport);
1639                         WCC->serv_sock = uds_connectsock(buf);
1640                 }
1641                 else {
1642                         /* tcp socket */
1643                         WCC->serv_sock = tcp_connectsock(ctdlhost, ctdlport);
1644                 }
1645
1646                 if (WCC->serv_sock < 0) {
1647                         do_logout();
1648                         goto SKIP_ALL_THIS_CRAP;
1649                 }
1650                 else {
1651                         WCC->connected = 1;
1652                         serv_getln(buf, sizeof buf);    /** get the server welcome message */
1653
1654                         /**
1655                          * From what host is our user connecting?  Go with
1656                          * the host at the other end of the HTTP socket,
1657                          * unless we are following X-Forwarded-For: headers
1658                          * and such a header has already turned up something.
1659                          */
1660                         if ( (!follow_xff) || (strlen(browser_host) == 0) ) {
1661                                 locate_host(browser_host, WCC->http_sock);
1662                         }
1663
1664                         get_serv_info(browser_host, user_agent);
1665                         if (serv_info.serv_rev_level < MINIMUM_CIT_VERSION) {
1666                                 begin_burst();
1667                                 wprintf(_("You are connected to a Citadel "
1668                                         "server running Citadel %d.%02d. \n"
1669                                         "In order to run this version of WebCit "
1670                                         "you must also have Citadel %d.%02d or"
1671                                         " newer.\n\n\n"),
1672                                                 serv_info.serv_rev_level / 100,
1673                                                 serv_info.serv_rev_level % 100,
1674                                                 MINIMUM_CIT_VERSION / 100,
1675                                                 MINIMUM_CIT_VERSION % 100
1676                                         );
1677                                 end_burst();
1678                                 end_webcit_session();
1679                                 goto SKIP_ALL_THIS_CRAP;
1680                         }
1681                 }
1682         }
1683 ////////todo: restore language in this case
1684         /*
1685          * Functions which can be performed without logging in
1686          */
1687         if (!strcasecmp(action, "listsub")) {
1688                 do_listsub();
1689                 goto SKIP_ALL_THIS_CRAP;
1690         }
1691         if (!strcasecmp(action, "freebusy")) {
1692                 do_freebusy(ChrPtr(ReqLine));
1693                 goto SKIP_ALL_THIS_CRAP;
1694         }
1695
1696         /*
1697          * If we're not logged in, but we have HTTP Authentication data,
1698          * try logging in to Citadel using that.
1699          */
1700         if ((!WCC->logged_in)
1701            && (strlen(c_httpauth_user) > 0)
1702            && (strlen(c_httpauth_pass) > 0)) {
1703                 serv_printf("USER %s", c_httpauth_user);
1704                 serv_getln(buf, sizeof buf);
1705                 if (buf[0] == '3') {
1706                         serv_printf("PASS %s", c_httpauth_pass);
1707                         serv_getln(buf, sizeof buf);
1708                         if (buf[0] == '2') {
1709                                 become_logged_in(c_httpauth_user,
1710                                                 c_httpauth_pass, buf);
1711                                 safestrncpy(WCC->httpauth_user, c_httpauth_user, sizeof WCC->httpauth_user);
1712                                 safestrncpy(WCC->httpauth_pass, c_httpauth_pass, sizeof WCC->httpauth_pass);
1713                         } else {
1714                                 /* Should only display when password is wrong */
1715                                 authorization_required(&buf[4]);
1716                                 goto SKIP_ALL_THIS_CRAP;
1717                         }
1718                 }
1719         }
1720
1721         /* This needs to run early */
1722 #ifdef TECH_PREVIEW
1723         if (!strcasecmp(action, "rss")) {
1724                 display_rss(bstr("room"), request_method);
1725                 goto SKIP_ALL_THIS_CRAP;
1726         }
1727 #endif
1728
1729         /* 
1730          * The GroupDAV stuff relies on HTTP authentication instead of
1731          * our session's authentication.
1732          */
1733         if (!strncasecmp(action, "groupdav", 8)) {
1734                 groupdav_main(HTTPHeaders, 
1735                               ReqLine, request_method,
1736                               ContentType, /* do GroupDAV methods */
1737                               ContentLength, content, body_start);
1738                 if (!WCC->logged_in) {
1739                         WCC->killthis = 1;      /* If not logged in, don't */
1740                 }                               /* keep the session active */
1741                 goto SKIP_ALL_THIS_CRAP;
1742         }
1743
1744
1745         /*
1746          * Automatically send requests with any method other than GET or
1747          * POST to the GroupDAV code as well.
1748          */
1749         if ((strcasecmp(ChrPtr(request_method), "GET")) && (strcasecmp(ChrPtr(request_method), "POST"))) {
1750                 groupdav_main(HTTPHeaders, ReqLine, 
1751                               request_method, ContentType, /** do GroupDAV methods */
1752                               ContentLength, content, body_start);
1753                 if (!WCC->logged_in) {
1754                         WCC->killthis = 1;      /** If not logged in, don't */
1755                 }                               /** keep the session active */
1756                 goto SKIP_ALL_THIS_CRAP;
1757         }
1758
1759         /*
1760          * If we're not logged in, but we have username and password cookies
1761          * supplied by the browser, try using them to log in.
1762          */
1763         if ((!WCC->logged_in)
1764            && (!IsEmptyStr(c_username))
1765            && (!IsEmptyStr(c_password))) {
1766                 serv_printf("USER %s", c_username);
1767                 serv_getln(buf, sizeof buf);
1768                 if (buf[0] == '3') {
1769                         serv_printf("PASS %s", c_password);
1770                         serv_getln(buf, sizeof buf);
1771                         if (buf[0] == '2') {
1772                                 StrBuf *Lang;
1773                                 become_logged_in(c_username, c_password, buf);
1774                                 if (get_preference("language", &Lang)) {
1775                                         set_selected_language(ChrPtr(Lang));
1776                                         go_selected_language();         /* set locale */
1777                                 }
1778                                 get_preference("default_header_charset", &WCC->DefaultCharset);
1779                         }
1780                 }
1781         }
1782         /*
1783          * If we don't have a current room, but a cookie specifying the
1784          * current room is supplied, make an effort to go there.
1785          */
1786         if ((IsEmptyStr(WCC->wc_roomname)) && (!IsEmptyStr(c_roomname))) {
1787                 serv_printf("GOTO %s", c_roomname);
1788                 serv_getln(buf, sizeof buf);
1789                 if (buf[0] == '2') {
1790                         safestrncpy(WCC->wc_roomname, c_roomname, sizeof WCC->wc_roomname);
1791                 }
1792         }
1793
1794         if (!strcasecmp(action, "image")) {
1795                 output_image();
1796         } else if (!strcasecmp(action, "display_mime_icon")) {
1797                 display_mime_icon();
1798         }
1799         else {
1800                 void *vHandler;
1801                 WebcitHandler *Handler;
1802                 
1803                 GetHash(HandlerHash, action, strlen(action) /* TODO*/, &vHandler),
1804                         Handler = (WebcitHandler*) vHandler;
1805                 if (Handler != NULL) {
1806                         if (!WCC->logged_in && ((Handler->Flags & ANONYMOUS) == 0)) {
1807                                 display_login(NULL);
1808                         }
1809                         else {
1810                                 if((Handler->Flags & NEED_URL)) {
1811                                         if (WCC->UrlFragment1 == NULL)
1812                                                 WCC->UrlFragment1 = NewStrBuf();
1813                                         if (WCC->UrlFragment2 == NULL)
1814                                                 WCC->UrlFragment2 = NewStrBuf();
1815                                         if (WCC->UrlFragment3 == NULL)
1816                                                 WCC->UrlFragment3 = NewStrBuf();
1817                                         StrBufPrintf(WCC->UrlFragment1, "%s", index[0]);
1818                                         StrBufPrintf(WCC->UrlFragment2, "%s", index[1]);
1819                                         StrBufPrintf(WCC->UrlFragment3, "%s", index[2]);
1820                                 }
1821                                 if ((Handler->Flags & AJAX) != 0)
1822                                         begin_ajax_response();
1823                                 Handler->F();
1824                                 if ((Handler->Flags & AJAX) != 0)
1825                                         end_ajax_response();
1826                         }
1827                 }
1828         /* When all else fais, display the main menu. */
1829         else {
1830                 if (!WCC->logged_in) 
1831                         display_login(NULL);
1832                 else
1833                         display_main_menu();
1834         }
1835 }
1836 SKIP_ALL_THIS_CRAP:
1837         fflush(stdout);
1838         if (content != NULL) {
1839                 FreeStrBuf(&content);
1840                 content = NULL;
1841         }
1842         free_urls();
1843         if (WCC->upload_length > 0) {
1844                 free(WCC->upload);
1845                 WCC->upload_length = 0;
1846         }
1847         FreeStrBuf(&WCC->trailing_javascript);
1848 }
1849
1850
1851 /*
1852  * Replacement for sleep() that uses select() in order to avoid SIGALRM
1853  */
1854 void sleeeeeeeeeep(int seconds)
1855 {
1856         struct timeval tv;
1857
1858         tv.tv_sec = seconds;
1859         tv.tv_usec = 0;
1860         select(0, NULL, NULL, NULL, &tv);
1861 }
1862
1863 void diagnostics(void)
1864 {
1865         output_headers(1, 1, 1, 0, 0, 0);
1866         wprintf("Session: %d<hr />\n", WC->wc_session);
1867         wprintf("Command: <br /><PRE>\n");
1868         StrEscPuts(WC->UrlFragment1);
1869         wprintf("<br />\n");
1870         StrEscPuts(WC->UrlFragment2);
1871         wprintf("<br />\n");
1872         StrEscPuts(WC->UrlFragment3);
1873         wprintf("</PRE><hr />\n");
1874         wprintf("Variables: <br /><PRE>\n");
1875         dump_vars();
1876         wprintf("</PRE><hr />\n");
1877         wDumpContent(1);
1878 }
1879
1880 void view_mimepart(void) {
1881         mimepart(ChrPtr(WC->UrlFragment2),
1882                  ChrPtr(WC->UrlFragment3),
1883                  0);
1884 }
1885
1886 void download_mimepart(void) {
1887         mimepart(ChrPtr(WC->UrlFragment2),
1888                  ChrPtr(WC->UrlFragment3),
1889                  1);
1890 }
1891
1892 void view_postpart(void) {
1893         postpart(WC->UrlFragment2,
1894                  WC->UrlFragment3,
1895                  0);
1896 }
1897
1898 void download_postpart(void) {
1899         postpart(WC->UrlFragment2,
1900                  WC->UrlFragment3,
1901                  1);
1902 }
1903
1904
1905 int ConditionalImportantMesage(WCTemplateToken *Tokens, void *Context, int ContextType)
1906 {
1907         struct wcsession *WCC = WC;
1908         if (WCC != NULL)
1909                 return (!IsEmptyStr(WCC->ImportantMessage));
1910         else
1911                 return 0;
1912 }
1913
1914 void tmplput_importantmessage(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1915 {
1916         struct wcsession *WCC = WC;
1917         
1918         if (WCC != NULL) {
1919 /*
1920                 StrBufAppendTemplate(Target, nArgs, Tokens, Context, ContextType,
1921                                      WCC->ImportantMessage, 0);
1922 */
1923                 StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
1924                 WCC->ImportantMessage[0] = '\0';
1925         }
1926 }
1927
1928 int ConditionalBstr(WCTemplateToken *Tokens, void *Context, int ContextType)
1929 {
1930         if(Tokens->nParameters == 3)
1931                 return HaveBstr(Tokens->Params[2]->Start, 
1932                                 Tokens->Params[2]->len);
1933         else
1934                 return strcmp(Bstr(Tokens->Params[2]->Start, 
1935                                    Tokens->Params[2]->len),
1936                               Tokens->Params[3]->Start) == 0;
1937 }
1938
1939 void tmplput_bstr(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1940 {
1941         const StrBuf *Buf = SBstr(Tokens->Params[0]->Start, 
1942                             Tokens->Params[0]->len);
1943         if (Buf != NULL)
1944                 StrBufAppendTemplate(Target, nArgs, Tokens, 
1945                                      Context, ContextType,
1946                                      Buf, 1);
1947 }
1948
1949
1950 void tmplput_csslocal(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1951 {
1952         extern StrBuf *csslocal;
1953         StrBufAppendBuf(Target, 
1954                         csslocal, 0);
1955 }
1956
1957 void tmplput_url_part(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1958 {
1959         StrBuf *UrlBuf;
1960         struct wcsession *WCC = WC;
1961         
1962         if (WCC != NULL) {
1963                 if (Tokens->Params[0]->lvalue == 0)
1964                         UrlBuf = WCC->UrlFragment1;
1965                 else if (Tokens->Params[0]->lvalue == 1)
1966                         UrlBuf = WCC->UrlFragment2;
1967                 else
1968                         UrlBuf = WCC->UrlFragment3;
1969
1970                 StrBufAppendTemplate(Target, nArgs, Tokens, Context, ContextType,
1971                                      UrlBuf, 1);
1972         }
1973 }
1974
1975
1976
1977
1978 void 
1979 InitModule_WEBCIT
1980 (void)
1981 {
1982         WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS);
1983         WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
1984         WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX);
1985         WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
1986         WebcitAddUrlHandler(HKEY("change_start_page"), change_start_page, 0);
1987         WebcitAddUrlHandler(HKEY("toggle_self_service"), toggle_self_service, 0);
1988         WebcitAddUrlHandler(HKEY("vcardphoto"), display_vcard_photo_img, NEED_URL);
1989         WebcitAddUrlHandler(HKEY("mimepart"), view_mimepart, NEED_URL);
1990         WebcitAddUrlHandler(HKEY("mimepart_download"), download_mimepart, NEED_URL);
1991         WebcitAddUrlHandler(HKEY("postpart"), view_postpart, NEED_URL);
1992         WebcitAddUrlHandler(HKEY("postpart_download"), download_postpart, NEED_URL);
1993         WebcitAddUrlHandler(HKEY("diagnostics"), diagnostics, NEED_URL);
1994
1995         RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage, CTX_NONE);
1996         RegisterConditional(HKEY("COND:BSTR"), 1, ConditionalBstr, CTX_NONE);
1997         RegisterNamespace("BSTR", 1, 2, tmplput_bstr, CTX_NONE);
1998         RegisterNamespace("URLPART", 1, 2, tmplput_url_part, CTX_NONE);
1999         RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, CTX_NONE);
2000         RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, CTX_NONE);
2001         RegisterNamespace("OFFERSTARTPAGE", 0, 0, offer_start_page, CTX_NONE);
2002         RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, CTX_NONE);
2003 }