af6eedce4ab6dfc32b215927a370aee238f8131f
[citadel.git] / webcit / webcit.c
1 /*
2  * webcit.c
3  *
4  * This is the actual program called by the webserver.  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  * $Id$
9  */
10
11 #include <ctype.h>
12 #include <stdlib.h>
13 #include <unistd.h>
14 #include <stdio.h>
15 #include <fcntl.h>
16 #include <signal.h>
17 #include <sys/types.h>
18 #include <sys/wait.h>
19 #include <sys/socket.h>
20 #include <sys/time.h>
21 #include <sys/stat.h>
22 #include <limits.h>
23 #include <netinet/in.h>
24 #include <netdb.h>
25 #include <string.h>
26 #include <pwd.h>
27 #include <errno.h>
28 #include <stdarg.h>
29 #include <pthread.h>
30 #include <signal.h>
31 #include "webcit.h"
32 #include "groupdav.h"
33 #include "webserver.h"
34 #include "mime_parser.h"
35
36 /*
37  * String to unset the cookie.
38  * Any date "in the past" will work, so I chose my birthday, right down to
39  * the exact minute.  :)
40  */
41 static char *unset = "; expires=28-May-1971 18:10:00 GMT";
42
43 void unescape_input(char *buf)
44 {
45         int a, b;
46         char hex[3];
47
48         while ((isspace(buf[strlen(buf) - 1])) && (strlen(buf) > 0))
49                 buf[strlen(buf) - 1] = 0;
50
51         for (a = 0; a < strlen(buf); ++a) {
52                 if (buf[a] == '+')
53                         buf[a] = ' ';
54                 if (buf[a] == '%') {
55                         hex[0] = buf[a + 1];
56                         hex[1] = buf[a + 2];
57                         hex[2] = 0;
58                         b = 0;
59                         sscanf(hex, "%02x", &b);
60                         buf[a] = (char) b;
61                         strcpy(&buf[a + 1], &buf[a + 3]);
62                 }
63         }
64
65 }
66
67
68 void addurls(char *url)
69 {
70         char *up, *ptr;
71         char buf[SIZ];
72         int a, b;
73         struct urlcontent *u;
74
75         up = url;
76         while (strlen(up) > 0) {
77
78                 /* locate the = sign */
79                 safestrncpy(buf, up, sizeof buf);
80                 b = (-1);
81                 for (a = 255; a >= 0; --a)
82                         if (buf[a] == '=')
83                                 b = a;
84                 if (b < 0)
85                         return;
86                 buf[b] = 0;
87
88                 u = (struct urlcontent *) malloc(sizeof(struct urlcontent));
89                 u->next = WC->urlstrings;
90                 WC->urlstrings = u;
91                 strcpy(u->url_key, buf);
92
93                 /* now chop that part off */
94                 for (a = 0; a <= b; ++a)
95                         ++up;
96
97                 /* locate "&" and "?" delimiters */
98                 ptr = up;
99                 b = strlen(up);
100                 for (a = 0; a < strlen(up); ++a) {
101                         if ( (ptr[0] == '&') || (ptr[0] == '?') ) {
102                                 b = a;
103                                 break;
104                         }
105                         ++ptr;
106                 }
107                 ptr = up;
108                 for (a = 0; a < b; ++a)
109                         ++ptr;
110                 strcpy(ptr, "");
111
112                 u->url_data = malloc(strlen(up) + 2);
113                 strcpy(u->url_data, up);
114                 u->url_data[b] = 0;
115                 unescape_input(u->url_data);
116                 up = ptr;
117                 ++up;
118         }
119 }
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  * 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 char *bstr(char *key)
146 {
147         struct urlcontent *u;
148
149         for (u = WC->urlstrings; u != NULL; u = u->next) {
150                 if (!strcasecmp(u->url_key, key))
151                         return (u->url_data);
152         }
153         return ("");
154 }
155
156
157 void wprintf(const char *format,...)
158 {
159         va_list arg_ptr;
160         char wbuf[4096];
161
162         va_start(arg_ptr, format);
163         vsnprintf(wbuf, sizeof wbuf, format, arg_ptr);
164         va_end(arg_ptr);
165
166         client_write(wbuf, strlen(wbuf));
167 }
168
169
170 /*
171  * wDumpContent() wraps up an HTTP session, closes tags, etc.
172  *
173  * print_standard_html_footer should be set to 0 to transmit only, 1 to
174  * append the main menu and closing tags, or 2 to
175  * append the closing tags only.
176  */
177 void wDumpContent(int print_standard_html_footer)
178 {
179         if (print_standard_html_footer) {
180                 wprintf("</DIV>\n");    /* end of "text" div */
181                 do_template("trailing");
182         }
183
184 }
185
186
187 /*
188  * Copy a string, escaping characters which have meaning in HTML.  If
189  * nbsp is nonzero, spaces are converted to non-breaking spaces.
190  */
191 void stresc(char *target, char *strbuf, int nbsp, int nolinebreaks)
192 {
193         int a;
194         strcpy(target, "");
195
196         for (a = 0; a < strlen(strbuf); ++a) {
197                 if (strbuf[a] == '<')
198                         strcat(target, "&lt;");
199                 else if (strbuf[a] == '>')
200                         strcat(target, "&gt;");
201                 else if (strbuf[a] == '&')
202                         strcat(target, "&amp;");
203                 else if (strbuf[a] == '\"')
204                         strcat(target, "&quot;");
205                 else if (strbuf[a] == '\'') 
206                         strcat(target, "&#39;");
207                 else if (strbuf[a] == LB)
208                         strcat(target, "<");
209                 else if (strbuf[a] == RB)
210                         strcat(target, ">");
211                 else if (strbuf[a] == QU)
212                         strcat(target, "\"");
213                 else if ((strbuf[a] == 32) && (nbsp == 1))
214                         strcat(target, "&nbsp;");
215                 else if ((strbuf[a] == '\n') && (nolinebreaks))
216                         strcat(target, "");     /* nothing */
217                 else if ((strbuf[a] == '\r') && (nolinebreaks))
218                         strcat(target, "");     /* nothing */
219                 else
220                         strncat(target, &strbuf[a], 1);
221         }
222 }
223
224 void escputs1(char *strbuf, int nbsp, int nolinebreaks)
225 {
226         char *buf;
227
228         if (strbuf == NULL) return;
229         buf = malloc( (3 * strlen(strbuf)) + SIZ );
230         stresc(buf, strbuf, nbsp, nolinebreaks);
231         wprintf("%s", buf);
232         free(buf);
233 }
234
235 void escputs(char *strbuf)
236 {
237         escputs1(strbuf, 0, 0);
238 }
239
240 /*
241  * Escape a string for feeding out as a URL.
242  * Returns a pointer to a buffer that must be freed by the caller!
243  */
244 void urlesc(char *outbuf, char *strbuf)
245 {
246         int a, b, c;
247         char *ec = " #&;`'|*?-~<>^()[]{}$\\";
248
249         strcpy(outbuf, "");
250
251         for (a = 0; a < strlen(strbuf); ++a) {
252                 c = 0;
253                 for (b = 0; b < strlen(ec); ++b) {
254                         if (strbuf[a] == ec[b])
255                                 c = 1;
256                 }
257                 b = strlen(outbuf);
258                 if (c == 1)
259                         sprintf(&outbuf[b], "%%%02x", strbuf[a]);
260                 else
261                         sprintf(&outbuf[b], "%c", strbuf[a]);
262         }
263 }
264
265 void urlescputs(char *strbuf)
266 {
267         char outbuf[SIZ];
268         
269         urlesc(outbuf, strbuf);
270         wprintf("%s", outbuf);
271 }
272
273
274 /*
275  * Copy a string, escaping characters for JavaScript strings.
276  */
277 void jsesc(char *target, char *strbuf)
278 {
279         int a;
280         strcpy(target, "");
281
282         for (a = 0; a < strlen(strbuf); ++a) {
283                 if (strbuf[a] == '<')
284                         strcat(target, "[");
285                 else if (strbuf[a] == '>')
286                         strcat(target, "]");
287                 else if (strbuf[a] == '\"')
288                         strcat(target, "&quot;");
289                 else if (strbuf[a] == '&')
290                         strcat(target, "&amp;;");
291                 else if (strbuf[a] == '\'') 
292                         strcat(target, "\\'");
293                 else {
294                         strncat(target, &strbuf[a], 1);
295                 }
296         }
297 }
298
299 void jsescputs(char *strbuf)
300 {
301         char outbuf[SIZ];
302         
303         jsesc(outbuf, strbuf);
304         wprintf("%s", outbuf);
305 }
306
307 /*
308  * Copy a string, escaping characters for message text hold
309  */
310 void msgesc(char *target, char *strbuf)
311 {
312         int a;
313         strcpy(target, "");
314
315         for (a = 0; a < strlen(strbuf); ++a) {
316                 if (strbuf[a] == '\'') 
317                         strcat(target, "\\'");
318                 else if (strbuf[a] == '\n')
319                         strcat(target, " ");
320                 else if (strbuf[a] == '\r')
321                         strcat(target, " ");
322                 else {
323                         strncat(target, &strbuf[a], 1);
324                 }
325         }
326 }
327
328 void msgescputs(char *strbuf) {
329         char *outbuf;
330
331         if (strbuf == NULL) return;
332         outbuf = malloc( (3 * strlen(strbuf)) + SIZ);
333         msgesc(outbuf, strbuf);
334         wprintf("%s", outbuf);
335         free(outbuf);
336 }
337
338
339
340
341 /*
342  * Output all that important stuff that the browser will want to see
343  */
344 void output_headers(    int do_httpheaders,     /* 1 = output HTTP headers                          */
345                         int do_htmlhead,        /* 1 = output HTML <head> section and <body> opener */
346
347                         int do_room_banner,     /* 0=no, 1=yes,                                     */
348                                                 /* 2 = I'm going to embed my own, so don't open the */
349                                                 /*     <div id="text"> either.                      */
350
351                         int unset_cookies,      /* 1 = session is terminating, so unset the cookies */
352                         int refresh30,          /* 1 = automatically refresh page every 30 seconds  */
353                         int suppress_check,     /* 1 = suppress check for instant messages          */
354                         int cache               /* 1 = allow browser to cache this page             */
355 ) {
356         char cookie[SIZ];
357         char httpnow[SIZ];
358
359         wprintf("HTTP/1.0 200 OK\n");
360         httpdate(httpnow, time(NULL));
361
362         if (do_httpheaders) {
363                 wprintf("Content-type: text/html\n"
364                         "Server: %s / %s\n", SERVER, serv_info.serv_software
365                 );
366                 if (!cache)
367                         wprintf("Connection: close\n"
368                                 "Pragma: no-cache\n"
369                                 "Cache-Control: no-store\n"
370                         );
371         }
372
373         stuff_to_cookie(cookie, WC->wc_session, WC->wc_username,
374                         WC->wc_password, WC->wc_roomname);
375
376         if (unset_cookies) {
377                 wprintf("Set-cookie: webcit=%s; path=/\n", unset);
378         } else {
379                 wprintf("Set-cookie: webcit=%s; path=/\n", cookie);
380                 if (server_cookie != NULL) {
381                         wprintf("%s\n", server_cookie);
382                 }
383         }
384
385         if (do_htmlhead) {
386                 wprintf("\n");
387
388                 if (refresh30) {
389                         svprintf("REFRESHTAG", WCS_STRING, "%s",
390                                 "<meta http-equiv=\"refresh\" content=\"30\" />\n");
391                 }
392                 else {
393                         svprintf("REFRESHTAG", WCS_STRING, "%s",
394                                 "<meta http-equiv=\"refresh\" content=\"500363689;\" />\n");
395                 }
396
397                 do_template("head");
398         }
399
400         /* ICONBAR */
401         if (do_htmlhead) {
402
403                 if (WC->HaveInstantMessages) {
404                         wprintf("<div id=\"page_popup\">\n");
405                         page_popup();
406                         wprintf("</div>\n");
407                 }
408                 if ( (WC->logged_in) && (!unset_cookies) ) {
409                         wprintf("<div id=\"iconbar\">");
410                         do_iconbar();
411                         wprintf("</div>\n");
412                 }
413                 if (do_room_banner == 1) {
414                         wprintf("<div id=\"banner\">\n");
415                         embed_room_banner(NULL, navbar_default);
416                         wprintf("</div>\n");
417                 }
418         }
419
420         if (do_room_banner != 2) {
421                 wprintf("<div id=\"content\">\n");
422
423
424                 if (strlen(WC->ImportantMessage) > 0) {
425                         do_template("beginbox_nt");
426                         wprintf("<SPAN CLASS=\"errormsg\">"
427                                 "%s</SPAN><br />\n", WC->ImportantMessage);
428                         do_template("endbox");
429                         strcpy(WC->ImportantMessage, "");
430                 }
431
432         }
433 }
434
435
436 /*
437  * Generic function to do an HTTP redirect.  Easy and fun.
438  */
439 void http_redirect(char *whichpage) {
440         wprintf("HTTP/1.0 302 Moved Temporarily\n");
441         wprintf("Location: %s\n", whichpage);
442         wprintf("URI: %s\n", whichpage);
443         wprintf("Content-type: text/html\n\n");
444         wprintf("<html><body>\n");
445         wprintf("you really want to be <A HREF=\"%s\">here</A> now\n",
446                 whichpage);
447         wprintf("</body></html>\n");
448 }
449
450
451
452 void check_for_instant_messages()
453 {
454         char buf[SIZ];
455
456         serv_puts("NOOP");
457         serv_gets(buf);
458         if (buf[3] == '*') WC->HaveInstantMessages = 1;
459 }
460
461
462
463
464 /* 
465  * Output a piece of content to the web browser
466  */
467 void http_transmit_thing(char *thing, size_t length, char *content_type,
468                          int is_static) {
469         if (is_static) {
470                 output_headers(0, 0, 0, 0, 0, 0, 1);
471         }
472         else {
473                 output_headers(0, 0, 0, 0, 0, 0, 0);
474         }
475         wprintf("Content-type: %s\n"
476                 "Content-length: %ld\n"
477                 "Server: %s\n"
478                 "Connection: close\n"
479                 "\n",
480                 content_type,
481                 (long) length,
482                 SERVER
483         );
484         client_write(thing, (size_t)length);
485 }
486
487
488
489
490 void output_static(char *what)
491 {
492         char buf[4096];
493         FILE *fp;
494         struct stat statbuf;
495         off_t bytes;
496         char *bigbuffer;
497         char content_type[SIZ];
498
499         sprintf(buf, "static/%s", what);
500         fp = fopen(buf, "rb");
501         if (fp == NULL) {
502                 wprintf("HTTP/1.0 404 %s\n", strerror(errno));
503                 wprintf("Content-Type: text/plain\n");
504                 wprintf("\n");
505                 wprintf("Cannot open %s: %s\n", what, strerror(errno));
506         } else {
507                 if (!strncasecmp(&what[strlen(what) - 4], ".gif", 4))
508                         strcpy(content_type, "image/gif");
509                 else if (!strncasecmp(&what[strlen(what) - 4], ".txt", 4))
510                         strcpy(content_type, "text/plain");
511                 else if (!strncasecmp(&what[strlen(what) - 4], ".css", 4))
512                         strcpy(content_type, "text/css");
513                 else if (!strncasecmp(&what[strlen(what) - 4], ".jpg", 4))
514                         strcpy(content_type, "image/jpeg");
515                 else if (!strncasecmp(&what[strlen(what) - 4], ".png", 4))
516                         strcpy(content_type, "image/png");
517                 else if (!strncasecmp(&what[strlen(what) - 4], ".ico", 4))
518                         strcpy(content_type, "image/x-icon");
519                 else if (!strncasecmp(&what[strlen(what) - 5], ".html", 5))
520                         strcpy(content_type, "text/html");
521                 else if (!strncasecmp(&what[strlen(what) - 4], ".htm", 4))
522                         strcpy(content_type, "text/html");
523                 else if (!strncasecmp(&what[strlen(what) - 4], ".wml", 4))
524                         strcpy(content_type, "text/vnd.wap.wml");
525                 else if (!strncasecmp(&what[strlen(what) - 5], ".wmls", 5))
526                         strcpy(content_type, "text/vnd.wap.wmlscript");
527                 else if (!strncasecmp(&what[strlen(what) - 5], ".wmlc", 5))
528                         strcpy(content_type, "application/vnd.wap.wmlc");
529                 else if (!strncasecmp(&what[strlen(what) - 6], ".wmlsc", 6))
530                         strcpy(content_type, "application/vnd.wap.wmlscriptc");
531                 else if (!strncasecmp(&what[strlen(what) - 5], ".wbmp", 5))
532                         strcpy(content_type, "image/vnd.wap.wbmp");
533                 else if (!strncasecmp(&what[strlen(what) - 3], ".js", 3))
534                         strcpy(content_type, "text/javascript");
535                 else
536                         strcpy(content_type, "application/octet-stream");
537
538                 fstat(fileno(fp), &statbuf);
539                 bytes = statbuf.st_size;
540                 lprintf(3, "Static: %s, (%s; %ld bytes)\n", what, content_type, bytes);
541                 bigbuffer = malloc(bytes + 2);
542                 fread(bigbuffer, bytes, 1, fp);
543                 fclose(fp);
544
545                 http_transmit_thing(bigbuffer, (size_t)bytes, content_type, 1);
546                 free(bigbuffer);
547         }
548         if (!strcasecmp(bstr("force_close_session"), "yes")) {
549                 end_webcit_session();
550         }
551 }
552
553
554 /*
555  * When the browser requests an image file from the Citadel server,
556  * this function is called to transmit it.
557  */
558 void output_image()
559 {
560         char buf[SIZ];
561         char *xferbuf = NULL;
562         off_t bytes;
563
564         serv_printf("OIMG %s|%s", bstr("name"), bstr("parm"));
565         serv_gets(buf);
566         if (buf[0] == '2') {
567                 bytes = extract_long(&buf[4], 0);
568                 xferbuf = malloc(bytes + 2);
569
570                 /* Read it from the server */
571                 read_server_binary(xferbuf, bytes);
572                 serv_puts("CLOS");
573                 serv_gets(buf);
574
575                 /* Write it to the browser */
576                 http_transmit_thing(xferbuf, (size_t)bytes, "image/gif", 0);
577                 free(xferbuf);
578
579         } else {
580
581                 /* Instead of an ugly 404, send a 1x1 transparent GIF
582                  * when there's no such image on the server.
583                  */
584                 output_static("blank.gif");
585
586                 /*
587                 wprintf("HTTP/1.0 404 %s\n", &buf[4]);
588                 output_headers(0, 0, 0, 0, 0, 0, 0);
589                 wprintf("Content-Type: text/plain\n"
590                         "\n"
591                         "Error retrieving image: %s\n",
592                         &buf[4]
593                 );
594                 */
595
596         }
597
598
599
600 }
601
602 /*
603  */
604 void output_mimepart()
605 {
606         char buf[SIZ];
607         off_t bytes;
608         char content_type[SIZ];
609         char *content = NULL;
610         
611         serv_printf("OPNA %s|%s", bstr("msgnum"), bstr("partnum"));
612         serv_gets(buf);
613         if (buf[0] == '2') {
614                 bytes = extract_long(&buf[4], 0);
615                 content = malloc(bytes + 2);
616                 extract(content_type, &buf[4], 3);
617                 output_headers(0, 0, 0, 0, 0, 0, 0);
618                 read_server_binary(content, bytes);
619                 serv_puts("CLOS");
620                 serv_gets(buf);
621                 http_transmit_thing(content, bytes, content_type, 0);
622                 free(content);
623         } else {
624                 wprintf("HTTP/1.0 404 %s\n", &buf[4]);
625                 output_headers(0, 0, 0, 0, 0, 0, 0);
626                 wprintf("Content-Type: text/plain\n");
627                 wprintf("\n");
628                 wprintf("Error retrieving part: %s\n", &buf[4]);
629         }
630
631 }
632
633
634 /*
635  */
636 char *load_mimepart(long msgnum, char *partnum)
637 {
638         char buf[SIZ];
639         off_t bytes;
640         char content_type[SIZ];
641         char *content;
642         
643         serv_printf("OPNA %ld|%s", msgnum, partnum);
644         serv_gets(buf);
645         if (buf[0] == '2') {
646                 bytes = extract_long(&buf[4], 0);
647                 extract(content_type, &buf[4], 3);
648
649                 content = malloc(bytes + 2);
650                 read_server_binary(content, bytes);
651
652                 serv_puts("CLOS");
653                 serv_gets(buf);
654                 content[bytes] = 0;     /* null terminate for good measure */
655                 return(content);
656         }
657         else {
658                 return(NULL);
659         }
660
661 }
662
663
664 /*
665  * Convenience functions to display a page containing only a string
666  */
667 void convenience_page(char *titlebarcolor, char *titlebarmsg, char *messagetext)
668 {
669         wprintf("HTTP/1.0 200 OK\n");
670         output_headers(1, 1, 2, 0, 0, 0, 0);
671         wprintf("<div id=\"banner\">\n");
672         wprintf("<TABLE WIDTH=100%% BORDER=0 BGCOLOR=\"#%s\"><TR><TD>", titlebarcolor);
673         wprintf("<SPAN CLASS=\"titlebar\">%s</SPAN>\n", titlebarmsg);
674         wprintf("</TD></TR></TABLE>\n");
675         wprintf("</div>\n<div id=\"content\">\n");
676         escputs(messagetext);
677
678         wprintf("<hr />\n");
679         wDumpContent(1);
680 }
681
682
683 /*
684  * Display a blank page.
685  */
686 void blank_page(void) {
687         output_headers(1, 1, 0, 0, 1, 0, 0);
688         wDumpContent(2);
689 }
690
691
692 /*
693  * A template has been requested
694  */
695 void url_do_template(void) {
696         do_template(bstr("template"));
697 }
698
699
700
701 /*
702  * Offer to make any page the user's "start page."
703  */
704 void offer_start_page(void) {
705         wprintf("<A HREF=\"/change_start_page?startpage=");
706         urlescputs(WC->this_page);
707         wprintf("\">"
708                 "<FONT SIZE=-2 COLOR=\"#AAAAAA\">Make this my start page</FONT>"
709                 "</A>"
710         );
711 }
712
713
714 /* 
715  * Change the user's start page
716  */
717 void change_start_page(void) {
718
719         if (bstr("startpage") == NULL) {
720                 strcpy(WC->ImportantMessage,
721                         "startpage set to null");
722                 display_main_menu();
723                 return;
724         }
725
726         set_preference("startpage", bstr("startpage"));
727
728         output_headers(1, 1, 0, 0, 0, 0, 0);
729         do_template("newstartpage");
730         wDumpContent(1);
731 }
732
733
734
735
736 void display_success(char *successmessage)
737 {
738         convenience_page("007700", "OK", successmessage);
739 }
740
741
742
743 void extract_action(char *actbuf, char *cmdbuf)
744 {
745         int i;
746
747         strcpy(actbuf, cmdbuf);
748
749         /*
750          * First strip out the http method
751          */
752         remove_token(actbuf, 0, ' ');
753         if (actbuf[0] == ' ') strcpy(actbuf, &actbuf[1]);
754         if (actbuf[0] == '/') strcpy(actbuf, &actbuf[1]);
755
756         /*
757          * Now kill invalid (for webcit) characters
758          */
759         for (i = 0; i < strlen(actbuf); ++i) {
760                 if (actbuf[i] == ' ') {
761                         actbuf[i] = 0;
762                         i = 0;
763                 }
764                 if (actbuf[i] == '/') {
765                         actbuf[i] = 0;
766                         i = 0;
767                 }
768                 if (actbuf[i] == '?') {
769                         actbuf[i] = 0;
770                         i = 0;
771                 }
772                 if (actbuf[i] == '&') {
773                         actbuf[i] = 0;
774                         i = 0;
775                 }
776         }
777 }
778
779
780 void upload_handler(char *name, char *filename, char *partnum, char *disp,
781                         void *content, char *cbtype, size_t length,
782                         char *encoding, void *userdata)
783 {
784         struct urlcontent *u;
785
786         /* Form fields */
787         if ( (length > 0) && (strlen(cbtype) == 0) ) {
788                 u = (struct urlcontent *) malloc(sizeof(struct urlcontent));
789                 u->next = WC->urlstrings;
790                 WC->urlstrings = u;
791                 safestrncpy(u->url_key, name, sizeof(u->url_key));
792                 u->url_data = malloc(length + 1);
793                 memcpy(u->url_data, content, length);
794                 u->url_data[length] = 0;
795         }
796
797         /* Uploaded files */
798         if ( (length > 0) && (strlen(cbtype) > 0) ) {
799                 WC->upload = malloc(length);
800                 if (WC->upload != NULL) {
801                         WC->upload_length = length;
802                         safestrncpy(WC->upload_filename, filename,
803                                         sizeof(WC->upload_filename));
804                         safestrncpy(WC->upload_content_type, cbtype,
805                                         sizeof(WC->upload_content_type));
806                         memcpy(WC->upload, content, length);
807                 }
808                 else {
809                         lprintf(3, "malloc() failed: %s\n", strerror(errno));
810                 }
811         }
812
813 }
814
815
816
817
818 /*
819  * Entry point for WebCit transaction
820  */
821 void session_loop(struct httprequest *req)
822 {
823         char cmd[SIZ];
824         char method[SIZ];
825         char action[SIZ];
826         char buf[SIZ];
827         int a, b;
828         int ContentLength = 0;
829         int BytesRead = 0;
830         char ContentType[512];
831         char *content = NULL;
832         char *content_end = NULL;
833         struct httprequest *hptr;
834         char browser_host[SIZ];
835         char user_agent[SIZ];
836         int body_start;
837
838         /* We stuff these with the values coming from the client cookies,
839          * so we can use them to reconnect a timed out session if we have to.
840          */
841         char c_username[SIZ];
842         char c_password[SIZ];
843         char c_roomname[SIZ];
844         char c_httpauth_string[SIZ];
845         char c_httpauth_user[SIZ];
846         char c_httpauth_pass[SIZ];
847         char cookie[SIZ];
848
849         strcpy(c_username, "");
850         strcpy(c_password, "");
851         strcpy(c_roomname, "");
852         strcpy(c_httpauth_string, "");
853         strcpy(c_httpauth_user, "");
854         strcpy(c_httpauth_pass, "");
855
856         WC->upload_length = 0;
857         WC->upload = NULL;
858         WC->vars = NULL;
859
860         WC->is_wap = 0;
861
862         hptr = req;
863         if (hptr == NULL) return;
864
865         strcpy(cmd, hptr->line);
866         hptr = hptr->next;
867         extract_token(method, cmd, 0, ' ');
868         extract_action(action, cmd);
869
870         while (hptr != NULL) {
871                 strcpy(buf, hptr->line);
872                 hptr = hptr->next;
873
874                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
875                         safestrncpy(cookie, &buf[15], sizeof cookie);
876                         cookie_to_stuff(cookie, NULL,
877                                       c_username, c_password, c_roomname);
878                 }
879                 else if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
880                         CtdlDecodeBase64(c_httpauth_string, &buf[21], strlen(&buf[21]));
881                         extract_token(c_httpauth_user, c_httpauth_string, 0, ':');
882                         extract_token(c_httpauth_pass, c_httpauth_string, 1, ':');
883                 }
884                 else if (!strncasecmp(buf, "Content-length: ", 16)) {
885                         ContentLength = atoi(&buf[16]);
886                 }
887                 else if (!strncasecmp(buf, "Content-type: ", 14)) {
888                         safestrncpy(ContentType, &buf[14], sizeof ContentType);
889                 }
890                 else if (!strncasecmp(buf, "User-agent: ", 12)) {
891                         safestrncpy(user_agent, &buf[12], sizeof user_agent);
892                 }
893                 else if (!strncasecmp(buf, "Host: ", 6)) {
894                         safestrncpy(WC->http_host, &buf[6], sizeof WC->http_host);
895                 }
896                 /* Only WAP gateways explicitly name this content-type */
897                 else if (strstr(buf, "text/vnd.wap.wml")) {
898                         WC->is_wap = 1;
899                 }
900         }
901
902         if (ContentLength > 0) {
903                 content = malloc(ContentLength + SIZ);
904                 memset(content, 0, ContentLength + SIZ);
905                 sprintf(content, "Content-type: %s\n"
906                                 "Content-length: %d\n\n",
907                                 ContentType, ContentLength);
908                 body_start = strlen(content);
909
910                 /* Be daring and read it all at once. */
911                 client_read(WC->http_sock, &content[BytesRead+body_start],
912                         ContentLength);
913
914                 if (!strncasecmp(ContentType,
915                               "application/x-www-form-urlencoded", 33)) {
916                         addurls(&content[body_start]);
917                 } else if (!strncasecmp(ContentType, "multipart", 9)) {
918                         content_end = content + ContentLength + body_start;
919                         mime_parser(content, content_end, *upload_handler,
920                                         NULL, NULL, NULL, 0);
921                 }
922         } else {
923                 content = NULL;
924         }
925
926         /* make a note of where we are in case the user wants to save it */
927         safestrncpy(WC->this_page, cmd, sizeof(WC->this_page));
928         remove_token(WC->this_page, 2, ' ');
929         remove_token(WC->this_page, 0, ' ');
930
931         /* If there are variables in the URL, we must grab them now */
932         for (a = 0; a < strlen(cmd); ++a) {
933                 if ((cmd[a] == '?') || (cmd[a] == '&')) {
934                         for (b = a; b < strlen(cmd); ++b)
935                                 if (isspace(cmd[b]))
936                                         cmd[b] = 0;
937                         addurls(&cmd[a + 1]);
938                         cmd[a] = 0;
939                 }
940         }
941
942         /* Static content can be sent without connecting to Citadel. */
943         if (!strcasecmp(action, "static")) {
944                 strcpy(buf, &cmd[12]);
945                 for (a = 0; a < strlen(buf); ++a)
946                         if (isspace(buf[a]))
947                                 buf[a] = 0;
948                 output_static(buf);
949                 goto SKIP_ALL_THIS_CRAP;        /* Don't try to connect */
950         }
951
952         /*
953          * If we're not connected to a Citadel server, try to hook up the
954          * connection now.
955          */
956         if (!WC->connected) {
957                 if (!strcasecmp(ctdlhost, "uds")) {
958                         /* unix domain socket */
959                         sprintf(buf, "%s/citadel.socket", ctdlport);
960                         WC->serv_sock = uds_connectsock(buf);
961                 }
962                 else {
963                         /* tcp socket */
964                         WC->serv_sock = tcp_connectsock(ctdlhost, ctdlport);
965                 }
966
967                 if (WC->serv_sock < 0) {
968                         do_logout();
969                         goto SKIP_ALL_THIS_CRAP;
970                 }
971                 else {
972                         WC->connected = 1;
973                         serv_gets(buf); /* get the server welcome message */
974                         locate_host(browser_host, WC->http_sock);
975                         get_serv_info(browser_host, user_agent);
976                         if (serv_info.serv_rev_level < MINIMUM_CIT_VERSION) {
977                                 wprintf("You are connected to a Citadel "
978                                         "server running Citadel %d.%02d;\nin "
979                                         "order to run this version of WebCit "
980                                         "you must also have Citadel %d.%02d or"
981                                         " newer.\n\n\n",
982                                                 serv_info.serv_rev_level / 100,
983                                                 serv_info.serv_rev_level % 100,
984                                                 MINIMUM_CIT_VERSION / 100,
985                                                 MINIMUM_CIT_VERSION % 100
986                                         );
987                                 end_webcit_session();
988                                 goto SKIP_ALL_THIS_CRAP;
989                         }
990                 }
991         }
992
993         /*
994          * Functions which can be performed without logging in
995          */
996         if (!strcasecmp(action, "listsub")) {
997                 do_listsub();
998                 goto SKIP_ALL_THIS_CRAP;
999         }
1000 #ifdef WEBCIT_WITH_CALENDAR_SERVICE
1001         if (!strcasecmp(action, "freebusy")) {
1002                 do_freebusy(cmd);
1003                 goto SKIP_ALL_THIS_CRAP;
1004         }
1005 #endif
1006
1007         /*
1008          * If we're not logged in, but we have HTTP Authentication data,
1009          * try logging in to Citadel using that.
1010          */
1011         if ((!WC->logged_in)
1012            && (strlen(c_httpauth_user) > 0)
1013            && (strlen(c_httpauth_pass) > 0)) {
1014                 serv_printf("USER %s", c_httpauth_user);
1015                 serv_gets(buf);
1016                 if (buf[0] == '3') {
1017                         serv_printf("PASS %s", c_httpauth_pass);
1018                         serv_gets(buf);
1019                         if (buf[0] == '2') {
1020                                 become_logged_in(c_httpauth_user,
1021                                                 c_httpauth_pass, buf);
1022                                 strcpy(WC->httpauth_user, c_httpauth_user);
1023                                 strcpy(WC->httpauth_pass, c_httpauth_pass);
1024                         }
1025                 }
1026         }
1027
1028         /* 
1029          * The GroupDAV stuff relies on HTTP authentication instead of
1030          * our session's authentication.
1031          */
1032         if (!strncasecmp(action, "groupdav", 8)) {
1033                 groupdav_main(req, ContentType, /* do GroupDAV methods */
1034                         ContentLength, content+body_start);
1035                 if (!WC->logged_in) {
1036                         WC->killthis = 1;       /* If not logged in, don't */
1037                 }                               /* keep the session active */
1038                 goto SKIP_ALL_THIS_CRAP;
1039         }
1040
1041         check_for_instant_messages();
1042
1043         /*
1044          * If we're not logged in, but we have username and password cookies
1045          * supplied by the browser, try using them to log in.
1046          */
1047         if ((!WC->logged_in)
1048            && (strlen(c_username) > 0)
1049            && (strlen(c_password) > 0)) {
1050                 serv_printf("USER %s", c_username);
1051                 serv_gets(buf);
1052                 if (buf[0] == '3') {
1053                         serv_printf("PASS %s", c_password);
1054                         serv_gets(buf);
1055                         if (buf[0] == '2') {
1056                                 become_logged_in(c_username, c_password, buf);
1057                         }
1058                 }
1059         }
1060         /*
1061          * If we don't have a current room, but a cookie specifying the
1062          * current room is supplied, make an effort to go there.
1063          */
1064         if ((strlen(WC->wc_roomname) == 0) && (strlen(c_roomname) > 0)) {
1065                 serv_printf("GOTO %s", c_roomname);
1066                 serv_gets(buf);
1067                 if (buf[0] == '2') {
1068                         strcpy(WC->wc_roomname, c_roomname);
1069                 }
1070         }
1071
1072         if (!strcasecmp(action, "image")) {
1073                 output_image();
1074
1075         /*
1076          * All functions handled below this point ... make sure we log in
1077          * before doing anything else!
1078          */
1079         } else if ((!WC->logged_in) && (!strcasecmp(action, "login"))) {
1080                 do_login();
1081         } else if (!WC->logged_in) {
1082                 display_login(NULL);
1083         }
1084
1085         /*
1086          * Various commands...
1087          */
1088
1089         else if (!strcasecmp(action, "do_welcome")) {
1090                 do_welcome();
1091         } else if (!strcasecmp(action, "blank")) {
1092                 blank_page();
1093         } else if (!strcasecmp(action, "do_template")) {
1094                 url_do_template();
1095         } else if (!strcasecmp(action, "display_main_menu")) {
1096                 display_main_menu();
1097         } else if (!strcasecmp(action, "whobbs")) {
1098                 whobbs();
1099         } else if (!strcasecmp(action, "knrooms")) {
1100                 knrooms();
1101         } else if (!strcasecmp(action, "gotonext")) {
1102                 slrp_highest();
1103                 gotonext();
1104         } else if (!strcasecmp(action, "skip")) {
1105                 gotonext();
1106         } else if (!strcasecmp(action, "ungoto")) {
1107                 ungoto();
1108         } else if (!strcasecmp(action, "dotgoto")) {
1109                 slrp_highest();
1110                 smart_goto(bstr("room"));
1111         } else if (!strcasecmp(action, "dotskip")) {
1112                 smart_goto(bstr("room"));
1113         } else if (!strcasecmp(action, "termquit")) {
1114                 do_logout();
1115         } else if (!strcasecmp(action, "readnew")) {
1116                 readloop("readnew");
1117         } else if (!strcasecmp(action, "readold")) {
1118                 readloop("readold");
1119         } else if (!strcasecmp(action, "readfwd")) {
1120                 readloop("readfwd");
1121         } else if (!strcasecmp(action, "headers")) {
1122                 readloop("headers");
1123         } else if (!strcasecmp(action, "display_enter")) {
1124                 display_enter();
1125         } else if (!strcasecmp(action, "post")) {
1126                 post_message();
1127         } else if (!strcasecmp(action, "do_stuff_to_one_msg")) {
1128                 do_stuff_to_one_msg();
1129         } else if (!strcasecmp(action, "move_msg")) {
1130                 move_msg();
1131         } else if (!strcasecmp(action, "userlist")) {
1132                 userlist();
1133         } else if (!strcasecmp(action, "showuser")) {
1134                 showuser();
1135         } else if (!strcasecmp(action, "display_page")) {
1136                 display_page();
1137         } else if (!strcasecmp(action, "page_user")) {
1138                 page_user();
1139         } else if (!strcasecmp(action, "chat")) {
1140                 do_chat();
1141         } else if (!strcasecmp(action, "display_private")) {
1142                 display_private("", 0);
1143         } else if (!strcasecmp(action, "goto_private")) {
1144                 goto_private();
1145         } else if (!strcasecmp(action, "zapped_list")) {
1146                 zapped_list();
1147         } else if (!strcasecmp(action, "display_zap")) {
1148                 display_zap();
1149         } else if (!strcasecmp(action, "zap")) {
1150                 zap();
1151         } else if (!strcasecmp(action, "display_entroom")) {
1152                 display_entroom();
1153         } else if (!strcasecmp(action, "entroom")) {
1154                 entroom();
1155         } else if (!strcasecmp(action, "display_editroom")) {
1156                 display_editroom();
1157         } else if (!strcasecmp(action, "netedit")) {
1158                 netedit();
1159         } else if (!strcasecmp(action, "editroom")) {
1160                 editroom();
1161         } else if (!strcasecmp(action, "display_whok")) {
1162                 display_whok();
1163         } else if (!strcasecmp(action, "display_editinfo")) {
1164                 display_edit("Room info", "EINF 0", "RINF", "/editinfo", 1);
1165         } else if (!strcasecmp(action, "editinfo")) {
1166                 save_edit("Room info", "EINF 1", 1);
1167         } else if (!strcasecmp(action, "display_editbio")) {
1168                 sprintf(buf, "RBIO %s", WC->wc_username);
1169                 display_edit("Your bio", "NOOP", buf, "editbio", 3);
1170         } else if (!strcasecmp(action, "editbio")) {
1171                 save_edit("Your bio", "EBIO", 0);
1172         } else if (!strcasecmp(action, "confirm_delete_room")) {
1173                 confirm_delete_room();
1174         } else if (!strcasecmp(action, "delete_room")) {
1175                 delete_room();
1176         } else if (!strcasecmp(action, "validate")) {
1177                 validate();
1178         } else if (!strcasecmp(action, "display_editpic")) {
1179                 display_graphics_upload("your photo",
1180                                         "UIMG 0|_userpic_",
1181                                         "/editpic");
1182         } else if (!strcasecmp(action, "editpic")) {
1183                 do_graphics_upload("UIMG 1|_userpic_");
1184         } else if (!strcasecmp(action, "display_editroompic")) {
1185                 display_graphics_upload("the graphic for this room",
1186                                         "UIMG 0|_roompic_",
1187                                         "/editroompic");
1188         } else if (!strcasecmp(action, "editroompic")) {
1189                 do_graphics_upload("UIMG 1|_roompic_");
1190         } else if (!strcasecmp(action, "delete_floor")) {
1191                 delete_floor();
1192         } else if (!strcasecmp(action, "rename_floor")) {
1193                 rename_floor();
1194         } else if (!strcasecmp(action, "create_floor")) {
1195                 create_floor();
1196         } else if (!strcasecmp(action, "display_editfloorpic")) {
1197                 sprintf(buf, "UIMG 0|_floorpic_|%s",
1198                         bstr("which_floor"));
1199                 display_graphics_upload("the graphic for this floor",
1200                                         buf,
1201                                         "/editfloorpic");
1202         } else if (!strcasecmp(action, "editfloorpic")) {
1203                 sprintf(buf, "UIMG 1|_floorpic_|%s",
1204                         bstr("which_floor"));
1205                 do_graphics_upload(buf);
1206         } else if (!strcasecmp(action, "display_reg")) {
1207                 display_reg(0);
1208         } else if (!strcasecmp(action, "display_changepw")) {
1209                 display_changepw();
1210         } else if (!strcasecmp(action, "changepw")) {
1211                 changepw();
1212         } else if (!strcasecmp(action, "display_edit_node")) {
1213                 display_edit_node();
1214         } else if (!strcasecmp(action, "edit_node")) {
1215                 edit_node();
1216         } else if (!strcasecmp(action, "display_netconf")) {
1217                 display_netconf();
1218         } else if (!strcasecmp(action, "display_confirm_delete_node")) {
1219                 display_confirm_delete_node();
1220         } else if (!strcasecmp(action, "delete_node")) {
1221                 delete_node();
1222         } else if (!strcasecmp(action, "display_add_node")) {
1223                 display_add_node();
1224         } else if (!strcasecmp(action, "add_node")) {
1225                 add_node();
1226         } else if (!strcasecmp(action, "terminate_session")) {
1227                 slrp_highest();
1228                 terminate_session();
1229         } else if (!strcasecmp(action, "edit_me")) {
1230                 edit_me();
1231         } else if (!strcasecmp(action, "display_siteconfig")) {
1232                 display_siteconfig();
1233         } else if (!strcasecmp(action, "chat_recv")) {
1234                 chat_recv();
1235         } else if (!strcasecmp(action, "chat_send")) {
1236                 chat_send();
1237         } else if (!strcasecmp(action, "siteconfig")) {
1238                 siteconfig();
1239         } else if (!strcasecmp(action, "display_generic")) {
1240                 display_generic();
1241         } else if (!strcasecmp(action, "do_generic")) {
1242                 do_generic();
1243         } else if (!strcasecmp(action, "display_menubar")) {
1244                 display_menubar(1);
1245         } else if (!strcasecmp(action, "output_mimepart")) {
1246                 output_mimepart();
1247         } else if (!strcasecmp(action, "edit_vcard")) {
1248                 edit_vcard();
1249         } else if (!strcasecmp(action, "submit_vcard")) {
1250                 submit_vcard();
1251         } else if (!strcasecmp(action, "select_user_to_edit")) {
1252                 select_user_to_edit(NULL, NULL);
1253         } else if (!strcasecmp(action, "display_edituser")) {
1254                 display_edituser(NULL, 0);
1255         } else if (!strcasecmp(action, "edituser")) {
1256                 edituser();
1257         } else if (!strcasecmp(action, "create_user")) {
1258                 create_user();
1259         } else if (!strcasecmp(action, "changeview")) {
1260                 change_view();
1261         } else if (!strcasecmp(action, "do_stuff_to_msgs")) {
1262                 do_stuff_to_msgs();
1263         } else if (!strcasecmp(action, "change_start_page")) {
1264                 change_start_page();
1265         } else if (!strcasecmp(action, "display_floorconfig")) {
1266                 display_floorconfig(NULL);
1267         } else if (!strcasecmp(action, "toggle_self_service")) {
1268                 toggle_self_service();
1269 #ifdef WEBCIT_WITH_CALENDAR_SERVICE
1270         } else if (!strcasecmp(action, "display_edit_task")) {
1271                 display_edit_task();
1272         } else if (!strcasecmp(action, "save_task")) {
1273                 save_task();
1274         } else if (!strcasecmp(action, "display_edit_event")) {
1275                 display_edit_event();
1276         } else if (!strcasecmp(action, "save_event")) {
1277                 save_event();
1278         } else if (!strcasecmp(action, "respond_to_request")) {
1279                 respond_to_request();
1280         } else if (!strcasecmp(action, "handle_rsvp")) {
1281                 handle_rsvp();
1282 #endif
1283         } else if (!strcasecmp(action, "summary")) {
1284                 summary();
1285         } else if (!strcasecmp(action, "iconbar")) {
1286                 do_iconbar();
1287         } else if (!strcasecmp(action, "display_customize_iconbar")) {
1288                 display_customize_iconbar();
1289         } else if (!strcasecmp(action, "commit_iconbar")) {
1290                 commit_iconbar();
1291         } else if (!strcasecmp(action, "set_room_policy")) {
1292                 set_room_policy();
1293         } else if (!strcasecmp(action, "display_inetconf")) {
1294                 display_inetconf();
1295         } else if (!strcasecmp(action, "save_inetconf")) {
1296                 save_inetconf();
1297         } else if (!strcasecmp(action, "diagnostics")) {
1298                 output_headers(1, 1, 1, 0, 0, 0, 0);
1299
1300                 wprintf("You're in session %d<hr />\n", WC->wc_session);
1301                 wprintf("Command: <br /><PRE>\n");
1302                 escputs(cmd);
1303                 wprintf("</PRE><hr />\n");
1304                 wprintf("Variables: <br /><PRE>\n");
1305                 dump_vars();
1306                 wprintf("</PRE><hr />\n");
1307                 wDumpContent(1);
1308         }
1309         /* When all else fais, display the main menu. */
1310         else {
1311                 display_main_menu();
1312         }
1313
1314 SKIP_ALL_THIS_CRAP:
1315         fflush(stdout);
1316         if (content != NULL) {
1317                 free(content);
1318                 content = NULL;
1319         }
1320         free_urls();
1321         if (WC->upload_length > 0) {
1322                 free(WC->upload);
1323                 WC->upload_length = 0;
1324         }
1325
1326 }