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