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