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