* upsi. its used elsewhere too.
[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 addurls(StrBuf *url)
99 {
100         const char *aptr, *bptr, *eptr, *up;
101 ///     char *buf;
102         int len, keylen;
103         urlcontent *u;
104         struct wcsession *WCC = WC;
105
106         if (WCC->urlstrings == NULL)
107                 WCC->urlstrings = NewHash(1, NULL);
108 //      buf = (char*) malloc (ulen + 1);
109 //      memcpy(buf, url, ulen);
110 ///     buf[ulen] = '\0';
111         eptr = ChrPtr(url) + StrLength(url);
112         up = ChrPtr(url);
113         while ((up < eptr) && (!IsEmptyStr(up))) {
114                 aptr = up;
115                 while ((aptr < eptr) && (*aptr != '\0') && (*aptr != '='))
116                         aptr++;
117                 if (*aptr != '=') {
118                         ///free(buf);
119                         return;
120                 }
121                 ///*aptr = '\0';
122                 aptr++;
123                 bptr = aptr;
124                 while ((bptr < eptr) && (*bptr != '\0')
125                       && (*bptr != '&') && (*bptr != '?') && (*bptr != ' ')) {
126                         bptr++;
127                 }
128                 //*bptr = '\0';
129                 keylen = aptr - up - 1; /* -1 -> '=' */
130                 if(keylen > sizeof(u->url_key)) {
131                         lprintf(1, "URLkey to long! [%s]", up);
132                         continue;
133                 }
134
135                 u = (urlcontent *) malloc(sizeof(urlcontent));
136                 memcpy(u->url_key, up, keylen);
137                 u->url_key[keylen] = '\0';
138                 if (keylen < 0) {
139                         lprintf(1, "URLkey to long! [%s]", up);
140                         free(u);
141                         continue;
142                 }
143
144                 Put(WCC->urlstrings, u->url_key, keylen, u, free_url);
145                 len = bptr - aptr;
146                 u->url_data = NewStrBufPlain(aptr, len);
147                 StrBufUnescape(u->url_data, 1);
148              
149                 up = bptr;
150                 ++up;
151 #ifdef DEBUG_URLSTRINGS
152                 lprintf(9, "%s = [%ld]  %s\n", u->url_key, u->url_data_size, ChrPtr(u->url_data)); 
153 #endif
154         }
155         //free(buf);
156 }
157
158 /*
159  * free urlstring memory
160  */
161 void free_urls(void)
162 {
163         DeleteHash(&WC->urlstrings);
164 }
165
166 /*
167  * Diagnostic function to display the contents of all variables
168  */
169
170 void dump_vars(void)
171 {
172         struct wcsession *WCC = WC;
173         urlcontent *u;
174         void *U;
175         long HKLen;
176         const char *HKey;
177         HashPos *Cursor;
178         
179         Cursor = GetNewHashPos ();
180         while (GetNextHashPos(WCC->urlstrings, Cursor, &HKLen, &HKey, &U)) {
181                 u = (urlcontent*) U;
182                 wprintf("%38s = %s\n", u->url_key, ChrPtr(u->url_data));
183         }
184 }
185
186 /*
187  * Return the value of a variable supplied to the current web page (from the url or a form)
188  */
189
190 const char *XBstr(char *key, size_t keylen, size_t *len)
191 {
192         void *U;
193
194         if ((WC->urlstrings != NULL) && 
195             GetHash(WC->urlstrings, key, keylen, &U)) {
196                 *len = StrLength(((urlcontent *)U)->url_data);
197                 return ChrPtr(((urlcontent *)U)->url_data);
198         }
199         else {
200                 *len = 0;
201                 return ("");
202         }
203 }
204
205 const char *XBSTR(char *key, size_t *len)
206 {
207         void *U;
208
209         if ((WC->urlstrings != NULL) &&
210             GetHash(WC->urlstrings, key, strlen (key), &U)){
211                 *len = StrLength(((urlcontent *)U)->url_data);
212                 return ChrPtr(((urlcontent *)U)->url_data);
213         }
214         else {
215                 *len = 0;
216                 return ("");
217         }
218 }
219
220
221 const char *BSTR(char *key)
222 {
223         void *U;
224
225         if ((WC->urlstrings != NULL) &&
226             GetHash(WC->urlstrings, key, strlen (key), &U))
227                 return ChrPtr(((urlcontent *)U)->url_data);
228         else    
229                 return ("");
230 }
231
232 const char *Bstr(char *key, size_t keylen)
233 {
234         void *U;
235
236         if ((WC->urlstrings != NULL) && 
237             GetHash(WC->urlstrings, key, keylen, &U))
238                 return ChrPtr(((urlcontent *)U)->url_data);
239         else    
240                 return ("");
241 }
242
243 const StrBuf *SBSTR(const char *key)
244 {
245         void *U;
246
247         if ((WC->urlstrings != NULL) &&
248             GetHash(WC->urlstrings, key, strlen (key), &U))
249                 return ((urlcontent *)U)->url_data;
250         else    
251                 return NULL;
252 }
253
254 const StrBuf *SBstr(const char *key, size_t keylen)
255 {
256         void *U;
257
258         if ((WC->urlstrings != NULL) && 
259             GetHash(WC->urlstrings, key, keylen, &U))
260                 return ((urlcontent *)U)->url_data;
261         else    
262                 return NULL;
263 }
264
265 long LBstr(char *key, size_t keylen)
266 {
267         void *U;
268
269         if ((WC->urlstrings != NULL) && 
270             GetHash(WC->urlstrings, key, keylen, &U))
271                 return StrTol(((urlcontent *)U)->url_data);
272         else    
273                 return (0);
274 }
275
276 long LBSTR(char *key)
277 {
278         void *U;
279
280         if ((WC->urlstrings != NULL) && 
281             GetHash(WC->urlstrings, key, strlen(key), &U))
282                 return StrTol(((urlcontent *)U)->url_data);
283         else    
284                 return (0);
285 }
286
287 int IBstr(char *key, size_t keylen)
288 {
289         void *U;
290
291         if ((WC->urlstrings != NULL) && 
292             GetHash(WC->urlstrings, key, keylen, &U))
293                 return StrTol(((urlcontent *)U)->url_data);
294         else    
295                 return (0);
296 }
297
298 int IBSTR(char *key)
299 {
300         void *U;
301
302         if ((WC->urlstrings != NULL) && 
303             GetHash(WC->urlstrings, key, strlen(key), &U))
304                 return StrToi(((urlcontent *)U)->url_data);
305         else    
306                 return (0);
307 }
308
309 int HaveBstr(char *key, size_t keylen)
310 {
311         void *U;
312
313         if ((WC->urlstrings != NULL) && 
314             GetHash(WC->urlstrings, key, keylen, &U))
315                 return (StrLength(((urlcontent *)U)->url_data) != 0);
316         else    
317                 return (0);
318 }
319
320 int HAVEBSTR(char *key)
321 {
322         void *U;
323
324         if ((WC->urlstrings != NULL) && 
325             GetHash(WC->urlstrings, key, strlen(key), &U))
326                 return (StrLength(((urlcontent *)U)->url_data) != 0);
327         else    
328                 return (0);
329 }
330
331
332 int YesBstr(char *key, size_t keylen)
333 {
334         void *U;
335
336         if ((WC->urlstrings != NULL) && 
337             GetHash(WC->urlstrings, key, keylen, &U))
338                 return strcmp( ChrPtr(((urlcontent *)U)->url_data), "yes") == 0;
339         else    
340                 return (0);
341 }
342
343 int YESBSTR(char *key)
344 {
345         void *U;
346
347         if ((WC->urlstrings != NULL) && 
348             GetHash(WC->urlstrings, key, strlen(key), &U))
349                 return strcmp( ChrPtr(((urlcontent *)U)->url_data), "yes") == 0;
350         else    
351                 return (0);
352 }
353
354 /*
355  * web-printing funcion. uses our vsnprintf wrapper
356  */
357 void wprintf(const char *format,...)
358 {
359         struct wcsession *WCC = WC;
360         va_list arg_ptr;
361
362         if (WCC->WBuf == NULL)
363                 WCC->WBuf = NewStrBuf();
364
365         va_start(arg_ptr, format);
366         StrBufVAppendPrintf(WCC->WBuf, format, arg_ptr);
367         va_end(arg_ptr);
368
369 ///     if (StrLength(WCC-WBuf) > 2048)
370                 ///client_write(wbuf, strlen(wbuf));
371 }
372
373 /*
374  * http-header-printing funcion. uses our vsnprintf wrapper
375  */
376 void hprintf(const char *format,...)
377 {
378         struct wcsession *WCC = WC;
379         va_list arg_ptr;
380
381         va_start(arg_ptr, format);
382         StrBufVAppendPrintf(WCC->HBuf, format, arg_ptr);
383         va_end(arg_ptr);
384
385 ///     if (StrLength(WCC-WBuf) > 2048)
386                 ///client_write(wbuf, strlen(wbuf));
387 }
388
389
390 /*
391  * wrap up an HTTP session, closes tags, etc.
392  *
393  * print_standard_html_footer should be set to:
394  * 0 to transmit only,
395  * 1 to append the main menu and closing tags,
396  * 2 to append the closing tags only.
397  */
398 void wDumpContent(int print_standard_html_footer)
399 {
400         if (print_standard_html_footer) {
401                 wprintf("</div>\n");    /* end of "text" div */
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 = NewStrBuf();
615
616         StrMsgEscAppend(OutBuf, NULL, strbuf);
617         StrEscAppend(WC->WBuf, OutBuf, NULL, 0, 0);
618 }
619
620 /*
621  * print a string to the client after cleaning it with msgesc()
622  */
623 void msgescputs(char *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
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         output_headers(0, 0, 0, 0, 0, is_static);
763
764         hprintf("Content-type: %s\r\n"
765                 "Server: %s\r\n"
766                 "Connection: close\r\n",
767                 content_type,
768                 PACKAGE_STRING);
769
770         end_burst();
771 }
772
773 /*
774  * print menu box like used in the floor view or admin interface.
775  * This function takes pair of strings as va_args, 
776  * Title        Title string of the box
777  * Class        CSS Class for the box
778  * nLines       How many string pairs should we print? (URL, UrlText)
779  * ...          Pairs of URL Strings and their Names
780  */
781 void print_menu_box(char* Title, char *Class, int nLines, ...)
782 {
783         va_list arg_list;
784         long i;
785         
786         svput("BOXTITLE", WCS_STRING, Title);
787         do_template("beginbox", NULL);
788         
789         wprintf("<ul class=\"%s\">", Class);
790         
791         va_start(arg_list, nLines);
792         for (i = 0; i < nLines; ++i)
793         { 
794                 wprintf("<li><a href=\"%s\">", va_arg(arg_list, char *));
795                 wprintf((char *) va_arg(arg_list, char *));
796                 wprintf("</a></li>\n");
797         }
798         va_end (arg_list);
799         
800         wprintf("</a></li>\n");
801         
802         wprintf("</ul>");
803         
804         do_template("endbox", NULL);
805 }
806
807
808 /*
809  * dump out static pages from disk
810  */
811 void output_static(char *what)
812 {
813         int fd;
814         struct stat statbuf;
815         off_t bytes;
816         off_t count = 0;
817         const char *content_type;
818         int len;
819         const char *Err;
820
821         fd = open(what, O_RDONLY);
822         if (fd <= 0) {
823                 lprintf(9, "output_static('%s')  -- NOT FOUND --\n", what);
824                 hprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
825                 hprintf("Content-Type: text/plain\r\n");
826                 wprintf("Cannot open %s: %s\r\n", what, strerror(errno));
827                 end_burst();
828         } else {
829                 len = strlen (what);
830                 content_type = GuessMimeByFilename(what, len);
831
832                 if (fstat(fd, &statbuf) == -1) {
833                         lprintf(9, "output_static('%s')  -- FSTAT FAILED --\n", what);
834                         hprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
835                         hprintf("Content-Type: text/plain\r\n");
836                         wprintf("Cannot fstat %s: %s\n", what, strerror(errno));
837                         end_burst();
838                         return;
839                 }
840
841                 count = 0;
842                 bytes = statbuf.st_size;
843
844                 if (StrBufReadBLOB(WC->WBuf, &fd, 1, bytes, &Err) < 0)
845                 {
846                         if (fd > 0) close(fd);
847                         lprintf(9, "output_static('%s')  -- FREAD FAILED (%s) --\n", what, strerror(errno));
848                                 hprintf("HTTP/1.1 500 internal server error \r\n");
849                                 hprintf("Content-Type: text/plain\r\n");
850                                 end_burst();
851                                 return;
852                 }
853
854
855                 close(fd);
856                 lprintf(9, "output_static('%s')  %s\n", what, content_type);
857                 http_transmit_thing(content_type, 1);
858         }
859         if (yesbstr("force_close_session")) {
860                 end_webcit_session();
861         }
862 }
863
864 /*
865  * When the browser requests an image file from the Citadel server,
866  * this function is called to transmit it.
867  */
868 void output_image()
869 {
870         struct wcsession *WCC = WC;
871         char buf[SIZ];
872         off_t bytes;
873         const char *MimeType;
874         
875         serv_printf("OIMG %s|%s", bstr("name"), bstr("parm"));
876         serv_getln(buf, sizeof buf);
877         if (buf[0] == '2') {
878                 bytes = extract_long(&buf[4], 0);
879
880                 /** Read it from the server */
881                 
882                 if (read_server_binary(WCC->WBuf, bytes) > 0) {
883                         serv_puts("CLOS");
884                         serv_getln(buf, sizeof buf);
885                 
886                         MimeType = GuessMimeType (ChrPtr(WCC->WBuf), StrLength(WCC->WBuf));
887                         /** Write it to the browser */
888                         if (!IsEmptyStr(MimeType))
889                         {
890                                 http_transmit_thing(MimeType, 0);
891                                 return;
892                         }
893                 }
894                 /* hm... unknown mimetype? fallback to blank gif */
895         } 
896
897         
898         /*
899          * Instead of an ugly 404, send a 1x1 transparent GIF
900          * when there's no such image on the server.
901          */
902         char blank_gif[SIZ];
903         snprintf (blank_gif, SIZ, "%s%s", static_dirs[0], "/blank.gif");
904         output_static(blank_gif);
905 }
906
907 /*
908  * Extract an embedded photo from a vCard for display on the client
909  */
910 void display_vcard_photo_img(void)
911 {
912         long msgnum = 0L;
913         char *vcard;
914         struct vCard *v;
915         char *photosrc;
916         const char *contentType;
917         struct wcsession *WCC = WC;
918
919         msgnum = StrTol(WCC->UrlFragment1);
920         
921         vcard = load_mimepart(msgnum,"1");
922         v = vcard_load(vcard);
923         
924         photosrc = vcard_get_prop(v, "PHOTO", 1,0,0);
925         FlushStrBuf(WCC->WBuf);
926         StrBufAppendBufPlain(WCC->WBuf, photosrc, -1, 0);
927         if (StrBufDecodeBase64(WCC->WBuf) <= 0) {
928                 FlushStrBuf(WCC->WBuf);
929                 
930                 hprintf("HTTP/1.1 500 %s\n","Unable to get photo");
931                 output_headers(0, 0, 0, 0, 0, 0);
932                 hprintf("Content-Type: text/plain\r\n");
933                 wprintf(_("Could Not decode vcard photo\n"));
934                 end_burst();
935                 return;
936         }
937         contentType = GuessMimeType(ChrPtr(WCC->WBuf), StrLength(WCC->WBuf));
938         http_transmit_thing(contentType, 0);
939         free(v);
940         free(photosrc);
941 }
942
943 /*
944  * Generic function to output an arbitrary MIME part from an arbitrary
945  * message number on the server.
946  *
947  * msgnum               Number of the item on the citadel server
948  * partnum              The MIME part to be output
949  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
950  */
951 void mimepart(const char *msgnum, const char *partnum, int force_download)
952 {
953         char buf[256];
954         off_t bytes;
955         char content_type[256];
956         char *content = NULL;
957         
958         serv_printf("OPNA %s|%s", msgnum, partnum);
959         serv_getln(buf, sizeof buf);
960         if (buf[0] == '2') {
961                 bytes = extract_long(&buf[4], 0);
962                 content = malloc(bytes + 2);
963                 if (force_download) {
964                         strcpy(content_type, "application/octet-stream");
965                 }
966                 else {
967                         extract_token(content_type, &buf[4], 3, '|', sizeof content_type);
968                 }
969                 output_headers(0, 0, 0, 0, 0, 0);
970
971                 read_server_binary(WC->WBuf, bytes);
972                 serv_puts("CLOS");
973                 serv_getln(buf, sizeof buf);
974                 http_transmit_thing(content_type, 0);
975         } else {
976                 hprintf("HTTP/1.1 404 %s\n", &buf[4]);
977                 output_headers(0, 0, 0, 0, 0, 0);
978                 hprintf("Content-Type: text/plain\r\n");
979                 wprintf(_("An error occurred while retrieving this part: %s\n"), &buf[4]);
980                 end_burst();
981         }
982
983 }
984
985
986 /*
987  * Read any MIME part of a message, from the server, into memory.
988  */
989 char *load_mimepart(long msgnum, char *partnum)
990 {
991         char buf[SIZ];
992         off_t bytes;
993         char content_type[SIZ];
994         char *content;
995         
996         serv_printf("DLAT %ld|%s", msgnum, partnum);
997         serv_getln(buf, sizeof buf);
998         if (buf[0] == '6') {
999                 bytes = extract_long(&buf[4], 0);
1000                 extract_token(content_type, &buf[4], 3, '|', sizeof content_type);
1001
1002                 content = malloc(bytes + 2);
1003                 serv_read(content, bytes);
1004
1005                 content[bytes] = 0;     /* null terminate for good measure */
1006                 return(content);
1007         }
1008         else {
1009                 return(NULL);
1010         }
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         DoTemplate(ChrPtr(Tmpl), StrLength(Tmpl), NULL, NULL);
1054         end_burst();
1055 }
1056
1057
1058
1059 /*
1060  * Offer to make any page the user's "start page."
1061  */
1062 void offer_start_page(void) {
1063         wprintf("<a href=\"change_start_page?startpage=");
1064         urlescputs(WC->this_page);
1065         wprintf("\">");
1066         wprintf(_("Make this my start page"));
1067         wprintf("</a>");
1068 #ifdef TECH_PREVIEW
1069         wprintf("<br/><a href=\"rss?room=");
1070         urlescputs(WC->wc_roomname);
1071         wprintf("\" title=\"RSS 2.0 feed for ");
1072         escputs(WC->wc_roomname);
1073         wprintf("\"><img alt=\"RSS\" border=\"0\" src=\"static/xml_button.gif\"/></a>\n");
1074 #endif
1075 }
1076
1077
1078 /*
1079  * Change the user's start page
1080  */
1081 void change_start_page(void) {
1082
1083         if (bstr("startpage") == NULL) {
1084                 safestrncpy(WC->ImportantMessage,
1085                         _("You no longer have a start page selected."),
1086                         sizeof WC->ImportantMessage);
1087                 display_main_menu();
1088                 return;
1089         }
1090
1091         set_preference("startpage", NewStrBufPlain(bstr("startpage"), -1), 1);
1092
1093         output_headers(1, 1, 0, 0, 0, 0);
1094         do_template("newstartpage", NULL);
1095         wDumpContent(1);
1096 }
1097
1098
1099
1100 /*
1101  * convenience function to indicate success
1102  */
1103 void display_success(char *successmessage)
1104 {
1105         convenience_page("007700", "OK", successmessage);
1106 }
1107
1108
1109 /*
1110  * Authorization required page 
1111  * This is probably temporary and should be revisited 
1112  */
1113 void authorization_required(const char *message)
1114 {
1115         hprintf("HTTP/1.1 401 Authorization Required\r\n");
1116         hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", serv_info.serv_humannode);
1117         hprintf("Content-Type: text/html\r\n");
1118         wprintf("<h1>");
1119         wprintf(_("Authorization Required"));
1120         wprintf("</h1>\r\n");
1121         wprintf(_("The resource you requested requires a valid username and password. "
1122                 "You could not be logged in: %s\n"), message);
1123         wDumpContent(0);
1124         
1125 }
1126
1127 /*
1128  * This function is called by the MIME parser to handle data uploaded by
1129  * the browser.  Form data, uploaded files, and the data from HTTP PUT
1130  * operations (such as those found in GroupDAV) all arrive this way.
1131  *
1132  * name         Name of the item being uploaded
1133  * filename     Filename of the item being uploaded
1134  * partnum      MIME part identifier (not needed)
1135  * disp         MIME content disposition (not needed)
1136  * content      The actual data
1137  * cbtype       MIME content-type
1138  * cbcharset    Character set
1139  * length       Content length
1140  * encoding     MIME encoding type (not needed)
1141  * userdata     Not used here
1142  */
1143 void upload_handler(char *name, char *filename, char *partnum, char *disp,
1144                         void *content, char *cbtype, char *cbcharset,
1145                         size_t length, char *encoding, void *userdata)
1146 {
1147         urlcontent *u;
1148 #ifdef DEBUG_URLSTRINGS
1149         lprintf(9, "upload_handler() name=%s, type=%s, len=%d\n", name, cbtype, length);
1150 #endif
1151         if (WC->urlstrings == NULL)
1152                 WC->urlstrings = NewHash(1, NULL);
1153
1154         /* Form fields */
1155         if ( (length > 0) && (IsEmptyStr(cbtype)) ) {
1156                 u = (urlcontent *) malloc(sizeof(urlcontent));
1157                 
1158                 safestrncpy(u->url_key, name, sizeof(u->url_key));
1159                 u->url_data = NewStrBufPlain(content, length);
1160                 
1161                 Put(WC->urlstrings, u->url_key, strlen(u->url_key), u, free_url);
1162 #ifdef DEBUG_URLSTRINGS
1163                 lprintf(9, "Key: <%s> len: [%ld] Data: <%s>\n", u->url_key, u->url_data_size, u->url_data);
1164 #endif
1165         }
1166
1167         /** Uploaded files */
1168         if ( (length > 0) && (!IsEmptyStr(cbtype)) ) {
1169                 WC->upload = malloc(length);
1170                 if (WC->upload != NULL) {
1171                         WC->upload_length = length;
1172                         safestrncpy(WC->upload_filename, filename,
1173                                         sizeof(WC->upload_filename));
1174                         safestrncpy(WC->upload_content_type, cbtype,
1175                                         sizeof(WC->upload_content_type));
1176                         memcpy(WC->upload, content, length);
1177                 }
1178                 else {
1179                         lprintf(3, "malloc() failed: %s\n", strerror(errno));
1180                 }
1181         }
1182
1183 }
1184
1185 /*
1186  * Convenience functions to wrap around asynchronous ajax responses
1187  */
1188 void begin_ajax_response(void) {
1189         output_headers(0, 0, 0, 0, 0, 0);
1190
1191         hprintf("Content-type: text/html; charset=UTF-8\r\n"
1192                 "Server: %s\r\n"
1193                 "Connection: close\r\n"
1194                 "Pragma: no-cache\r\n"
1195                 "Cache-Control: no-cache\r\n"
1196                 "Expires: -1\r\n"
1197                 ,
1198                 PACKAGE_STRING);
1199         begin_burst();
1200 }
1201
1202 /*
1203  * print ajax response footer 
1204  */
1205 void end_ajax_response(void) {
1206         ///hprintf("\r\n");///// todo: is this right?
1207         wDumpContent(0);
1208 }
1209
1210 /*
1211  * Wraps a Citadel server command in an AJAX transaction.
1212  */
1213 void ajax_servcmd(void)
1214 {
1215         char buf[1024];
1216         char gcontent[1024];
1217         char *junk;
1218         size_t len;
1219
1220         begin_ajax_response();
1221
1222         serv_printf("%s", bstr("g_cmd"));
1223         serv_getln(buf, sizeof buf);
1224         wprintf("%s\n", buf);
1225
1226         if (buf[0] == '8') {
1227                 serv_printf("\n\n000");
1228         }
1229         if ((buf[0] == '1') || (buf[0] == '8')) {
1230                 while (serv_getln(gcontent, sizeof gcontent), strcmp(gcontent, "000")) {
1231                         wprintf("%s\n", gcontent);
1232                 }
1233                 wprintf("000");
1234         }
1235         if (buf[0] == '4') {
1236                 text_to_server(bstr("g_input"));
1237                 serv_puts("000");
1238         }
1239         if (buf[0] == '6') {
1240                 len = atol(&buf[4]);
1241                 junk = malloc(len);
1242                 serv_read(junk, len);
1243                 free(junk);
1244         }
1245         if (buf[0] == '7') {
1246                 len = atol(&buf[4]);
1247                 junk = malloc(len);
1248                 memset(junk, 0, len);
1249                 serv_write(junk, len);
1250                 free(junk);
1251         }
1252
1253         end_ajax_response();
1254         
1255         /*
1256          * This is kind of an ugly hack, but this is the only place it can go.
1257          * If the command was GEXP, then the instant messenger window must be
1258          * running, so reset the "last_pager_check" watchdog timer so
1259          * that page_popup() doesn't try to open it a second time.
1260          */
1261         if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
1262                 WC->last_pager_check = time(NULL);
1263         }
1264 }
1265
1266
1267 /*
1268  * Helper function for the asynchronous check to see if we need
1269  * to open the instant messenger window.
1270  */
1271 void seconds_since_last_gexp(void)
1272 {
1273         char buf[256];
1274
1275         begin_ajax_response();
1276         if ( (time(NULL) - WC->last_pager_check) < 30) {
1277                 wprintf("NO\n");
1278         }
1279         else {
1280                 serv_puts("NOOP");
1281                 serv_getln(buf, sizeof buf);
1282                 if (buf[3] == '*') {
1283                         wprintf("YES");
1284                 }
1285                 else {
1286                         wprintf("NO");
1287                 }
1288         }
1289         end_ajax_response();
1290 }
1291
1292 /**
1293  * \brief Detects a 'mobile' user agent 
1294  */
1295 int is_mobile_ua(char *user_agent) {
1296       if (strstr(user_agent,"iPhone OS") != NULL) {
1297         return 1;
1298       } else if (strstr(user_agent,"Windows CE") != NULL) {
1299         return 1;
1300       } else if (strstr(user_agent,"SymbianOS") != NULL) {
1301         return 1;
1302       } else if (strstr(user_agent, "Opera Mobi") != NULL) {
1303         return 1;
1304       } else if (strstr(user_agent, "Firefox/2.0.0 Opera 9.51 Beta") != NULL) {
1305                  // For some reason a new install of Opera 9.51beta decided to spoof.
1306           return 1;
1307           }
1308       return 0;
1309 }
1310
1311
1312 /*
1313  * Entry point for WebCit transaction
1314  */
1315 void session_loop(struct httprequest *req)
1316 {
1317         char cmd[1024];
1318         char action[1024];
1319         char arg[8][128];
1320         size_t sizes[10];
1321         char *index[10];
1322         char buf[SIZ];
1323         char request_method[128];
1324         char pathname[1024];
1325         int a, b, nBackDots, nEmpty;
1326         int ContentLength = 0;
1327         char ContentType[512];
1328         char *content = NULL;
1329         char *content_end = NULL;
1330         struct httprequest *hptr;
1331         char browser_host[256];
1332         char user_agent[256];
1333         int body_start = 0;
1334         int is_static = 0;
1335         int n_static = 0;
1336         int len = 0;
1337         /*
1338          * We stuff these with the values coming from the client cookies,
1339          * so we can use them to reconnect a timed out session if we have to.
1340          */
1341         char c_username[SIZ];
1342         char c_password[SIZ];
1343         char c_roomname[SIZ];
1344         char c_httpauth_string[SIZ];
1345         char c_httpauth_user[SIZ];
1346         char c_httpauth_pass[SIZ];
1347         char cookie[SIZ];
1348         struct wcsession *WCC;
1349         
1350         safestrncpy(c_username, "", sizeof c_username);
1351         safestrncpy(c_password, "", sizeof c_password);
1352         safestrncpy(c_roomname, "", sizeof c_roomname);
1353         safestrncpy(c_httpauth_string, "", sizeof c_httpauth_string);
1354         safestrncpy(c_httpauth_user, DEFAULT_HTTPAUTH_USER, sizeof c_httpauth_user);
1355         safestrncpy(c_httpauth_pass, DEFAULT_HTTPAUTH_PASS, sizeof c_httpauth_pass);
1356         strcpy(browser_host, "");
1357
1358         WCC= WC;
1359         if (WCC->WBuf == NULL)
1360                 WC->WBuf = NewStrBufPlain(NULL, 32768);
1361         FlushStrBuf(WCC->WBuf);
1362
1363         if (WCC->HBuf == NULL)
1364                 WCC->HBuf = NewStrBuf();
1365         FlushStrBuf(WCC->HBuf);
1366
1367         WCC->upload_length = 0;
1368         WCC->upload = NULL;
1369         WCC->is_mobile = 0;
1370
1371         hptr = req;
1372         if (hptr == NULL) return;
1373
1374         safestrncpy(cmd, hptr->line, sizeof cmd);
1375         hptr = hptr->next;
1376         extract_token(request_method, cmd, 0, ' ', sizeof request_method);
1377         extract_token(pathname, cmd, 1, ' ', sizeof pathname);
1378
1379         /** Figure out the action */
1380         index[0] = action;
1381         sizes[0] = sizeof action;
1382         for (a=1; a<9; a++)
1383         {
1384                 index[a] = arg[a-1];
1385                 sizes[a] = sizeof arg[a-1];
1386         }
1387 ////    index[9] = &foo; todo
1388         nBackDots = 0;
1389         nEmpty = 0;
1390         for ( a = 0; a < 9; ++a)
1391         {
1392                 extract_token(index[a], pathname, a + 1, '/', sizes[a]);
1393                 if (strstr(index[a], "?")) *strstr(index[a], "?") = 0;
1394                 if (strstr(index[a], "&")) *strstr(index[a], "&") = 0;
1395                 if (strstr(index[a], " ")) *strstr(index[a], " ") = 0;
1396                 if ((index[a][0] == '.') && (index[a][1] == '.'))
1397                         nBackDots++;
1398                 if (index[a][0] == '\0')
1399                         nEmpty++;
1400         }
1401
1402         while (hptr != NULL) {
1403                 safestrncpy(buf, hptr->line, sizeof buf);
1404                 /* lprintf(9, "HTTP HEADER: %s\n", buf); */
1405                 hptr = hptr->next;
1406
1407                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
1408                         safestrncpy(cookie, &buf[15], sizeof cookie);
1409                         cookie_to_stuff(cookie, NULL,
1410                                         c_username, sizeof c_username,
1411                                         c_password, sizeof c_password,
1412                                         c_roomname, sizeof c_roomname);
1413                 }
1414                 else if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
1415                         CtdlDecodeBase64(c_httpauth_string, &buf[21], strlen(&buf[21]));
1416                         extract_token(c_httpauth_user, c_httpauth_string, 0, ':', sizeof c_httpauth_user);
1417                         extract_token(c_httpauth_pass, c_httpauth_string, 1, ':', sizeof c_httpauth_pass);
1418                 }
1419                 else if (!strncasecmp(buf, "Content-length: ", 16)) {
1420                         ContentLength = atoi(&buf[16]);
1421                 }
1422                 else if (!strncasecmp(buf, "Content-type: ", 14)) {
1423                         safestrncpy(ContentType, &buf[14], sizeof ContentType);
1424                 }
1425                 else if (!strncasecmp(buf, "User-agent: ", 12)) {
1426                         safestrncpy(user_agent, &buf[12], sizeof user_agent);
1427                         #ifdef TECH_PREVIEW
1428                         if (is_mobile_ua(&buf[12])) {
1429                                 WCC->is_mobile = 1;
1430                         }
1431                         #endif
1432                 }
1433                 else if (!strncasecmp(buf, "X-Forwarded-Host: ", 18)) {
1434                         if (follow_xff) {
1435                                 safestrncpy(WCC->http_host, &buf[18], sizeof WCC->http_host);
1436                         }
1437                 }
1438                 else if (!strncasecmp(buf, "Host: ", 6)) {
1439                         if (IsEmptyStr(WCC->http_host)) {
1440                                 safestrncpy(WCC->http_host, &buf[6], sizeof WCC->http_host);
1441                         }
1442                 }
1443                 else if (!strncasecmp(buf, "X-Forwarded-For: ", 17)) {
1444                         safestrncpy(browser_host, &buf[17], sizeof browser_host);
1445                         while (num_tokens(browser_host, ',') > 1) {
1446                                 remove_token(browser_host, 0, ',');
1447                         }
1448                         striplt(browser_host);
1449                 }
1450         }
1451
1452         if (ContentLength > 0) {
1453                 int BuffSize;
1454
1455                 BuffSize = ContentLength + SIZ;
1456                 content = malloc(BuffSize);
1457                 memset(content, 0, BuffSize);
1458                 hprintf("Content-type: %s\n"
1459                         "Content-length: %d\n\n",
1460                         ContentType, ContentLength);
1461                 body_start = strlen(content);
1462
1463                 /** Read the entire input data at once. */
1464                 client_read(WCC->http_sock, &content[body_start], ContentLength);
1465
1466                 if (!strncasecmp(ContentType, "application/x-www-form-urlencoded", 33)) {
1467                         StrBuf *Content;
1468
1469                         Content = _NewConstStrBuf(&content[body_start],ContentLength);
1470                         addurls(Content);
1471                         FreeStrBuf(&Content);
1472                 } else if (!strncasecmp(ContentType, "multipart", 9)) {
1473                         content_end = content + ContentLength + body_start;
1474                         mime_parser(content, content_end, *upload_handler, NULL, NULL, NULL, 0);
1475                 }
1476         } else {
1477                 content = NULL;
1478         }
1479
1480         /* make a note of where we are in case the user wants to save it */
1481         safestrncpy(WCC->this_page, cmd, sizeof(WCC->this_page));
1482         remove_token(WCC->this_page, 2, ' ');
1483         remove_token(WCC->this_page, 0, ' ');
1484
1485         /* If there are variables in the URL, we must grab them now */
1486         len = strlen(cmd);
1487         for (a = 0; a < len; ++a) {
1488                 if ((cmd[a] == '?') || (cmd[a] == '&')) {
1489                         StrBuf *Params;
1490                         for (b = a; b < len; ++b) {
1491                                 if (isspace(cmd[b])){
1492                                         cmd[b] = 0;
1493                                         len = b - 1;
1494                                 }
1495                         }
1496                         //cmd[len - a] = '\0';
1497                         Params = _NewConstStrBuf(&cmd[a + 1], len - a);
1498                         addurls(Params);
1499                         cmd[a] = 0;
1500                         len = a - 1;
1501                 }
1502         }
1503
1504         /* If it's a "force 404" situation then display the error and bail. */
1505         if (!strcmp(action, "404")) {
1506                 hprintf("HTTP/1.1 404 Not found\r\n");
1507                 hprintf("Content-Type: text/plain\r\n");
1508                 wprintf("Not found\r\n");
1509                 end_burst();
1510                 goto SKIP_ALL_THIS_CRAP;
1511         }
1512
1513         /* Static content can be sent without connecting to Citadel. */
1514         is_static = 0;
1515         for (a=0; a<ndirs; ++a) {
1516                 if (!strcasecmp(action, (char*)static_content_dirs[a])) { /* map web to disk location */
1517                         is_static = 1;
1518                         n_static = a;
1519                 }
1520         }
1521         if (is_static) {
1522                 if (nBackDots < 2)
1523                 {
1524                         snprintf(buf, sizeof buf, "%s/%s/%s/%s/%s/%s/%s/%s",
1525                                  static_dirs[n_static], 
1526                                  index[1], index[2], index[3], index[4], index[5], index[6], index[7]);
1527                         for (a=0; a<8; ++a) {
1528                                 if (buf[strlen(buf)-1] == '/') {
1529                                         buf[strlen(buf)-1] = 0;
1530                                 }
1531                         }
1532                         for (a = 0; a < strlen(buf); ++a) {
1533                                 if (isspace(buf[a])) {
1534                                         buf[a] = 0;
1535                                 }
1536                         }
1537                         output_static(buf);
1538                 }
1539                 else 
1540                 {
1541                         lprintf(9, "Suspicious request. Ignoring.");
1542                         hprintf("HTTP/1.1 404 Security check failed\r\n");
1543                         hprintf("Content-Type: text/plain\r\n");
1544                         wprintf("You have sent a malformed or invalid request.\r\n");
1545                         end_burst();
1546                 }
1547                 goto SKIP_ALL_THIS_CRAP;        /* Don't try to connect */
1548         }
1549
1550         /* If the client sent a nonce that is incorrect, kill the request. */
1551         if (strlen(bstr("nonce")) > 0) {
1552                 lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n", 
1553                         bstr("nonce"), WCC->nonce);
1554                 if (ibstr("nonce") != WCC->nonce) {
1555                         lprintf(9, "Ignoring request with mismatched nonce.\n");
1556                         hprintf("HTTP/1.1 404 Security check failed\r\n");
1557                         hprintf("Content-Type: text/plain\r\n");
1558                         wprintf("Security check failed.\r\n");
1559                         end_burst();
1560                         goto SKIP_ALL_THIS_CRAP;
1561                 }
1562         }
1563
1564         /*
1565          * If we're not connected to a Citadel server, try to hook up the
1566          * connection now.
1567          */
1568         if (!WCC->connected) {
1569                 if (!strcasecmp(ctdlhost, "uds")) {
1570                         /* unix domain socket */
1571                         snprintf(buf, SIZ, "%s/citadel.socket", ctdlport);
1572                         WCC->serv_sock = uds_connectsock(buf);
1573                 }
1574                 else {
1575                         /* tcp socket */
1576                         WCC->serv_sock = tcp_connectsock(ctdlhost, ctdlport);
1577                 }
1578
1579                 if (WCC->serv_sock < 0) {
1580                         do_logout();
1581                         goto SKIP_ALL_THIS_CRAP;
1582                 }
1583                 else {
1584                         WCC->connected = 1;
1585                         serv_getln(buf, sizeof buf);    /** get the server welcome message */
1586
1587                         /**
1588                          * From what host is our user connecting?  Go with
1589                          * the host at the other end of the HTTP socket,
1590                          * unless we are following X-Forwarded-For: headers
1591                          * and such a header has already turned up something.
1592                          */
1593                         if ( (!follow_xff) || (strlen(browser_host) == 0) ) {
1594                                 locate_host(browser_host, WCC->http_sock);
1595                         }
1596
1597                         get_serv_info(browser_host, user_agent);
1598                         if (serv_info.serv_rev_level < MINIMUM_CIT_VERSION) {
1599                                 wprintf(_("You are connected to a Citadel "
1600                                         "server running Citadel %d.%02d. \n"
1601                                         "In order to run this version of WebCit "
1602                                         "you must also have Citadel %d.%02d or"
1603                                         " newer.\n\n\n"),
1604                                                 serv_info.serv_rev_level / 100,
1605                                                 serv_info.serv_rev_level % 100,
1606                                                 MINIMUM_CIT_VERSION / 100,
1607                                                 MINIMUM_CIT_VERSION % 100
1608                                         );
1609                                 end_webcit_session();
1610                                 goto SKIP_ALL_THIS_CRAP;
1611                         }
1612                 }
1613         }
1614 ////////todo: restorte language in this case
1615         /*
1616          * Functions which can be performed without logging in
1617          */
1618         if (!strcasecmp(action, "listsub")) {
1619                 do_listsub();
1620                 goto SKIP_ALL_THIS_CRAP;
1621         }
1622         if (!strcasecmp(action, "freebusy")) {
1623                 do_freebusy(cmd);
1624                 goto SKIP_ALL_THIS_CRAP;
1625         }
1626
1627         /*
1628          * If we're not logged in, but we have HTTP Authentication data,
1629          * try logging in to Citadel using that.
1630          */
1631         if ((!WCC->logged_in)
1632            && (strlen(c_httpauth_user) > 0)
1633            && (strlen(c_httpauth_pass) > 0)) {
1634                 serv_printf("USER %s", c_httpauth_user);
1635                 serv_getln(buf, sizeof buf);
1636                 if (buf[0] == '3') {
1637                         serv_printf("PASS %s", c_httpauth_pass);
1638                         serv_getln(buf, sizeof buf);
1639                         if (buf[0] == '2') {
1640                                 become_logged_in(c_httpauth_user,
1641                                                 c_httpauth_pass, buf);
1642                                 safestrncpy(WCC->httpauth_user, c_httpauth_user, sizeof WCC->httpauth_user);
1643                                 safestrncpy(WCC->httpauth_pass, c_httpauth_pass, sizeof WCC->httpauth_pass);
1644                         } else {
1645                                 /* Should only display when password is wrong */
1646                                 authorization_required(&buf[4]);
1647                                 goto SKIP_ALL_THIS_CRAP;
1648                         }
1649                 }
1650         }
1651
1652         /* This needs to run early */
1653 #ifdef TECH_PREVIEW
1654         if (!strcasecmp(action, "rss")) {
1655                 display_rss(bstr("room"), request_method);
1656                 goto SKIP_ALL_THIS_CRAP;
1657         }
1658 #endif
1659
1660         /* 
1661          * The GroupDAV stuff relies on HTTP authentication instead of
1662          * our session's authentication.
1663          */
1664         if (!strncasecmp(action, "groupdav", 8)) {
1665                 groupdav_main(req, ContentType, /* do GroupDAV methods */
1666                         ContentLength, content+body_start);
1667                 if (!WCC->logged_in) {
1668                         WCC->killthis = 1;      /* If not logged in, don't */
1669                 }                               /* keep the session active */
1670                 goto SKIP_ALL_THIS_CRAP;
1671         }
1672
1673
1674         /*
1675          * Automatically send requests with any method other than GET or
1676          * POST to the GroupDAV code as well.
1677          */
1678         if ((strcasecmp(request_method, "GET")) && (strcasecmp(request_method, "POST"))) {
1679                 groupdav_main(req, 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                 free(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         escputs(WC->UrlFragment1);
1792         wprintf("<br />\n");
1793         escputs(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 void 
1814 InitModule_WEBCIT
1815 (void)
1816 {
1817         WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS);
1818         WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
1819         WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX);
1820         WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
1821         WebcitAddUrlHandler(HKEY("change_start_page"), change_start_page, 0);
1822         WebcitAddUrlHandler(HKEY("toggle_self_service"), toggle_self_service, 0);
1823         WebcitAddUrlHandler(HKEY("vcardphoto"), display_vcard_photo_img, NEED_URL);
1824         WebcitAddUrlHandler(HKEY("mimepart"), view_mimepart, NEED_URL);
1825         WebcitAddUrlHandler(HKEY("mimepart_download"), download_mimepart, NEED_URL);
1826         WebcitAddUrlHandler(HKEY("diagnostics"), diagnostics, NEED_URL);
1827 }