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