sneaking up on that bug like a cat prowling in the jungle
[citadel.git] / webcit / webcit.c
index f304e6506c69c532c1cda18315ed757be49b6680..6d789dc4879b990725c30b5df3882f15eb085733 100644 (file)
 /*
- * $Id$
- *
  * This is the main transaction loop of the web service.  It maintains a
  * persistent session to the Citadel server, handling HTTP WebCit requests as
  * they arrive and presenting a user interface.
+ *
+ * Copyright (c) 1996-2011 by the citadel.org team
+ *
+ * This program is open source software.  You can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  */
+
 #define SHOW_ME_VAPPEND_PRINTF
 #include <stdio.h>
 #include <stdarg.h>
 #include "webcit.h"
-#include "groupdav.h"
+#include "dav.h"
 #include "webserver.h"
 
+StrBuf *csslocal = NULL;
+HashList *HandlerHash = NULL;
 
-/*
- * String to unset the cookie.
- * Any date "in the past" will work, so I chose my birthday, right down to
- * the exact minute.  :)
- */
-static char *unset = "; expires=28-May-1971 18:10:00 GMT";
+void stuff_to_cookie(int unset_cookie);
+int GetConnected(void);
 
-HashList *HandlerHash = NULL;
 
-void WebcitAddUrlHandler(const char * UrlString, 
-                        long UrlSLen, 
+void PutRequestLocalMem(void *Data, DeleteHashDataFunc DeleteIt)
+{
+        wcsession *WCC = WC;
+       int n;
+       
+       n = GetCount(WCC->Hdr->HTTPHeaders);
+       Put(WCC->Hdr->HTTPHeaders, IKEY(n), Data, DeleteIt);
+}
+
+void DeleteWebcitHandler(void *vHandler)
+{
+       WebcitHandler *Handler = (WebcitHandler*) vHandler;
+       FreeStrBuf(&Handler->Name);
+       FreeStrBuf(&Handler->DisplayName);
+       free (Handler);
+}
+
+void WebcitAddUrlHandler(const char * UrlString, long UrlSLen, 
+                        const char *DisplayName, long dslen,
                         WebcitHandlerFunc F, 
                         long Flags)
 {
-       WebcitHandler *NewHandler;
-
-       if (HandlerHash == NULL)
-               HandlerHash = NewHash(1, NULL);
-       
+       WebcitHandler *NewHandler;      
        NewHandler = (WebcitHandler*) malloc(sizeof(WebcitHandler));
        NewHandler->F = F;
        NewHandler->Flags = Flags;
-       Put(HandlerHash, UrlString, UrlSLen, NewHandler, NULL);
+       NewHandler->Name = NewStrBufPlain(UrlString, UrlSLen);
+       StrBufShrinkToFit(NewHandler->Name, 1);
+       NewHandler->DisplayName = NewStrBufPlain(DisplayName, dslen);
+       StrBufShrinkToFit(NewHandler->DisplayName, 1);
+       Put(HandlerHash, UrlString, UrlSLen, NewHandler, DeleteWebcitHandler);
+}
+
+void tmplput_HANDLER_DISPLAYNAME(StrBuf *Target, WCTemplputParams *TP) 
+{
+       wcsession *WCC = WC;
+       if (WCC->Hdr->HR.Handler != NULL)
+               StrBufAppendTemplate(Target, TP, WCC->Hdr->HR.Handler->DisplayName, 0);
 }
 
 
 /*
  * web-printing funcion. uses our vsnprintf wrapper
  */
-void wprintf(const char *format,...)
+#ifdef UBER_VERBOSE_DEBUGGING
+void wcc_printf(const char *FILE, const char *FUNCTION, long LINE, const char *format,...)
+#else
+void wc_printf(const char *format,...)
+#endif
 {
        wcsession *WCC = WC;
        va_list arg_ptr;
 
        if (WCC->WBuf == NULL)
                WCC->WBuf = NewStrBuf();
+#ifdef UBER_VERBOSE_DEBUGGING
+       StrBufAppendPrintf(WCC->WBuf, "\n%s:%s:%d[", FILE, FUNCTION, LINE);
+#endif
 
        va_start(arg_ptr, format);
        StrBufVAppendPrintf(WCC->WBuf, format, arg_ptr);
        va_end(arg_ptr);
+#ifdef UBER_VERBOSE_DEBUGGING
+       StrBufAppendPrintf(WCC->WBuf, "]\n");
+#endif
 }
 
 /*
@@ -80,8 +126,8 @@ void hprintf(const char *format,...)
 void wDumpContent(int print_standard_html_footer)
 {
        if (print_standard_html_footer) {
-               wprintf("</div> <!-- end of 'content' div -->\n");
-               do_template("trailing", NULL);
+               wc_printf("</div> <!-- end of 'content' div -->\n");
+               do_template("trailing");
        }
 
        /* If we've been saving it all up for one big output burst,
@@ -96,20 +142,19 @@ void wDumpContent(int print_standard_html_footer)
 /*
  * Output HTTP headers and leading HTML for a page
  */
-void output_headers(   int do_httpheaders,     /* 1 = output HTTP headers                          */
+void output_headers(   int do_httpheaders,     /* 1 = output HTTP headers                        */
                        int do_htmlhead,        /* 1 = output HTML <head> section and <body> opener */
 
-                       int do_room_banner,     /* 0=no, 1=yes,                                     
+                       int do_room_banner,     /* 0=no, 1=yes,                              
                                                 * 2 = I'm going to embed my own, so don't open the 
-                                                *     <div id="content"> either.                   
+                                                *     <div id="content"> either.                  
                                                 */
 
                        int unset_cookies,      /* 1 = session is terminating, so unset the cookies */
-                       int suppress_check,     /* 1 = suppress check for instant messages          */
-                       int cache               /* 1 = allow browser to cache this page             */
+                       int suppress_check,     /* 1 = suppress check for instant messages        */
+                       int cache               /* 1 = allow browser to cache this page      */
 ) {
        wcsession *WCC = WC;
-       char cookie[1024];
        char httpnow[128];
 
        hprintf("HTTP/1.1 200 OK\n");
@@ -129,7 +174,7 @@ void output_headers(        int do_httpheaders,     /* 1 = output HTTP headers
                                PACKAGE_STRING);
        }
 
-       if (cache) {
+       if (cache > 0) {
                char httpTomorow[128];
 
                http_datestring(httpTomorow, sizeof httpTomorow, 
@@ -150,51 +195,37 @@ void output_headers(      int do_httpheaders,     /* 1 = output HTTP headers
                );
        }
 
-       stuff_to_cookie(cookie, 1024, 
-                       WCC->wc_session, WCC->wc_username,
-                       WCC->wc_password, WCC->wc_roomname);
-
-       if (unset_cookies) {
-               hprintf("Set-cookie: webcit=%s; path=/\r\n", unset);
-       } else {
-               hprintf("Set-cookie: webcit=%s; path=/\r\n", cookie);
-               if (server_cookie != NULL) {
-                       hprintf("%s\n", server_cookie);
-               }
-       }
+       if (cache < 2) stuff_to_cookie(unset_cookies);
 
        if (do_htmlhead) {
                begin_burst();
-               do_template("head", NULL);
+               do_template("head");
 
                /* check for ImportantMessages (these display in a div overlaying the main screen) */
-               if (!IsEmptyStr(WC->ImportantMessage)) {
-                       wprintf("<div id=\"important_message\">\n"
+               if (StrLength(WCC->ImportantMsg) > 0) {
+                       wc_printf("<div id=\"important_message\">\n"
                                "<span class=\"imsg\">");
-                       escputs(WC->ImportantMessage);
-                       wprintf("</span><br />\n"
+                       StrEscAppend(WCC->WBuf, WCC->ImportantMsg, NULL, 0, 0);
+                       wc_printf("</span><br>\n"
                                "</div>\n"
                        );
-                       StrBufAppendPrintf(WCC->trailing_javascript,
-                               "setTimeout('hide_imsg_popup()', 5000); \n"
+                       StrBufAppendBufPlain(WCC->trailing_javascript,
+                                            HKEY("setTimeout('hide_imsg_popup()', 5000);       \n"),
+                                            0
                        );
-                       WCC->ImportantMessage[0] = 0;
+                       FlushStrBuf(WCC->ImportantMsg);
                }
-
                if ( (WCC->logged_in) && (!unset_cookies) ) {
-                 //DoTemplate(HKEY("iconbar"), NULL, &NoCtx);
-                       page_popup();
+                       DoTemplate(HKEY("paging"), NULL, &NoCtx);
                }
 
                if (do_room_banner == 1) {
-                       wprintf("<div id=\"banner\">\n");
-                       embed_room_banner(NULL, navbar_default);
-                       wprintf("</div>\n");
+                       tmplput_roombanner(NULL, NULL);
                }
        }
 
        if (do_room_banner == 1) {
-               wprintf("<div id=\"content\">\n");
+               wc_printf("<div id=\"content\">\n");
        }
 }
 
@@ -214,9 +245,10 @@ void http_redirect(const char *whichpage) {
        hprintf("Location: %s\r\n", whichpage);
        hprintf("URI: %s\r\n", whichpage);
        hprintf("Content-type: text/html; charset=utf-8\r\n");
-       wprintf("<html><body>");
-       wprintf("Go <a href=\"%s\">here</A>.", whichpage);
-       wprintf("</body></html>\n");
+       begin_burst();
+       wc_printf("<html><body>");
+       wc_printf("Go <a href=\"%s\">here</A>.", whichpage);
+       wc_printf("</body></html>\n");
        end_burst();
 }
 
@@ -225,15 +257,10 @@ void http_redirect(const char *whichpage) {
 /*
  * Output a piece of content to the web browser using conformant HTTP and MIME semantics
  */
-void http_transmit_thing(const char *content_type,
-                        int is_static) {
+void http_transmit_thing(const char *content_type, int is_static)
+{
 
-#ifndef TECH_PREVIEW
-       lprintf(9, "http_transmit_thing(%s)%s\n",
-               content_type,
-               (is_static ? " (static)" : "")
-       );
-#endif
+       syslog(9, "http_transmit_thing(%s)%s", content_type, ((is_static > 0) ? " (static)" : ""));
        output_headers(0, 0, 0, 0, 0, is_static);
 
        hprintf("Content-type: %s\r\n"
@@ -245,99 +272,6 @@ void http_transmit_thing(const char *content_type,
        end_burst();
 }
 
-/*
- * print menu box like used in the floor view or admin interface.
- * This function takes pair of strings as va_args, 
- * Title       Title string of the box
- * Class       CSS Class for the box
- * nLines      How many string pairs should we print? (URL, UrlText)
- * ...         Pairs of URL Strings and their Names
- */
-void print_menu_box(char* Title, char *Class, int nLines, ...)
-{
-       va_list arg_list;
-       long i;
-       
-       svput("BOXTITLE", WCS_STRING, Title);
-       do_template("beginboxx", NULL);
-       
-       wprintf("<ul class=\"%s\">", Class);
-       
-       va_start(arg_list, nLines);
-       for (i = 0; i < nLines; ++i)
-       { 
-               wprintf("<li><a href=\"%s\">", va_arg(arg_list, char *));
-               wprintf((char *) va_arg(arg_list, char *));
-               wprintf("</a></li>\n");
-       }
-       va_end (arg_list);
-       
-       wprintf("</a></li>\n");
-       
-       wprintf("</ul>");
-       
-       do_template("endbox", NULL);
-}
-
-
-/*
- * dump out static pages from disk
- */
-void output_static(const char *what)
-{
-       int fd;
-       struct stat statbuf;
-       off_t bytes;
-       off_t count = 0;
-       const char *content_type;
-       int len;
-       const char *Err;
-
-       fd = open(what, O_RDONLY);
-       if (fd <= 0) {
-               lprintf(9, "output_static('%s')  -- NOT FOUND --\n", what);
-               hprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
-               hprintf("Content-Type: text/plain\r\n");
-               wprintf("Cannot open %s: %s\r\n", what, strerror(errno));
-               end_burst();
-       } else {
-               len = strlen (what);
-               content_type = GuessMimeByFilename(what, len);
-
-               if (fstat(fd, &statbuf) == -1) {
-                       lprintf(9, "output_static('%s')  -- FSTAT FAILED --\n", what);
-                       hprintf("HTTP/1.1 404 %s\r\n", strerror(errno));
-                       hprintf("Content-Type: text/plain\r\n");
-                       wprintf("Cannot fstat %s: %s\n", what, strerror(errno));
-                       end_burst();
-                       return;
-               }
-
-               count = 0;
-               bytes = statbuf.st_size;
-
-               if (StrBufReadBLOB(WC->WBuf, &fd, 1, bytes, &Err) < 0)
-               {
-                       if (fd > 0) close(fd);
-                       lprintf(9, "output_static('%s')  -- FREAD FAILED (%s) --\n", what, strerror(errno));
-                               hprintf("HTTP/1.1 500 internal server error \r\n");
-                               hprintf("Content-Type: text/plain\r\n");
-                               end_burst();
-                               return;
-               }
-
-
-               close(fd);
-#ifndef TECH_PREVIEW
-               lprintf(9, "output_static('%s')  %s\n", what, content_type);
-#endif
-               http_transmit_thing(content_type, 1);
-       }
-       if (yesbstr("force_close_session")) {
-               end_webcit_session();
-       }
-}
-
 
 /*
  * Convenience functions to display a page containing only a string
@@ -350,14 +284,14 @@ void convenience_page(const char *titlebarcolor, const char *titlebarmsg, const
 {
        hprintf("HTTP/1.1 200 OK\n");
        output_headers(1, 1, 2, 0, 0, 0);
-       wprintf("<div id=\"banner\">\n");
-       wprintf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
-       wprintf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
-       wprintf("</td></tr></table>\n");
-       wprintf("</div>\n<div id=\"content\">\n");
+       wc_printf("<div id=\"banner\">\n");
+       wc_printf("<table width=100%% border=0 bgcolor=\"#%s\"><tr><td>", titlebarcolor);
+       wc_printf("<span class=\"titlebar\">%s</span>\n", titlebarmsg);
+       wc_printf("</td></tr></table>\n");
+       wc_printf("</div>\n<div id=\"content\">\n");
        escputs(messagetext);
 
-       wprintf("<hr />\n");
+       wc_printf("<hr />\n");
        wDumpContent(1);
 }
 
@@ -378,7 +312,6 @@ void url_do_template(void) {
        const StrBuf *MimeType;
        const StrBuf *Tmpl = sbstr("template");
        begin_burst();
-       output_headers(0, 0, 0, 0, 1, 0);
        MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
        http_transmit_thing(ChrPtr(MimeType), 0);
 }
@@ -388,28 +321,44 @@ void url_do_template(void) {
 /*
  * convenience function to indicate success
  */
-void display_success(char *successmessage)
+void display_success(const char *successmessage)
 {
        convenience_page("007700", "OK", successmessage);
 }
 
 
 /*
- * Authorization required page 
- * This is probably temporary and should be revisited 
+ * Authorization required page (sends a 401, causing the browser to request login credentials)
  */
-void authorization_required(const char *message)
+void authorization_required(void)
 {
+       wcsession *WCC = WC;
+       const char *message = "";
+
        hprintf("HTTP/1.1 401 Authorization Required\r\n");
+       hprintf(
+               "Server: %s / %s\r\n"
+               "Connection: close\r\n",
+               PACKAGE_STRING, ChrPtr(WC->serv_info->serv_software)
+       );
        hprintf("WWW-Authenticate: Basic realm=\"%s\"\r\n", ChrPtr(WC->serv_info->serv_humannode));
        hprintf("Content-Type: text/html\r\n");
-       wprintf("<h1>");
-       wprintf(_("Authorization Required"));
-       wprintf("</h1>\r\n");
-       wprintf(_("The resource you requested requires a valid username and password. "
-               "You could not be logged in: %s\n"), message);
+       begin_burst();
+       wc_printf("<h1>");
+       wc_printf(_("Authorization Required"));
+       wc_printf("</h1>\r\n");
+
+       if (WCC->ImportantMsg != NULL) {
+               message = ChrPtr(WCC->ImportantMsg);
+       }
+
+       wc_printf(
+               _("The resource you requested requires a valid username and password. "
+               "You could not be logged in: %s\n"),
+               message
+       );
        wDumpContent(0);
-       
+       end_webcit_session();
 }
 
 /*
@@ -419,23 +368,25 @@ void begin_ajax_response(void) {
        wcsession *WCC = WC;
 
        FlushStrBuf(WCC->HBuf);
-        output_headers(0, 0, 0, 0, 0, 0);
+       output_headers(0, 0, 0, 0, 0, 0);
 
-        hprintf("Content-type: text/html; charset=UTF-8\r\n"
-                "Server: %s\r\n"
-                "Connection: close\r\n"
+       hprintf("Content-type: text/html; charset=UTF-8\r\n"
+               "Server: %s\r\n"
+               "Connection: close\r\n"
                ,
-                PACKAGE_STRING);
-        begin_burst();
+               PACKAGE_STRING);
+       begin_burst();
 }
 
 /*
  * print ajax response footer 
  */
 void end_ajax_response(void) {
-        wDumpContent(0);
+       wDumpContent(0);
 }
 
+
+
 /*
  * Wraps a Citadel server command in an AJAX transaction.
  */
@@ -447,6 +398,7 @@ void ajax_servcmd(void)
        char *junk;
        size_t len;
 
+       syslog(LOG_DEBUG, "ajax_servcmd() g_cmd=\"%s\"", bstr("g_cmd") );
        begin_ajax_response();
        Buf = NewStrBuf();
        serv_puts(bstr("g_cmd"));
@@ -464,12 +416,12 @@ void ajax_servcmd(void)
                }
        case 1:
                while (!Done) {
-                       StrBuf_ServGetlnBuffered(Buf);
+                       if (StrBuf_ServGetln(Buf) < 0)
+                               break;
                        if ( (StrLength(Buf)==3) && 
                             !strcmp(ChrPtr(Buf), "000")) {
                                Done = 1;
                        }
-                       lprintf (1,"ajax: [%s]\n",ChrPtr(Buf));
                        StrBufAppendBuf(WCC->WBuf, Buf, 0);
                        StrBufAppendBufPlain(WCC->WBuf, HKEY("\n"), 0);
                }
@@ -496,7 +448,7 @@ void ajax_servcmd(void)
         * This is kind of an ugly hack, but this is the only place it can go.
         * If the command was GEXP, then the instant messenger window must be
         * running, so reset the "last_pager_check" watchdog timer so
-        * that page_popup() doesn't try to open it a second time.
+        * that page_popup() doesn't try to open it a second time. TODO: page_popup isn't with us anymore.
         */
        if (!strncasecmp(bstr("g_cmd"), "GEXP", 4)) {
                WCC->last_pager_check = time(NULL);
@@ -514,581 +466,420 @@ void seconds_since_last_gexp(void)
        char buf[256];
 
        if ( (time(NULL) - WC->last_pager_check) < 30) {
-               wprintf("NO\n");
+               wc_printf("NO\n");
        }
        else {
                memset(buf, 0, 5);
                serv_puts("NOOP");
                serv_getln(buf, sizeof buf);
                if (buf[3] == '*') {
-                       wprintf("YES");
+                       wc_printf("YES");
                }
                else {
-                       wprintf("NO");
+                       wc_printf("NO");
                }
        }
 }
 
-/**
- * \brief Detects a 'mobile' user agent 
+
+/*
+ * Save a URL destination so we can go to it later
  */
-int is_mobile_ua(char *user_agent) {
-      if (strstr(user_agent,"iPhone OS") != NULL) {
-       return 1;
-      } else if (strstr(user_agent,"Windows CE") != NULL) {
-       return 1;
-      } else if (strstr(user_agent,"SymbianOS") != NULL) {
-       return 1;
-      } else if (strstr(user_agent, "Opera Mobi") != NULL) {
-       return 1;
-      } else if (strstr(user_agent, "Firefox/2.0.0 Opera 9.51 Beta") != NULL) {
-             /*  For some reason a new install of Opera 9.51beta decided to spoof. */
-         return 1;
-         }
-      return 0;
-}
+void push_destination(void) {
+       wcsession *WCC = WC;
 
+       if (!WCC) {
+               wc_printf("no session");
+               return;
+       }
+
+       FreeStrBuf(&WCC->PushedDestination);
+       WCC->PushedDestination = NewStrBufDup(SBSTR("url"));
+       syslog(9, "Push: %s", ChrPtr(WCC->PushedDestination));
+       wc_printf("OK");
+}
 
 /*
- * Entry point for WebCit transaction
+ * Go to the URL saved by push_destination()
  */
-void session_loop(HashList *HTTPHeaders, 
-                 StrBuf *ReqLine, 
-                 StrBuf *request_method, 
-                 StrBuf *ReadBuf,
-                 const char **Pos)
-{
-       StrBuf *Buf;
-       const char *pch, *pchs, *pche;
-       void *vLine;
-       char action[1024];
-       char arg[8][128];
-       size_t sizes[10];
-       char *index[10];
-       char buf[SIZ];
-       int a, nBackDots, nEmpty;
-       int ContentLength = 0;
-       StrBuf *ContentType = NULL;
-       StrBuf *UrlLine = NULL;
-       StrBuf *content = NULL;
-       const char *content_end = NULL;
-       StrBuf *browser_host = NULL;
-       char user_agent[256];
-       int body_start = 0;
-       int is_static = 0;
-       int n_static = 0;
-       int len = 0;
-       void *vHandler;
-       WebcitHandler *Handler;
-       struct timeval tx_start;
-       struct timeval tx_finish;
+void pop_destination(void) {
+       wcsession *WCC = WC;
 
        /*
-        * 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.
+        * If we are in the middle of a new user signup, the server may request that
+        * we first pass through a registration screen.
         */
-       StrBuf *c_username;
-       StrBuf *c_password;
-       StrBuf *c_roomname;
-       char c_httpauth_string[SIZ];
-       StrBuf *c_httpauth_user;
-       StrBuf *c_httpauth_pass;
-       wcsession *WCC;
+       if ((WCC) && (WCC->need_regi)) {
+               if ((WCC->PushedDestination != NULL) && (StrLength(WCC->PushedDestination) > 0)) {
+                       /* Registering will take us to the My Citadel Config room, so save our place */
+                       StrBufAppendBufPlain(WCC->PushedDestination, HKEY("?go="), 0);
+                       StrBufUrlescAppend(WCC->PushedDestination, WCC->CurRoom.name, NULL);
+               }
+               WCC->need_regi = 0;
+               display_reg(1);
+               return;
+       }
 
-       gettimeofday(&tx_start, NULL);          /* start a stopwatch for performance timing */
-       
-       Buf = NewStrBuf();
-       c_username = NewStrBuf();
-       c_password = NewStrBuf();
-       c_roomname = NewStrBuf();
-       safestrncpy(c_httpauth_string, "", sizeof c_httpauth_string);
-       c_httpauth_user = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_USER));
-       c_httpauth_pass = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_PASS));
+       /*
+        * Do something reasonable if we somehow ended up requesting a pop without
+        * having first done a push.
+        */
+       if ( (!WCC) || (WCC->PushedDestination == NULL) || (StrLength(WCC->PushedDestination) == 0) ) {
+               do_welcome();
+               return;
+       }
 
-       WCC= WC;
-       if (WCC->WBuf == NULL)
-               WC->WBuf = NewStrBufPlain(NULL, 32768);
-       FlushStrBuf(WCC->WBuf);
+       /*
+        * All righty then!  We have a destination saved, so go there now.
+        */
+       syslog(9, "Pop: %s", ChrPtr(WCC->PushedDestination));
+       http_redirect(ChrPtr(WCC->PushedDestination));
+}
 
-       if (WCC->HBuf == NULL)
-               WCC->HBuf = NewStrBuf();
-       FlushStrBuf(WCC->HBuf);
 
-       WCC->upload_length = 0;
-       WCC->upload = NULL;
-       WCC->is_mobile = 0;
-       WCC->trailing_javascript = NewStrBuf();
-       WCC->nWildfireHeaders = 0;
 
-       /** Figure out the action */
-       index[0] = action;
-       sizes[0] = sizeof action;
-       for (a=1; a<9; a++)
+int ReadPostData(void)
+{
+       int rc;
+       int urlencoded_post = 0;
+       wcsession *WCC = WC;
+       StrBuf *content = NULL;
+       
+       urlencoded_post = (strncasecmp(ChrPtr(WCC->Hdr->HR.ContentType), "application/x-www-form-urlencoded", 33) == 0) ;
+
+       content = NewStrBufPlain(NULL, WCC->Hdr->HR.ContentLength + 256);
+
+       if (!urlencoded_post)
        {
-               index[a] = arg[a-1];
-               sizes[a] = sizeof arg[a-1];
+               StrBufPrintf(content, 
+                    "Content-type: %s\n"
+                            "Content-length: %ld\n\n",
+                            ChrPtr(WCC->Hdr->HR.ContentType), 
+                            WCC->Hdr->HR.ContentLength);
        }
-       nBackDots = 0;
-       nEmpty = 0;
-       for ( a = 0; a < 9; ++a)
-       {
-               extract_token(index[a], ChrPtr(ReqLine), a + 1, '/', sizes[a]);
-               if (strstr(index[a], "?")) *strstr(index[a], "?") = 0;
-               if (strstr(index[a], "&")) *strstr(index[a], "&") = 0;
-               if (strstr(index[a], " ")) *strstr(index[a], " ") = 0;
-               if ((index[a][0] == '.') && (index[a][1] == '.'))
-                       nBackDots++;
-               if (index[a][0] == '\0')
-                       nEmpty++;
+
+       /** Read the entire input data at once. */
+       rc = client_read_to(WCC->Hdr, content, 
+                           WCC->Hdr->HR.ContentLength,
+                           SLEEPING);
+       if (rc < 0)
+               return rc;
+               
+       
+       if (urlencoded_post) {
+               ParseURLParams(content);
+       } else if (!strncasecmp(ChrPtr(WCC->Hdr->HR.ContentType), "multipart", 9)) {
+               char *Buf;
+               char *BufEnd;
+               long len;
+
+               len = StrLength(content);
+               Buf = SmashStrBuf(&content);
+               BufEnd = Buf + len;
+               mime_parser(Buf, BufEnd, *upload_handler, NULL, NULL, NULL, 0);
+               free(Buf);
+       } else if (WCC->Hdr->HR.ContentLength > 0) {
+               WCC->upload = content;
+               WCC->upload_length = StrLength(WCC->upload);
+               content = NULL;
        }
+       FreeStrBuf(&content);
+       return 1;
+}
 
+#if 0
+void ParseREST_URL(void)
+{
+       StrBuf *Buf;
+       StrBuf *pFloor = NULL;
+       wcsession *WCC = WC;
+       long i = 0;
+       const char *pCh = NULL;
+       HashList *Floors;
+       void *vFloor;
 
-       if (GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) && 
-           (vLine != NULL)){
-               cookie_to_stuff((StrBuf *)vLine, NULL,
-                               c_username,
-                               c_password,
-                               c_roomname);
-       }
-       if (GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) &&
-           (vLine!=NULL)) {
-               StrBufDecodeBase64((StrBuf*)vLine);
-               StrBufExtract_token(c_httpauth_user, (StrBuf*)vLine, 0, ':');
-               StrBufExtract_token(c_httpauth_pass, (StrBuf*)vLine, 1, ':');
-       }
-       if (GetHash(HTTPHeaders, HKEY("CONTENT-LENGTH"), &vLine) &&
-           (vLine!=NULL)) {
-               ContentLength = StrToi((StrBuf*)vLine);
-       }
-       if (GetHash(HTTPHeaders, HKEY("CONTENT-TYPE"), &vLine) &&
-           (vLine!=NULL)) {
-               ContentType = (StrBuf*)vLine;
-       }
-       if (GetHash(HTTPHeaders, HKEY("USER-AGENT"), &vLine) &&
-           (vLine!=NULL)) {
-               safestrncpy(user_agent, ChrPtr((StrBuf*)vLine), sizeof user_agent);
-#ifdef TECH_PREVIEW
-               if ((WCC->is_mobile < 0) && is_mobile_ua(&buf[12])) {                   
-                       WCC->is_mobile = 1;
-               }
-               else {
-                       WCC->is_mobile = 0;
+       syslog(1, "parsing rest URL: %s", ChrPtr(WCC->Hdr->HR.ReqLine));
+
+       WCC->Directory = NewHash(1, Flathash);
+       WCC->CurrentFloor = NULL;
+
+       Buf = NewStrBuf();
+       while (StrBufExtract_NextToken(Buf, WCC->Hdr->HR.ReqLine, &pCh,  '/') >= 0)
+       {
+               if (StrLength(Buf) != 0) {
+                       /* ignore empty path segments */
+                       StrBufUnescape(Buf, 1);
+                       Put(WCC->Directory, IKEY(i), Buf, HFreeStrBuf);
+                       if (i==0)
+                               pFloor = Buf;
+                       Buf = NewStrBuf();
                }
-#endif
+               i++;
        }
-       if ((follow_xff) &&
-           GetHash(HTTPHeaders, HKEY("X-FORWARDED-HOST"), &vLine) &&
-           (vLine != NULL)) {
-               WCC->http_host = (StrBuf*)vLine;
-       }
-       if ((StrLength(WCC->http_host) == 0) && 
-           GetHash(HTTPHeaders, HKEY("HOST"), &vLine) &&
-           (vLine!=NULL)) {
-               WCC->http_host = (StrBuf*)vLine;
+
+       FreeStrBuf(&Buf);
+       if (pFloor != NULL)
+       {
+               Floors = GetFloorListHash(NULL, NULL);
+               
+               if (Floors != NULL)
+               {
+                       if (GetHash(WCC->FloorsByName, SKEY(pFloor), &vFloor))
+                               WCC->CurrentFloor = (Floor*) vFloor;
+               }
        }
+}
+#endif
+
+int Conditional_REST_DEPTH(StrBuf *Target, WCTemplputParams *TP)
+{
+       long Depth, IsDepth;
+       long offset = 0;
+       wcsession *WCC = WC;
 
-       if (GetHash(HTTPHeaders, HKEY("X-FORWARDED-FOR"), &vLine) &&
-           (vLine!=NULL)) {
-               browser_host = (StrBuf*) vLine;
+       if (WCC->Hdr->HR.Handler != NULL)
+               offset ++;
+       Depth = GetTemplateTokenNumber(Target, TP, 2, 0);
+       IsDepth = GetCount(WCC->Directory) + offset;
 
-               while (StrBufNum_tokens(browser_host, ',') > 1) {
-                       StrBufRemove_token(browser_host, 0, ',');
-               }
-               StrBufTrim(browser_host);
+//     LogTemplateError(Target, "bla", 1, TP, "REST_DEPTH: %ld : %ld\n", Depth, IsDepth);
+       if (Depth < 0) {
+               Depth = -Depth;
+               return IsDepth > Depth;
        }
+       else 
+               return Depth == IsDepth;
+}
+
+
 
-       if (ContentLength > 0) {
-               content = NewStrBuf();
-               StrBufPrintf(content, "Content-type: %s\n"
-                        "Content-length: %d\n\n",
-                        ChrPtr(ContentType), ContentLength);
 /*
-               hprintf("Content-type: %s\n"
-                       "Content-length: %d\n\n",
-                       ContentType, ContentLength);
-*/
-               body_start = StrLength(content);
-
-               /** Read the entire input data at once. */
-               client_read_to(&WCC->http_sock, 
-                              content, 
-                              ReadBuf, Pos,
-                              ContentLength,
-                              SLEEPING);
-
-               if (!strncasecmp(ChrPtr(ContentType), "application/x-www-form-urlencoded", 33)) {
-                       StrBufCutLeft(content, body_start);
-                       ParseURLParams(content);
-               } else if (!strncasecmp(ChrPtr(ContentType), "multipart", 9)) {
-                       content_end = ChrPtr(content) + ContentLength + body_start;
-                       mime_parser(ChrPtr(content), content_end, *upload_handler, NULL, NULL, NULL, 0);
+ * Entry point for WebCit transaction
+ */
+void session_loop(void)
+{
+       int xhttp;
+       StrBuf *Buf;
+       
+       /*
+        * 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.
+        */
+       wcsession *WCC;
+      
+       WCC= WC;
+       WCC->upload_length = 0;
+       WCC->upload = NULL;
+       WCC->Hdr->nWildfireHeaders = 0;
+
+       if (WCC->Hdr->HR.ContentLength > 0) {
+               if (ReadPostData() < 0) {
+                       return;
                }
-       } else {
-               content = NULL;
        }
 
-       /* make a note of where we are in case the user wants to save it */
-       WCC->this_page = NewStrBufDup(ReqLine);
-       StrBufRemove_token(WCC->this_page, 2, ' ');
-       StrBufRemove_token(WCC->this_page, 0, ' ');
+       Buf = NewStrBuf();
+       WCC->trailing_javascript = NewStrBuf();
 
-       /* If there are variables in the URL, we must grab them now */
-       UrlLine = NewStrBufDup(ReqLine);
-       len = StrLength(UrlLine);
-       pch = pchs = ChrPtr(UrlLine);
-       pche = pchs + len;
-       while (pch < pche) {
-               if ((*pch == '?') || (*pch == '&')) {
-                       StrBufCutLeft(UrlLine, pch - pchs + 1);
-                       ParseURLParams(UrlLine);
-                       break;
-               }
-               pch ++;
-       }
-       FreeStrBuf(&UrlLine);
-
-       /* If it's a "force 404" situation then display the error and bail. */
-       if (!strcmp(action, "404")) {
-               hprintf("HTTP/1.1 404 Not found\r\n");
-               hprintf("Content-Type: text/plain\r\n");
-               wprintf("Not found\r\n");
-               end_burst();
+       /* Convert base64-encoded URL's back to plain text */
+       if (!strncmp(ChrPtr(WCC->Hdr->this_page), "/B64", 4)) {
+               StrBufCutLeft(WCC->Hdr->this_page, 4);
+               StrBufDecodeBase64(WCC->Hdr->this_page);
+               http_redirect(ChrPtr(WCC->Hdr->this_page));
                goto SKIP_ALL_THIS_CRAP;
        }
 
-       /* Static content can be sent without connecting to Citadel. */
-       is_static = 0;
-       for (a=0; a<ndirs && ! is_static; ++a) {
-               if (!strcasecmp(action, (char*)static_content_dirs[a])) { /* map web to disk location */
-                       is_static = 1;
-                       n_static = a;
-               }
-       }
-       if (is_static) {
-               if (nBackDots < 2)
-               {
-                       snprintf(buf, sizeof buf, "%s/%s/%s/%s/%s/%s/%s/%s",
-                                static_dirs[n_static], 
-                                index[1], index[2], index[3], index[4], index[5], index[6], index[7]);
-                       for (a=0; a<8; ++a) {
-                               if (buf[strlen(buf)-1] == '/') {
-                                       buf[strlen(buf)-1] = 0;
-                               }
-                       }
-                       for (a = 0; a < strlen(buf); ++a) {
-                               if (isspace(buf[a])) {
-                                       buf[a] = 0;
-                               }
-                       }
-                       output_static(buf);
-               }
-               else 
-               {
-                       lprintf(9, "Suspicious request. Ignoring.");
-                       hprintf("HTTP/1.1 404 Security check failed\r\n");
-                       hprintf("Content-Type: text/plain\r\n\r\n");
-                       wprintf("You have sent a malformed or invalid request.\r\n");
-                       end_burst();
-               }
-               goto SKIP_ALL_THIS_CRAP;        /* Don't try to connect */
-       }
+       /* If there are variables in the URL, we must grab them now */
+       if (WCC->Hdr->PlainArgs != NULL)
+               ParseURLParams(WCC->Hdr->PlainArgs);
 
        /* If the client sent a nonce that is incorrect, kill the request. */
-       if (strlen(bstr("nonce")) > 0) {
-               lprintf(9, "Comparing supplied nonce %s to session nonce %ld\n", 
-                       bstr("nonce"), WCC->nonce);
+       if (havebstr("nonce")) {
+               syslog(9, "Comparing supplied nonce %s to session nonce %d", 
+                       bstr("nonce"), WCC->nonce
+               );
                if (ibstr("nonce") != WCC->nonce) {
-                       lprintf(9, "Ignoring request with mismatched nonce.\n");
+                       syslog(9, "Ignoring request with mismatched nonce.");
                        hprintf("HTTP/1.1 404 Security check failed\r\n");
-                       hprintf("Content-Type: text/plain\r\n\r\n");
-                       wprintf("Security check failed.\r\n");
+                       hprintf("Content-Type: text/plain\r\n");
+                       begin_burst();
+                       wc_printf("Security check failed.\r\n");
                        end_burst();
                        goto SKIP_ALL_THIS_CRAP;
                }
        }
 
        /*
-        * If we're not connected to a Citadel server, try to hook up the
-        * connection now.
+        * If we're not connected to a Citadel server, try to hook up the connection now.
         */
        if (!WCC->connected) {
-               if (WCC->ReadBuf == NULL)
-                       WCC->ReadBuf = NewStrBuf();
-               if (!strcasecmp(ctdlhost, "uds")) {
-                       /* unix domain socket */
-                       snprintf(buf, SIZ, "%s/citadel.socket", ctdlport);
-                       WCC->serv_sock = uds_connectsock(buf);
-               }
-               else {
-                       /* tcp socket */
-                       WCC->serv_sock = tcp_connectsock(ctdlhost, ctdlport);
-               }
-
-               if (WCC->serv_sock < 0) {
-                       do_logout();
-                       FreeStrBuf(&WCC->ReadBuf);
+               if (GetConnected()) {
+                       hprintf("HTTP/1.1 503 Service Unavailable\r\n");
+                       hprintf("Content-Type: text/html\r\n");
+                       begin_burst();
+                       wc_printf("<html><head><title>503 Service Unavailable</title></head><body>\n");
+                       wc_printf(_("This program was unable to connect or stay "
+                               "connected to the Citadel server.  Please report "
+                               "this problem to your system administrator.")
+                       );
+                       wc_printf("<br>");
+                       wc_printf("<a href=\"http://www.citadel.org/doku.php/"
+                               "faq:generalquestions:webcit_unable_to_connect\">%s</a>",
+                               _("Read More...")
+                       );
+                       wc_printf("</body></html>\n");
+                       end_burst();
                        goto SKIP_ALL_THIS_CRAP;
                }
-               else {
-                       WCC->connected = 1;
-                       serv_getln(buf, sizeof buf);    /* get the server greeting */
-
-                       /* Are there too many users already logged in? */
-                       if (!strncmp(buf, "571", 3)) {
-                               wprintf(_("This server is already serving its maximum number of users and cannot accept any additional logins at this time.  Please try again later or contact your system administrator."));
-                               end_burst();
-                               end_webcit_session();
-                               goto SKIP_ALL_THIS_CRAP;
-                       }
-
-                       /*
-                        * From what host is our user connecting?  Go with
-                        * the host at the other end of the HTTP socket,
-                        * unless we are following X-Forwarded-For: headers
-                        * and such a header has already turned up something.
-                        */
-                       if ( (!follow_xff) || (StrLength(browser_host) == 0) ) {
-                               if (browser_host == NULL) {
-                                       browser_host = NewStrBuf();
-                                       Put(HTTPHeaders, HKEY("FreeMeWithTheOtherHeaders"), 
-                                           browser_host, HFreeStrBuf);
-                               }
-                               locate_host(browser_host, WCC->http_sock);
-                       }
-                       if (WCC->serv_info == NULL)
-                               WCC->serv_info = get_serv_info(browser_host, user_agent);
-                       if (WCC->serv_info == NULL){
-                               begin_burst();
-                               wprintf(_("Received unexpected answer from Citadel "
-                                         "server; bailing out."));
-                               hprintf("HTTP/1.1 200 OK\r\n");
-                               hprintf("Content-type: text/plain; charset=utf-8\r\n");
-                               end_burst();
-                               end_webcit_session();
-                               goto SKIP_ALL_THIS_CRAP;
-                       }
-                       if (WCC->serv_info->serv_rev_level < MINIMUM_CIT_VERSION) {
-                               begin_burst();
-                               wprintf(_("You are connected to a Citadel "
-                                       "server running Citadel %d.%02d. \n"
-                                       "In order to run this version of WebCit "
-                                       "you must also have Citadel %d.%02d or"
-                                       " newer.\n\n\n"),
-                                               WCC->serv_info->serv_rev_level / 100,
-                                               WCC->serv_info->serv_rev_level % 100,
-                                               MINIMUM_CIT_VERSION / 100,
-                                               MINIMUM_CIT_VERSION % 100
-                                       );
-                               hprintf("HTTP/1.1 200 OK\r\n");
-                               hprintf("Content-type: text/plain; charset=utf-8\r\n");
-                               end_burst();
-                               end_webcit_session();
-                               goto SKIP_ALL_THIS_CRAP;
-                       }
-               }
-       }
-
-       /*
-        * Functions which can be performed without logging in
-        */
-       if (!strcasecmp(action, "listsub")) {
-               do_listsub();
-               goto SKIP_ALL_THIS_CRAP;
-       }
-       if (!strcasecmp(action, "freebusy")) {
-               do_freebusy(ChrPtr(ReqLine));
-               goto SKIP_ALL_THIS_CRAP;
        }
 
        /*
-        * If we're not logged in, but we have HTTP Authentication data,
-        * try logging in to Citadel using that.
+        * If we're not logged in, but we have authentication data (either from
+        * a cookie or from http-auth), try logging in to Citadel using that.
         */
        if ((!WCC->logged_in)
-           && (StrLength(c_httpauth_user) > 0)
-           && (StrLength(c_httpauth_pass) > 0))
+           && (StrLength(WCC->Hdr->c_username) > 0)
+           && (StrLength(WCC->Hdr->c_password) > 0))
        {
+               long Status;
+
                FlushStrBuf(Buf);
-               serv_printf("USER %s", ChrPtr(c_httpauth_user));
+               serv_printf("USER %s", ChrPtr(WCC->Hdr->c_username));
                StrBuf_ServGetln(Buf);
-               if (GetServerStatus(Buf, NULL) == 3) {
-                       serv_printf("PASS %s", ChrPtr(c_httpauth_pass));
+               if (GetServerStatus(Buf, &Status) == 3) {
+                       serv_printf("PASS %s", ChrPtr(WCC->Hdr->c_password));
                        StrBuf_ServGetln(Buf);
                        if (GetServerStatus(Buf, NULL) == 2) {
-                               become_logged_in(c_httpauth_user,
-                                               c_httpauth_pass, Buf);
-                               if (WCC->httpauth_user == NULL)
-                                       WCC->httpauth_user = NewStrBufDup(c_httpauth_user);
-                               else {
-                                       FlushStrBuf(WCC->httpauth_user);
-                                       StrBufAppendBuf(WCC->httpauth_user, c_httpauth_user, 0);
-                               }
-                               if (WCC->httpauth_pass == NULL)
-                                       WCC->httpauth_pass = NewStrBufDup(c_httpauth_pass);
-                               else {
-                                       FlushStrBuf(WCC->httpauth_pass);
-                                       StrBufAppendBuf(WCC->httpauth_pass, c_httpauth_pass, 0);
-                               }
+                               become_logged_in(WCC->Hdr->c_username,
+                                                WCC->Hdr->c_password, Buf);
                        } else {
                                /* Should only display when password is wrong */
-                               authorization_required(&buf[4]);
+                               WCC->ImportantMsg = NewStrBufPlain(ChrPtr(Buf) + 4, StrLength(Buf) - 4);
+                               authorization_required();
                                FreeStrBuf(&Buf);
                                goto SKIP_ALL_THIS_CRAP;
                        }
                }
+               else if (Status == 541) {
+                       WCC->logged_in = 1;
+               }
        }
 
-       /* This needs to run early */
-#ifdef TECH_PREVIEW
-       if (!strcasecmp(action, "rss")) {
-               display_rss(sbstr("room"), request_method);
-               goto SKIP_ALL_THIS_CRAP;
-       }
-#endif
-
-       /* 
-        * The GroupDAV stuff relies on HTTP authentication instead of
-        * our session's authentication.
-        */
-       if (!strncasecmp(action, "groupdav", 8)) {
-               groupdav_main(HTTPHeaders, 
-                             ReqLine, request_method,
-                             ContentType, /* do GroupDAV methods */
-                             ContentLength, content, body_start);
-               if (!WCC->logged_in) {
-                       WCC->killthis = 1;      /* If not logged in, don't */
-               }                               /* keep the session active */
-               goto SKIP_ALL_THIS_CRAP;
-       }
-
+       xhttp = (WCC->Hdr->HR.eReqType != eGET) &&
+               (WCC->Hdr->HR.eReqType != ePOST) &&
+               (WCC->Hdr->HR.eReqType != eHEAD);
 
        /*
-        * Automatically send requests with any method other than GET or
-        * POST to the GroupDAV code as well.
+        * If a 'go' (or 'gotofirst') parameter has been specified, attempt to goto that room
+        * prior to doing anything else.
         */
-       if ((strcasecmp(ChrPtr(request_method), "GET")) && (strcasecmp(ChrPtr(request_method), "POST"))) {
-               groupdav_main(HTTPHeaders, ReqLine, 
-                             request_method, ContentType, /** do GroupDAV methods */
-                             ContentLength, content, body_start);
-               if (!WCC->logged_in) {
-                       WCC->killthis = 1;      /** If not logged in, don't */
-               }                               /** keep the session active */
-               goto SKIP_ALL_THIS_CRAP;
+       if (havebstr("go")) {
+               int ret;
+               syslog(9, "Explicit room selection: %s", bstr("go"));
+               ret = gotoroom(sbstr("go"));    /* do quietly to avoid session output! */
+               if ((ret/100) != 2) {
+                       syslog(1, "Unable to change to [%s]; Reason: %d", bstr("go"), ret);
+               }
        }
-
-       /*
-        * If we're not logged in, but we have username and password cookies
-        * supplied by the browser, try using them to log in.
-        */
-       if ((!WCC->logged_in)
-          && (StrLength(c_username)>0)
-          && (StrLength(c_password)>0)) {
-               serv_printf("USER %s", ChrPtr(c_username));
-               StrBuf_ServGetln(Buf);
-               if (GetServerStatus(Buf, NULL) == 3) {
-                       serv_printf("PASS %s", ChrPtr(c_password));
-                       StrBuf_ServGetln(Buf);
-                       if (GetServerStatus(Buf, NULL) == 2) {
-                               become_logged_in(c_username, c_password, Buf);
-                               get_preference("default_header_charset", &WCC->DefaultCharset);
-                       }
+       else if (havebstr("gotofirst")) {
+               int ret;
+               syslog(9, "Explicit room selection: %s", bstr("gotofirst"));
+               ret = gotoroom(sbstr("gotofirst"));     /* do quietly to avoid session output! */
+               if ((ret/100) != 2) {
+                       syslog(1, "Unable to change to [%s]; Reason: %d", bstr("gotofirst"), ret);
                }
        }
 
        /*
-        * If a 'gotofirst' parameter has been specified, attempt to goto that room
-        * prior to doing anything else.
+        * If we aren't in any room yet, but we have cookie data telling us where we're
+        * supposed to be, and 'go' was not specified, then go there.
         */
-       if (havebstr("gotofirst")) {
-               gotoroom(sbstr("gotofirst"));   /* do this quietly to avoid session output! */
-       }
+       else if ( (StrLength(WCC->CurRoom.name) == 0) && ( (StrLength(WCC->Hdr->c_roomname) > 0) )) {
+               int ret;
 
-       /*
-        * If we don't have a current room, but a cookie specifying the
-        * current room is supplied, make an effort to go there.
-        */
-       if ((StrLength(WCC->wc_roomname) == 0) && (StrLength(c_roomname) > 0)) {
-               serv_printf("GOTO %s", ChrPtr(c_roomname));
-               StrBuf_ServGetln(Buf);
-               if (GetServerStatus(Buf, NULL) == 2) {
-                       if (WCC->wc_roomname == NULL) {
-                               WCC->wc_roomname = NewStrBufDup(c_roomname);
-                       }
-                       else {
-                               FlushStrBuf(WCC->wc_roomname);
-                               StrBufAppendBuf(WCC->wc_roomname, c_roomname, 0);
-                       }
+               syslog(9, "We are in '%s' but cookie indicates '%s', going there...",
+                       ChrPtr(WCC->CurRoom.name),
+                       ChrPtr(WCC->Hdr->c_roomname)
+               );
+               ret = gotoroom(WCC->Hdr->c_roomname);   /* do quietly to avoid session output! */
+               if ((ret/100) != 2) {
+                       syslog(1, "COOKIEGOTO: Unable to change to [%s]; Reason: %d",
+                               ChrPtr(WCC->Hdr->c_roomname), ret);
                }
        }
-       
-       GetHash(HandlerHash, action, strlen(action) /* TODO*/, &vHandler),
-               Handler = (WebcitHandler*) vHandler;
-       if (Handler != NULL) {
-               if (!WCC->logged_in && ((Handler->Flags & ANONYMOUS) == 0)) {
-                       display_login(NULL);
+
+       if (WCC->Hdr->HR.Handler != NULL) {
+               if (    (!WCC->logged_in)
+                       && ((WCC->Hdr->HR.Handler->Flags & ANONYMOUS) == 0)
+                       && (WCC->serv_info->serv_supports_guest == 0)
+               ) {
+                       display_login();
                }
                else {
-                       if((Handler->Flags & NEED_URL)) {
-                               if (WCC->UrlFragment1 == NULL)
-                                       WCC->UrlFragment1 = NewStrBuf();
-                               if (WCC->UrlFragment2 == NULL)
-                                       WCC->UrlFragment2 = NewStrBuf();
-                               if (WCC->UrlFragment3 == NULL)
-                                       WCC->UrlFragment3 = NewStrBuf();
-                               if (WCC->UrlFragment4 == NULL)
-                                       WCC->UrlFragment4 = NewStrBuf();
-                               StrBufPlain(WCC->UrlFragment1, index[0], -1);
-                               StrBufPlain(WCC->UrlFragment2, index[1], -1);
-                               StrBufPlain(WCC->UrlFragment3, index[2], -1);
-                               StrBufPlain(WCC->UrlFragment4, index[3], -1);
-                       }
-                       if ((Handler->Flags & AJAX) != 0)
+#if 0
+                       if ((WCC->Hdr->HR.Handler->Flags & PARSE_REST_URL) != 0)
+                               ParseREST_URL();
+#endif
+                       if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
                                begin_ajax_response();
-                       Handler->F();
-                       if ((Handler->Flags & AJAX) != 0)
+                       WCC->Hdr->HR.Handler->F();
+                       if ((WCC->Hdr->HR.Handler->Flags & AJAX) != 0)
                                end_ajax_response();
                }
        }
-       /* When all else fais, display the main menu. */
+       /* When all else fails, display the default landing page or a main menu. */
        else {
-               if (!WCC->logged_in) 
-                       display_login(NULL);
-               else
-                       display_main_menu();
+               /* 
+                * ordinary browser users get a nice login screen, DAV etc. requsets
+                * are given a 401 so they can handle it appropriate.
+                */
+               if (!WCC->logged_in)  {
+                       if (xhttp) {
+                               authorization_required();
+                       }
+                       else {
+                               display_default_landing_page();
+                       }
+               }
+               /*
+                * Toplevel dav requests? or just a flat browser request? 
+                */
+               else {
+                       if (xhttp)
+                               dav_main();
+                       else
+                               display_main_menu();
+               }
        }
 
 SKIP_ALL_THIS_CRAP:
-       if (WCC->SavePrefsToServer) {
-               save_preferences();
-               WCC->SavePrefsToServer = 0;
-       }
        FreeStrBuf(&Buf);
-       FreeStrBuf(&c_username);
-       FreeStrBuf(&c_password);
-       FreeStrBuf(&c_roomname);
-       FreeStrBuf(&c_httpauth_user);
-       FreeStrBuf(&c_httpauth_pass);
-       FreeStrBuf(&WCC->this_page);
        fflush(stdout);
-       if (content != NULL) {
-               FreeStrBuf(&content);
-               content = NULL;
+}
+
+
+
+/*
+ * Display the appropriate landing page for this site.
+ */
+void display_default_landing_page(void) {
+       wcsession *WCC = WC;
+
+       if (WCC && WCC->serv_info && WCC->serv_info->serv_supports_guest) {
+               /* default action */
+
+               if (default_landing_page) {
+                       http_redirect(default_landing_page);
+               }
+               else {
+                       StrBuf *teh_lobby = NewStrBufPlain(HKEY("_BASEROOM_"));
+                       smart_goto(teh_lobby);
+                       FreeStrBuf(&teh_lobby);
+               }
        }
-       DeleteHash(&WCC->urlstrings);
-       if (WCC->upload_length > 0) {
-               free(WCC->upload);
-               WCC->upload_length = 0;
+       else {
+               display_login();
        }
-       FreeStrBuf(&WCC->trailing_javascript);
-       WCC->http_host = NULL;
-
-       /* How long did this transaction take? */
-       gettimeofday(&tx_finish, NULL);
-       
-       lprintf(9, "Transaction completed in %ld.%06ld seconds.\n",
-               ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) / 1000000,
-               ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) % 1000000
-       );
 }
 
 
@@ -1104,12 +895,27 @@ void sleeeeeeeeeep(int seconds)
        select(0, NULL, NULL, NULL, &tv);
 }
 
+int Conditional_IS_HTTPS(StrBuf *Target, WCTemplputParams *TP)
+{
+       return is_https != 0;
+}
+
+void AppendImportantMessage(const char *pch, long len)
+{
+       wcsession *WCC = WC;
+
+       if (StrLength(WCC->ImportantMsg) > 0) {
+               StrBufAppendBufPlain(WCC->ImportantMsg, HKEY("\n"), 0);
+       }
+               
+       StrBufAppendBufPlain(WCC->ImportantMsg, pch, len, 0);
+}
 
 int ConditionalImportantMesage(StrBuf *Target, WCTemplputParams *TP)
 {
        wcsession *WCC = WC;
        if (WCC != NULL)
-               return (!IsEmptyStr(WCC->ImportantMessage));
+               return (StrLength(WCC->ImportantMsg) > 0);
        else
                return 0;
 }
@@ -1119,12 +925,10 @@ void tmplput_importantmessage(StrBuf *Target, WCTemplputParams *TP)
        wcsession *WCC = WC;
        
        if (WCC != NULL) {
-/*
-               StrBufAppendTemplate(Target, nArgs, Tokens, Context, ContextType,
-                                    WCC->ImportantMessage, 0);
-*/
-               StrEscAppend(Target, NULL, WCC->ImportantMessage, 0, 0);
-               WCC->ImportantMessage[0] = '\0';
+               if (StrLength(WCC->ImportantMsg) > 0) {
+                       StrEscAppend(Target, WCC->ImportantMsg, NULL, 0, 0);
+                       FlushStrBuf(WCC->ImportantMsg);
+               }
        }
 }
 
@@ -1138,25 +942,109 @@ void tmplput_trailing_javascript(StrBuf *Target, WCTemplputParams *TP)
 
 void tmplput_csslocal(StrBuf *Target, WCTemplputParams *TP)
 {
-       extern StrBuf *csslocal;
        StrBufAppendBuf(Target, 
                        csslocal, 0);
 }
 
+void tmplput_packagestring(StrBuf *Target, WCTemplputParams *TP)
+{
+       StrBufAppendBufPlain(Target, 
+                            HKEY(PACKAGE_STRING), 0);
+}
 
+extern char static_local_dir[PATH_MAX];
 
 
 void 
 InitModule_WEBCIT
 (void)
 {
-       WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS);
-       WebcitAddUrlHandler(HKEY("do_template"), url_do_template, ANONYMOUS);
-       WebcitAddUrlHandler(HKEY("sslg"), seconds_since_last_gexp, AJAX);
-       WebcitAddUrlHandler(HKEY("ajax_servcmd"), ajax_servcmd, 0);
-
+       char dir[SIZ];
+       WebcitAddUrlHandler(HKEY("blank"), "", 0, blank_page, ANONYMOUS|COOKIEUNNEEDED|ISSTATIC);
+       WebcitAddUrlHandler(HKEY("do_template"), "", 0, url_do_template, ANONYMOUS);
+       WebcitAddUrlHandler(HKEY("sslg"), "", 0, seconds_since_last_gexp, AJAX|LOGCHATTY);
+       WebcitAddUrlHandler(HKEY("ajax_servcmd"), "", 0, ajax_servcmd, 0);
+       WebcitAddUrlHandler(HKEY("webcit"), "", 0, blank_page, URLNAMESPACE);
+       WebcitAddUrlHandler(HKEY("push"), "", 0, push_destination, AJAX);
+       WebcitAddUrlHandler(HKEY("pop"), "", 0, pop_destination, 0);
+
+       WebcitAddUrlHandler(HKEY("401"), "", 0, authorization_required, ANONYMOUS|COOKIEUNNEEDED);
        RegisterConditional(HKEY("COND:IMPMSG"), 0, ConditionalImportantMesage, CTX_NONE);
-       RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, CTX_NONE);
-       RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, CTX_NONE);
-       RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, CTX_NONE);
+       RegisterConditional(HKEY("COND:REST:DEPTH"), 0, Conditional_REST_DEPTH, CTX_NONE);
+       RegisterConditional(HKEY("COND:IS_HTTPS"), 0, Conditional_IS_HTTPS, CTX_NONE);
+
+       RegisterNamespace("CSSLOCAL", 0, 0, tmplput_csslocal, NULL, CTX_NONE);
+       RegisterNamespace("IMPORTANTMESSAGE", 0, 0, tmplput_importantmessage, NULL, CTX_NONE);
+       RegisterNamespace("TRAILING_JAVASCRIPT", 0, 0, tmplput_trailing_javascript, NULL, CTX_NONE);
+       RegisterNamespace("URL:DISPLAYNAME", 0, 1, tmplput_HANDLER_DISPLAYNAME, NULL, CTX_NONE);
+       RegisterNamespace("PACKAGESTRING", 0, 1, tmplput_packagestring, NULL, CTX_NONE);
+
+       
+       snprintf(dir, SIZ, "%s/webcit.css", static_local_dir);
+       if (!access(dir, R_OK)) {
+               syslog(9, "Using local Stylesheet [%s]", dir);
+               csslocal = NewStrBufPlain(HKEY("<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\" />"));
+       }
+       else
+               syslog(9, "No Site-local Stylesheet [%s] installed.", dir);
+
+}
+
+void
+ServerStartModule_WEBCIT
+(void)
+{
+       HandlerHash = NewHash(1, NULL);
+}
+
+
+void 
+ServerShutdownModule_WEBCIT
+(void)
+{
+       FreeStrBuf(&csslocal);
+       DeleteHash(&HandlerHash);
+}
+
+
+
+void
+SessionNewModule_WEBCIT
+(wcsession *sess)
+{
+       sess->ImportantMsg = NewStrBuf();
+       sess->WBuf = NewStrBufPlain(NULL, SIZ * 4);
+       sess->HBuf = NewStrBufPlain(NULL, SIZ / 4);
+}
+
+void
+SessionDetachModule_WEBCIT
+(wcsession *sess)
+{
+       DeleteHash(&sess->Directory);
+
+       FreeStrBuf(&sess->upload);
+       sess->upload_length = 0;
+       
+       FreeStrBuf(&sess->trailing_javascript);
+
+       if (StrLength(sess->WBuf) > SIZ * 30) /* Bigger than 120K? release. */
+       {
+               FreeStrBuf(&sess->WBuf);
+               sess->WBuf = NewStrBuf();
+       }
+       else
+               FlushStrBuf(sess->WBuf);
+       FlushStrBuf(sess->HBuf);
 }
+
+void 
+SessionDestroyModule_WEBCIT
+(wcsession *sess)
+{
+       FreeStrBuf(&sess->WBuf);
+       FreeStrBuf(&sess->HBuf);
+       FreeStrBuf(&sess->ImportantMsg);
+       FreeStrBuf(&sess->PushedDestination);
+}
+