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