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