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