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