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