* Removed the gzip compression stuff due to bugs in Internet Explorer.
[citadel.git] / webcit / webcit.c
index 7ab86d6c84a67442732409e657c2ebe8bc0d07e4..7707a6820dbb12c25eda5c668b158d13d98557ad 100644 (file)
@@ -8,48 +8,36 @@
  * $Id$
  */
 
+#include <ctype.h>
 #include <stdlib.h>
-#ifdef HAVE_UNISTD_H
 #include <unistd.h>
-#endif
 #include <stdio.h>
-#include <ctype.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <sys/stat.h>
+#include <limits.h>
+#include <netinet/in.h>
+#include <netdb.h>
 #include <string.h>
+#include <pwd.h>
 #include <errno.h>
-#include <sys/stat.h>
 #include <stdarg.h>
+#include <pthread.h>
+#include <signal.h>
 #include "webcit.h"
-#include "child.h"
+#include "webserver.h"
 #include "mime_parser.h"
 
-int wc_session;
-char wc_username[256];
-char wc_password[256];
-char wc_roomname[256];
-int TransactionCount = 0;
-int connected = 0;
-int logged_in = 0;
-int axlevel;
-char *ExpressMessages = NULL;
-int new_mail = 0;
-int need_vali = 0;
-
-/* This variable is set to 1 if the room banner and menubar have been
- * displayed, and we need to close the <TABLE> tags.
+/*
+ * String to unset the cookie.
+ * Any date "in the past" will work, so I chose my birthday, right down to
+ * the exact minute.  :)
  */
-int fake_frames = 0;
-
-struct webcontent *wlist = NULL;
-struct webcontent *wlast = NULL;
-
-struct urlcontent *urlstrings = NULL;
-
-static const char *defaulthost = DEFAULT_HOST;
-static const char *defaultport = DEFAULT_PORT;
-
-int upload_length = 0;
-char *upload;
-
+static char *unset = "; expires=28-May-1971 18:10:00 GMT";
 
 void unescape_input(char *buf)
 {
@@ -78,7 +66,7 @@ void unescape_input(char *buf)
 void addurls(char *url)
 {
        char *up, *ptr;
-       char buf[256];
+       char buf[SIZ];
        int a, b;
        struct urlcontent *u;
 
@@ -86,7 +74,7 @@ void addurls(char *url)
        while (strlen(up) > 0) {
 
                /* locate the = sign */
-               strncpy(buf, up, 255);
+               safestrncpy(buf, up, sizeof buf);
                b = (-1);
                for (a = 255; a >= 0; --a)
                        if (buf[a] == '=')
@@ -96,8 +84,8 @@ void addurls(char *url)
                buf[b] = 0;
 
                u = (struct urlcontent *) malloc(sizeof(struct urlcontent));
-               u->next = urlstrings;
-               urlstrings = u;
+               u->next = WC->urlstrings;
+               WC->urlstrings = u;
                strcpy(u->url_key, buf);
 
                /* now chop that part off */
@@ -132,11 +120,11 @@ void free_urls(void)
 {
        struct urlcontent *u;
 
-       while (urlstrings != NULL) {
-               free(urlstrings->url_data);
-               u = urlstrings->next;
-               free(urlstrings);
-               urlstrings = u;
+       while (WC->urlstrings != NULL) {
+               free(WC->urlstrings->url_data);
+               u = WC->urlstrings->next;
+               free(WC->urlstrings);
+               WC->urlstrings = u;
        }
 }
 
@@ -147,7 +135,7 @@ void dump_vars(void)
 {
        struct urlcontent *u;
 
-       for (u = urlstrings; u != NULL; u = u->next) {
+       for (u = WC->urlstrings; u != NULL; u = u->next) {
                wprintf("%38s = %s\n", u->url_key, u->url_data);
        }
 }
@@ -156,7 +144,7 @@ char *bstr(char *key)
 {
        struct urlcontent *u;
 
-       for (u = urlstrings; u != NULL; u = u->next) {
+       for (u = WC->urlstrings; u != NULL; u = u->next) {
                if (!strcasecmp(u->url_key, key))
                        return (u->url_data);
        }
@@ -167,40 +155,18 @@ char *bstr(char *key)
 void wprintf(const char *format,...)
 {
        va_list arg_ptr;
-       struct webcontent *wptr;
-
-       wptr = (struct webcontent *) malloc(sizeof(struct webcontent));
-       wptr->next = NULL;
-       if (wlist == NULL) {
-               wlist = wptr;
-               wlast = wptr;
-       } else {
-               wlast->next = wptr;
-               wlast = wptr;
-       }
+       char wbuf[1024];
 
        va_start(arg_ptr, format);
-       vsprintf(wptr->w_data, format, arg_ptr);
+       vsprintf(wbuf, format, arg_ptr);
        va_end(arg_ptr);
-}
 
-int wContentLength(void)
-{
-       struct webcontent *wptr;
-       int len = 0;
-
-       for (wptr = wlist; wptr != NULL; wptr = wptr->next) {
-               len = len + strlen(wptr->w_data);
-       }
-
-       return (len);
+       write(WC->http_sock, wbuf, strlen(wbuf));
 }
 
+
 /*
- * wDumpContent() takes all the stuff that's been queued up using
- * the wprintf() and escputs() functions, and sends it out to the browser.
- * By queuing instead of transmitting as it's generated, we're able to
- * calculate a Content-length: header.
+ * wDumpContent() wraps up an HTTP session, closes tags, etc.
  *
  * print_standard_html_footer should be set to 0 to transmit only, 1 to
  * append the main menu and closing tags, or 2 to
@@ -208,22 +174,9 @@ int wContentLength(void)
  */
 void wDumpContent(int print_standard_html_footer)
 {
-       struct webcontent *wptr;
-
-       if (fake_frames) {
-               wprintf("<CENTER><FONT SIZE=-1>"
-                       "<A HREF=\"/ungoto\">"
-                       "<IMG SRC=\"/static/back.gif\" BORDER=0>"
-                       "Ungoto</A>&nbsp;&nbsp;&nbsp;");
-               wprintf("<A HREF=\"#TheTop\">"
-                       "<IMG SRC=\"/static/up.gif\" BORDER=0>"
-                       "Top of page</A>&nbsp;&nbsp;&nbsp;");
-               wprintf("<A HREF=\"/gotonext\">"
-                       "Goto next room"
-                       "<IMG SRC=\"/static/forward.gif\" BORDER=0></A>"
-                       "</FONT>\n"
-                       "</TD></TR></TABLE></TABLE>\n");
-               fake_frames = 0;
+       if (WC->fake_frames) {
+               wprintf("</TABLE>\n");
+               WC->fake_frames = 0;
        }
 
        if (print_standard_html_footer) {
@@ -232,59 +185,65 @@ void wDumpContent(int print_standard_html_footer)
                }
                wprintf("</BODY></HTML>\n");
        }
-       printf("Content-type: text/html\n");
-       printf("Content-length: %d\n", wContentLength());
-       printf("\n");
 
-       while (wlist != NULL) {
-               fwrite(wlist->w_data, strlen(wlist->w_data), 1, stdout);
-               wptr = wlist->next;
-               free(wlist);
-               wlist = wptr;
-       }
-       wlast = NULL;
+
 }
 
 
-void escputs1(char *strbuf, int nbsp)
+/*
+ * Copy a string, escaping characters which have meaning in HTML.  If
+ * nbsp is nonzero, spaces are converted to non-breaking spaces.
+ */
+void stresc(char *target, char *strbuf, int nbsp)
 {
        int a;
+       strcpy(target, "");
 
        for (a = 0; a < strlen(strbuf); ++a) {
                if (strbuf[a] == '<')
-                       wprintf("&lt;");
+                       strcat(target, "&lt;");
                else if (strbuf[a] == '>')
-                       wprintf("&gt;");
+                       strcat(target, "&gt;");
                else if (strbuf[a] == '&')
-                       wprintf("&amp;");
-               else if (strbuf[a] == 34)
-                       wprintf("&quot;");
+                       strcat(target, "&amp;");
+               else if (strbuf[a] == '\"')
+                       strcat(target, "&quot;");
+               else if (strbuf[a] == '\'') 
+                       strcat(target, "&#39;");
                else if (strbuf[a] == LB)
-                       wprintf("<");
+                       strcat(target, "<");
                else if (strbuf[a] == RB)
-                       wprintf(">");
+                       strcat(target, ">");
                else if (strbuf[a] == QU)
-                       wprintf("\"");
+                       strcat(target, "\"");
                else if ((strbuf[a] == 32) && (nbsp == 1)) {
-                       wprintf("&nbsp;");
+                       strcat(target, "&nbsp;");
                } else {
-                       wprintf("%c", strbuf[a]);
+                       strncat(target, &strbuf[a], 1);
                }
        }
 }
 
+void escputs1(char *strbuf, int nbsp)
+{
+       char buf[1024];
+       stresc(buf, strbuf, nbsp);
+       wprintf("%s", buf);
+}
+
 void escputs(char *strbuf)
 {
        escputs1(strbuf, 0);
 }
 
-
-
-char *urlesc(char *strbuf)
+/*
+ * Escape a string for feeding out as a URL.
+ * Returns a pointer to a buffer that must be freed by the caller!
+ */
+void urlesc(char *outbuf, char *strbuf)
 {
        int a, b, c;
        char *ec = " #&;`'|*?-~<>^()[]{}$\\";
-       static char outbuf[512];
 
        strcpy(outbuf, "");
 
@@ -300,146 +259,165 @@ char *urlesc(char *strbuf)
                else
                        sprintf(&outbuf[b], "%c", strbuf[a]);
        }
-       return (outbuf);
 }
 
 void urlescputs(char *strbuf)
 {
-       wprintf("%s", urlesc(strbuf));
+       char outbuf[SIZ];
+       
+       urlesc(outbuf, strbuf);
+       wprintf("%s", outbuf);
 }
 
 
 
 
-/*
- * Get a line of text from the webserver (which originally came from the
- * user's browser), checking for sanity etc.
- */
-char *getz(char *buf)
-{
-       int e = 0;
-
-       bzero(buf, 256);
-
-       /* If fgets() fails, it's because the webserver crashed, so kill off
-        * the session too.
-        */
-       if (fgets(buf, 256, stdin) == NULL) {
-               e = errno;
-               fprintf(stderr, "webcit: exit code %d (%s)\n",
-                       e, strerror(e));
-               fflush(stderr);
-               exit(e);
-               
-       /* Otherwise, strip out nonprintables and resume our happy day.
-        */
-       } else {
-               while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1])))
-                       buf[strlen(buf) - 1] = 0;
-               return buf;
-       }
-}
-
-
-
 /*
  * Output all that important stuff that the browser will want to see
  *
- * print_standard_html_head values:
+ * control codes:
+ * 
+ * Bits 0 and 1:
  * 0 = Nothing.  Do not display any leading HTTP or HTML.
- * 1 = HTTP headers plus the "fake frames" found in most windows.
+ * 1 = HTTP headers plus the room banner
  * 2 = HTTP headers required to terminate the session (unset cookies)
- * 3 = HTTP headers only.
+ * 3 = HTTP and HTML headers, but no room banner
+ *
+ * Bit 2: Set to 1 to auto-refresh page every 30 seconds
+ *
+ * Bit 3: suppress check for express messages
  */
-void output_headers(int print_standard_html_head)
+void output_headers(int controlcode)
 {
+       char cookie[SIZ];
+       int print_standard_html_head = 0;
+       int refresh30 = 0;
+       int suppress_check = 0;
+       char httpnow[SIZ];
+       static int pageseq = 0;
+       print_standard_html_head        =       controlcode & 0x03;
+       refresh30                       =       ((controlcode & 0x04) >> 2);
+       suppress_check                  =       ((controlcode & 0x08) >> 3);
 
-       static char *unset = "; expires=28-May-1971 18:10:00 GMT";
-       char cookie[256];
+       wprintf("HTTP/1.0 200 OK\n");
 
-       printf("Server: %s\n", SERVER);
-       printf("Connection: close\n");
+       httpdate(httpnow, time(NULL));
 
        if (print_standard_html_head > 0) {
-               printf("Pragma: no-cache\n");
-               printf("Cache-Control: no-store\n");
+               wprintf("Content-type: text/html\n"
+                       "Server: %s\n", SERVER
+               );
+               wprintf("Connection: close\n"
+                       "Pragma: no-cache\n"
+                       "Cache-Control: no-store\n"
+               );
        }
-       stuff_to_cookie(cookie, wc_session, wc_username,
-                       wc_password, wc_roomname);
+       stuff_to_cookie(cookie, WC->wc_session, WC->wc_username,
+                       WC->wc_password, WC->wc_roomname);
        if (print_standard_html_head == 2) {
-               printf("X-WebCit-Session: close\n");
-               printf("Set-cookie: webcit=%s\n", unset);
+               wprintf("Set-cookie: webcit=%s\n", unset);
        } else {
-               printf("Set-cookie: webcit=%s\n", cookie);
+               wprintf("Set-cookie: webcit=%s\n", cookie);
+               if (server_cookie != NULL) {
+                       wprintf("%s\n", server_cookie);
+               }
        }
 
        if (print_standard_html_head > 0) {
+               wprintf("\n");
+
                wprintf("<HTML><HEAD><TITLE>");
                escputs(serv_info.serv_humannode);
-               wprintf("</TITLE></HEAD>");
-               if (ExpressMessages != NULL) {
-                       wprintf("<SCRIPT language=\"javascript\">\n");
-                       wprintf("function ExpressMessage() {\n");
-                       wprintf(" alert(\"");
-                       escputs(ExpressMessages);
-                       wprintf("\")\n");
-                       wprintf(" }\n </SCRIPT>\n");
-               }
-               wprintf("<BODY ");
-               if (ExpressMessages != NULL) {
-                       wprintf("onload=\"ExpressMessage()\" ");
-                       free(ExpressMessages);
-                       ExpressMessages = NULL;
-               }
-               wprintf("BACKGROUND=\"/image&name=background\" TEXT=\"#000000\" LINK=\"#004400\">\n");
-       
-       
-       if (print_standard_html_head == 1) {
-               wprintf("<A NAME=\"TheTop\"></A>"
-                       "<TABLE border=0 width=100%>"
-                       "<TR VALIGN=TOP><TD>");
+               wprintf("</TITLE>\n"
+                       "<META HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\">\n"
+                       "<META HTTP-EQUIV=\"expired\" CONTENT=\"28-May-1971 18:10:00 GMT\">\n"
+                       "<META NAME=\"MSSmartTagsPreventParsing\" CONTENT=\"TRUE\">\n");
+               if (refresh30) wprintf(
+                       "<META HTTP-EQUIV=\"refresh\" CONTENT=\"30\">\n");
+               else wprintf(
+                       "<META HTTP-EQUIV=\"refresh\" CONTENT=\"500363689;\">\n");
+               wprintf("</HEAD>\n");
+
+               /* script for checking for pages (not always launched) */
+               wprintf("<SCRIPT LANGUAGE=\"JavaScript\">\n");
+               wprintf("function launch_page_popup() {\n");
+               wprintf("pwin = window.open('/page_popup', 'CitaPage%d', "
+                       "'toolbar=no,location=no,copyhistory=no,status=no,"
+                       "scrollbars=yes,resizable=no,height=250,width=400');\n",
+                       ++pageseq);
+               wprintf("}\n");
+               wprintf("</SCRIPT>\n");
+               /* end script */
+
+               /* (JavaScript keyboard-based navigation would go here) */
+
+               if (!suppress_check) if (WC->HaveExpressMessages) {
+                       svprintf("extrabodyparms", WCS_STRING, "%s", 
+                               "onload=\"launch_page_popup()\" ");
+                       WC->HaveExpressMessages = 0;
+               }
+               do_template("background");
+               clear_local_substs();
 
-               display_menubar(0);
+       if (print_standard_html_head == 1) {
+               wprintf("<A NAME=\"TheTop\"></A>");
 
-               wprintf("</TD><TD VALIGN=TOP>"
-                       "<TABLE border=0 width=100%><TR VALIGN=TOP>"
+               wprintf("<TABLE border=0 width=100%%><TR VALIGN=TOP>"
                        "<TD>\n");
 
                embed_room_banner(NULL);
 
                wprintf("</TD></TR><TR VALIGN=TOP><TD>\n");
                
-               fake_frames = 1;
+               WC->fake_frames = 1;
                }
        }
 }
 
 
-
-void ExpressMessageCat(char *buf) {
-       if (ExpressMessages == NULL) {
-               ExpressMessages = malloc(strlen(buf) + 4);
-               strcpy(ExpressMessages, "");
-       } else {
-               ExpressMessages = realloc(ExpressMessages,
-                       (strlen(ExpressMessages) + strlen(buf) + 4));
-       }
-       strcat(ExpressMessages, buf);
-       strcat(ExpressMessages, "\\n");
+/*
+ *
+ */
+void http_redirect(char *whichpage) {
+       wprintf("HTTP/1.0 302 Moved Temporarily\n");
+       wprintf("Location: %s\n", whichpage);
+       wprintf("URI: %s\n", whichpage);
+       wprintf("Content-type: text/html\n\n");
+       wprintf("<html><body>\n");
+       wprintf("you really want to be <A HREF=\"%s\">here</A> now\n",
+               whichpage);
+       wprintf("</body></html>\n");
 }
 
 
+
 void check_for_express_messages()
 {
-       char buf[256];
+       char buf[SIZ];
 
-       serv_puts("PEXP");
+       serv_puts("NOOP");
        serv_gets(buf);
-       if (buf[0] == '1') {
-               while (serv_gets(buf), strcmp(buf, "000")) {
-                       ExpressMessageCat(buf);
-               }
-       }
+       if (buf[3] == '*') WC->HaveExpressMessages = 1;
+}
+
+
+
+
+/* 
+ * Output a piece of content to the web browser
+ */
+void http_transmit_thing(char *thing, size_t length, char *content_type) {
+       output_headers(0);
+       wprintf("Content-type: %s\n"
+               "Content-length: %ld\n"
+               "Server: %s\n"
+               "Connection: close\n"
+               "\n",
+               content_type,
+               (long) length,
+               SERVER
+       );
+       write(WC->http_sock, thing, (size_t)length);
 }
 
 
@@ -447,89 +425,221 @@ void check_for_express_messages()
 
 void output_static(char *what)
 {
-       char buf[256];
+       char buf[4096];
        FILE *fp;
        struct stat statbuf;
        off_t bytes;
+       char *bigbuffer;
+       char content_type[SIZ];
 
        sprintf(buf, "static/%s", what);
        fp = fopen(buf, "rb");
        if (fp == NULL) {
-               printf("HTTP/1.0 404 %s\n", strerror(errno));
-               output_headers(0);
-               printf("Content-Type: text/plain\n");
-               sprintf(buf, "%s: %s\n", what, strerror(errno));
-               printf("Content-length: %d\n", strlen(buf));
-               printf("\n");
-               fwrite(buf, strlen(buf), 1, stdout);
+               wprintf("HTTP/1.0 404 %s\n", strerror(errno));
+               wprintf("Content-Type: text/plain\n");
+               wprintf("\n");
+               wprintf("Cannot open %s: %s\n", what, strerror(errno));
        } else {
-               printf("HTTP/1.0 200 OK\n");
-               output_headers(0);
-
                if (!strncasecmp(&what[strlen(what) - 4], ".gif", 4))
-                       printf("Content-type: image/gif\n");
+                       strcpy(content_type, "image/gif");
+               else if (!strncasecmp(&what[strlen(what) - 4], ".txt", 4))
+                       strcpy(content_type, "text/plain");
+               else if (!strncasecmp(&what[strlen(what) - 4], ".css", 4))
+                       strcpy(content_type, "text/css");
                else if (!strncasecmp(&what[strlen(what) - 4], ".jpg", 4))
-                       printf("Content-type: image/jpeg\n");
+                       strcpy(content_type, "image/jpeg");
+               else if (!strncasecmp(&what[strlen(what) - 4], ".png", 4))
+                       strcpy(content_type, "image/png");
                else if (!strncasecmp(&what[strlen(what) - 5], ".html", 5))
-                       printf("Content-type: text/html\n");
+                       strcpy(content_type, "text/html");
+               else if (!strncasecmp(&what[strlen(what) - 4], ".wml", 4))
+                       strcpy(content_type, "text/vnd.wap.wml");
+               else if (!strncasecmp(&what[strlen(what) - 5], ".wmls", 5))
+                       strcpy(content_type, "text/vnd.wap.wmlscript");
+               else if (!strncasecmp(&what[strlen(what) - 5], ".wmlc", 5))
+                       strcpy(content_type, "application/vnd.wap.wmlc");
+               else if (!strncasecmp(&what[strlen(what) - 6], ".wmlsc", 6))
+                       strcpy(content_type, "application/vnd.wap.wmlscriptc");
+               else if (!strncasecmp(&what[strlen(what) - 5], ".wbmp", 5))
+                       wprintf("Content-type: image/vnd.wap.wbmp");
                else
-                       printf("Content-type: application/octet-stream\n");
+                       wprintf("Content-type: application/octet-stream");
 
                fstat(fileno(fp), &statbuf);
                bytes = statbuf.st_size;
-               printf("Content-length: %ld\n", (long) bytes);
-               printf("\n");
-               while (bytes--) {
-                       putc(getc(fp), stdout);
-               }
-               fflush(stdout);
+               lprintf(3, "Static: %s, %ld bytes\n", what, bytes);
+               bigbuffer = malloc(bytes);
+               fread(bigbuffer, bytes, 1, fp);
                fclose(fp);
+
+               http_transmit_thing(bigbuffer, (size_t)bytes, content_type);
+               free(bigbuffer);
+       }
+       if (!strcasecmp(bstr("force_close_session"), "yes")) {
+               end_webcit_session();
        }
 }
 
+
+/*
+ * When the browser requests an image file from the Citadel server,
+ * this function is called to transmit it.
+ */
 void output_image()
 {
-       char buf[256];
-       char xferbuf[4096];
+       char buf[SIZ];
+       char *xferbuf = NULL;
        off_t bytes;
        off_t thisblock;
        off_t accomplished = 0L;
 
-
        serv_printf("OIMG %s|%s", bstr("name"), bstr("parm"));
        serv_gets(buf);
        if (buf[0] == '2') {
                bytes = extract_long(&buf[4], 0);
-               printf("HTTP/1.0 200 OK\n");
+               xferbuf = malloc(bytes);
+
+               /* Read it from the server */
+               while (bytes > (off_t) 0) {
+                       thisblock = 4096;
+                       if (thisblock > bytes) {
+                               thisblock = bytes;
+                       }
+                       serv_printf("READ %ld|%ld", accomplished, thisblock);
+                       serv_gets(buf);
+                       if (buf[0] == '6') {
+                               thisblock = extract_long(&buf[4], 0);
+                               serv_read(&xferbuf[accomplished],
+                                       (int) thisblock);
+                       }
+                       else {
+                               memset(&xferbuf[accomplished], 0, thisblock);
+                       }
+                       bytes = bytes - thisblock;
+                       accomplished += thisblock;
+               }
+               serv_puts("CLOS");
+               serv_gets(buf);
+
+               /* Write it to the browser */
+               http_transmit_thing(xferbuf, (size_t)accomplished,
+                                       "image/gif");
+
+       } else {
+               wprintf("HTTP/1.0 404 %s\n", &buf[4]);
+               output_headers(0);
+               wprintf("Content-Type: text/plain\n"
+                       "\n"
+                       "Error retrieving image: %s\n",
+                       &buf[4]
+               );
+       }
+
+       if (xferbuf) {
+               free(xferbuf);
+       }
+
+
+}
+
+/*
+ */
+void output_mimepart()
+{
+       char buf[SIZ];
+       char xferbuf[4096];
+       off_t bytes;
+       off_t thisblock;
+       off_t accomplished = 0L;
+       char content_type[SIZ];
+       
+       serv_printf("OPNA %s|%s", bstr("msgnum"), bstr("partnum"));
+       serv_gets(buf);
+       if (buf[0] == '2') {
+               bytes = extract_long(&buf[4], 0);
+               extract(content_type, &buf[4], 3);
                output_headers(0);
-               printf("Content-type: image/gif\n");
-               printf("Content-length: %ld\n", (long) bytes);
-               printf("\n");
+               wprintf("Content-type: %s\n", content_type);
+               wprintf("Content-length: %ld\n", (long) bytes);
+               wprintf("\n");
 
                while (bytes > (off_t) 0) {
                        thisblock = (off_t) sizeof(xferbuf);
-                       if (thisblock > bytes)
+                       if (thisblock > bytes) {
                                thisblock = bytes;
+                       }
                        serv_printf("READ %ld|%ld", accomplished, thisblock);
                        serv_gets(buf);
-                       if (buf[0] == '6')
+                       if (buf[0] == '6') {
                                thisblock = extract_long(&buf[4], 0);
-                       serv_read(xferbuf, (int) thisblock);
-                       fwrite(xferbuf, thisblock, 1, stdout);
+                               serv_read(xferbuf, (int) thisblock);
+                       }
+                       else {
+                               memset(xferbuf, 0, thisblock);
+                       }
+                       write(WC->http_sock, xferbuf, thisblock);
                        bytes = bytes - thisblock;
                        accomplished = accomplished + thisblock;
                }
-               fflush(stdout);
                serv_puts("CLOS");
                serv_gets(buf);
        } else {
-               printf("HTTP/1.0 404 %s\n", strerror(errno));
+               wprintf("HTTP/1.0 404 %s\n", &buf[4]);
                output_headers(0);
-               printf("Content-Type: text/plain\n");
-               sprintf(buf, "Error retrieving image\n");
-               printf("Content-length: %d\n", strlen(buf));
-               printf("\n");
-               fwrite(buf, strlen(buf), 1, stdout);
+               wprintf("Content-Type: text/plain\n");
+               wprintf("\n");
+               wprintf("Error retrieving part: %s\n", &buf[4]);
+       }
+
+}
+
+
+/*
+ */
+char *load_mimepart(long msgnum, char *partnum)
+{
+       char buf[SIZ];
+       off_t bytes;
+       off_t thisblock;
+       off_t accomplished = 0L;
+       char content_type[SIZ];
+       char *content;
+       
+       serv_printf("OPNA %ld|%s", msgnum, partnum);
+       serv_gets(buf);
+       if (buf[0] == '2') {
+               bytes = extract_long(&buf[4], 0);
+               extract(content_type, &buf[4], 3);
+
+               content = malloc(bytes + 1);
+
+               while (bytes > (off_t) 0) {
+                       thisblock = bytes;
+                       if (thisblock > 4096L) {
+                               thisblock = 4096L;
+                       }
+                       if (thisblock > bytes) {
+                               thisblock = bytes;
+                       }
+                       serv_printf("READ %ld|%ld", accomplished, thisblock);
+                       serv_gets(buf);
+                       if (buf[0] == '6') {
+                               thisblock = extract_long(&buf[4], 0);
+                               serv_read(&content[accomplished], (int) thisblock);
+                       }
+                       else {
+                               memset(&content[accomplished], 0, thisblock);
+                       }
+                       bytes = bytes - thisblock;
+                       accomplished = accomplished + thisblock;
+               }
+               serv_puts("CLOS");
+               serv_gets(buf);
+               content[accomplished] = 0;      /* null terminate for good measure */
+               return(content);
+       }
+       else {
+               return(NULL);
        }
 
 }
@@ -540,19 +650,77 @@ void output_image()
  */
 void convenience_page(char *titlebarcolor, char *titlebarmsg, char *messagetext)
 {
-       printf("HTTP/1.0 200 OK\n");
+       wprintf("HTTP/1.0 200 OK\n");
        output_headers(1);
-       wprintf("<TABLE WIDTH=100% BORDER=0 BGCOLOR=%s><TR><TD>", titlebarcolor);
+       wprintf("<TABLE WIDTH=100%% BORDER=0 BGCOLOR=%s><TR><TD>", titlebarcolor);
        wprintf("<FONT SIZE=+1 COLOR=\"FFFFFF\"");
        wprintf("<B>%s</B>\n", titlebarmsg);
        wprintf("</FONT></TD></TR></TABLE><BR>\n");
        escputs(messagetext);
 
        wprintf("<HR>\n");
-       embed_main_menu();
        wDumpContent(1);
 }
 
+
+/*
+ * Display a blank page.
+ */
+void blank_page(void) {
+       output_headers(7);
+       wDumpContent(2);
+}
+
+
+
+
+/*
+ * Offer to make any page the user's "start page."
+ */
+void offer_start_page(void) {
+       wprintf("<A HREF=\"/change_start_page?startpage=");
+       urlescputs(WC->this_page);
+       wprintf("\">"
+               "<FONT SIZE=-2 COLOR=#AAAAAA>Make this my start page</FONT>"
+               "</A>"
+       );
+}
+
+
+/* 
+ * Change the user's start page
+ */
+void change_start_page(void) {
+
+       if (bstr("startpage") == NULL) {
+               display_error("startpage set to null");
+               return;
+       }
+
+       set_preference("startpage", bstr("startpage"));
+
+       output_headers(3);
+       wprintf("<TABLE WIDTH=100%% BORDER=0 BGCOLOR=000077><TR><TD>");
+       wprintf("<FONT SIZE=+1 COLOR=\"FFFFFF\"");
+       wprintf("<B>New start page</B>\n");
+       wprintf("</FONT></TD></TR></TABLE>\n");
+
+       wprintf("<CENTER>"
+               "<font size=+2>Your start page has been changed.</font>"
+               "<BR><BR>\n"
+               "<I>(Note: this does not change your browser's home page. "
+               "It changes the page you begin on when you log on to ");
+       escputs(serv_info.serv_humannode);
+       wprintf(".)</I><BR><BR>"
+               "<a href = \"javascript:history.back()\">Back...</a>"
+               "</CENTER>");
+
+       wDumpContent(1);
+}
+
+
+
+
 void display_error(char *errormessage)
 {
        convenience_page("770000", "Error", errormessage);
@@ -598,46 +766,61 @@ void extract_action(char *actbuf, char *cmdbuf)
 }
 
 
-void upload_handler(char *name, char *filename, char *encoding,
-                   void *content, char *cbtype, size_t length)
+void upload_handler(char *name, char *filename, char *partnum, char *disp,
+                       void *content, char *cbtype, size_t length,
+                       char *encoding, void *userdata)
 {
 
-       fprintf(stderr, "UPLOAD HANDLER CALLED\n");
-       fprintf(stderr, "    name = %s\n", name);
-       fprintf(stderr, "filename = %s\n", filename);
-       fprintf(stderr, "encoding = %s\n", encoding);
-       fprintf(stderr, "    type = %s\n", cbtype);
-       fprintf(stderr, "  length = %d\n", length);
-
-       if (strlen(name) > 0) {
-               upload = malloc(length);
-               if (upload != NULL) {
-                       upload_length = length;
-                       memcpy(upload, content, length);
+       lprintf(5, "UPLOAD HANDLER CALLED\n");
+       lprintf(5, "    name = %s\n", name);
+       lprintf(5, "filename = %s\n", filename);
+       lprintf(5, "encoding = %s\n", encoding);
+       lprintf(5, "    type = %s\n", cbtype);
+       lprintf(5, "  length = %ld\n", (long)length);
+
+       if (length > 0) {
+               WC->upload = malloc(length);
+               if (WC->upload != NULL) {
+                       WC->upload_length = length;
+                       memcpy(WC->upload, content, length);
+               }
+               else {
+                       lprintf(9, "malloc() failed: %s\n",
+                               strerror(errno));
                }
        }
 }
 
 
-void session_loop(char *browser_host, char *user_agent)
+
+
+/*
+ * Entry point for WebCit transaction
+ */
+void session_loop(struct httprequest *req)
 {
-       char cmd[256];
-       char action[256];
-       char buf[256];
+       char cmd[SIZ];
+       char action[SIZ];
+       char buf[SIZ];
        int a, b;
        int ContentLength = 0;
+       int BytesRead;
        char ContentType[512];
        char *content;
+       char *content_end;
+       struct httprequest *hptr;
+       char browser_host[SIZ];
+       char user_agent[SIZ];
 
        /* We stuff these with the values coming from the client cookies,
         * so we can use them to reconnect a timed out session if we have to.
         */
-       char c_host[256];
-       char c_port[256];
-       char c_username[256];
-       char c_password[256];
-       char c_roomname[256];
-       char cookie[256];
+       char c_host[SIZ];
+       char c_port[SIZ];
+       char c_username[SIZ];
+       char c_password[SIZ];
+       char c_roomname[SIZ];
+       char cookie[SIZ];
 
        strcpy(c_host, defaulthost);
        strcpy(c_port, defaultport);
@@ -645,51 +828,77 @@ void session_loop(char *browser_host, char *user_agent)
        strcpy(c_password, "");
        strcpy(c_roomname, "");
 
-       upload_length = 0;
-       upload = NULL;
+       WC->upload_length = 0;
+       WC->upload = NULL;
 
-       if (getz(cmd) == NULL)
-               return;
+       WC->is_wap = 0;
+
+       hptr = req;
+       if (hptr == NULL) return;
+
+       strcpy(cmd, hptr->line);
+       hptr = hptr->next;
        extract_action(action, cmd);
 
-       do {
-               if (getz(buf) == NULL)
-                       return;
+       while (hptr != NULL) {
+               strcpy(buf, hptr->line);
+               hptr = hptr->next;
 
                if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
                        strcpy(cookie, &buf[15]);
                        cookie_to_stuff(cookie, NULL,
                                      c_username, c_password, c_roomname);
                }
-               if (!strncasecmp(buf, "Content-length: ", 16)) {
+               else if (!strncasecmp(buf, "Content-length: ", 16)) {
                        ContentLength = atoi(&buf[16]);
                }
-               if (!strncasecmp(buf, "Content-type: ", 14)) {
-                       strcpy(ContentType, &buf[14]);
+               else if (!strncasecmp(buf, "Content-type: ", 14)) {
+                       safestrncpy(ContentType, &buf[14], sizeof ContentType);
                }
-       } while (strlen(buf) > 0);
-
-       ++TransactionCount;
+               else if (!strncasecmp(buf, "User-agent: ", 12)) {
+                       safestrncpy(user_agent, &buf[12], sizeof user_agent);
+               }
+               else if (!strncasecmp(buf, "Host: ", 6)) {
+                       safestrncpy(WC->http_host, &buf[6], sizeof WC->http_host);
+               }
+               /* Only WAP gateways explicitly name this content-type */
+               else if (strstr(buf, "text/vnd.wap.wml")) {
+                       WC->is_wap = 1;
+               }
+       }
 
        if (ContentLength > 0) {
+               lprintf(5, "Content length: %d\n", ContentLength);
                content = malloc(ContentLength + 1);
-               fread(content, ContentLength, 1, stdin);
-
-               content[ContentLength] = 0;
+               memset(content, 0, ContentLength+1);
+               BytesRead = 0;
+
+               while (BytesRead < ContentLength) {
+                       a=read(WC->http_sock, &content[BytesRead],
+                               ContentLength - BytesRead);
+                       if (a <= 0) BytesRead = ContentLength;
+                       else BytesRead += a;
+               }
 
                if (!strncasecmp(ContentType,
                              "application/x-www-form-urlencoded", 33)) {
                        addurls(content);
                } else if (!strncasecmp(ContentType, "multipart", 9)) {
-                       mime_parser(content, ContentLength, ContentType,
-                                   *upload_handler);
+                       content_end = content + ContentLength;
+                       mime_parser(content, content_end, *upload_handler,
+                                       NULL, NULL, NULL, 0);
                }
        } else {
                content = NULL;
        }
 
+       /* make a note of where we are in case the user wants to save it */
+       safestrncpy(WC->this_page, cmd, sizeof(WC->this_page));
+       remove_token(WC->this_page, 2, ' ');
+       remove_token(WC->this_page, 0, ' ');
+
        /* If there are variables in the URL, we must grab them now */
-       for (a = 0; a < strlen(cmd); ++a)
+       for (a = 0; a < strlen(cmd); ++a) {
                if ((cmd[a] == '?') || (cmd[a] == '&')) {
                        for (b = a; b < strlen(cmd); ++b)
                                if (isspace(cmd[b]))
@@ -697,28 +906,56 @@ void session_loop(char *browser_host, char *user_agent)
                        addurls(&cmd[a + 1]);
                        cmd[a] = 0;
                }
+       }
+
        /*
         * If we're not connected to a Citadel server, try to hook up the
         * connection now.  Preference is given to the host and port specified
         * by browser cookies, if cookies have been supplied.
         */
-       if (!connected) {
+       if (!WC->connected) {
                if (strlen(bstr("host")) > 0)
                        strcpy(c_host, bstr("host"));
                if (strlen(bstr("port")) > 0)
                        strcpy(c_port, bstr("port"));
-               serv_sock = connectsock(c_host, c_port, "tcp");
-               connected = 1;
-               serv_gets(buf); /* get the server welcome message */
-               get_serv_info(browser_host, user_agent);
+
+               if (!strcasecmp(c_host, "uds")) {
+                       /* unix domain socket */
+                       sprintf(buf, "%s/citadel.socket", c_port);
+                       WC->serv_sock = uds_connectsock(buf);
+               }
+               else {
+                       /* tcp socket */
+                       WC->serv_sock = tcp_connectsock(c_host, c_port);
+               }
+
+               if (WC->serv_sock < 0) {
+                       do_logout();
+                       goto SKIP_ALL_THIS_CRAP;
+               }
+               else {
+                       WC->connected = 1;
+                       serv_gets(buf); /* get the server welcome message */
+                       locate_host(browser_host, WC->http_sock);
+                       get_serv_info(browser_host, user_agent);
+               }
+       }
+
+       /*
+        * Functions which can be performed without logging in
+        */
+       if (!strcasecmp(action, "listsub")) {
+               do_listsub();
+               goto SKIP_ALL_THIS_CRAP;
        }
+
        check_for_express_messages();
 
        /*
         * If we're not logged in, but we have username and password cookies
         * supplied by the browser, try using them to log in.
         */
-       if ((!logged_in) && (strlen(c_username) > 0) && (strlen(c_password) > 0)) {
+       if ((!WC->logged_in) && (strlen(c_username) > 0) && (strlen(c_password) > 0)) {
                serv_printf("USER %s", c_username);
                serv_gets(buf);
                if (buf[0] == '3') {
@@ -733,11 +970,11 @@ void session_loop(char *browser_host, char *user_agent)
         * If we don't have a current room, but a cookie specifying the
         * current room is supplied, make an effort to go there.
         */
-       if ((strlen(wc_roomname) == 0) && (strlen(c_roomname) > 0)) {
+       if ((strlen(WC->wc_roomname) == 0) && (strlen(c_roomname) > 0)) {
                serv_printf("GOTO %s", c_roomname);
                serv_gets(buf);
                if (buf[0] == '2') {
-                       strcpy(wc_roomname, c_roomname);
+                       strcpy(WC->wc_roomname, c_roomname);
                }
        }
        if (!strcasecmp(action, "static")) {
@@ -748,23 +985,31 @@ void session_loop(char *browser_host, char *user_agent)
                output_static(buf);
        } else if (!strcasecmp(action, "image")) {
                output_image();
-       } else if ((!logged_in) && (!strcasecmp(action, "login"))) {
+
+       /*
+        * All functions handled below this point ... make sure we log in
+        * before doing anything else!
+        */
+       } else if ((!WC->logged_in) && (!strcasecmp(action, "login"))) {
                do_login();
-       } else if (!logged_in) {
+       } else if (!WC->logged_in) {
                display_login(NULL);
        }
-       /* Various commands... */
+
+       /*
+        * Various commands...
+        */
 
        else if (!strcasecmp(action, "do_welcome")) {
                do_welcome();
+       } else if (!strcasecmp(action, "blank")) {
+               blank_page();
        } else if (!strcasecmp(action, "display_main_menu")) {
                display_main_menu();
-       } else if (!strcasecmp(action, "advanced")) {
-               display_advanced_menu();
        } else if (!strcasecmp(action, "whobbs")) {
                whobbs();
        } else if (!strcasecmp(action, "knrooms")) {
-               list_all_rooms_by_floor();
+               knrooms();
        } else if (!strcasecmp(action, "gotonext")) {
                slrp_highest();
                gotonext();
@@ -775,6 +1020,8 @@ void session_loop(char *browser_host, char *user_agent)
        } else if (!strcasecmp(action, "dotgoto")) {
                slrp_highest();
                smart_goto(bstr("room"));
+       } else if (!strcasecmp(action, "dotskip")) {
+               smart_goto(bstr("room"));
        } else if (!strcasecmp(action, "termquit")) {
                do_logout();
        } else if (!strcasecmp(action, "readnew")) {
@@ -783,12 +1030,12 @@ void session_loop(char *browser_host, char *user_agent)
                readloop("readold");
        } else if (!strcasecmp(action, "readfwd")) {
                readloop("readfwd");
+       } else if (!strcasecmp(action, "headers")) {
+               readloop("headers");
        } else if (!strcasecmp(action, "display_enter")) {
                display_enter();
        } else if (!strcasecmp(action, "post")) {
                post_message();
-       } else if (!strcasecmp(action, "confirm_delete_msg")) {
-               confirm_delete_msg();
        } else if (!strcasecmp(action, "delete_msg")) {
                delete_msg();
        } else if (!strcasecmp(action, "confirm_move_msg")) {
@@ -821,14 +1068,18 @@ void session_loop(char *browser_host, char *user_agent)
                entroom();
        } else if (!strcasecmp(action, "display_editroom")) {
                display_editroom();
+       } else if (!strcasecmp(action, "netedit")) {
+               netedit();
        } else if (!strcasecmp(action, "editroom")) {
                editroom();
+        } else if (!strcasecmp(action, "display_whok")) {
+                display_whok();
        } else if (!strcasecmp(action, "display_editinfo")) {
                display_edit("Room info", "EINF 0", "RINF", "/editinfo");
        } else if (!strcasecmp(action, "editinfo")) {
                save_edit("Room info", "EINF 1", 1);
        } else if (!strcasecmp(action, "display_editbio")) {
-               sprintf(buf, "RBIO %s", wc_username);
+               sprintf(buf, "RBIO %s", WC->wc_username);
                display_edit("Your bio", "NOOP", buf, "editbio");
        } else if (!strcasecmp(action, "editbio")) {
                save_edit("Your bio", "EBIO", 0);
@@ -850,8 +1101,12 @@ void session_loop(char *browser_host, char *user_agent)
                                        "/editroompic");
        } else if (!strcasecmp(action, "editroompic")) {
                do_graphics_upload("UIMG 1|_roompic_");
-       } else if (!strcasecmp(action, "select_floor_to_edit_pic")) {
-               select_floor_to_edit_pic();
+       } else if (!strcasecmp(action, "delete_floor")) {
+               delete_floor();
+       } else if (!strcasecmp(action, "rename_floor")) {
+               rename_floor();
+       } else if (!strcasecmp(action, "create_floor")) {
+               create_floor();
        } else if (!strcasecmp(action, "display_editfloorpic")) {
                sprintf(buf, "UIMG 0|_floorpic_|%s",
                        bstr("which_floor"));
@@ -872,30 +1127,27 @@ void session_loop(char *browser_host, char *user_agent)
                changepw();
        } else if (!strcasecmp(action, "display_edit_node")) {
                display_edit_node();
+       } else if (!strcasecmp(action, "edit_node")) {
+               edit_node();
        } else if (!strcasecmp(action, "display_netconf")) {
                display_netconf();
-       } else if (!strcasecmp(action, "display_confirm_unshare")) {
-               display_confirm_unshare();
        } else if (!strcasecmp(action, "display_confirm_delete_node")) {
                display_confirm_delete_node();
        } else if (!strcasecmp(action, "delete_node")) {
                delete_node();
-       } else if (!strcasecmp(action, "unshare")) {
-               unshare();
        } else if (!strcasecmp(action, "display_add_node")) {
                display_add_node();
        } else if (!strcasecmp(action, "add_node")) {
                add_node();
-       } else if (!strcasecmp(action, "display_share")) {
-               display_share();
-       } else if (!strcasecmp(action, "share")) {
-               share();
        } else if (!strcasecmp(action, "terminate_session")) {
+               slrp_highest();
                terminate_session();
        } else if (!strcasecmp(action, "edit_me")) {
                edit_me();
        } else if (!strcasecmp(action, "display_siteconfig")) {
                display_siteconfig();
+       } else if (!strcasecmp(action, "page_popup")) {
+               page_popup();
        } else if (!strcasecmp(action, "siteconfig")) {
                siteconfig();
        } else if (!strcasecmp(action, "display_generic")) {
@@ -904,12 +1156,48 @@ void session_loop(char *browser_host, char *user_agent)
                do_generic();
        } else if (!strcasecmp(action, "display_menubar")) {
                display_menubar(1);
+       } else if (!strcasecmp(action, "output_mimepart")) {
+               output_mimepart();
+       } else if (!strcasecmp(action, "edit_vcard")) {
+               edit_vcard();
+       } else if (!strcasecmp(action, "submit_vcard")) {
+               submit_vcard();
+       } else if (!strcasecmp(action, "select_user_to_edit")) {
+               select_user_to_edit(NULL, NULL);
+       } else if (!strcasecmp(action, "display_edituser")) {
+               display_edituser(NULL);
+       } else if (!strcasecmp(action, "edituser")) {
+               edituser();
+       } else if (!strcasecmp(action, "create_user")) {
+               create_user();
+       } else if (!strcasecmp(action, "changeview")) {
+               change_view();
+       } else if (!strcasecmp(action, "folders")) {
+               folders();
+       } else if (!strcasecmp(action, "do_stuff_to_msgs")) {
+               do_stuff_to_msgs();
+       } else if (!strcasecmp(action, "change_start_page")) {
+               change_start_page();
+       } else if (!strcasecmp(action, "display_floorconfig")) {
+               display_floorconfig(NULL);
+       } else if (!strcasecmp(action, "toggle_self_service")) {
+               toggle_self_service();
+#ifdef HAVE_ICAL_H
+       } else if (!strcasecmp(action, "display_edit_task")) {
+               display_edit_task();
+       } else if (!strcasecmp(action, "save_task")) {
+               save_task();
+       } else if (!strcasecmp(action, "display_edit_event")) {
+               display_edit_event();
+       } else if (!strcasecmp(action, "save_event")) {
+               save_event();
+#endif
+       } else if (!strcasecmp(action, "summary")) {
+               summary();
        } else if (!strcasecmp(action, "diagnostics")) {
-               printf("HTTP/1.0 200 OK\n");
                output_headers(1);
 
-               wprintf("TransactionCount is %d<BR>\n", TransactionCount);
-               wprintf("You're in session %d<HR>\n", wc_session);
+               wprintf("You're in session %d<HR>\n", WC->wc_session);
                wprintf("Command: <BR><PRE>\n");
                escputs(cmd);
                wprintf("</PRE><HR>\n");
@@ -923,49 +1211,16 @@ void session_loop(char *browser_host, char *user_agent)
                display_main_menu();
        }
 
+SKIP_ALL_THIS_CRAP:
        fflush(stdout);
        if (content != NULL) {
                free(content);
                content = NULL;
        }
        free_urls();
-       if (upload_length > 0) {
-               free(upload);
-               upload_length = 0;
-       }
-}
-
-int main(int argc, char *argv[])
-{
-
-       char browser[256];
-       int bd;
-
-       if (argc != 6) {
-               fprintf(stderr,
-                       "webcit: usage error (argc must be 6, not %d)\n",
-                       argc);
-               return 1;
+       if (WC->upload_length > 0) {
+               free(WC->upload);
+               WC->upload_length = 0;
        }
 
-       wc_session = atoi(argv[1]);
-       defaulthost = argv[2];
-       defaultport = argv[3];
-
-       strcpy(wc_username, "");
-       strcpy(wc_password, "");
-       strcpy(wc_roomname, "");
-
-       /* Clear out serv_info and temporarily set the value of serv_humannode
-        * to a default value, because it'll be used in HTML page titles
-        */
-       memset(&serv_info, 0, sizeof(serv_info));
-       strcpy(serv_info.serv_humannode, "WebCit");
-
-       strcpy(browser, argv[5]);
-       bd = browser_braindamage_check(browser);
-
-       while (1) {
-               session_loop(argv[4], browser);
-       }
 }