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