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