* add more module handlers:
[citadel.git] / webcit / context_loop.c
index 7af1790c1cbf491564e47fb61071ae1fddf11870..208521386eb318cefe76e92a27da39b1a5a6462c 100644 (file)
 
 #include "webcit.h"
 #include "webserver.h"
+#include "modules_init.h"
 
 /* Only one thread may manipulate SessionList at a time... */
 pthread_mutex_t SessionListMutex;
 
-struct wcsession *SessionList = NULL; /**< our sessions ????*/
+wcsession *SessionList = NULL; /**< our sessions ????*/
 
 pthread_key_t MyConKey;         /**< TSD key for MySession() */
 
 
-/*
- * free the memory used for viewing atachments
- */
-void free_attachment(void *vattach) {
-       wc_attachment *att = (wc_attachment*) vattach;
-       FreeStrBuf(&att->content_type);
-       FreeStrBuf(&att->filename);
-       free(att->data);
-       free(att);
-}
 
-
-void DestroySession(struct wcsession **sessions_to_kill)
+void DestroySession(wcsession **sessions_to_kill)
 {
        close((*sessions_to_kill)->serv_sock);
        close((*sessions_to_kill)->chat_sock);
+/*
 //             if ((*sessions_to_kill)->preferences != NULL) {
 //                     free((*sessions_to_kill)->preferences);
 //             }
+*/
        if ((*sessions_to_kill)->cache_fold != NULL) {
                free((*sessions_to_kill)->cache_fold);
        }
-       DeleteHash(&((*sessions_to_kill)->attachments));
+       DeleteServInfo(&((*sessions_to_kill)->serv_info));
        free_march_list((*sessions_to_kill));
-       DeleteHash(&((*sessions_to_kill)->hash_prefs));
-       DeleteHash(&((*sessions_to_kill)->IconBarSetttings));
-       DeleteHash(&((*sessions_to_kill)->ServCfg));
-       FreeStrBuf(&((*sessions_to_kill)->UrlFragment1));
-       FreeStrBuf(&((*sessions_to_kill)->UrlFragment2));
-       FreeStrBuf(&((*sessions_to_kill)->UrlFragment3));
-       FreeStrBuf(&((*sessions_to_kill)->WBuf));
-       FreeStrBuf(&((*sessions_to_kill)->HBuf));
-       FreeStrBuf(&((*sessions_to_kill)->CLineBuf));
+       
+       session_destroy_modules(*sessions_to_kill);
+
        free((*sessions_to_kill));
        (*sessions_to_kill) = NULL;
 }
 
 void shutdown_sessions(void)
 {
-       struct wcsession *sptr;
+       wcsession *sptr;
        
        for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
                        sptr->killthis = 1;
@@ -67,8 +53,8 @@ void shutdown_sessions(void)
 
 void do_housekeeping(void)
 {
-       struct wcsession *sptr, *ss;
-       struct wcsession *sessions_to_kill = NULL;
+       wcsession *sptr, *ss;
+       wcsession *sessions_to_kill = NULL;
        int num_sessions = 0;
        static int num_threads = MIN_WORKER_THREADS;
 
@@ -134,8 +120,8 @@ void do_housekeeping(void)
 }
 
 
-/**
- * \brief Wake up occasionally and clean house
+/*
+ * Wake up occasionally and clean house
  */
 void housekeeping_loop(void)
 {
@@ -146,13 +132,10 @@ void housekeeping_loop(void)
 }
 
 
-/**
- * \brief Create a Session id
+/*
+ * Create a Session id
  * Generate a unique WebCit session ID (which is not the same thing as the
  * Citadel session ID).
- *
- * \todo FIXME ... ensure that session number is truly unique
- *
  */
 int GenerateSessionID(void)
 {
@@ -166,55 +149,6 @@ int GenerateSessionID(void)
 }
 
 
-/*
- * Collapse multiple cookies on one line
- */
-////int req_gets(int *sock, char *buf, char *hold, size_t hlen)
-////{
-////   int a, b;
-////
-////   if (IsEmptyStr(hold)) {
-////           strcpy(buf, "");
-////           a = client_getln(sock, buf, SIZ);
-////           if (a<1) return(-1);
-////   } else {
-////           safestrncpy(buf, hold, SIZ);
-////   }
-////   strcpy(hold, "");
-////
-////   if (!strncasecmp(buf, "Cookie: ", 8)) {
-////           int len;
-////           len = strlen(buf);
-////           for (a = 0; a < len; ++a)
-////                   if (buf[a] == ';') {
-////                           // we don't refresh len, because of we 
-////                           // only exit from here.
-////                           snprintf(hold, hlen, "Cookie: %s", &buf[a + 1]);
-////                           buf[a] = 0;
-////                           b = 8;
-////                           while (isspace(hold[b]))
-////                                   b++;
-////                           
-////                           memmove(&hold[8], &hold[b], len - b + 1);
-////                           return(0);
-////                   }
-////   }
-////
-////   return(0);
-////}
-
-
-/*
- * Collapse multiple cookies on one line
- */
-int ReqGetStrBuf(int *sock, StrBuf *Target, StrBuf *buf)
-{
-       
-       return ClientGetLine(sock, Target, buf);
-}
-
-
-
 /*
  * lingering_close() a`la Apache. see
  * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
@@ -253,28 +187,26 @@ int lingering_close(int fd)
 
 
 
-/**
- * \brief      sanity requests
- *             Check for bogus requests coming from brain-dead Windows boxes.
- *
- * \param      http_cmd        The HTTP request to check
+/*
+ * Look for commonly-found probes of malware such as worms, viruses, trojans, and Microsoft Office.
+ * Short-circuit these requests so we don't have to send them through the full processing loop.
  */
 int is_bogus(StrBuf *http_cmd) {
        const char *url;
        int i, max;
+       const char *bogus_prefixes[] = {
+               "/scripts/root.exe",    /* Worms and trojans and viruses, oh my! */
+               "/c/winnt",
+               "/MSADC/",
+               "/_vti",                /* Broken Microsoft DAV implementation */
+               "/MSOffice",            /* Stoopid MSOffice thinks everyone is IIS */
+               "/nonexistenshit"       /* Exploit found in the wild January 2009 */
+       };
 
        url = ChrPtr(http_cmd);
        if (IsEmptyStr(url)) return(1);
        ++url;
 
-       char *bogus_prefixes[] = {
-               "/scripts/root.exe",    /**< Worms and trojans and viruses, oh my! */
-               "/c/winnt",
-               "/MSADC/",
-               "/_vti",                /**< Broken Microsoft DAV implementation */
-               "/MSOffice"             /**< Stoopid MSOffice thinks everyone is IIS */
-       };
-
        max = sizeof(bogus_prefixes) / sizeof(char *);
 
        for (i=0; i<max; ++i) {
@@ -287,10 +219,11 @@ int is_bogus(StrBuf *http_cmd) {
 }
 
 
-const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}
+/*const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}*/
 
-/**
- * \brief handle one request
+/*
+ * handle one request
+ *
  * This loop gets called once for every HTTP connection made to WebCit.  At
  * this entry point we have an HTTP socket with a browser allegedly on the
  * other end, but we have not yet bound to a WebCit session.
@@ -300,25 +233,23 @@ const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}
  * transaction loop.  Afterwards, we unbind from the session.  When this
  * function returns, the worker thread is then free to handle another
  * transaction.
- * \param sock the socket we will put our answer to
  */
 void context_loop(int *sock)
 {
+       const char *Pos = NULL;
        const char *buf;
        int desired_session = 0;
        int got_cookie = 0;
        int gzip_ok = 0;
-       struct wcsession *TheSession, *sptr;
+       wcsession *TheSession, *sptr;
        char httpauth_string[1024];
        char httpauth_user[1024];
        char httpauth_pass[1024];
-       char *ptr = NULL;
        int session_is_new = 0;
        int nLine = 0;
        int LineLen;
        void *vLine;
        StrBuf *Buf, *Line, *LastLine, *HeaderName, *ReqLine, *ReqType, *HTTPVersion;
-       StrBuf *accept_language = NULL;
        const char *pch, *pchs, *pche;
        HashList *HTTPHeaders;
 
@@ -326,20 +257,23 @@ void context_loop(int *sock)
        strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
        strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
 
-       /**
+       /*
         * Find out what it is that the web browser is asking for
         */
        HeaderName = NewStrBuf();
        Buf = NewStrBuf();
        LastLine = NULL;
        HTTPHeaders = NewHash(1, NULL);
-       /**
+
+       /*
         * Read in the request
         */
        do {
                nLine ++;
                Line = NewStrBuf();
-               if (ReqGetStrBuf(sock, Line, Buf) < 0) return;
+
+
+               if (ClientGetLine(sock, Line, Buf, &Pos) < 0) return;
 
                LineLen = StrLength(Line);
 
@@ -352,7 +286,7 @@ void context_loop(int *sock)
                        continue;
                }
 
-               /** Do we need to Unfold? */
+               /* Do we need to Unfold? */
                if ((LastLine != NULL) && 
                    (isspace(*ChrPtr(Line)))) {
                        pch = pchs = ChrPtr(Line);
@@ -365,8 +299,8 @@ void context_loop(int *sock)
                        continue;
                }
 
+               StrBufSanitizeAscii(Line, 'ยง');
                StrBufExtract_token(HeaderName, Line, 0, ':');
-       //// TODO: filter bad chars!
 
                pchs = ChrPtr(Line);
                pch = pchs + StrLength(HeaderName) + 1;
@@ -381,10 +315,10 @@ void context_loop(int *sock)
        } while (LineLen > 0);
        FreeStrBuf(&HeaderName);
 
-////   dbg_PrintHash(HTTPHeaders, nix, NULL);
+/*     dbg_PrintHash(HTTPHeaders, nix, NULL);  */
 
 
-       /**
+       /*
         * Can we compress?
         */
        if (GetHash(HTTPHeaders, HKEY("ACCEPT-ENCODING"), &vLine) && 
@@ -395,19 +329,17 @@ void context_loop(int *sock)
                }
        }
 
-       /**
-        * Browser-based sessions use cookies for session 
-
-authentication
+       /*
+        * Browser-based sessions use cookies for session authentication
         */
        if (GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) && 
            (vLine != NULL)) {
                cookie_to_stuff(vLine, &desired_session,
-                               NULL, 0, NULL, 0, NULL, 0);
+                               NULL, NULL, NULL);
                got_cookie = 1;
        }
 
-       /**
+       /*
         * GroupDAV-based sessions use HTTP authentication
         */
        if (GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) && 
@@ -428,18 +360,8 @@ authentication
                if_modified_since = httpdate_to_timestamp((StrBuf*)vLine);
        }
 
-       if (GetHash(HTTPHeaders, HKEY("ACCEPT-LANGUAGE"), &vLine) && 
-           (vLine != NULL)) {
-               accept_language = (StrBuf*) vLine;
-       }
 
 
-       /**
-        * If the request is prefixed by "/webcit" then chop that off.  This
-        * allows a front end web server to forward all /webcit requests to us
-        * while still using the same web server port for other things.
-        */
-
        ReqType = NewStrBuf();
        HTTPVersion = NewStrBuf();
        StrBufExtract_token(HTTPVersion, ReqLine, 2, ' ');
@@ -447,13 +369,16 @@ authentication
        StrBufCutLeft(ReqLine, StrLength(ReqType) + 1);
        StrBufCutRight(ReqLine, StrLength(HTTPVersion) + 1);
 
-       if ((follow_xff == 1) && (StrLength(ReqLine) >= 8) &&
-           (ptr = strstr(ChrPtr(ReqLine), "/webcit/"), /*< Handle "/webcit/" */
-            (ptr != NULL))) {
+       /*
+        * If the request is prefixed by "/webcit" then chop that off.  This
+        * allows a front end web server to forward all /webcit requests to us
+        * while still using the same web server port for other things.
+        */
+       if ( (StrLength(ReqLine) >= 8) && (strstr(ChrPtr(ReqLine), "/webcit/")) ) {
                StrBufCutLeft(ReqLine, 7);
        }
 
-       /** Begin parsing the request. */
+       /* Begin parsing the request. */
 #ifdef TECH_PREVIEW
        if ((strncmp(ChrPtr(ReqLine), "/sslg", 5) != 0) &&
            (strncmp(ChrPtr(ReqLine), "/static/", 8) != 0) &&
@@ -517,12 +442,14 @@ authentication
 
        if (TheSession == NULL) {
                pthread_mutex_lock(&SessionListMutex);
-               for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
+               for (sptr = SessionList; 
+                    ((sptr != NULL) && (TheSession == NULL)); 
+                     sptr = sptr->next) {
 
                        /** If HTTP-AUTH, look for a session with matching credentials */
                        if ( (!IsEmptyStr(httpauth_user))
-                          &&(!strcasecmp(sptr->httpauth_user, httpauth_user))
-                          &&(!strcasecmp(sptr->httpauth_pass, httpauth_pass)) ) {
+                            &&(!strcasecmp(ChrPtr(sptr->httpauth_user), httpauth_user))
+                            &&(!strcasecmp(ChrPtr(sptr->httpauth_pass), httpauth_pass)) ) {
                                TheSession = sptr;
                        }
 
@@ -540,9 +467,10 @@ authentication
         */
        if (TheSession == NULL) {
                lprintf(3, "Creating a new session\n");
-               TheSession = (struct wcsession *)
-                       malloc(sizeof(struct wcsession));
-               memset(TheSession, 0, sizeof(struct wcsession));
+               TheSession = (wcsession *)
+                       malloc(sizeof(wcsession));
+               memset(TheSession, 0, sizeof(wcsession));
+               TheSession->headers = HTTPHeaders;
                TheSession->serv_sock = (-1);
                TheSession->chat_sock = (-1);
        
@@ -559,22 +487,22 @@ authentication
                        TheSession->wc_session = desired_session;
                }
 
-               strcpy(TheSession->httpauth_user, httpauth_user);
-               strcpy(TheSession->httpauth_pass, httpauth_pass);
-               TheSession->hash_prefs = NewHash(1,NULL);       /* Get a hash table for the user preferences */
+               TheSession->httpauth_user = NewStrBufPlain(httpauth_user, -1);
+               TheSession->httpauth_pass = NewStrBufPlain(httpauth_user, -1);
+
+               pthread_setspecific(MyConKey, (void *)TheSession);
+               session_new_modules(TheSession);
+
                pthread_mutex_init(&TheSession->SessionMutex, NULL);
                pthread_mutex_lock(&SessionListMutex);
-               TheSession->urlstrings = NULL;
-               TheSession->vars = NULL;
                TheSession->nonce = rand();
-               TheSession->WBuf = NULL;
-               TheSession->CLineBuf = NewStrBuf();
                TheSession->next = SessionList;
                TheSession->is_mobile = -1;
                SessionList = TheSession;
                pthread_mutex_unlock(&SessionListMutex);
                session_is_new = 1;
        }
+       TheSession->headers = HTTPHeaders;
 
        /*
         * A future improvement might be to check the session integrity
@@ -587,28 +515,16 @@ authentication
        pthread_mutex_lock(&TheSession->SessionMutex);          /* bind */
        pthread_setspecific(MyConKey, (void *)TheSession);
        
-       TheSession->urlstrings = NewHash(1,NULL);
-       TheSession->vars = NewHash(1,NULL);
-       TheSession->http_sock = *sock;
        TheSession->lastreq = time(NULL);                       /* log */
+       TheSession->http_sock = *sock;
        TheSession->gzip_ok = gzip_ok;
-#ifdef ENABLE_NLS
-       if (session_is_new) {
-               httplang_to_locale(accept_language);
-       }
-       go_selected_language();                                 /* set locale */
-#endif
-       session_loop(HTTPHeaders, ReqLine, ReqType, Buf);                               /* do transaction */
-#ifdef ENABLE_NLS
-       stop_selected_language();                               /* unset locale */
-#endif
-       DeleteHash(&TheSession->summ);
-       DeleteHash(&TheSession->urlstrings);
-       DeleteHash(&TheSession->vars);
-       FreeStrBuf(&TheSession->WBuf);
-       FreeStrBuf(&TheSession->HBuf);
-       
-       
+
+       session_attach_modules(TheSession);
+
+       session_loop(ReqLine, ReqType, Buf, &Pos);                              /* do transaction */
+       session_detach_modules(TheSession);
+
+       TheSession->headers = NULL;
        pthread_mutex_unlock(&TheSession->SessionMutex);        /* unbind */
 
        /* Free the request buffer */
@@ -616,24 +532,32 @@ authentication
        FreeStrBuf(&ReqLine);
        FreeStrBuf(&ReqType);
        FreeStrBuf(&Buf);
-       /*
-        * Free up any session-local substitution variables which
-        * were set during this transaction
-        */
-       
-       
 }
 
-void tmpl_nonce(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
+void tmplput_nonce(StrBuf *Target, WCTemplputParams *TP)
 {
-       struct wcsession *WCC = WC;
+       wcsession *WCC = WC;
        StrBufAppendPrintf(Target, "%ld",
                           (WCC != NULL)? WCC->nonce:0);                   
 }
 
+void tmplput_current_user(StrBuf *Target, WCTemplputParams *TP)
+{
+       StrBufAppendTemplate(Target, TP, WC->wc_fullname, 0);
+}
+
+void tmplput_current_room(StrBuf *Target, WCTemplputParams *TP)
+{
+       StrBufAppendTemplate(Target, TP, WC->wc_roomname, 0); 
+}
+
+
+
 void 
 InitModule_CONTEXT
 (void)
 {
-       RegisterNamespace("NONCE", 0, 0, tmpl_nonce, 0);
+       RegisterNamespace("CURRENT_USER", 0, 1, tmplput_current_user, CTX_NONE);
+       RegisterNamespace("CURRENT_ROOM", 0, 1, tmplput_current_room, CTX_NONE);
+       RegisterNamespace("NONCE", 0, 0, tmplput_nonce, 0);
 }