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