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