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