* Cleaned up the rcs/cvs Id tags and leading comments at the top of some files
[citadel.git] / webcit / webcit.c
1 /*
2  * $Id$
3  *
4  * This is the main transaction loop of the web service.  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  */
9
10 #include <ctype.h>
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include <stdio.h>
14 #include <fcntl.h>
15 #include <signal.h>
16 #include <sys/types.h>
17 #include <sys/wait.h>
18 #include <sys/socket.h>
19 #include <sys/time.h>
20 #include <sys/stat.h>
21 #include <limits.h>
22 #include <netinet/in.h>
23 #include <netdb.h>
24 #include <string.h>
25 #include <pwd.h>
26 #include <errno.h>
27 #include <stdarg.h>
28 #include <pthread.h>
29 #include <signal.h>
30 #include "webcit.h"
31 #include "groupdav.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                         b = 0;
58                         sscanf(hex, "%02x", &b);
59                         buf[a] = (char) b;
60                         strcpy(&buf[a + 1], &buf[a + 3]);
61                 }
62         }
63
64 }
65
66
67 void addurls(char *url)
68 {
69         char *up, *ptr;
70         char buf[SIZ];
71         int a, b;
72         struct urlcontent *u;
73
74         up = url;
75         while (strlen(up) > 0) {
76
77                 /* locate the = sign */
78                 safestrncpy(buf, up, sizeof buf);
79                 b = (-1);
80                 for (a = 255; a >= 0; --a)
81                         if (buf[a] == '=')
82                                 b = a;
83                 if (b < 0)
84                         return;
85                 buf[b] = 0;
86
87                 u = (struct urlcontent *) malloc(sizeof(struct urlcontent));
88                 u->next = WC->urlstrings;
89                 WC->urlstrings = u;
90                 strcpy(u->url_key, buf);
91
92                 /* now chop that part off */
93                 for (a = 0; a <= b; ++a)
94                         ++up;
95
96                 /* locate "&" and "?" delimiters */
97                 ptr = up;
98                 b = strlen(up);
99                 for (a = 0; a < strlen(up); ++a) {
100                         if ( (ptr[0] == '&') || (ptr[0] == '?') ) {
101                                 b = a;
102                                 break;
103                         }
104                         ++ptr;
105                 }
106                 ptr = up;
107                 for (a = 0; a < b; ++a)
108                         ++ptr;
109                 strcpy(ptr, "");
110
111                 u->url_data = malloc(strlen(up) + 2);
112                 strcpy(u->url_data, up);
113                 u->url_data[b] = 0;
114                 unescape_input(u->url_data);
115                 up = ptr;
116                 ++up;
117         }
118 }
119
120 void free_urls(void)
121 {
122         struct urlcontent *u;
123
124         while (WC->urlstrings != NULL) {
125                 free(WC->urlstrings->url_data);
126                 u = WC->urlstrings->next;
127                 free(WC->urlstrings);
128                 WC->urlstrings = u;
129         }
130 }
131
132 /*
133  * Diagnostic function to display the contents of all variables
134  */
135 void dump_vars(void)
136 {
137         struct urlcontent *u;
138
139         for (u = WC->urlstrings; u != NULL; u = u->next) {
140                 wprintf("%38s = %s\n", u->url_key, u->url_data);
141         }
142 }
143
144 char *bstr(char *key)
145 {
146         struct urlcontent *u;
147
148         for (u = WC->urlstrings; u != NULL; u = u->next) {
149                 if (!strcasecmp(u->url_key, key))
150                         return (u->url_data);
151         }
152         return ("");
153 }
154
155
156 void wprintf(const char *format,...)
157 {
158         va_list arg_ptr;
159         char wbuf[4096];
160
161         va_start(arg_ptr, format);
162         vsnprintf(wbuf, sizeof wbuf, format, arg_ptr);
163         va_end(arg_ptr);
164
165         client_write(wbuf, strlen(wbuf));
166 }
167
168
169 /*
170  * wDumpContent() wraps up an HTTP session, closes tags, etc.
171  *
172  * print_standard_html_footer should be set to 0 to transmit only, 1 to
173  * append the main menu and closing tags, or 2 to
174  * append the closing tags only.
175  */
176 void wDumpContent(int print_standard_html_footer)
177 {
178         if (print_standard_html_footer) {
179                 wprintf("</DIV>\n");    /* end of "text" div */
180                 do_template("trailing");
181         }
182
183 }
184
185
186 /*
187  * Copy a string, escaping characters which have meaning in HTML.  If
188  * nbsp is nonzero, spaces are converted to non-breaking spaces.
189  */
190 void stresc(char *target, char *strbuf, int nbsp, int nolinebreaks)
191 {
192         int a;
193         strcpy(target, "");
194
195         for (a = 0; a < strlen(strbuf); ++a) {
196                 if (strbuf[a] == '<')
197                         strcat(target, "&lt;");
198                 else if (strbuf[a] == '>')
199                         strcat(target, "&gt;");
200                 else if (strbuf[a] == '&')
201                         strcat(target, "&amp;");
202                 else if (strbuf[a] == '\"')
203                         strcat(target, "&quot;");
204                 else if (strbuf[a] == '\'') 
205                         strcat(target, "&#39;");
206                 else if (strbuf[a] == LB)
207                         strcat(target, "<");
208                 else if (strbuf[a] == RB)
209                         strcat(target, ">");
210                 else if (strbuf[a] == QU)
211                         strcat(target, "\"");
212                 else if ((strbuf[a] == 32) && (nbsp == 1))
213                         strcat(target, "&nbsp;");
214                 else if ((strbuf[a] == '\n') && (nolinebreaks))
215                         strcat(target, "");     /* nothing */
216                 else if ((strbuf[a] == '\r') && (nolinebreaks))
217                         strcat(target, "");     /* nothing */
218                 else
219                         strncat(target, &strbuf[a], 1);
220         }
221 }
222
223 void escputs1(char *strbuf, int nbsp, int nolinebreaks)
224 {
225         char *buf;
226
227         if (strbuf == NULL) return;
228         buf = malloc( (3 * strlen(strbuf)) + SIZ );
229         stresc(buf, strbuf, nbsp, nolinebreaks);
230         wprintf("%s", buf);
231         free(buf);
232 }
233
234 void escputs(char *strbuf)
235 {
236         escputs1(strbuf, 0, 0);
237 }
238
239 /*
240  * Escape a string for feeding out as a URL.
241  * Returns a pointer to a buffer that must be freed by the caller!
242  */
243 void urlesc(char *outbuf, char *strbuf)
244 {
245         int a, b, c;
246         char *ec = " #&;`'|*?-~<>^()[]{}$\\";
247
248         strcpy(outbuf, "");
249
250         for (a = 0; a < strlen(strbuf); ++a) {
251                 c = 0;
252                 for (b = 0; b < strlen(ec); ++b) {
253                         if (strbuf[a] == ec[b])
254                                 c = 1;
255                 }
256                 b = strlen(outbuf);
257                 if (c == 1)
258                         sprintf(&outbuf[b], "%%%02x", strbuf[a]);
259                 else
260                         sprintf(&outbuf[b], "%c", strbuf[a]);
261         }
262 }
263
264 void urlescputs(char *strbuf)
265 {
266         char outbuf[SIZ];
267         
268         urlesc(outbuf, strbuf);
269         wprintf("%s", outbuf);
270 }
271
272
273 /*
274  * Copy a string, escaping characters for JavaScript strings.
275  */
276 void jsesc(char *target, char *strbuf)
277 {
278         int a;
279         strcpy(target, "");
280
281         for (a = 0; a < strlen(strbuf); ++a) {
282                 if (strbuf[a] == '<')
283                         strcat(target, "[");
284                 else if (strbuf[a] == '>')
285                         strcat(target, "]");
286                 else if (strbuf[a] == '\"')
287                         strcat(target, "&quot;");
288                 else if (strbuf[a] == '&')
289                         strcat(target, "&amp;;");
290                 else if (strbuf[a] == '\'') 
291                         strcat(target, "\\'");
292                 else {
293                         strncat(target, &strbuf[a], 1);
294                 }
295         }
296 }
297
298 void jsescputs(char *strbuf)
299 {
300         char outbuf[SIZ];
301         
302         jsesc(outbuf, strbuf);
303         wprintf("%s", outbuf);
304 }
305
306 /*
307  * Copy a string, escaping characters for message text hold
308  */
309 void msgesc(char *target, char *strbuf)
310 {
311         int a;
312         strcpy(target, "");
313
314         for (a = 0; a < strlen(strbuf); ++a) {
315                 if (strbuf[a] == '\'') 
316                         strcat(target, "\\'");
317                 else if (strbuf[a] == '\n')
318                         strcat(target, " ");
319                 else if (strbuf[a] == '\r')
320                         strcat(target, " ");
321                 else {
322                         strncat(target, &strbuf[a], 1);
323                 }
324         }
325 }
326
327 void msgescputs(char *strbuf) {
328         char *outbuf;
329
330         if (strbuf == NULL) return;
331         outbuf = malloc( (3 * strlen(strbuf)) + SIZ);
332         msgesc(outbuf, strbuf);
333         wprintf("%s", outbuf);
334         free(outbuf);
335 }
336
337
338
339
340 /*
341  * Output all that important stuff that the browser will want to see
342  */
343 void output_headers(    int do_httpheaders,     /* 1 = output HTTP headers                          */
344                         int do_htmlhead,        /* 1 = output HTML <head> section and <body> opener */
345
346                         int do_room_banner,     /* 0=no, 1=yes,                                     */
347                                                 /* 2 = I'm going to embed my own, so don't open the */
348                                                 /*     <div id="text"> either.                      */
349
350                         int unset_cookies,      /* 1 = session is terminating, so unset the cookies */
351                         int refresh30,          /* 1 = automatically refresh page every 30 seconds  */
352                         int suppress_check,     /* 1 = suppress check for instant messages          */
353                         int cache               /* 1 = allow browser to cache this page             */
354 ) {
355         char cookie[SIZ];
356         char httpnow[SIZ];
357
358         wprintf("HTTP/1.0 200 OK\n");
359         httpdate(httpnow, time(NULL));
360
361         if (do_httpheaders) {
362                 wprintf("Content-type: text/html\n"
363                         "Server: %s / %s\n", SERVER, serv_info.serv_software
364                 );
365                 if (!cache)
366                         wprintf("Connection: close\n"
367                                 "Pragma: no-cache\n"
368                                 "Cache-Control: no-store\n"
369                         );
370         }
371
372         stuff_to_cookie(cookie, WC->wc_session, WC->wc_username,
373                         WC->wc_password, WC->wc_roomname);
374
375         if (unset_cookies) {
376                 wprintf("Set-cookie: webcit=%s; path=/\n", unset);
377         } else {
378                 wprintf("Set-cookie: webcit=%s; path=/\n", cookie);
379                 if (server_cookie != NULL) {
380                         wprintf("%s\n", server_cookie);
381                 }
382         }
383
384         if (do_htmlhead) {
385                 wprintf("\n");
386
387                 if (refresh30) {
388                         svprintf("REFRESHTAG", WCS_STRING, "%s",
389                                 "<meta http-equiv=\"refresh\" content=\"30\" />\n");
390                 }
391                 else {
392                         svprintf("REFRESHTAG", WCS_STRING, "%s",
393                                 "<meta http-equiv=\"refresh\" content=\"500363689;\" />\n");
394                 }
395
396                 do_template("head");
397         }
398
399         /* ICONBAR */
400         if (do_htmlhead) {
401
402                 if (WC->HaveInstantMessages) {
403                         wprintf("<div id=\"page_popup\">\n");
404                         page_popup();
405                         wprintf("</div>\n");
406                 }
407                 if ( (WC->logged_in) && (!unset_cookies) ) {
408                         wprintf("<div id=\"iconbar\">");
409                         do_iconbar();
410                         wprintf("</div>\n");
411                 }
412                 if (do_room_banner == 1) {
413                         wprintf("<div id=\"banner\">\n");
414                         embed_room_banner(NULL, navbar_default);
415                         wprintf("</div>\n");
416                 }
417         }
418
419         if (do_room_banner != 2) {
420                 wprintf("<div id=\"content\">\n");
421
422
423                 if (strlen(WC->ImportantMessage) > 0) {
424                         do_template("beginbox_nt");
425                         wprintf("<SPAN CLASS=\"errormsg\">"
426                                 "%s</SPAN><br />\n", WC->ImportantMessage);
427                         do_template("endbox");
428                         strcpy(WC->ImportantMessage, "");
429                 }
430
431         }
432 }
433
434
435 /*
436  * Generic function to do an HTTP redirect.  Easy and fun.
437  */
438 void http_redirect(char *whichpage) {
439         wprintf("HTTP/1.0 302 Moved Temporarily\n");
440         wprintf("Location: %s\n", whichpage);
441         wprintf("URI: %s\n", whichpage);
442         wprintf("Content-type: text/html\n\n");
443         wprintf("<html><body>\n");
444         wprintf("you really want to be <A HREF=\"%s\">here</A> now\n",
445                 whichpage);
446         wprintf("</body></html>\n");
447 }
448
449
450
451 void check_for_instant_messages()
452 {
453         char buf[SIZ];
454
455         serv_puts("NOOP");
456         serv_gets(buf);
457         if (buf[3] == '*') WC->HaveInstantMessages = 1;
458 }
459
460
461
462
463 /* 
464  * Output a piece of content to the web browser
465  */
466 void http_transmit_thing(char *thing, size_t length, char *content_type,
467                          int is_static) {
468         if (is_static) {
469                 output_headers(0, 0, 0, 0, 0, 0, 1);
470         }
471         else {
472                 output_headers(0, 0, 0, 0, 0, 0, 0);
473         }
474         wprintf("Content-type: %s\n"
475                 "Content-length: %ld\n"
476                 "Server: %s\n"
477                 "Connection: close\n"
478                 "\n",
479                 content_type,
480                 (long) length,
481                 SERVER
482         );
483         client_write(thing, (size_t)length);
484 }
485
486
487
488
489 void output_static(char *what)
490 {
491         char buf[4096];
492         FILE *fp;
493         struct stat statbuf;
494         off_t bytes;
495         char *bigbuffer;
496         char content_type[SIZ];
497
498         sprintf(buf, "static/%s", what);
499         fp = fopen(buf, "rb");
500         if (fp == NULL) {
501                 wprintf("HTTP/1.0 404 %s\n", strerror(errno));
502                 wprintf("Content-Type: text/plain\n");
503                 wprintf("\n");
504                 wprintf("Cannot open %s: %s\n", what, strerror(errno));
505         } else {
506                 if (!strncasecmp(&what[strlen(what) - 4], ".gif", 4))
507                         strcpy(content_type, "image/gif");
508                 else if (!strncasecmp(&what[strlen(what) - 4], ".txt", 4))
509                         strcpy(content_type, "text/plain");
510                 else if (!strncasecmp(&what[strlen(what) - 4], ".css", 4))
511                         strcpy(content_type, "text/css");
512                 else if (!strncasecmp(&what[strlen(what) - 4], ".jpg", 4))
513                         strcpy(content_type, "image/jpeg");
514                 else if (!strncasecmp(&what[strlen(what) - 4], ".png", 4))
515                         strcpy(content_type, "image/png");
516                 else if (!strncasecmp(&what[strlen(what) - 4], ".ico", 4))
517                         strcpy(content_type, "image/x-icon");
518                 else if (!strncasecmp(&what[strlen(what) - 5], ".html", 5))
519                         strcpy(content_type, "text/html");
520                 else if (!strncasecmp(&what[strlen(what) - 4], ".htm", 4))
521                         strcpy(content_type, "text/html");
522                 else if (!strncasecmp(&what[strlen(what) - 4], ".wml", 4))
523                         strcpy(content_type, "text/vnd.wap.wml");
524                 else if (!strncasecmp(&what[strlen(what) - 5], ".wmls", 5))
525                         strcpy(content_type, "text/vnd.wap.wmlscript");
526                 else if (!strncasecmp(&what[strlen(what) - 5], ".wmlc", 5))
527                         strcpy(content_type, "application/vnd.wap.wmlc");
528                 else if (!strncasecmp(&what[strlen(what) - 6], ".wmlsc", 6))
529                         strcpy(content_type, "application/vnd.wap.wmlscriptc");
530                 else if (!strncasecmp(&what[strlen(what) - 5], ".wbmp", 5))
531                         strcpy(content_type, "image/vnd.wap.wbmp");
532                 else if (!strncasecmp(&what[strlen(what) - 3], ".js", 3))
533                         strcpy(content_type, "text/javascript");
534                 else
535                         strcpy(content_type, "application/octet-stream");
536
537                 fstat(fileno(fp), &statbuf);
538                 bytes = statbuf.st_size;
539                 lprintf(3, "Static: %s, (%s; %ld bytes)\n", what, content_type, bytes);
540                 bigbuffer = malloc(bytes + 2);
541                 fread(bigbuffer, bytes, 1, fp);
542                 fclose(fp);
543
544                 http_transmit_thing(bigbuffer, (size_t)bytes, content_type, 1);
545                 free(bigbuffer);
546         }
547         if (!strcasecmp(bstr("force_close_session"), "yes")) {
548                 end_webcit_session();
549         }
550 }
551
552
553 /*
554  * When the browser requests an image file from the Citadel server,
555  * this function is called to transmit it.
556  */
557 void output_image()
558 {
559         char buf[SIZ];
560         char *xferbuf = NULL;
561         off_t bytes;
562
563         serv_printf("OIMG %s|%s", bstr("name"), bstr("parm"));
564         serv_gets(buf);
565         if (buf[0] == '2') {
566                 bytes = extract_long(&buf[4], 0);
567                 xferbuf = malloc(bytes + 2);
568
569                 /* Read it from the server */
570                 read_server_binary(xferbuf, bytes);
571                 serv_puts("CLOS");
572                 serv_gets(buf);
573
574                 /* Write it to the browser */
575                 http_transmit_thing(xferbuf, (size_t)bytes, "image/gif", 0);
576                 free(xferbuf);
577
578         } else {
579
580                 /* Instead of an ugly 404, send a 1x1 transparent GIF
581                  * when there's no such image on the server.
582                  */
583                 output_static("blank.gif");
584
585                 /*
586                 wprintf("HTTP/1.0 404 %s\n", &buf[4]);
587                 output_headers(0, 0, 0, 0, 0, 0, 0);
588                 wprintf("Content-Type: text/plain\n"
589                         "\n"
590                         "Error retrieving image: %s\n",
591                         &buf[4]
592                 );
593                 */
594
595         }
596
597
598
599 }
600
601 /*
602  */
603 void output_mimepart()
604 {
605         char buf[SIZ];
606         off_t bytes;
607         char content_type[SIZ];
608         char *content = NULL;
609         
610         serv_printf("OPNA %s|%s", bstr("msgnum"), bstr("partnum"));
611         serv_gets(buf);
612         if (buf[0] == '2') {
613                 bytes = extract_long(&buf[4], 0);
614                 content = malloc(bytes + 2);
615                 extract(content_type, &buf[4], 3);
616                 output_headers(0, 0, 0, 0, 0, 0, 0);
617                 read_server_binary(content, bytes);
618                 serv_puts("CLOS");
619                 serv_gets(buf);
620                 http_transmit_thing(content, bytes, content_type, 0);
621                 free(content);
622         } else {
623                 wprintf("HTTP/1.0 404 %s\n", &buf[4]);
624                 output_headers(0, 0, 0, 0, 0, 0, 0);
625                 wprintf("Content-Type: text/plain\n");
626                 wprintf("\n");
627                 wprintf("Error retrieving part: %s\n", &buf[4]);
628         }
629
630 }
631
632
633 /*
634  */
635 char *load_mimepart(long msgnum, char *partnum)
636 {
637         char buf[SIZ];
638         off_t bytes;
639         char content_type[SIZ];
640         char *content;
641         
642         serv_printf("OPNA %ld|%s", msgnum, partnum);
643         serv_gets(buf);
644         if (buf[0] == '2') {
645                 bytes = extract_long(&buf[4], 0);
646                 extract(content_type, &buf[4], 3);
647
648                 content = malloc(bytes + 2);
649                 read_server_binary(content, bytes);
650
651                 serv_puts("CLOS");
652                 serv_gets(buf);
653                 content[bytes] = 0;     /* null terminate for good measure */
654                 return(content);
655         }
656         else {
657                 return(NULL);
658         }
659
660 }
661
662
663 /*
664  * Convenience functions to display a page containing only a string
665  */
666 void convenience_page(char *titlebarcolor, char *titlebarmsg, char *messagetext)
667 {
668         wprintf("HTTP/1.0 200 OK\n");
669         output_headers(1, 1, 2, 0, 0, 0, 0);
670         wprintf("<div id=\"banner\">\n");
671         wprintf("<TABLE WIDTH=100%% BORDER=0 BGCOLOR=\"#%s\"><TR><TD>", titlebarcolor);
672         wprintf("<SPAN CLASS=\"titlebar\">%s</SPAN>\n", titlebarmsg);
673         wprintf("</TD></TR></TABLE>\n");
674         wprintf("</div>\n<div id=\"content\">\n");
675         escputs(messagetext);
676
677         wprintf("<hr />\n");
678         wDumpContent(1);
679 }
680
681
682 /*
683  * Display a blank page.
684  */
685 void blank_page(void) {
686         output_headers(1, 1, 0, 0, 1, 0, 0);
687         wDumpContent(2);
688 }
689
690
691 /*
692  * A template has been requested
693  */
694 void url_do_template(void) {
695         do_template(bstr("template"));
696 }
697
698
699
700 /*
701  * Offer to make any page the user's "start page."
702  */
703 void offer_start_page(void) {
704         wprintf("<A HREF=\"/change_start_page?startpage=");
705         urlescputs(WC->this_page);
706         wprintf("\">"
707                 "<FONT SIZE=-2 COLOR=\"#AAAAAA\">Make this my start page</FONT>"
708                 "</A>"
709         );
710 }
711
712
713 /* 
714  * Change the user's start page
715  */
716 void change_start_page(void) {
717
718         if (bstr("startpage") == NULL) {
719                 strcpy(WC->ImportantMessage,
720                         "startpage set to null");
721                 display_main_menu();
722                 return;
723         }
724
725         set_preference("startpage", bstr("startpage"));
726
727         output_headers(1, 1, 0, 0, 0, 0, 0);
728         do_template("newstartpage");
729         wDumpContent(1);
730 }
731
732
733
734
735 void display_success(char *successmessage)
736 {
737         convenience_page("007700", "OK", successmessage);
738 }
739
740
741
742 void extract_action(char *actbuf, char *cmdbuf)
743 {
744         int i;
745
746         strcpy(actbuf, cmdbuf);
747
748         /*
749          * First strip out the http method
750          */
751         remove_token(actbuf, 0, ' ');
752         if (actbuf[0] == ' ') strcpy(actbuf, &actbuf[1]);
753         if (actbuf[0] == '/') strcpy(actbuf, &actbuf[1]);
754
755         /*
756          * Now kill invalid (for webcit) characters
757          */
758         for (i = 0; i < strlen(actbuf); ++i) {
759                 if (actbuf[i] == ' ') {
760                         actbuf[i] = 0;
761                         i = 0;
762                 }
763                 if (actbuf[i] == '/') {
764                         actbuf[i] = 0;
765                         i = 0;
766                 }
767                 if (actbuf[i] == '?') {
768                         actbuf[i] = 0;
769                         i = 0;
770                 }
771                 if (actbuf[i] == '&') {
772                         actbuf[i] = 0;
773                         i = 0;
774                 }
775         }
776 }
777
778
779 void upload_handler(char *name, char *filename, char *partnum, char *disp,
780                         void *content, char *cbtype, size_t length,
781                         char *encoding, void *userdata)
782 {
783         struct urlcontent *u;
784
785         /* Form fields */
786         if ( (length > 0) && (strlen(cbtype) == 0) ) {
787                 u = (struct urlcontent *) malloc(sizeof(struct urlcontent));
788                 u->next = WC->urlstrings;
789                 WC->urlstrings = u;
790                 safestrncpy(u->url_key, name, sizeof(u->url_key));
791                 u->url_data = malloc(length + 1);
792                 memcpy(u->url_data, content, length);
793                 u->url_data[length] = 0;
794         }
795
796         /* Uploaded files */
797         if ( (length > 0) && (strlen(cbtype) > 0) ) {
798                 WC->upload = malloc(length);
799                 if (WC->upload != NULL) {
800                         WC->upload_length = length;
801                         safestrncpy(WC->upload_filename, filename,
802                                         sizeof(WC->upload_filename));
803                         safestrncpy(WC->upload_content_type, cbtype,
804                                         sizeof(WC->upload_content_type));
805                         memcpy(WC->upload, content, length);
806                 }
807                 else {
808                         lprintf(3, "malloc() failed: %s\n", strerror(errno));
809                 }
810         }
811
812 }
813
814
815
816
817 /*
818  * Entry point for WebCit transaction
819  */
820 void session_loop(struct httprequest *req)
821 {
822         char cmd[SIZ];
823         char method[SIZ];
824         char action[SIZ];
825         char buf[SIZ];
826         int a, b;
827         int ContentLength = 0;
828         int BytesRead = 0;
829         char ContentType[512];
830         char *content = NULL;
831         char *content_end = NULL;
832         struct httprequest *hptr;
833         char browser_host[SIZ];
834         char user_agent[SIZ];
835         int body_start;
836
837         /* We stuff these with the values coming from the client cookies,
838          * so we can use them to reconnect a timed out session if we have to.
839          */
840         char c_username[SIZ];
841         char c_password[SIZ];
842         char c_roomname[SIZ];
843         char c_httpauth_string[SIZ];
844         char c_httpauth_user[SIZ];
845         char c_httpauth_pass[SIZ];
846         char cookie[SIZ];
847
848         strcpy(c_username, "");
849         strcpy(c_password, "");
850         strcpy(c_roomname, "");
851         strcpy(c_httpauth_string, "");
852         strcpy(c_httpauth_user, "");
853         strcpy(c_httpauth_pass, "");
854
855         WC->upload_length = 0;
856         WC->upload = NULL;
857         WC->vars = NULL;
858
859         WC->is_wap = 0;
860
861         hptr = req;
862         if (hptr == NULL) return;
863
864         strcpy(cmd, hptr->line);
865         hptr = hptr->next;
866         extract_token(method, cmd, 0, ' ');
867         extract_action(action, cmd);
868
869         while (hptr != NULL) {
870                 strcpy(buf, hptr->line);
871                 hptr = hptr->next;
872
873                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
874                         safestrncpy(cookie, &buf[15], sizeof cookie);
875                         cookie_to_stuff(cookie, NULL,
876                                       c_username, c_password, c_roomname);
877                 }
878                 else if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
879                         CtdlDecodeBase64(c_httpauth_string, &buf[21], strlen(&buf[21]));
880                         extract_token(c_httpauth_user, c_httpauth_string, 0, ':');
881                         extract_token(c_httpauth_pass, c_httpauth_string, 1, ':');
882                 }
883                 else if (!strncasecmp(buf, "Content-length: ", 16)) {
884                         ContentLength = atoi(&buf[16]);
885                 }
886                 else if (!strncasecmp(buf, "Content-type: ", 14)) {
887                         safestrncpy(ContentType, &buf[14], sizeof ContentType);
888                 }
889                 else if (!strncasecmp(buf, "User-agent: ", 12)) {
890                         safestrncpy(user_agent, &buf[12], sizeof user_agent);
891                 }
892                 else if (!strncasecmp(buf, "Host: ", 6)) {
893                         safestrncpy(WC->http_host, &buf[6], sizeof WC->http_host);
894                 }
895                 /* Only WAP gateways explicitly name this content-type */
896                 else if (strstr(buf, "text/vnd.wap.wml")) {
897                         WC->is_wap = 1;
898                 }
899         }
900
901         if (ContentLength > 0) {
902                 content = malloc(ContentLength + SIZ);
903                 memset(content, 0, ContentLength + SIZ);
904                 sprintf(content, "Content-type: %s\n"
905                                 "Content-length: %d\n\n",
906                                 ContentType, ContentLength);
907                 body_start = strlen(content);
908
909                 /* Be daring and read it all at once. */
910                 client_read(WC->http_sock, &content[BytesRead+body_start],
911                         ContentLength);
912
913                 if (!strncasecmp(ContentType,
914                               "application/x-www-form-urlencoded", 33)) {
915                         addurls(&content[body_start]);
916                 } else if (!strncasecmp(ContentType, "multipart", 9)) {
917                         content_end = content + ContentLength + body_start;
918                         mime_parser(content, content_end, *upload_handler,
919                                         NULL, NULL, NULL, 0);
920                 }
921         } else {
922                 content = NULL;
923         }
924
925         /* make a note of where we are in case the user wants to save it */
926         safestrncpy(WC->this_page, cmd, sizeof(WC->this_page));
927         remove_token(WC->this_page, 2, ' ');
928         remove_token(WC->this_page, 0, ' ');
929
930         /* If there are variables in the URL, we must grab them now */
931         for (a = 0; a < strlen(cmd); ++a) {
932                 if ((cmd[a] == '?') || (cmd[a] == '&')) {
933                         for (b = a; b < strlen(cmd); ++b)
934                                 if (isspace(cmd[b]))
935                                         cmd[b] = 0;
936                         addurls(&cmd[a + 1]);
937                         cmd[a] = 0;
938                 }
939         }
940
941         /* Static content can be sent without connecting to Citadel. */
942         if (!strcasecmp(action, "static")) {
943                 strcpy(buf, &cmd[12]);
944                 for (a = 0; a < strlen(buf); ++a)
945                         if (isspace(buf[a]))
946                                 buf[a] = 0;
947                 output_static(buf);
948                 goto SKIP_ALL_THIS_CRAP;        /* Don't try to connect */
949         }
950
951         /*
952          * If we're not connected to a Citadel server, try to hook up the
953          * connection now.
954          */
955         if (!WC->connected) {
956                 if (!strcasecmp(ctdlhost, "uds")) {
957                         /* unix domain socket */
958                         sprintf(buf, "%s/citadel.socket", ctdlport);
959                         WC->serv_sock = uds_connectsock(buf);
960                 }
961                 else {
962                         /* tcp socket */
963                         WC->serv_sock = tcp_connectsock(ctdlhost, ctdlport);
964                 }
965
966                 if (WC->serv_sock < 0) {
967                         do_logout();
968                         goto SKIP_ALL_THIS_CRAP;
969                 }
970                 else {
971                         WC->connected = 1;
972                         serv_gets(buf); /* get the server welcome message */
973                         locate_host(browser_host, WC->http_sock);
974                         get_serv_info(browser_host, user_agent);
975                         if (serv_info.serv_rev_level < MINIMUM_CIT_VERSION) {
976                                 wprintf("You are connected to a Citadel "
977                                         "server running Citadel %d.%02d;\nin "
978                                         "order to run this version of WebCit "
979                                         "you must also have Citadel %d.%02d or"
980                                         " newer.\n\n\n",
981                                                 serv_info.serv_rev_level / 100,
982                                                 serv_info.serv_rev_level % 100,
983                                                 MINIMUM_CIT_VERSION / 100,
984                                                 MINIMUM_CIT_VERSION % 100
985                                         );
986                                 end_webcit_session();
987                                 goto SKIP_ALL_THIS_CRAP;
988                         }
989                 }
990         }
991
992         /*
993          * Functions which can be performed without logging in
994          */
995         if (!strcasecmp(action, "listsub")) {
996                 do_listsub();
997                 goto SKIP_ALL_THIS_CRAP;
998         }
999 #ifdef WEBCIT_WITH_CALENDAR_SERVICE
1000         if (!strcasecmp(action, "freebusy")) {
1001                 do_freebusy(cmd);
1002                 goto SKIP_ALL_THIS_CRAP;
1003         }
1004 #endif
1005
1006         /*
1007          * If we're not logged in, but we have HTTP Authentication data,
1008          * try logging in to Citadel using that.
1009          */
1010         if ((!WC->logged_in)
1011            && (strlen(c_httpauth_user) > 0)
1012            && (strlen(c_httpauth_pass) > 0)) {
1013                 serv_printf("USER %s", c_httpauth_user);
1014                 serv_gets(buf);
1015                 if (buf[0] == '3') {
1016                         serv_printf("PASS %s", c_httpauth_pass);
1017                         serv_gets(buf);
1018                         if (buf[0] == '2') {
1019                                 become_logged_in(c_httpauth_user,
1020                                                 c_httpauth_pass, buf);
1021                                 strcpy(WC->httpauth_user, c_httpauth_user);
1022                                 strcpy(WC->httpauth_pass, c_httpauth_pass);
1023                         }
1024                 }
1025         }
1026
1027         /* 
1028          * The GroupDAV stuff relies on HTTP authentication instead of
1029          * our session's authentication.
1030          */
1031         if (!strncasecmp(action, "groupdav", 8)) {
1032                 groupdav_main(req, ContentType, /* do GroupDAV methods */
1033                         ContentLength, content+body_start);
1034                 if (!WC->logged_in) {
1035                         WC->killthis = 1;       /* If not logged in, don't */
1036                 }                               /* keep the session active */
1037                 goto SKIP_ALL_THIS_CRAP;
1038         }
1039
1040         check_for_instant_messages();
1041
1042         /*
1043          * If we're not logged in, but we have username and password cookies
1044          * supplied by the browser, try using them to log in.
1045          */
1046         if ((!WC->logged_in)
1047            && (strlen(c_username) > 0)
1048            && (strlen(c_password) > 0)) {
1049                 serv_printf("USER %s", c_username);
1050                 serv_gets(buf);
1051                 if (buf[0] == '3') {
1052                         serv_printf("PASS %s", c_password);
1053                         serv_gets(buf);
1054                         if (buf[0] == '2') {
1055                                 become_logged_in(c_username, c_password, buf);
1056                         }
1057                 }
1058         }
1059         /*
1060          * If we don't have a current room, but a cookie specifying the
1061          * current room is supplied, make an effort to go there.
1062          */
1063         if ((strlen(WC->wc_roomname) == 0) && (strlen(c_roomname) > 0)) {
1064                 serv_printf("GOTO %s", c_roomname);
1065                 serv_gets(buf);
1066                 if (buf[0] == '2') {
1067                         strcpy(WC->wc_roomname, c_roomname);
1068                 }
1069         }
1070
1071         if (!strcasecmp(action, "image")) {
1072                 output_image();
1073
1074         /*
1075          * All functions handled below this point ... make sure we log in
1076          * before doing anything else!
1077          */
1078         } else if ((!WC->logged_in) && (!strcasecmp(action, "login"))) {
1079                 do_login();
1080         } else if (!WC->logged_in) {
1081                 display_login(NULL);
1082         }
1083
1084         /*
1085          * Various commands...
1086          */
1087
1088         else if (!strcasecmp(action, "do_welcome")) {
1089                 do_welcome();
1090         } else if (!strcasecmp(action, "blank")) {
1091                 blank_page();
1092         } else if (!strcasecmp(action, "do_template")) {
1093                 url_do_template();
1094         } else if (!strcasecmp(action, "display_main_menu")) {
1095                 display_main_menu();
1096         } else if (!strcasecmp(action, "whobbs")) {
1097                 whobbs();
1098         } else if (!strcasecmp(action, "knrooms")) {
1099                 knrooms();
1100         } else if (!strcasecmp(action, "gotonext")) {
1101                 slrp_highest();
1102                 gotonext();
1103         } else if (!strcasecmp(action, "skip")) {
1104                 gotonext();
1105         } else if (!strcasecmp(action, "ungoto")) {
1106                 ungoto();
1107         } else if (!strcasecmp(action, "dotgoto")) {
1108                 slrp_highest();
1109                 smart_goto(bstr("room"));
1110         } else if (!strcasecmp(action, "dotskip")) {
1111                 smart_goto(bstr("room"));
1112         } else if (!strcasecmp(action, "termquit")) {
1113                 do_logout();
1114         } else if (!strcasecmp(action, "readnew")) {
1115                 readloop("readnew");
1116         } else if (!strcasecmp(action, "readold")) {
1117                 readloop("readold");
1118         } else if (!strcasecmp(action, "readfwd")) {
1119                 readloop("readfwd");
1120         } else if (!strcasecmp(action, "headers")) {
1121                 readloop("headers");
1122         } else if (!strcasecmp(action, "display_enter")) {
1123                 display_enter();
1124         } else if (!strcasecmp(action, "post")) {
1125                 post_message();
1126         } else if (!strcasecmp(action, "do_stuff_to_one_msg")) {
1127                 do_stuff_to_one_msg();
1128         } else if (!strcasecmp(action, "move_msg")) {
1129                 move_msg();
1130         } else if (!strcasecmp(action, "userlist")) {
1131                 userlist();
1132         } else if (!strcasecmp(action, "showuser")) {
1133                 showuser();
1134         } else if (!strcasecmp(action, "display_page")) {
1135                 display_page();
1136         } else if (!strcasecmp(action, "page_user")) {
1137                 page_user();
1138         } else if (!strcasecmp(action, "chat")) {
1139                 do_chat();
1140         } else if (!strcasecmp(action, "display_private")) {
1141                 display_private("", 0);
1142         } else if (!strcasecmp(action, "goto_private")) {
1143                 goto_private();
1144         } else if (!strcasecmp(action, "zapped_list")) {
1145                 zapped_list();
1146         } else if (!strcasecmp(action, "display_zap")) {
1147                 display_zap();
1148         } else if (!strcasecmp(action, "zap")) {
1149                 zap();
1150         } else if (!strcasecmp(action, "display_entroom")) {
1151                 display_entroom();
1152         } else if (!strcasecmp(action, "entroom")) {
1153                 entroom();
1154         } else if (!strcasecmp(action, "display_editroom")) {
1155                 display_editroom();
1156         } else if (!strcasecmp(action, "netedit")) {
1157                 netedit();
1158         } else if (!strcasecmp(action, "editroom")) {
1159                 editroom();
1160         } else if (!strcasecmp(action, "display_whok")) {
1161                 display_whok();
1162         } else if (!strcasecmp(action, "display_editinfo")) {
1163                 display_edit("Room info", "EINF 0", "RINF", "/editinfo", 1);
1164         } else if (!strcasecmp(action, "editinfo")) {
1165                 save_edit("Room info", "EINF 1", 1);
1166         } else if (!strcasecmp(action, "display_editbio")) {
1167                 sprintf(buf, "RBIO %s", WC->wc_username);
1168                 display_edit("Your bio", "NOOP", buf, "editbio", 3);
1169         } else if (!strcasecmp(action, "editbio")) {
1170                 save_edit("Your bio", "EBIO", 0);
1171         } else if (!strcasecmp(action, "confirm_delete_room")) {
1172                 confirm_delete_room();
1173         } else if (!strcasecmp(action, "delete_room")) {
1174                 delete_room();
1175         } else if (!strcasecmp(action, "validate")) {
1176                 validate();
1177         } else if (!strcasecmp(action, "display_editpic")) {
1178                 display_graphics_upload("your photo",
1179                                         "UIMG 0|_userpic_",
1180                                         "/editpic");
1181         } else if (!strcasecmp(action, "editpic")) {
1182                 do_graphics_upload("UIMG 1|_userpic_");
1183         } else if (!strcasecmp(action, "display_editroompic")) {
1184                 display_graphics_upload("the graphic for this room",
1185                                         "UIMG 0|_roompic_",
1186                                         "/editroompic");
1187         } else if (!strcasecmp(action, "editroompic")) {
1188                 do_graphics_upload("UIMG 1|_roompic_");
1189         } else if (!strcasecmp(action, "delete_floor")) {
1190                 delete_floor();
1191         } else if (!strcasecmp(action, "rename_floor")) {
1192                 rename_floor();
1193         } else if (!strcasecmp(action, "create_floor")) {
1194                 create_floor();
1195         } else if (!strcasecmp(action, "display_editfloorpic")) {
1196                 sprintf(buf, "UIMG 0|_floorpic_|%s",
1197                         bstr("which_floor"));
1198                 display_graphics_upload("the graphic for this floor",
1199                                         buf,
1200                                         "/editfloorpic");
1201         } else if (!strcasecmp(action, "editfloorpic")) {
1202                 sprintf(buf, "UIMG 1|_floorpic_|%s",
1203                         bstr("which_floor"));
1204                 do_graphics_upload(buf);
1205         } else if (!strcasecmp(action, "display_reg")) {
1206                 display_reg(0);
1207         } else if (!strcasecmp(action, "display_changepw")) {
1208                 display_changepw();
1209         } else if (!strcasecmp(action, "changepw")) {
1210                 changepw();
1211         } else if (!strcasecmp(action, "display_edit_node")) {
1212                 display_edit_node();
1213         } else if (!strcasecmp(action, "edit_node")) {
1214                 edit_node();
1215         } else if (!strcasecmp(action, "display_netconf")) {
1216                 display_netconf();
1217         } else if (!strcasecmp(action, "display_confirm_delete_node")) {
1218                 display_confirm_delete_node();
1219         } else if (!strcasecmp(action, "delete_node")) {
1220                 delete_node();
1221         } else if (!strcasecmp(action, "display_add_node")) {
1222                 display_add_node();
1223         } else if (!strcasecmp(action, "add_node")) {
1224                 add_node();
1225         } else if (!strcasecmp(action, "terminate_session")) {
1226                 slrp_highest();
1227                 terminate_session();
1228         } else if (!strcasecmp(action, "edit_me")) {
1229                 edit_me();
1230         } else if (!strcasecmp(action, "display_siteconfig")) {
1231                 display_siteconfig();
1232         } else if (!strcasecmp(action, "chat_recv")) {
1233                 chat_recv();
1234         } else if (!strcasecmp(action, "chat_send")) {
1235                 chat_send();
1236         } else if (!strcasecmp(action, "siteconfig")) {
1237                 siteconfig();
1238         } else if (!strcasecmp(action, "display_generic")) {
1239                 display_generic();
1240         } else if (!strcasecmp(action, "do_generic")) {
1241                 do_generic();
1242         } else if (!strcasecmp(action, "display_menubar")) {
1243                 display_menubar(1);
1244         } else if (!strcasecmp(action, "output_mimepart")) {
1245                 output_mimepart();
1246         } else if (!strcasecmp(action, "edit_vcard")) {
1247                 edit_vcard();
1248         } else if (!strcasecmp(action, "submit_vcard")) {
1249                 submit_vcard();
1250         } else if (!strcasecmp(action, "select_user_to_edit")) {
1251                 select_user_to_edit(NULL, NULL);
1252         } else if (!strcasecmp(action, "display_edituser")) {
1253                 display_edituser(NULL, 0);
1254         } else if (!strcasecmp(action, "edituser")) {
1255                 edituser();
1256         } else if (!strcasecmp(action, "create_user")) {
1257                 create_user();
1258         } else if (!strcasecmp(action, "changeview")) {
1259                 change_view();
1260         } else if (!strcasecmp(action, "do_stuff_to_msgs")) {
1261                 do_stuff_to_msgs();
1262         } else if (!strcasecmp(action, "change_start_page")) {
1263                 change_start_page();
1264         } else if (!strcasecmp(action, "display_floorconfig")) {
1265                 display_floorconfig(NULL);
1266         } else if (!strcasecmp(action, "toggle_self_service")) {
1267                 toggle_self_service();
1268 #ifdef WEBCIT_WITH_CALENDAR_SERVICE
1269         } else if (!strcasecmp(action, "display_edit_task")) {
1270                 display_edit_task();
1271         } else if (!strcasecmp(action, "save_task")) {
1272                 save_task();
1273         } else if (!strcasecmp(action, "display_edit_event")) {
1274                 display_edit_event();
1275         } else if (!strcasecmp(action, "save_event")) {
1276                 save_event();
1277         } else if (!strcasecmp(action, "respond_to_request")) {
1278                 respond_to_request();
1279         } else if (!strcasecmp(action, "handle_rsvp")) {
1280                 handle_rsvp();
1281 #endif
1282         } else if (!strcasecmp(action, "summary")) {
1283                 summary();
1284         } else if (!strcasecmp(action, "iconbar")) {
1285                 do_iconbar();
1286         } else if (!strcasecmp(action, "display_customize_iconbar")) {
1287                 display_customize_iconbar();
1288         } else if (!strcasecmp(action, "commit_iconbar")) {
1289                 commit_iconbar();
1290         } else if (!strcasecmp(action, "set_room_policy")) {
1291                 set_room_policy();
1292         } else if (!strcasecmp(action, "display_inetconf")) {
1293                 display_inetconf();
1294         } else if (!strcasecmp(action, "save_inetconf")) {
1295                 save_inetconf();
1296         } else if (!strcasecmp(action, "diagnostics")) {
1297                 output_headers(1, 1, 1, 0, 0, 0, 0);
1298
1299                 wprintf("You're in session %d<hr />\n", WC->wc_session);
1300                 wprintf("Command: <br /><PRE>\n");
1301                 escputs(cmd);
1302                 wprintf("</PRE><hr />\n");
1303                 wprintf("Variables: <br /><PRE>\n");
1304                 dump_vars();
1305                 wprintf("</PRE><hr />\n");
1306                 wDumpContent(1);
1307         }
1308         /* When all else fais, display the main menu. */
1309         else {
1310                 display_main_menu();
1311         }
1312
1313 SKIP_ALL_THIS_CRAP:
1314         fflush(stdout);
1315         if (content != NULL) {
1316                 free(content);
1317                 content = NULL;
1318         }
1319         free_urls();
1320         if (WC->upload_length > 0) {
1321                 free(WC->upload);
1322                 WC->upload_length = 0;
1323         }
1324
1325 }