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