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