* Finished gzip compression of dynamic pages (when browser supports it)
[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 the & sign */
96                 ptr = up;
97                 b = strlen(up);
98                 for (a = 0; a < strlen(up); ++a) {
99                         if (!strncmp(ptr, "&", 1)) {
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) + 1);
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 #ifdef WITH_ZLIB
156
157 ssize_t http_write(int fd, const void *buf, size_t count) {
158
159         if (WC->gzfd) {
160                 return gzwrite(WC->gzfd, buf, count);
161         }
162         else {
163                 return write(fd, buf, count);
164         }
165
166
167 }
168
169 #else
170
171 ssize_t http_write(int fd, const void *buf, size_t count) {
172         return write(fd, buf, count);
173 }
174
175 #endif
176
177
178
179
180 void wprintf(const char *format,...)
181 {
182         va_list arg_ptr;
183         char wbuf[1024];
184
185         va_start(arg_ptr, format);
186         vsprintf(wbuf, format, arg_ptr);
187         va_end(arg_ptr);
188
189         http_write(WC->http_sock, wbuf, strlen(wbuf));
190 }
191
192
193 /*
194  * wDumpContent() wraps up an HTTP session, closes tags, etc.
195  *
196  * print_standard_html_footer should be set to 0 to transmit only, 1 to
197  * append the main menu and closing tags, or 2 to
198  * append the closing tags only.
199  */
200 void wDumpContent(int print_standard_html_footer)
201 {
202         if (WC->fake_frames) {
203                 wprintf("</TABLE>\n");
204                 WC->fake_frames = 0;
205         }
206
207         if (print_standard_html_footer) {
208                 if (print_standard_html_footer != 2) {
209                         wprintf("<BR>");
210                 }
211                 wprintf("</BODY></HTML>\n");
212         }
213
214
215 }
216
217
218 /*
219  * Copy a string, escaping characters which have meaning in HTML.  If
220  * nbsp is nonzero, spaces are converted to non-breaking spaces.
221  */
222 void stresc(char *target, char *strbuf, int nbsp)
223 {
224         int a;
225         strcpy(target, "");
226
227         for (a = 0; a < strlen(strbuf); ++a) {
228                 if (strbuf[a] == '<')
229                         strcat(target, "&lt;");
230                 else if (strbuf[a] == '>')
231                         strcat(target, "&gt;");
232                 else if (strbuf[a] == '&')
233                         strcat(target, "&amp;");
234                 else if (strbuf[a] == '\"')
235                         strcat(target, "&quot;");
236                 else if (strbuf[a] == '\'') 
237                         strcat(target, "&#39;");
238                 else if (strbuf[a] == LB)
239                         strcat(target, "<");
240                 else if (strbuf[a] == RB)
241                         strcat(target, ">");
242                 else if (strbuf[a] == QU)
243                         strcat(target, "\"");
244                 else if ((strbuf[a] == 32) && (nbsp == 1)) {
245                         strcat(target, "&nbsp;");
246                 } else {
247                         strncat(target, &strbuf[a], 1);
248                 }
249         }
250 }
251
252 void escputs1(char *strbuf, int nbsp)
253 {
254         char buf[1024];
255         stresc(buf, strbuf, nbsp);
256         wprintf("%s", buf);
257 }
258
259 void escputs(char *strbuf)
260 {
261         escputs1(strbuf, 0);
262 }
263
264 /*
265  * Escape a string for feeding out as a URL.
266  * Returns a pointer to a buffer that must be freed by the caller!
267  */
268 void urlesc(char *outbuf, char *strbuf)
269 {
270         int a, b, c;
271         char *ec = " #&;`'|*?-~<>^()[]{}$\\";
272
273         strcpy(outbuf, "");
274
275         for (a = 0; a < strlen(strbuf); ++a) {
276                 c = 0;
277                 for (b = 0; b < strlen(ec); ++b) {
278                         if (strbuf[a] == ec[b])
279                                 c = 1;
280                 }
281                 b = strlen(outbuf);
282                 if (c == 1)
283                         sprintf(&outbuf[b], "%%%02x", strbuf[a]);
284                 else
285                         sprintf(&outbuf[b], "%c", strbuf[a]);
286         }
287 }
288
289 void urlescputs(char *strbuf)
290 {
291         char outbuf[SIZ];
292         
293         urlesc(outbuf, strbuf);
294         wprintf("%s", outbuf);
295 }
296
297
298
299
300 /*
301  * Output all that important stuff that the browser will want to see
302  *
303  * control codes:
304  * 
305  * Bits 0 and 1:
306  * 0 = Nothing.  Do not display any leading HTTP or HTML.
307  * 1 = HTTP headers plus the room banner
308  * 2 = HTTP headers required to terminate the session (unset cookies)
309  * 3 = HTTP and HTML headers, but no room banner
310  *
311  * Bit 2: Set to 1 to auto-refresh page every 30 seconds
312  *
313  * Bit 3: suppress check for express messages
314  */
315 void output_headers(int controlcode)
316 {
317         char cookie[SIZ];
318         int print_standard_html_head = 0;
319         int refresh30 = 0;
320         int suppress_check = 0;
321         char httpnow[SIZ];
322         static int pageseq = 0;
323 #ifdef WITH_ZLIB
324         gzFile temp_gzfd = NULL;
325 #endif
326
327         print_standard_html_head        =       controlcode & 0x03;
328         refresh30                       =       ((controlcode & 0x04) >> 2);
329         suppress_check                  =       ((controlcode & 0x08) >> 3);
330
331         wprintf("HTTP/1.0 200 OK\n");
332
333         httpdate(httpnow, time(NULL));
334
335 #ifdef WITH_ZLIB
336         if (WC->gzcompressed) {
337                 temp_gzfd = gzdopen(WC->http_sock, "wb9");
338         }
339 #endif
340
341         if (print_standard_html_head > 0) {
342                 wprintf("Content-type: text/html\n");
343                 wprintf("Server: %s\n", SERVER);
344                 wprintf("Connection: close\n");
345                 wprintf("Pragma: no-cache\n");
346                 wprintf("Cache-Control: no-store\n");
347 #ifdef WITH_ZLIB
348                 if (temp_gzfd != NULL) {
349                         wprintf("Content-Encoding: gzip\n");
350                 }
351 #endif
352         }
353         stuff_to_cookie(cookie, WC->wc_session, WC->wc_username,
354                         WC->wc_password, WC->wc_roomname);
355         if (print_standard_html_head == 2) {
356                 wprintf("Set-cookie: webcit=%s\n", unset);
357         } else {
358                 wprintf("Set-cookie: webcit=%s\n", cookie);
359                 if (server_cookie != NULL) {
360                         wprintf("%s\n", server_cookie);
361                 }
362         }
363
364         if (print_standard_html_head > 0) {
365                 wprintf("\n");
366
367 #ifdef WITH_ZLIB
368                 if (temp_gzfd != NULL) {
369                         WC->gzfd = temp_gzfd;
370                 }
371 #endif
372
373                 wprintf("<HTML><HEAD><TITLE>");
374                 escputs(serv_info.serv_humannode);
375                 wprintf("</TITLE>\n"
376                         "<META HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\">\n"
377                         "<META HTTP-EQUIV=\"expired\" CONTENT=\"28-May-1971 18:10:00 GMT\">\n"
378                         "<META NAME=\"MSSmartTagsPreventParsing\" CONTENT=\"TRUE\">\n");
379                 if (refresh30) wprintf(
380                         "<META HTTP-EQUIV=\"refresh\" CONTENT=\"30\">\n");
381                 else wprintf(
382                         "<META HTTP-EQUIV=\"refresh\" CONTENT=\"500363689;\">\n");
383                 wprintf("</HEAD>\n");
384
385                 /* script for checking for pages (not always launched) */
386                 wprintf("<SCRIPT LANGUAGE=\"JavaScript\">\n");
387                 wprintf("function launch_page_popup() {\n");
388                 wprintf("pwin = window.open('/page_popup', 'CitaPage%d', "
389                         "'toolbar=no,location=no,copyhistory=no,status=no,"
390                         "scrollbars=yes,resizable=no,height=250,width=400');\n",
391                         ++pageseq);
392                 wprintf("}\n");
393                 wprintf("</SCRIPT>\n");
394                 /* end script */
395
396                 /* (JavaScript keyboard-based navigation would go here) */
397
398                 if (!suppress_check) if (WC->HaveExpressMessages) {
399                         svprintf("extrabodyparms", WCS_STRING, "%s", 
400                                 "onload=\"launch_page_popup()\" ");
401                         WC->HaveExpressMessages = 0;
402                 }
403                 do_template("background");
404                 clear_local_substs();
405
406         if (print_standard_html_head == 1) {
407                 wprintf("<A NAME=\"TheTop\"></A>");
408
409                 wprintf("<TABLE border=0 width=100%%><TR VALIGN=TOP>"
410                         "<TD>\n");
411
412                 embed_room_banner(NULL);
413
414                 wprintf("</TD></TR><TR VALIGN=TOP><TD>\n");
415                 
416                 WC->fake_frames = 1;
417                 }
418         }
419 }
420
421
422 /*
423  *
424  */
425 void http_redirect(char *whichpage) {
426         wprintf("HTTP/1.0 302 Moved Temporarily\n");
427         wprintf("Location: %s\n", whichpage);
428         wprintf("URI: %s\n", whichpage);
429         wprintf("Content-type: text/html\n\n");
430         wprintf("<html><body>\n");
431         wprintf("you really want to be <A HREF=\"%s\">here</A> now\n",
432                 whichpage);
433         wprintf("</body></html>\n");
434 }
435
436
437
438 void check_for_express_messages()
439 {
440         char buf[SIZ];
441
442         serv_puts("NOOP");
443         serv_gets(buf);
444         if (buf[3] == '*') WC->HaveExpressMessages = 1;
445 }
446
447
448
449
450 void output_static(char *what)
451 {
452         char buf[4096];
453         FILE *fp;
454         struct stat statbuf;
455         off_t bytes;
456         char *bigbuffer;
457
458         sprintf(buf, "static/%s", what);
459         fp = fopen(buf, "rb");
460         if (fp == NULL) {
461                 wprintf("HTTP/1.0 404 %s\n", strerror(errno));
462                 wprintf("Content-Type: text/plain\n");
463                 wprintf("\n");
464                 wprintf("Cannot open %s: %s\n", what, strerror(errno));
465         } else {
466                 output_headers(0);
467
468                 if (!strncasecmp(&what[strlen(what) - 4], ".gif", 4))
469                         wprintf("Content-type: image/gif\n");
470                 else if (!strncasecmp(&what[strlen(what) - 4], ".txt", 4))
471                         wprintf("Content-type: text/plain\n");
472                 else if (!strncasecmp(&what[strlen(what) - 4], ".css", 4))
473                         wprintf("Content-type: text/css\n");
474                 else if (!strncasecmp(&what[strlen(what) - 4], ".jpg", 4))
475                         wprintf("Content-type: image/jpeg\n");
476                 else if (!strncasecmp(&what[strlen(what) - 4], ".png", 4))
477                         wprintf("Content-type: image/png\n");
478                 else if (!strncasecmp(&what[strlen(what) - 5], ".html", 5))
479                         wprintf("Content-type: text/html\n");
480                 else if (!strncasecmp(&what[strlen(what) - 4], ".wml", 4))
481                         wprintf("Content-type: text/vnd.wap.wml\n");
482                 else if (!strncasecmp(&what[strlen(what) - 5], ".wmls", 5))
483                         wprintf("Content-type: text/vnd.wap.wmlscript\n");
484                 else if (!strncasecmp(&what[strlen(what) - 5], ".wmlc", 5))
485                         wprintf("Content-type: application/vnd.wap.wmlc\n");
486                 else if (!strncasecmp(&what[strlen(what) - 6], ".wmlsc", 6))
487                         wprintf("Content-type: application/vnd.wap.wmlscriptc\n");
488                 else if (!strncasecmp(&what[strlen(what) - 5], ".wbmp", 5))
489                         wprintf("Content-type: image/vnd.wap.wbmp\n");
490                 else
491                         wprintf("Content-type: application/octet-stream\n");
492
493                 fstat(fileno(fp), &statbuf);
494                 bytes = statbuf.st_size;
495                 lprintf(3, "Static: %s, %ld bytes\n", what, bytes);
496                 wprintf("Content-length: %ld\n", (long) bytes);
497                 wprintf("\n");
498                 bigbuffer = malloc(bytes);
499                 fread(bigbuffer, bytes, 1, fp);
500                 fclose(fp);
501                 http_write(WC->http_sock, bigbuffer, bytes);
502                 free(bigbuffer);
503         }
504         if (!strcasecmp(bstr("force_close_session"), "yes")) {
505                 end_webcit_session();
506         }
507 }
508
509
510 /*
511  * When the browser requests an image file from the Citadel server,
512  * this function is called to transmit it.
513  */
514 void output_image()
515 {
516         char buf[SIZ];
517         char xferbuf[4096];
518         off_t bytes;
519         off_t thisblock;
520         off_t accomplished = 0L;
521
522         lprintf(5, "output_image() called\n");
523         serv_printf("OIMG %s|%s", bstr("name"), bstr("parm"));
524         serv_gets(buf);
525         if (buf[0] == '2') {
526                 bytes = extract_long(&buf[4], 0);
527                 output_headers(0);
528                 wprintf("Content-type: image/gif\n");
529                 wprintf("Content-length: %ld\n", (long) bytes);
530                 wprintf("\n");
531
532                 while (bytes > (off_t) 0) {
533                         thisblock = (off_t) sizeof(xferbuf);
534                         if (thisblock > bytes) {
535                                 thisblock = bytes;
536                         }
537                         serv_printf("READ %ld|%ld", accomplished, thisblock);
538                         serv_gets(buf);
539                         if (buf[0] == '6') {
540                                 thisblock = extract_long(&buf[4], 0);
541                                 serv_read(xferbuf, (int) thisblock);
542                         }
543                         else {
544                                 memset(xferbuf, 0, thisblock);
545                         }
546                         http_write(WC->http_sock, xferbuf, thisblock);
547                         bytes = bytes - thisblock;
548                         accomplished = accomplished + thisblock;
549                 }
550                 serv_puts("CLOS");
551                 serv_gets(buf);
552         } else {
553                 wprintf("HTTP/1.0 404 %s\n", &buf[4]);
554                 output_headers(0);
555                 wprintf("Content-Type: text/plain\n");
556                 wprintf("\n");
557                 wprintf("Error retrieving image: %s\n", &buf[4]);
558         }
559
560 }
561
562 /*
563  */
564 void output_mimepart()
565 {
566         char buf[SIZ];
567         char xferbuf[4096];
568         off_t bytes;
569         off_t thisblock;
570         off_t accomplished = 0L;
571         char content_type[SIZ];
572         
573         serv_printf("OPNA %s|%s", bstr("msgnum"), bstr("partnum"));
574         serv_gets(buf);
575         if (buf[0] == '2') {
576                 bytes = extract_long(&buf[4], 0);
577                 extract(content_type, &buf[4], 3);
578                 output_headers(0);
579                 wprintf("Content-type: %s\n", content_type);
580                 wprintf("Content-length: %ld\n", (long) bytes);
581                 wprintf("\n");
582
583                 while (bytes > (off_t) 0) {
584                         thisblock = (off_t) sizeof(xferbuf);
585                         if (thisblock > bytes) {
586                                 thisblock = bytes;
587                         }
588                         serv_printf("READ %ld|%ld", accomplished, thisblock);
589                         serv_gets(buf);
590                         if (buf[0] == '6') {
591                                 thisblock = extract_long(&buf[4], 0);
592                                 serv_read(xferbuf, (int) thisblock);
593                         }
594                         else {
595                                 memset(xferbuf, 0, thisblock);
596                         }
597                         http_write(WC->http_sock, xferbuf, thisblock);
598                         bytes = bytes - thisblock;
599                         accomplished = accomplished + thisblock;
600                 }
601                 serv_puts("CLOS");
602                 serv_gets(buf);
603         } else {
604                 wprintf("HTTP/1.0 404 %s\n", &buf[4]);
605                 output_headers(0);
606                 wprintf("Content-Type: text/plain\n");
607                 wprintf("\n");
608                 wprintf("Error retrieving part: %s\n", &buf[4]);
609         }
610
611 }
612
613
614 /*
615  */
616 char *load_mimepart(long msgnum, char *partnum)
617 {
618         char buf[SIZ];
619         off_t bytes;
620         off_t thisblock;
621         off_t accomplished = 0L;
622         char content_type[SIZ];
623         char *content;
624         
625         serv_printf("OPNA %ld|%s", msgnum, partnum);
626         serv_gets(buf);
627         if (buf[0] == '2') {
628                 bytes = extract_long(&buf[4], 0);
629                 extract(content_type, &buf[4], 3);
630
631                 content = malloc(bytes + 1);
632
633                 while (bytes > (off_t) 0) {
634                         thisblock = bytes;
635                         if (thisblock > 4096L) {
636                                 thisblock = 4096L;
637                         }
638                         if (thisblock > bytes) {
639                                 thisblock = bytes;
640                         }
641                         serv_printf("READ %ld|%ld", accomplished, thisblock);
642                         serv_gets(buf);
643                         if (buf[0] == '6') {
644                                 thisblock = extract_long(&buf[4], 0);
645                                 serv_read(&content[accomplished], (int) thisblock);
646                         }
647                         else {
648                                 memset(&content[accomplished], 0, thisblock);
649                         }
650                         bytes = bytes - thisblock;
651                         accomplished = accomplished + thisblock;
652                 }
653                 serv_puts("CLOS");
654                 serv_gets(buf);
655                 content[accomplished] = 0;      /* null terminate for good measure */
656                 return(content);
657         }
658         else {
659                 return(NULL);
660         }
661
662 }
663
664
665 /*
666  * Convenience functions to display a page containing only a string
667  */
668 void convenience_page(char *titlebarcolor, char *titlebarmsg, char *messagetext)
669 {
670         wprintf("HTTP/1.0 200 OK\n");
671         output_headers(1);
672         wprintf("<TABLE WIDTH=100%% BORDER=0 BGCOLOR=%s><TR><TD>", titlebarcolor);
673         wprintf("<FONT SIZE=+1 COLOR=\"FFFFFF\"");
674         wprintf("<B>%s</B>\n", titlebarmsg);
675         wprintf("</FONT></TD></TR></TABLE><BR>\n");
676         escputs(messagetext);
677
678         wprintf("<HR>\n");
679         wDumpContent(1);
680 }
681
682
683 /*
684  * Display a blank page.
685  */
686 void blank_page(void) {
687         output_headers(7);
688         wDumpContent(2);
689 }
690
691
692
693
694 /*
695  * Offer to make any page the user's "start page."
696  */
697 void offer_start_page(void) {
698         wprintf("<A HREF=\"/change_start_page?startpage=");
699         urlescputs(WC->this_page);
700         wprintf("\">"
701                 "<FONT SIZE=-2 COLOR=#AAAAAA>Make this my start page</FONT>"
702                 "</A>"
703         );
704 }
705
706
707 /* 
708  * Change the user's start page
709  */
710 void change_start_page(void) {
711
712         if (bstr("startpage") == NULL) {
713                 display_error("startpage set to null");
714                 return;
715         }
716
717         set_preference("startpage", bstr("startpage"));
718
719         output_headers(3);
720         wprintf("<TABLE WIDTH=100%% BORDER=0 BGCOLOR=000077><TR><TD>");
721         wprintf("<FONT SIZE=+1 COLOR=\"FFFFFF\"");
722         wprintf("<B>New start page</B>\n");
723         wprintf("</FONT></TD></TR></TABLE>\n");
724
725         wprintf("<CENTER>"
726                 "<font size=+2>Your start page has been changed.</font>"
727                 "<BR><BR>\n"
728                 "<I>(Note: this does not change your browser's home page. "
729                 "It changes the page you begin on when you log on to ");
730         escputs(serv_info.serv_humannode);
731         wprintf(".)</I><BR><BR>"
732                 "<a href = \"javascript:history.back()\">Back...</a>"
733                 "</CENTER>");
734
735         wDumpContent(1);
736 }
737
738
739
740
741 void display_error(char *errormessage)
742 {
743         convenience_page("770000", "Error", errormessage);
744 }
745
746 void display_success(char *successmessage)
747 {
748         convenience_page("007700", "OK", successmessage);
749 }
750
751
752
753 void extract_action(char *actbuf, char *cmdbuf)
754 {
755         int i;
756
757         strcpy(actbuf, cmdbuf);
758         if (!strncasecmp(actbuf, "GET /", 5))
759                 strcpy(actbuf, &actbuf[5]);
760         if (!strncasecmp(actbuf, "PUT /", 5))
761                 strcpy(actbuf, &actbuf[5]);
762         if (!strncasecmp(actbuf, "POST /", 6))
763                 strcpy(actbuf, &actbuf[6]);
764
765         for (i = 0; i < strlen(actbuf); ++i) {
766                 if (actbuf[i] == ' ') {
767                         actbuf[i] = 0;
768                         i = 0;
769                 }
770                 if (actbuf[i] == '/') {
771                         actbuf[i] = 0;
772                         i = 0;
773                 }
774                 if (actbuf[i] == '?') {
775                         actbuf[i] = 0;
776                         i = 0;
777                 }
778                 if (actbuf[i] == '&') {
779                         actbuf[i] = 0;
780                         i = 0;
781                 }
782         }
783 }
784
785
786 void upload_handler(char *name, char *filename, char *partnum, char *disp,
787                         void *content, char *cbtype, size_t length,
788                         char *encoding, void *userdata)
789 {
790
791         lprintf(5, "UPLOAD HANDLER CALLED\n");
792         lprintf(5, "    name = %s\n", name);
793         lprintf(5, "filename = %s\n", filename);
794         lprintf(5, "encoding = %s\n", encoding);
795         lprintf(5, "    type = %s\n", cbtype);
796         lprintf(5, "  length = %ld\n", (long)length);
797
798         if (length > 0) {
799                 WC->upload = malloc(length);
800                 if (WC->upload != NULL) {
801                         WC->upload_length = length;
802                         memcpy(WC->upload, content, length);
803                 }
804                 else {
805                         lprintf(9, "malloc() failed: %s\n",
806                                 strerror(errno));
807                 }
808         }
809 }
810
811
812
813
814 /*
815  * Entry point for WebCit transaction
816  */
817 void session_loop(struct httprequest *req, int gzip)
818 {
819         char cmd[SIZ];
820         char action[SIZ];
821         char buf[SIZ];
822         int a, b;
823         int ContentLength = 0;
824         int BytesRead;
825         char ContentType[512];
826         char *content;
827         char *content_end;
828         struct httprequest *hptr;
829         char browser_host[SIZ];
830         char user_agent[SIZ];
831
832         /* We stuff these with the values coming from the client cookies,
833          * so we can use them to reconnect a timed out session if we have to.
834          */
835         char c_host[SIZ];
836         char c_port[SIZ];
837         char c_username[SIZ];
838         char c_password[SIZ];
839         char c_roomname[SIZ];
840         char cookie[SIZ];
841
842         strcpy(c_host, defaulthost);
843         strcpy(c_port, defaultport);
844         strcpy(c_username, "");
845         strcpy(c_password, "");
846         strcpy(c_roomname, "");
847
848         WC->upload_length = 0;
849         WC->upload = NULL;
850
851         WC->is_wap = 0;
852
853         if (gzip) {
854                 WC->gzcompressed = 1;
855         }
856         else {
857                 WC->gzcompressed = 0;
858         }
859
860         hptr = req;
861         if (hptr == NULL) return;
862
863         strcpy(cmd, hptr->line);
864         hptr = hptr->next;
865         extract_action(action, cmd);
866
867         while (hptr != NULL) {
868                 strcpy(buf, hptr->line);
869                 hptr = hptr->next;
870
871                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
872                         strcpy(cookie, &buf[15]);
873                         cookie_to_stuff(cookie, NULL,
874                                       c_username, c_password, c_roomname);
875                 }
876                 else if (!strncasecmp(buf, "Content-length: ", 16)) {
877                         ContentLength = atoi(&buf[16]);
878                 }
879                 else if (!strncasecmp(buf, "Content-type: ", 14)) {
880                         safestrncpy(ContentType, &buf[14], sizeof ContentType);
881                 }
882                 else if (!strncasecmp(buf, "User-agent: ", 12)) {
883                         safestrncpy(user_agent, &buf[12], sizeof user_agent);
884                 }
885                 else if (!strncasecmp(buf, "Host: ", 6)) {
886                         safestrncpy(WC->http_host, &buf[6], sizeof WC->http_host);
887                 }
888                 /* Only WAP gateways explicitly name this content-type */
889                 else if (strstr(buf, "text/vnd.wap.wml")) {
890                         WC->is_wap = 1;
891                 }
892         }
893
894         if (ContentLength > 0) {
895                 lprintf(5, "Content length: %d\n", ContentLength);
896                 content = malloc(ContentLength + 1);
897                 memset(content, 0, ContentLength+1);
898                 BytesRead = 0;
899
900                 while (BytesRead < ContentLength) {
901                         a=read(WC->http_sock, &content[BytesRead],
902                                 ContentLength - BytesRead);
903                         if (a <= 0) BytesRead = ContentLength;
904                         else BytesRead += a;
905                 }
906
907                 if (!strncasecmp(ContentType,
908                               "application/x-www-form-urlencoded", 33)) {
909                         addurls(content);
910                 } else if (!strncasecmp(ContentType, "multipart", 9)) {
911                         content_end = content + ContentLength;
912                         mime_parser(content, content_end, *upload_handler,
913                                         NULL, NULL, NULL, 0);
914                 }
915         } else {
916                 content = NULL;
917         }
918
919         /* make a note of where we are in case the user wants to save it */
920         safestrncpy(WC->this_page, cmd, sizeof(WC->this_page));
921         remove_token(WC->this_page, 2, ' ');
922         remove_token(WC->this_page, 0, ' ');
923
924         /* If there are variables in the URL, we must grab them now */
925         for (a = 0; a < strlen(cmd); ++a) {
926                 if ((cmd[a] == '?') || (cmd[a] == '&')) {
927                         for (b = a; b < strlen(cmd); ++b)
928                                 if (isspace(cmd[b]))
929                                         cmd[b] = 0;
930                         addurls(&cmd[a + 1]);
931                         cmd[a] = 0;
932                 }
933         }
934
935         /*
936          * If we're not connected to a Citadel server, try to hook up the
937          * connection now.  Preference is given to the host and port specified
938          * by browser cookies, if cookies have been supplied.
939          */
940         if (!WC->connected) {
941                 if (strlen(bstr("host")) > 0)
942                         strcpy(c_host, bstr("host"));
943                 if (strlen(bstr("port")) > 0)
944                         strcpy(c_port, bstr("port"));
945
946                 if (!strcasecmp(c_host, "uds")) {
947                         /* unix domain socket */
948                         sprintf(buf, "%s/citadel.socket", c_port);
949                         WC->serv_sock = uds_connectsock(buf);
950                 }
951                 else {
952                         /* tcp socket */
953                         WC->serv_sock = tcp_connectsock(c_host, c_port);
954                 }
955
956                 if (WC->serv_sock < 0) {
957                         do_logout();
958                         goto SKIP_ALL_THIS_CRAP;
959                 }
960                 else {
961                         WC->connected = 1;
962                         serv_gets(buf); /* get the server welcome message */
963                         locate_host(browser_host, WC->http_sock);
964                         get_serv_info(browser_host, user_agent);
965                 }
966         }
967
968         /*
969          * Functions which can be performed without logging in
970          */
971         if (!strcasecmp(action, "listsub")) {
972                 do_listsub();
973                 goto SKIP_ALL_THIS_CRAP;
974         }
975
976         check_for_express_messages();
977
978         /*
979          * If we're not logged in, but we have username and password cookies
980          * supplied by the browser, try using them to log in.
981          */
982         if ((!WC->logged_in) && (strlen(c_username) > 0) && (strlen(c_password) > 0)) {
983                 serv_printf("USER %s", c_username);
984                 serv_gets(buf);
985                 if (buf[0] == '3') {
986                         serv_printf("PASS %s", c_password);
987                         serv_gets(buf);
988                         if (buf[0] == '2') {
989                                 become_logged_in(c_username, c_password, buf);
990                         }
991                 }
992         }
993         /*
994          * If we don't have a current room, but a cookie specifying the
995          * current room is supplied, make an effort to go there.
996          */
997         if ((strlen(WC->wc_roomname) == 0) && (strlen(c_roomname) > 0)) {
998                 serv_printf("GOTO %s", c_roomname);
999                 serv_gets(buf);
1000                 if (buf[0] == '2') {
1001                         strcpy(WC->wc_roomname, c_roomname);
1002                 }
1003         }
1004         if (!strcasecmp(action, "static")) {
1005                 strcpy(buf, &cmd[12]);
1006                 for (a = 0; a < strlen(buf); ++a)
1007                         if (isspace(buf[a]))
1008                                 buf[a] = 0;
1009                 output_static(buf);
1010         } else if (!strcasecmp(action, "image")) {
1011                 output_image();
1012
1013         /*
1014          * All functions handled below this point ... make sure we log in
1015          * before doing anything else!
1016          */
1017         } else if ((!WC->logged_in) && (!strcasecmp(action, "login"))) {
1018                 do_login();
1019         } else if (!WC->logged_in) {
1020                 display_login(NULL);
1021         }
1022
1023         /*
1024          * Various commands...
1025          */
1026
1027         else if (!strcasecmp(action, "do_welcome")) {
1028                 do_welcome();
1029         } else if (!strcasecmp(action, "blank")) {
1030                 blank_page();
1031         } else if (!strcasecmp(action, "display_main_menu")) {
1032                 display_main_menu();
1033         } else if (!strcasecmp(action, "whobbs")) {
1034                 whobbs();
1035         } else if (!strcasecmp(action, "knrooms")) {
1036                 knrooms();
1037         } else if (!strcasecmp(action, "gotonext")) {
1038                 slrp_highest();
1039                 gotonext();
1040         } else if (!strcasecmp(action, "skip")) {
1041                 gotonext();
1042         } else if (!strcasecmp(action, "ungoto")) {
1043                 ungoto();
1044         } else if (!strcasecmp(action, "dotgoto")) {
1045                 slrp_highest();
1046                 smart_goto(bstr("room"));
1047         } else if (!strcasecmp(action, "dotskip")) {
1048                 smart_goto(bstr("room"));
1049         } else if (!strcasecmp(action, "termquit")) {
1050                 do_logout();
1051         } else if (!strcasecmp(action, "readnew")) {
1052                 readloop("readnew");
1053         } else if (!strcasecmp(action, "readold")) {
1054                 readloop("readold");
1055         } else if (!strcasecmp(action, "readfwd")) {
1056                 readloop("readfwd");
1057         } else if (!strcasecmp(action, "headers")) {
1058                 readloop("headers");
1059         } else if (!strcasecmp(action, "display_enter")) {
1060                 display_enter();
1061         } else if (!strcasecmp(action, "post")) {
1062                 post_message();
1063         } else if (!strcasecmp(action, "delete_msg")) {
1064                 delete_msg();
1065         } else if (!strcasecmp(action, "confirm_move_msg")) {
1066                 confirm_move_msg();
1067         } else if (!strcasecmp(action, "move_msg")) {
1068                 move_msg();
1069         } else if (!strcasecmp(action, "userlist")) {
1070                 userlist();
1071         } else if (!strcasecmp(action, "showuser")) {
1072                 showuser();
1073         } else if (!strcasecmp(action, "display_page")) {
1074                 display_page();
1075         } else if (!strcasecmp(action, "page_user")) {
1076                 page_user();
1077         } else if (!strcasecmp(action, "chat")) {
1078                 do_chat();
1079         } else if (!strcasecmp(action, "display_private")) {
1080                 display_private("", 0);
1081         } else if (!strcasecmp(action, "goto_private")) {
1082                 goto_private();
1083         } else if (!strcasecmp(action, "zapped_list")) {
1084                 zapped_list();
1085         } else if (!strcasecmp(action, "display_zap")) {
1086                 display_zap();
1087         } else if (!strcasecmp(action, "zap")) {
1088                 zap();
1089         } else if (!strcasecmp(action, "display_entroom")) {
1090                 display_entroom();
1091         } else if (!strcasecmp(action, "entroom")) {
1092                 entroom();
1093         } else if (!strcasecmp(action, "display_editroom")) {
1094                 display_editroom();
1095         } else if (!strcasecmp(action, "netedit")) {
1096                 netedit();
1097         } else if (!strcasecmp(action, "editroom")) {
1098                 editroom();
1099         } else if (!strcasecmp(action, "display_whok")) {
1100                 display_whok();
1101         } else if (!strcasecmp(action, "display_editinfo")) {
1102                 display_edit("Room info", "EINF 0", "RINF", "/editinfo");
1103         } else if (!strcasecmp(action, "editinfo")) {
1104                 save_edit("Room info", "EINF 1", 1);
1105         } else if (!strcasecmp(action, "display_editbio")) {
1106                 sprintf(buf, "RBIO %s", WC->wc_username);
1107                 display_edit("Your bio", "NOOP", buf, "editbio");
1108         } else if (!strcasecmp(action, "editbio")) {
1109                 save_edit("Your bio", "EBIO", 0);
1110         } else if (!strcasecmp(action, "confirm_delete_room")) {
1111                 confirm_delete_room();
1112         } else if (!strcasecmp(action, "delete_room")) {
1113                 delete_room();
1114         } else if (!strcasecmp(action, "validate")) {
1115                 validate();
1116         } else if (!strcasecmp(action, "display_editpic")) {
1117                 display_graphics_upload("your photo",
1118                                         "UIMG 0|_userpic_",
1119                                         "/editpic");
1120         } else if (!strcasecmp(action, "editpic")) {
1121                 do_graphics_upload("UIMG 1|_userpic_");
1122         } else if (!strcasecmp(action, "display_editroompic")) {
1123                 display_graphics_upload("the graphic for this room",
1124                                         "UIMG 0|_roompic_",
1125                                         "/editroompic");
1126         } else if (!strcasecmp(action, "editroompic")) {
1127                 do_graphics_upload("UIMG 1|_roompic_");
1128         } else if (!strcasecmp(action, "delete_floor")) {
1129                 delete_floor();
1130         } else if (!strcasecmp(action, "rename_floor")) {
1131                 rename_floor();
1132         } else if (!strcasecmp(action, "create_floor")) {
1133                 create_floor();
1134         } else if (!strcasecmp(action, "display_editfloorpic")) {
1135                 sprintf(buf, "UIMG 0|_floorpic_|%s",
1136                         bstr("which_floor"));
1137                 display_graphics_upload("the graphic for this floor",
1138                                         buf,
1139                                         "/editfloorpic");
1140         } else if (!strcasecmp(action, "editfloorpic")) {
1141                 sprintf(buf, "UIMG 1|_floorpic_|%s",
1142                         bstr("which_floor"));
1143                 do_graphics_upload(buf);
1144         } else if (!strcasecmp(action, "display_reg")) {
1145                 display_reg(0);
1146         } else if (!strcasecmp(action, "register")) {
1147                 register_user();
1148         } else if (!strcasecmp(action, "display_changepw")) {
1149                 display_changepw();
1150         } else if (!strcasecmp(action, "changepw")) {
1151                 changepw();
1152         } else if (!strcasecmp(action, "display_edit_node")) {
1153                 display_edit_node();
1154         } else if (!strcasecmp(action, "edit_node")) {
1155                 edit_node();
1156         } else if (!strcasecmp(action, "display_netconf")) {
1157                 display_netconf();
1158         } else if (!strcasecmp(action, "display_confirm_delete_node")) {
1159                 display_confirm_delete_node();
1160         } else if (!strcasecmp(action, "delete_node")) {
1161                 delete_node();
1162         } else if (!strcasecmp(action, "display_add_node")) {
1163                 display_add_node();
1164         } else if (!strcasecmp(action, "add_node")) {
1165                 add_node();
1166         } else if (!strcasecmp(action, "terminate_session")) {
1167                 slrp_highest();
1168                 terminate_session();
1169         } else if (!strcasecmp(action, "edit_me")) {
1170                 edit_me();
1171         } else if (!strcasecmp(action, "display_siteconfig")) {
1172                 display_siteconfig();
1173         } else if (!strcasecmp(action, "page_popup")) {
1174                 page_popup();
1175         } else if (!strcasecmp(action, "siteconfig")) {
1176                 siteconfig();
1177         } else if (!strcasecmp(action, "display_generic")) {
1178                 display_generic();
1179         } else if (!strcasecmp(action, "do_generic")) {
1180                 do_generic();
1181         } else if (!strcasecmp(action, "display_menubar")) {
1182                 display_menubar(1);
1183         } else if (!strcasecmp(action, "output_mimepart")) {
1184                 output_mimepart();
1185         } else if (!strcasecmp(action, "edit_vcard")) {
1186                 edit_vcard();
1187         } else if (!strcasecmp(action, "submit_vcard")) {
1188                 submit_vcard();
1189         } else if (!strcasecmp(action, "select_user_to_edit")) {
1190                 select_user_to_edit(NULL, NULL);
1191         } else if (!strcasecmp(action, "display_edituser")) {
1192                 display_edituser(NULL);
1193         } else if (!strcasecmp(action, "edituser")) {
1194                 edituser();
1195         } else if (!strcasecmp(action, "create_user")) {
1196                 create_user();
1197         } else if (!strcasecmp(action, "changeview")) {
1198                 change_view();
1199         } else if (!strcasecmp(action, "folders")) {
1200                 folders();
1201         } else if (!strcasecmp(action, "do_stuff_to_msgs")) {
1202                 do_stuff_to_msgs();
1203         } else if (!strcasecmp(action, "change_start_page")) {
1204                 change_start_page();
1205         } else if (!strcasecmp(action, "display_floorconfig")) {
1206                 display_floorconfig(NULL);
1207         } else if (!strcasecmp(action, "toggle_self_service")) {
1208                 toggle_self_service();
1209         } else if (!strcasecmp(action, "summary")) {
1210                 summary();
1211         } else if (!strcasecmp(action, "diagnostics")) {
1212                 output_headers(1);
1213
1214                 wprintf("You're in session %d<HR>\n", WC->wc_session);
1215                 wprintf("Command: <BR><PRE>\n");
1216                 escputs(cmd);
1217                 wprintf("</PRE><HR>\n");
1218                 wprintf("Variables: <BR><PRE>\n");
1219                 dump_vars();
1220                 wprintf("</PRE><HR>\n");
1221                 wDumpContent(1);
1222         }
1223         /* When all else fais, display the main menu. */
1224         else {
1225                 display_main_menu();
1226         }
1227
1228 SKIP_ALL_THIS_CRAP:
1229         fflush(stdout);
1230         if (content != NULL) {
1231                 free(content);
1232                 content = NULL;
1233         }
1234         free_urls();
1235         if (WC->upload_length > 0) {
1236                 free(WC->upload);
1237                 WC->upload_length = 0;
1238         }
1239
1240 #ifdef WITH_ZLIB
1241         if (WC->gzfd) {
1242                 gzclose(WC->gzfd);
1243                 WC->gzfd = NULL;
1244                 WC->gzcompressed = 0;
1245         }
1246 #endif
1247 }