fd6398f59256fe79ea35cce90edc1b3388c1afb7
[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                 do_template("trailing");
179         }
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  * control codes:
343  * 
344  * Bits 0 and 1:
345  * 0 = Nothing.  Do not display any leading HTTP or HTML.
346  * 1 = HTTP headers plus the room banner
347  * 2 = HTTP headers required to terminate the session (unset cookies)
348  * 3 = HTTP and HTML headers, but no room banner
349  *
350  * Bit 2: Set to 1 to auto-refresh page every 30 seconds
351  * Bit 3: suppress check for express messages
352  * Bit 4: Allow browser to cache this document
353  *
354  */
355 void output_headers(int controlcode)
356 {
357         char cookie[SIZ];
358         int print_standard_html_head = 0;
359         int refresh30 = 0;
360         int suppress_check = 0;
361         int cache = 0;
362         char httpnow[SIZ];
363         char onload_fcn[SIZ];
364         static int pageseq = 0;
365         print_standard_html_head        =       controlcode & 0x03;
366         refresh30                       =       ((controlcode & 0x04) >> 2);
367         suppress_check                  =       ((controlcode & 0x08) >> 3);
368         cache                           =       ((controlcode & 0x10) >> 4);
369
370
371         wprintf("HTTP/1.0 200 OK\n");
372
373         httpdate(httpnow, time(NULL));
374
375         if (print_standard_html_head > 0) {
376                 wprintf("Content-type: text/html\n"
377                         "Server: %s\n", SERVER
378                 );
379                 if (!cache)
380                         wprintf("Connection: close\n"
381                                 "Pragma: no-cache\n"
382                                 "Cache-Control: no-store\n"
383                         );
384         }
385
386         stuff_to_cookie(cookie, WC->wc_session, WC->wc_username,
387                         WC->wc_password, WC->wc_roomname);
388
389         if (print_standard_html_head == 2) {
390                 wprintf("Set-cookie: webcit=%s; path=/\n", unset);
391         } else {
392                 wprintf("Set-cookie: webcit=%s; path=/\n", cookie);
393                 if (server_cookie != NULL) {
394                         wprintf("%s\n", server_cookie);
395                 }
396         }
397
398         if (print_standard_html_head > 0) {
399                 wprintf("\n");
400
401                 if (refresh30) {
402                         svprintf("REFRESHTAG", WCS_STRING, "%s",
403                                 "<META HTTP-EQUIV=\"refresh\" CONTENT=\"30\">\n");
404                 }
405                 else {
406                         svprintf("REFRESHTAG", WCS_STRING, "%s",
407                                 "<META HTTP-EQUIV=\"refresh\" CONTENT=\"500363689;\">\n");
408                 }
409
410                 /* script for checking for pages (not always launched) */
411
412                 sprintf(onload_fcn, "function onload_fcn() { \n");
413                 if (!WC->outside_frameset_allowed) {
414                         strcat(onload_fcn, "  force_frameset();  \n");
415                 }
416                 if (!suppress_check) if (WC->HaveExpressMessages) {
417                         strcat(onload_fcn, "  launch_page_popup();  \n");
418                         WC->HaveExpressMessages = 0;
419                 }
420                 strcat(onload_fcn, "} \n");
421
422                 svprintf("PAGERSCRIPT", WCS_STRING,
423                         "<SCRIPT LANGUAGE=\"JavaScript\">\n"
424                         "function launch_page_popup() {\n"
425                         "pwin = window.open('/page_popup', 'CitaPage%d', "
426                         "'toolbar=no,location=no,copyhistory=no,status=no,"
427                         "scrollbars=yes,resizable=no,height=250,width=400');\n"
428                         "}\n"
429                         "function force_frameset() { \n"
430                         " if (top.frames.length == 0) { \n"
431                         "  top.location.replace('/do_welcome'); \n"
432                         " } \n"
433                         "} \n"
434                         "%s\n"
435                         "</SCRIPT>\n",
436                         ++pageseq,
437                         onload_fcn
438                 );
439                 /* end script */
440
441                 do_template("head");
442
443                 svprintf("extrabodyparms", WCS_STRING, "%s", 
444                         "onload='onload_fcn();' ");
445
446                 do_template("background");
447         }
448
449         if (print_standard_html_head == 1) {
450                 wprintf("<A NAME=\"TheTop\"></A>");
451                 embed_room_banner(NULL);
452         }
453
454         if (strlen(WC->ImportantMessage) > 0) {
455                 do_template("beginbox_nt");
456                 wprintf("<SPAN CLASS=\"errormsg\">"
457                         "%s</SPAN><BR>\n", WC->ImportantMessage);
458                 do_template("endbox");
459                 strcpy(WC->ImportantMessage, "");
460         }       
461 }
462
463
464 /*
465  *
466  */
467 void http_redirect(char *whichpage) {
468         wprintf("HTTP/1.0 302 Moved Temporarily\n");
469         wprintf("Location: %s\n", whichpage);
470         wprintf("URI: %s\n", whichpage);
471         wprintf("Content-type: text/html\n\n");
472         wprintf("<html><body>\n");
473         wprintf("you really want to be <A HREF=\"%s\">here</A> now\n",
474                 whichpage);
475         wprintf("</body></html>\n");
476 }
477
478
479
480 void check_for_express_messages()
481 {
482         char buf[SIZ];
483
484         serv_puts("NOOP");
485         serv_gets(buf);
486         if (buf[3] == '*') WC->HaveExpressMessages = 1;
487 }
488
489
490
491
492 /* 
493  * Output a piece of content to the web browser
494  */
495 void http_transmit_thing(char *thing, size_t length, char *content_type,
496                          int is_static) {
497         output_headers(is_static ? 0x10 : 0x00);
498         wprintf("Content-type: %s\n"
499                 "Content-length: %ld\n"
500                 "Server: %s\n"
501                 "Connection: close\n"
502                 "\n",
503                 content_type,
504                 (long) length,
505                 SERVER
506         );
507         client_write(thing, (size_t)length);
508 }
509
510
511
512
513 void output_static(char *what)
514 {
515         char buf[4096];
516         FILE *fp;
517         struct stat statbuf;
518         off_t bytes;
519         char *bigbuffer;
520         char content_type[SIZ];
521
522         sprintf(buf, "static/%s", what);
523         fp = fopen(buf, "rb");
524         if (fp == NULL) {
525                 wprintf("HTTP/1.0 404 %s\n", strerror(errno));
526                 wprintf("Content-Type: text/plain\n");
527                 wprintf("\n");
528                 wprintf("Cannot open %s: %s\n", what, strerror(errno));
529         } else {
530                 if (!strncasecmp(&what[strlen(what) - 4], ".gif", 4))
531                         strcpy(content_type, "image/gif");
532                 else if (!strncasecmp(&what[strlen(what) - 4], ".txt", 4))
533                         strcpy(content_type, "text/plain");
534                 else if (!strncasecmp(&what[strlen(what) - 4], ".css", 4))
535                         strcpy(content_type, "text/css");
536                 else if (!strncasecmp(&what[strlen(what) - 4], ".jpg", 4))
537                         strcpy(content_type, "image/jpeg");
538                 else if (!strncasecmp(&what[strlen(what) - 4], ".png", 4))
539                         strcpy(content_type, "image/png");
540                 else if (!strncasecmp(&what[strlen(what) - 4], ".ico", 4))
541                         strcpy(content_type, "image/x-icon");
542                 else if (!strncasecmp(&what[strlen(what) - 5], ".html", 5))
543                         strcpy(content_type, "text/html");
544                 else if (!strncasecmp(&what[strlen(what) - 4], ".htm", 4))
545                         strcpy(content_type, "text/html");
546                 else if (!strncasecmp(&what[strlen(what) - 4], ".wml", 4))
547                         strcpy(content_type, "text/vnd.wap.wml");
548                 else if (!strncasecmp(&what[strlen(what) - 5], ".wmls", 5))
549                         strcpy(content_type, "text/vnd.wap.wmlscript");
550                 else if (!strncasecmp(&what[strlen(what) - 5], ".wmlc", 5))
551                         strcpy(content_type, "application/vnd.wap.wmlc");
552                 else if (!strncasecmp(&what[strlen(what) - 6], ".wmlsc", 6))
553                         strcpy(content_type, "application/vnd.wap.wmlscriptc");
554                 else if (!strncasecmp(&what[strlen(what) - 5], ".wbmp", 5))
555                         strcpy(content_type, "image/vnd.wap.wbmp");
556                 else if (!strncasecmp(&what[strlen(what) - 3], ".js", 3))
557                         strcpy(content_type, "text/javascript");
558                 else
559                         strcpy(content_type, "application/octet-stream");
560
561                 fstat(fileno(fp), &statbuf);
562                 bytes = statbuf.st_size;
563                 lprintf(3, "Static: %s, (%s; %ld bytes)\n", what, content_type, bytes);
564                 bigbuffer = malloc(bytes + 2);
565                 fread(bigbuffer, bytes, 1, fp);
566                 fclose(fp);
567
568                 http_transmit_thing(bigbuffer, (size_t)bytes, content_type, 1);
569                 free(bigbuffer);
570         }
571         if (!strcasecmp(bstr("force_close_session"), "yes")) {
572                 end_webcit_session();
573         }
574 }
575
576
577 /*
578  * When the browser requests an image file from the Citadel server,
579  * this function is called to transmit it.
580  */
581 void output_image()
582 {
583         char buf[SIZ];
584         char *xferbuf = NULL;
585         off_t bytes;
586
587         serv_printf("OIMG %s|%s", bstr("name"), bstr("parm"));
588         serv_gets(buf);
589         if (buf[0] == '2') {
590                 bytes = extract_long(&buf[4], 0);
591                 xferbuf = malloc(bytes + 2);
592
593                 /* Read it from the server */
594                 read_server_binary(xferbuf, bytes);
595                 serv_puts("CLOS");
596                 serv_gets(buf);
597
598                 /* Write it to the browser */
599                 http_transmit_thing(xferbuf, (size_t)bytes, "image/gif", 0);
600                 free(xferbuf);
601
602         } else {
603
604                 /* Instead of an ugly 404, send a 1x1 transparent GIF
605                  * when there's no such image on the server.
606                  */
607                 output_static("blank.gif");
608
609                 /*
610                 wprintf("HTTP/1.0 404 %s\n", &buf[4]);
611                 output_headers(0);
612                 wprintf("Content-Type: text/plain\n"
613                         "\n"
614                         "Error retrieving image: %s\n",
615                         &buf[4]
616                 );
617                 */
618
619         }
620
621
622
623 }
624
625 /*
626  */
627 void output_mimepart()
628 {
629         char buf[SIZ];
630         off_t bytes;
631         char content_type[SIZ];
632         char *content = NULL;
633         
634         serv_printf("OPNA %s|%s", bstr("msgnum"), bstr("partnum"));
635         serv_gets(buf);
636         if (buf[0] == '2') {
637                 bytes = extract_long(&buf[4], 0);
638                 content = malloc(bytes + 2);
639                 extract(content_type, &buf[4], 3);
640                 output_headers(0);
641                 read_server_binary(content, bytes);
642                 serv_puts("CLOS");
643                 serv_gets(buf);
644                 http_transmit_thing(content, bytes, content_type, 0);
645                 free(content);
646         } else {
647                 wprintf("HTTP/1.0 404 %s\n", &buf[4]);
648                 output_headers(0);
649                 wprintf("Content-Type: text/plain\n");
650                 wprintf("\n");
651                 wprintf("Error retrieving part: %s\n", &buf[4]);
652         }
653
654 }
655
656
657 /*
658  */
659 char *load_mimepart(long msgnum, char *partnum)
660 {
661         char buf[SIZ];
662         off_t bytes;
663         char content_type[SIZ];
664         char *content;
665         
666         serv_printf("OPNA %ld|%s", msgnum, partnum);
667         serv_gets(buf);
668         if (buf[0] == '2') {
669                 bytes = extract_long(&buf[4], 0);
670                 extract(content_type, &buf[4], 3);
671
672                 content = malloc(bytes + 2);
673                 read_server_binary(content, bytes);
674
675                 serv_puts("CLOS");
676                 serv_gets(buf);
677                 content[bytes] = 0;     /* null terminate for good measure */
678                 return(content);
679         }
680         else {
681                 return(NULL);
682         }
683
684 }
685
686
687 /*
688  * Convenience functions to display a page containing only a string
689  */
690 void convenience_page(char *titlebarcolor, char *titlebarmsg, char *messagetext)
691 {
692         wprintf("HTTP/1.0 200 OK\n");
693         output_headers(1);
694         wprintf("<TABLE WIDTH=100%% BORDER=0 BGCOLOR=\"#%s\"><TR><TD>", titlebarcolor);
695         wprintf("<SPAN CLASS=\"titlebar\">%s</SPAN>\n", titlebarmsg);
696         wprintf("</TD></TR></TABLE><BR>\n");
697         escputs(messagetext);
698
699         wprintf("<HR>\n");
700         wDumpContent(1);
701 }
702
703
704 /*
705  * Display a blank page.
706  */
707 void blank_page(void) {
708         output_headers(7);
709         wDumpContent(2);
710 }
711
712
713 /*
714  * A template has been requested
715  */
716 void url_do_template(void) {
717         do_template(bstr("template"));
718 }
719
720
721
722 /*
723  * Offer to make any page the user's "start page."
724  */
725 void offer_start_page(void) {
726         wprintf("<A HREF=\"/change_start_page?startpage=");
727         urlescputs(WC->this_page);
728         wprintf("\">"
729                 "<FONT SIZE=-2 COLOR=\"#AAAAAA\">Make this my start page</FONT>"
730                 "</A>"
731         );
732 }
733
734
735 /* 
736  * Change the user's start page
737  */
738 void change_start_page(void) {
739
740         if (bstr("startpage") == NULL) {
741                 strcpy(WC->ImportantMessage,
742                         "startpage set to null");
743                 display_main_menu();
744                 return;
745         }
746
747         set_preference("startpage", bstr("startpage"));
748
749         output_headers(3);
750         do_template("newstartpage");
751         wDumpContent(1);
752 }
753
754
755
756
757 void display_success(char *successmessage)
758 {
759         convenience_page("007700", "OK", successmessage);
760 }
761
762
763
764 void extract_action(char *actbuf, char *cmdbuf)
765 {
766         int i;
767
768         strcpy(actbuf, cmdbuf);
769         if (!strncasecmp(actbuf, "GET /", 5))
770                 strcpy(actbuf, &actbuf[5]);
771         if (!strncasecmp(actbuf, "PUT /", 5))
772                 strcpy(actbuf, &actbuf[5]);
773         if (!strncasecmp(actbuf, "POST /", 6))
774                 strcpy(actbuf, &actbuf[6]);
775
776         for (i = 0; i < strlen(actbuf); ++i) {
777                 if (actbuf[i] == ' ') {
778                         actbuf[i] = 0;
779                         i = 0;
780                 }
781                 if (actbuf[i] == '/') {
782                         actbuf[i] = 0;
783                         i = 0;
784                 }
785                 if (actbuf[i] == '?') {
786                         actbuf[i] = 0;
787                         i = 0;
788                 }
789                 if (actbuf[i] == '&') {
790                         actbuf[i] = 0;
791                         i = 0;
792                 }
793         }
794 }
795
796
797 void upload_handler(char *name, char *filename, char *partnum, char *disp,
798                         void *content, char *cbtype, size_t length,
799                         char *encoding, void *userdata)
800 {
801         struct urlcontent *u;
802
803         /* Form fields */
804         if ( (length > 0) && (strlen(cbtype) == 0) ) {
805                 u = (struct urlcontent *) malloc(sizeof(struct urlcontent));
806                 u->next = WC->urlstrings;
807                 WC->urlstrings = u;
808                 safestrncpy(u->url_key, name, sizeof(u->url_key));
809                 u->url_data = malloc(length + 1);
810                 memcpy(u->url_data, content, length);
811                 u->url_data[length] = 0;
812         }
813
814         /* Uploaded files */
815         if ( (length > 0) && (strlen(cbtype) > 0) ) {
816                 WC->upload = malloc(length);
817                 if (WC->upload != NULL) {
818                         WC->upload_length = length;
819                         safestrncpy(WC->upload_filename, filename,
820                                         sizeof(WC->upload_filename));
821                         safestrncpy(WC->upload_content_type, cbtype,
822                                         sizeof(WC->upload_content_type));
823                         memcpy(WC->upload, content, length);
824                 }
825                 else {
826                         lprintf(3, "malloc() failed: %s\n", strerror(errno));
827                 }
828         }
829
830 }
831
832
833
834
835 /*
836  * Entry point for WebCit transaction
837  */
838 void session_loop(struct httprequest *req)
839 {
840         char cmd[SIZ];
841         char action[SIZ];
842         char buf[SIZ];
843         int a, b;
844         int ContentLength = 0;
845         int BytesRead = 0;
846         char ContentType[512];
847         char *content;
848         char *content_end;
849         struct httprequest *hptr;
850         char browser_host[SIZ];
851         char user_agent[SIZ];
852         int body_start;
853
854         /* We stuff these with the values coming from the client cookies,
855          * so we can use them to reconnect a timed out session if we have to.
856          */
857         char c_username[SIZ];
858         char c_password[SIZ];
859         char c_roomname[SIZ];
860         char cookie[SIZ];
861
862         strcpy(c_username, "");
863         strcpy(c_password, "");
864         strcpy(c_roomname, "");
865
866         WC->upload_length = 0;
867         WC->upload = NULL;
868         WC->vars = NULL;
869
870         WC->is_wap = 0;
871
872         hptr = req;
873         if (hptr == NULL) return;
874
875         strcpy(cmd, hptr->line);
876         hptr = hptr->next;
877         extract_action(action, cmd);
878
879         while (hptr != NULL) {
880                 strcpy(buf, hptr->line);
881                 hptr = hptr->next;
882
883                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
884                         safestrncpy(cookie, &buf[15], sizeof cookie);
885                         cookie_to_stuff(cookie, NULL,
886                                       c_username, c_password, c_roomname);
887                 }
888                 else if (!strncasecmp(buf, "Content-length: ", 16)) {
889                         ContentLength = atoi(&buf[16]);
890                 }
891                 else if (!strncasecmp(buf, "Content-type: ", 14)) {
892                         safestrncpy(ContentType, &buf[14], sizeof ContentType);
893                 }
894                 else if (!strncasecmp(buf, "User-agent: ", 12)) {
895                         safestrncpy(user_agent, &buf[12], sizeof user_agent);
896                 }
897                 else if (!strncasecmp(buf, "Host: ", 6)) {
898                         safestrncpy(WC->http_host, &buf[6], sizeof WC->http_host);
899                 }
900                 /* Only WAP gateways explicitly name this content-type */
901                 else if (strstr(buf, "text/vnd.wap.wml")) {
902                         WC->is_wap = 1;
903                 }
904         }
905
906         if (ContentLength > 0) {
907                 content = malloc(ContentLength + SIZ);
908                 memset(content, 0, ContentLength + SIZ);
909                 sprintf(content, "Content-type: %s\n"
910                                 "Content-length: %d\n\n",
911                                 ContentType, ContentLength);
912                 body_start = strlen(content);
913
914 /***** old version
915                 BytesRead = 0;
916                 while (BytesRead < ContentLength) {
917                         a=read(WC->http_sock, &content[BytesRead+body_start],
918                                 ContentLength - BytesRead);
919                         if (a <= 0) BytesRead = ContentLength;
920                         else BytesRead += a;
921                 }
922 *******/
923
924                 /* Now we're daring and read it all at once. */
925                 client_read(WC->http_sock, &content[BytesRead+body_start], ContentLength);
926
927                 if (!strncasecmp(ContentType,
928                               "application/x-www-form-urlencoded", 33)) {
929                         addurls(&content[body_start]);
930                 } else if (!strncasecmp(ContentType, "multipart", 9)) {
931                         content_end = content + ContentLength + body_start;
932                         mime_parser(content, content_end, *upload_handler,
933                                         NULL, NULL, NULL, 0);
934                 }
935         } else {
936                 content = NULL;
937         }
938
939         /* make a note of where we are in case the user wants to save it */
940         safestrncpy(WC->this_page, cmd, sizeof(WC->this_page));
941         remove_token(WC->this_page, 2, ' ');
942         remove_token(WC->this_page, 0, ' ');
943
944         /* If there are variables in the URL, we must grab them now */
945         for (a = 0; a < strlen(cmd); ++a) {
946                 if ((cmd[a] == '?') || (cmd[a] == '&')) {
947                         for (b = a; b < strlen(cmd); ++b)
948                                 if (isspace(cmd[b]))
949                                         cmd[b] = 0;
950                         addurls(&cmd[a + 1]);
951                         cmd[a] = 0;
952                 }
953         }
954
955         /* Static content can be sent without connecting to Citadel. */
956         if (!strcasecmp(action, "static")) {
957                 strcpy(buf, &cmd[12]);
958                 for (a = 0; a < strlen(buf); ++a)
959                         if (isspace(buf[a]))
960                                 buf[a] = 0;
961                 output_static(buf);
962                 goto SKIP_ALL_THIS_CRAP;        /* Don't try to connect */
963         }
964
965         /*
966          * If we're not connected to a Citadel server, try to hook up the
967          * connection now.
968          */
969         if (!WC->connected) {
970                 if (!strcasecmp(ctdlhost, "uds")) {
971                         /* unix domain socket */
972                         sprintf(buf, "%s/citadel.socket", ctdlport);
973                         WC->serv_sock = uds_connectsock(buf);
974                 }
975                 else {
976                         /* tcp socket */
977                         WC->serv_sock = tcp_connectsock(ctdlhost, ctdlport);
978                 }
979
980                 if (WC->serv_sock < 0) {
981                         do_logout();
982                         goto SKIP_ALL_THIS_CRAP;
983                 }
984                 else {
985                         WC->connected = 1;
986                         serv_gets(buf); /* get the server welcome message */
987                         locate_host(browser_host, WC->http_sock);
988                         get_serv_info(browser_host, user_agent);
989                         if (serv_info.serv_rev_level < MINIMUM_CIT_VERSION) {
990                                 wprintf("You are connected to a Citadel "
991                                         "server running Citadel %d.%02d;\nin "
992                                         "order to run this version of WebCit "
993                                         "you must also have Citadel %d.%02d or"
994                                         " newer.\n\n\n",
995                                                 serv_info.serv_rev_level / 100,
996                                                 serv_info.serv_rev_level % 100,
997                                                 MINIMUM_CIT_VERSION / 100,
998                                                 MINIMUM_CIT_VERSION % 100
999                                         );
1000                                 end_webcit_session();
1001                                 goto SKIP_ALL_THIS_CRAP;
1002                         }
1003                 }
1004         }
1005
1006         /*
1007          * Functions which can be performed without logging in
1008          */
1009         if (!strcasecmp(action, "listsub")) {
1010                 do_listsub();
1011                 goto SKIP_ALL_THIS_CRAP;
1012         }
1013 #ifdef WEBCIT_WITH_CALENDAR_SERVICE
1014         if (!strcasecmp(action, "freebusy")) {
1015                 do_freebusy(cmd);
1016                 goto SKIP_ALL_THIS_CRAP;
1017         }
1018 #endif
1019
1020         check_for_express_messages();
1021
1022         /*
1023          * If we're not logged in, but we have username and password cookies
1024          * supplied by the browser, try using them to log in.
1025          */
1026         if ((!WC->logged_in) && (strlen(c_username) > 0) && (strlen(c_password) > 0)) {
1027                 serv_printf("USER %s", c_username);
1028                 serv_gets(buf);
1029                 if (buf[0] == '3') {
1030                         serv_printf("PASS %s", c_password);
1031                         serv_gets(buf);
1032                         if (buf[0] == '2') {
1033                                 become_logged_in(c_username, c_password, buf);
1034                         }
1035                 }
1036         }
1037         /*
1038          * If we don't have a current room, but a cookie specifying the
1039          * current room is supplied, make an effort to go there.
1040          */
1041         if ((strlen(WC->wc_roomname) == 0) && (strlen(c_roomname) > 0)) {
1042                 serv_printf("GOTO %s", c_roomname);
1043                 serv_gets(buf);
1044                 if (buf[0] == '2') {
1045                         strcpy(WC->wc_roomname, c_roomname);
1046                 }
1047         }
1048
1049         if (!strcasecmp(action, "image")) {
1050                 output_image();
1051
1052         /*
1053          * All functions handled below this point ... make sure we log in
1054          * before doing anything else!
1055          */
1056         } else if ((!WC->logged_in) && (!strcasecmp(action, "login"))) {
1057                 do_login();
1058         } else if (!WC->logged_in) {
1059                 display_login(NULL);
1060         }
1061
1062         /*
1063          * Various commands...
1064          */
1065
1066         else if (!strcasecmp(action, "do_welcome")) {
1067                 do_welcome();
1068         } else if (!strcasecmp(action, "blank")) {
1069                 blank_page();
1070         } else if (!strcasecmp(action, "do_template")) {
1071                 url_do_template();
1072         } else if (!strcasecmp(action, "display_main_menu")) {
1073                 display_main_menu();
1074         } else if (!strcasecmp(action, "whobbs")) {
1075                 whobbs();
1076         } else if (!strcasecmp(action, "knrooms")) {
1077                 knrooms();
1078         } else if (!strcasecmp(action, "gotonext")) {
1079                 slrp_highest();
1080                 gotonext();
1081         } else if (!strcasecmp(action, "skip")) {
1082                 gotonext();
1083         } else if (!strcasecmp(action, "ungoto")) {
1084                 ungoto();
1085         } else if (!strcasecmp(action, "dotgoto")) {
1086                 slrp_highest();
1087                 smart_goto(bstr("room"));
1088         } else if (!strcasecmp(action, "dotskip")) {
1089                 smart_goto(bstr("room"));
1090         } else if (!strcasecmp(action, "termquit")) {
1091                 do_logout();
1092         } else if (!strcasecmp(action, "readnew")) {
1093                 readloop("readnew");
1094         } else if (!strcasecmp(action, "readold")) {
1095                 readloop("readold");
1096         } else if (!strcasecmp(action, "readfwd")) {
1097                 readloop("readfwd");
1098         } else if (!strcasecmp(action, "headers")) {
1099                 readloop("headers");
1100         } else if (!strcasecmp(action, "display_enter")) {
1101                 display_enter();
1102         } else if (!strcasecmp(action, "post")) {
1103                 post_message();
1104         } else if (!strcasecmp(action, "do_stuff_to_one_msg")) {
1105                 do_stuff_to_one_msg();
1106         } else if (!strcasecmp(action, "move_msg")) {
1107                 move_msg();
1108         } else if (!strcasecmp(action, "userlist")) {
1109                 userlist();
1110         } else if (!strcasecmp(action, "showuser")) {
1111                 showuser();
1112         } else if (!strcasecmp(action, "display_page")) {
1113                 display_page();
1114         } else if (!strcasecmp(action, "page_user")) {
1115                 page_user();
1116         } else if (!strcasecmp(action, "chat")) {
1117                 do_chat();
1118         } else if (!strcasecmp(action, "display_private")) {
1119                 display_private("", 0);
1120         } else if (!strcasecmp(action, "goto_private")) {
1121                 goto_private();
1122         } else if (!strcasecmp(action, "zapped_list")) {
1123                 zapped_list();
1124         } else if (!strcasecmp(action, "display_zap")) {
1125                 display_zap();
1126         } else if (!strcasecmp(action, "zap")) {
1127                 zap();
1128         } else if (!strcasecmp(action, "display_entroom")) {
1129                 display_entroom();
1130         } else if (!strcasecmp(action, "entroom")) {
1131                 entroom();
1132         } else if (!strcasecmp(action, "display_editroom")) {
1133                 display_editroom();
1134         } else if (!strcasecmp(action, "netedit")) {
1135                 netedit();
1136         } else if (!strcasecmp(action, "editroom")) {
1137                 editroom();
1138         } else if (!strcasecmp(action, "display_whok")) {
1139                 display_whok();
1140         } else if (!strcasecmp(action, "display_editinfo")) {
1141                 display_edit("Room info", "EINF 0", "RINF", "/editinfo", 1);
1142         } else if (!strcasecmp(action, "editinfo")) {
1143                 save_edit("Room info", "EINF 1", 1);
1144         } else if (!strcasecmp(action, "display_editbio")) {
1145                 sprintf(buf, "RBIO %s", WC->wc_username);
1146                 display_edit("Your bio", "NOOP", buf, "editbio", 3);
1147         } else if (!strcasecmp(action, "editbio")) {
1148                 save_edit("Your bio", "EBIO", 0);
1149         } else if (!strcasecmp(action, "confirm_delete_room")) {
1150                 confirm_delete_room();
1151         } else if (!strcasecmp(action, "delete_room")) {
1152                 delete_room();
1153         } else if (!strcasecmp(action, "validate")) {
1154                 validate();
1155         } else if (!strcasecmp(action, "display_editpic")) {
1156                 display_graphics_upload("your photo",
1157                                         "UIMG 0|_userpic_",
1158                                         "/editpic");
1159         } else if (!strcasecmp(action, "editpic")) {
1160                 do_graphics_upload("UIMG 1|_userpic_");
1161         } else if (!strcasecmp(action, "display_editroompic")) {
1162                 display_graphics_upload("the graphic for this room",
1163                                         "UIMG 0|_roompic_",
1164                                         "/editroompic");
1165         } else if (!strcasecmp(action, "editroompic")) {
1166                 do_graphics_upload("UIMG 1|_roompic_");
1167         } else if (!strcasecmp(action, "delete_floor")) {
1168                 delete_floor();
1169         } else if (!strcasecmp(action, "rename_floor")) {
1170                 rename_floor();
1171         } else if (!strcasecmp(action, "create_floor")) {
1172                 create_floor();
1173         } else if (!strcasecmp(action, "display_editfloorpic")) {
1174                 sprintf(buf, "UIMG 0|_floorpic_|%s",
1175                         bstr("which_floor"));
1176                 display_graphics_upload("the graphic for this floor",
1177                                         buf,
1178                                         "/editfloorpic");
1179         } else if (!strcasecmp(action, "editfloorpic")) {
1180                 sprintf(buf, "UIMG 1|_floorpic_|%s",
1181                         bstr("which_floor"));
1182                 do_graphics_upload(buf);
1183         } else if (!strcasecmp(action, "display_reg")) {
1184                 display_reg(0);
1185         } else if (!strcasecmp(action, "display_changepw")) {
1186                 display_changepw();
1187         } else if (!strcasecmp(action, "changepw")) {
1188                 changepw();
1189         } else if (!strcasecmp(action, "display_edit_node")) {
1190                 display_edit_node();
1191         } else if (!strcasecmp(action, "edit_node")) {
1192                 edit_node();
1193         } else if (!strcasecmp(action, "display_netconf")) {
1194                 display_netconf();
1195         } else if (!strcasecmp(action, "display_confirm_delete_node")) {
1196                 display_confirm_delete_node();
1197         } else if (!strcasecmp(action, "delete_node")) {
1198                 delete_node();
1199         } else if (!strcasecmp(action, "display_add_node")) {
1200                 display_add_node();
1201         } else if (!strcasecmp(action, "add_node")) {
1202                 add_node();
1203         } else if (!strcasecmp(action, "terminate_session")) {
1204                 slrp_highest();
1205                 terminate_session();
1206         } else if (!strcasecmp(action, "edit_me")) {
1207                 edit_me();
1208         } else if (!strcasecmp(action, "display_siteconfig")) {
1209                 display_siteconfig();
1210         } else if (!strcasecmp(action, "chat_recv")) {
1211                 chat_recv();
1212         } else if (!strcasecmp(action, "chat_send")) {
1213                 chat_send();
1214         } else if (!strcasecmp(action, "page_popup")) {
1215                 page_popup();
1216         } else if (!strcasecmp(action, "siteconfig")) {
1217                 siteconfig();
1218         } else if (!strcasecmp(action, "display_generic")) {
1219                 display_generic();
1220         } else if (!strcasecmp(action, "do_generic")) {
1221                 do_generic();
1222         } else if (!strcasecmp(action, "display_menubar")) {
1223                 display_menubar(1);
1224         } else if (!strcasecmp(action, "output_mimepart")) {
1225                 output_mimepart();
1226         } else if (!strcasecmp(action, "edit_vcard")) {
1227                 edit_vcard();
1228         } else if (!strcasecmp(action, "submit_vcard")) {
1229                 submit_vcard();
1230         } else if (!strcasecmp(action, "select_user_to_edit")) {
1231                 select_user_to_edit(NULL, NULL);
1232         } else if (!strcasecmp(action, "display_edituser")) {
1233                 display_edituser(NULL, 0);
1234         } else if (!strcasecmp(action, "edituser")) {
1235                 edituser();
1236         } else if (!strcasecmp(action, "create_user")) {
1237                 create_user();
1238         } else if (!strcasecmp(action, "changeview")) {
1239                 change_view();
1240         } else if (!strcasecmp(action, "do_stuff_to_msgs")) {
1241                 do_stuff_to_msgs();
1242         } else if (!strcasecmp(action, "change_start_page")) {
1243                 change_start_page();
1244         } else if (!strcasecmp(action, "display_floorconfig")) {
1245                 display_floorconfig(NULL);
1246         } else if (!strcasecmp(action, "toggle_self_service")) {
1247                 toggle_self_service();
1248 #ifdef WEBCIT_WITH_CALENDAR_SERVICE
1249         } else if (!strcasecmp(action, "display_edit_task")) {
1250                 display_edit_task();
1251         } else if (!strcasecmp(action, "save_task")) {
1252                 save_task();
1253         } else if (!strcasecmp(action, "display_edit_event")) {
1254                 display_edit_event();
1255         } else if (!strcasecmp(action, "save_event")) {
1256                 save_event();
1257         } else if (!strcasecmp(action, "respond_to_request")) {
1258                 respond_to_request();
1259         } else if (!strcasecmp(action, "handle_rsvp")) {
1260                 handle_rsvp();
1261 #endif
1262         } else if (!strcasecmp(action, "summary")) {
1263                 summary();
1264         } else if (!strcasecmp(action, "iconbar")) {
1265                 do_iconbar();
1266         } else if (!strcasecmp(action, "display_customize_iconbar")) {
1267                 display_customize_iconbar();
1268         } else if (!strcasecmp(action, "commit_iconbar")) {
1269                 commit_iconbar();
1270         } else if (!strcasecmp(action, "set_room_policy")) {
1271                 set_room_policy();
1272         } else if (!strcasecmp(action, "display_inetconf")) {
1273                 display_inetconf();
1274         } else if (!strcasecmp(action, "save_inetconf")) {
1275                 save_inetconf();
1276         } else if (!strcasecmp(action, "diagnostics")) {
1277                 output_headers(1);
1278
1279                 wprintf("You're in session %d<HR>\n", WC->wc_session);
1280                 wprintf("Command: <BR><PRE>\n");
1281                 escputs(cmd);
1282                 wprintf("</PRE><HR>\n");
1283                 wprintf("Variables: <BR><PRE>\n");
1284                 dump_vars();
1285                 wprintf("</PRE><HR>\n");
1286                 wDumpContent(1);
1287         }
1288         /* When all else fais, display the main menu. */
1289         else {
1290                 display_main_menu();
1291         }
1292
1293 SKIP_ALL_THIS_CRAP:
1294         fflush(stdout);
1295         if (content != NULL) {
1296                 free(content);
1297                 content = NULL;
1298         }
1299         free_urls();
1300         if (WC->upload_length > 0) {
1301                 free(WC->upload);
1302                 WC->upload_length = 0;
1303         }
1304
1305 }