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