xmpp non sasl authenticate does not need the resource name
[citadel.git] / citadel / modules / xmpp / serv_xmpp.c
index 977b6dea4c68a8b8453dde178f2a5176c41c0d46..d62bcfe468ee99ced792b01fde6632897838bbb7 100644 (file)
@@ -1,10 +1,8 @@
 /*
- * $Id$ 
- *
  * XMPP (Jabber) service for the Citadel system
- * Copyright (c) 2007-2010 by Art Cancro
+ * Copyright (c) 2007-2018 by Art Cancro and citadel.org
  *
- * This program is free software; you can redistribute it and/or modify
+ * 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.
 #include "ctdl_module.h"
 #include "serv_xmpp.h"
 
+/* uncomment for more verbosity - it will log all received XML tags */
+#define XMPP_XML_DEBUG
+
+/* XML_StopParser is present in expat 2.x */
+#if XML_MAJOR_VERSION > 1
+#define HAVE_XML_STOPPARSER
+#endif
+
 struct xmpp_event *xmpp_queue = NULL;
 
-/* We have just received a <stream> tag from the client, so send them ours */
 
+#ifdef HAVE_XML_STOPPARSER
+/* Stop the parser if an entity declaration is hit. */
+static void xmpp_entity_declaration(void *userData, const XML_Char *entityName,
+                               int is_parameter_entity, const XML_Char *value,
+                               int value_length, const XML_Char *base,
+                               const XML_Char *systemId, const XML_Char *publicId,
+                               const XML_Char *notationName
+) {
+       syslog(LOG_WARNING, "xmpp: illegal entity declaration encountered; stopping parser.");
+       XML_StopParser(XMPP->xp, XML_FALSE);
+}
+#endif
+
+
+/*
+ * Given a source string and a target buffer, returns the string
+ * properly escaped for insertion into an XML stream.  Returns a
+ * pointer to the target buffer for convenience.
+ */
+static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
+{
+       int n = 0;
+        unsigned char test = (1<<7);
+
+       if ((*CharS & 0xC0) != 0xC0) 
+               return 1;
+
+       while ((n < 8) && 
+              ((test & ((unsigned char)*CharS)) != 0)) 
+       {
+               test = test >> 1;
+               n ++;
+       }
+       if ((n > 6) || ((CharE - CharS) < n))
+               n = 0;
+       return n;
+}
+
+
+char *xmlesc(char *buf, char *str, int bufsiz)
+{
+       int IsUtf8Sequence;
+       char *ptr, *pche;
+       unsigned char ch;
+       int inlen;
+       int len = 0;
+
+       if (!buf) return(NULL);
+       buf[0] = 0;
+       len = 0;
+       if (!str) {
+               return(buf);
+       }
+       inlen = strlen(str);
+       pche = str + inlen;
+
+       for (ptr=str; *ptr; ptr++) {
+               ch = *ptr;
+               if (ch == '<') {
+                       strcpy(&buf[len], "&lt;");
+                       len += 4;
+               }
+               else if (ch == '>') {
+                       strcpy(&buf[len], "&gt;");
+                       len += 4;
+               }
+               else if (ch == '&') {
+                       strcpy(&buf[len], "&amp;");
+                       len += 5;
+               }
+               else if ((ch >= 0x20) && (ch <= 0x7F)) {
+                       buf[len++] = ch;
+                       buf[len] = 0;
+               }
+               else if (ch < 0x20) {
+                       /* we probably shouldn't be doing this */
+                       buf[len++] = '_';
+                       buf[len] = 0;
+               }
+               else {
+                       IsUtf8Sequence =  Ctdl_GetUtf8SequenceLength(ptr, pche);
+                       if (IsUtf8Sequence)
+                       {
+                               while ((IsUtf8Sequence > 0) && 
+                                      (ptr < pche))
+                               {
+                                       buf[len] = *ptr;
+                                       ptr ++;
+                                       --IsUtf8Sequence;
+                               }
+                       }
+                       else
+                       {
+                               char oct[10];
+                               sprintf(oct, "&#%o;", ch);
+                               strcpy(&buf[len], oct);
+                               len += strlen(oct);
+                       }
+               }
+               if ((len + 6) > bufsiz) {
+                       return(buf);
+               }
+       }
+       return(buf);
+}
+
+
+/*
+ * We have just received a <stream> tag from the client, so send them ours
+ */
 void xmpp_stream_start(void *data, const char *supplied_el, const char **attr)
 {
+       char xmlbuf[256];
+
        while (*attr) {
                if (!strcasecmp(attr[0], "to")) {
                        safestrncpy(XMPP->server_name, attr[1], sizeof XMPP->server_name);
@@ -75,7 +192,7 @@ void xmpp_stream_start(void *data, const char *supplied_el, const char **attr)
        cprintf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
 
        cprintf("<stream:stream ");
-       cprintf("from=\"%s\" ", XMPP->server_name);
+       cprintf("from=\"%s\" ", xmlesc(xmlbuf, XMPP->server_name, sizeof xmlbuf));
        cprintf("id=\"%08x\" ", CC->cs_pid);
        cprintf("version=\"1.0\" ");
        cprintf("xmlns:stream=\"http://etherx.jabber.org/streams\" ");
@@ -84,8 +201,10 @@ void xmpp_stream_start(void *data, const char *supplied_el, const char **attr)
        /* The features of this stream are... */
        cprintf("<stream:features>");
 
-#ifdef HAVE_OPENSSL_XXXX_COMMENTED_OUT
-       /* TLS encryption (but only if it isn't already active) */
+       /*
+        * TLS encryption (but only if it isn't already active)
+        */ 
+#ifdef HAVE_OPENSSL
        if (!CC->redirect_ssl) {
                cprintf("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'></starttls>");
        }
@@ -120,12 +239,12 @@ void xmpp_xml_start(void *data, const char *supplied_el, const char **attr) {
                strcpy(el, ++sep);
        }
 
-       /*
-       CtdlLogPrintf(CTDL_DEBUG, "XMPP ELEMENT START: <%s>\n", el);
+#ifdef XMPP_XML_DEBUG
+       syslog(LOG_DEBUG, "xmpp: ELEMENT START: <%s>", el);
        for (i=0; attr[i] != NULL; i+=2) {
-               CtdlLogPrintf(CTDL_DEBUG, "                    Attribute '%s' = '%s'\n", attr[i], attr[i+1]);
+               syslog(LOG_DEBUG, "xmpp: Attribute '%s' = '%s'", attr[i], attr[i+1]);
        }
-       uncomment for more verbosity */
+#endif
 
        if (!strcasecmp(el, "stream")) {
                xmpp_stream_start(data, supplied_el, attr);
@@ -184,6 +303,7 @@ void xmpp_xml_start(void *data, const char *supplied_el, const char **attr) {
 void xmpp_xml_end(void *data, const char *supplied_el) {
        char el[256];
        char *sep = NULL;
+       char xmlbuf[256];
 
        /* Axe the namespace, we don't care about it */
        safestrncpy(el, supplied_el, sizeof el);
@@ -191,33 +311,30 @@ void xmpp_xml_end(void *data, const char *supplied_el) {
                strcpy(el, ++sep);
        }
 
-       /*
-       CtdlLogPrintf(CTDL_DEBUG, "XMPP ELEMENT END  : <%s>\n", el);
+#ifdef XMPP_XML_DEBUG
+       syslog(LOG_DEBUG, "xmpp: ELEMENT END  : <%s>", el);
        if (XMPP->chardata_len > 0) {
-               CtdlLogPrintf(CTDL_DEBUG, "          chardata: %s\n", XMPP->chardata);
+               syslog(LOG_DEBUG, "xmpp: chardata: %s", XMPP->chardata);
        }
-       uncomment for more verbosity */
+#endif
 
        if (!strcasecmp(el, "resource")) {
                if (XMPP->chardata_len > 0) {
-                       safestrncpy(XMPP->iq_client_resource, XMPP->chardata,
-                               sizeof XMPP->iq_client_resource);
+                       safestrncpy(XMPP->iq_client_resource, XMPP->chardata, sizeof XMPP->iq_client_resource);
                        striplt(XMPP->iq_client_resource);
                }
        }
 
        else if (!strcasecmp(el, "username")) {         /* NON SASL ONLY */
                if (XMPP->chardata_len > 0) {
-                       safestrncpy(XMPP->iq_client_username, XMPP->chardata,
-                               sizeof XMPP->iq_client_username);
+                       safestrncpy(XMPP->iq_client_username, XMPP->chardata, sizeof XMPP->iq_client_username);
                        striplt(XMPP->iq_client_username);
                }
        }
 
        else if (!strcasecmp(el, "password")) {         /* NON SASL ONLY */
                if (XMPP->chardata_len > 0) {
-                       safestrncpy(XMPP->iq_client_password, XMPP->chardata,
-                               sizeof XMPP->iq_client_password);
+                       safestrncpy(XMPP->iq_client_password, XMPP->chardata, sizeof XMPP->iq_client_password);
                        striplt(XMPP->iq_client_password);
                }
        }
@@ -233,8 +350,7 @@ void xmpp_xml_end(void *data, const char *supplied_el) {
                         * Query on a namespace
                         */
                        if (!IsEmptyStr(XMPP->iq_query_xmlns)) {
-                               xmpp_query_namespace(XMPP->iq_id, XMPP->iq_from,
-                                               XMPP->iq_to, XMPP->iq_query_xmlns);
+                               xmpp_query_namespace(XMPP->iq_id, XMPP->iq_from, XMPP->iq_to, XMPP->iq_query_xmlns);
                        }
 
                        /*
@@ -243,23 +359,20 @@ void xmpp_xml_end(void *data, const char *supplied_el) {
                        else if (XMPP->ping_requested) {
                                cprintf("<iq type=\"result\" ");
                                if (!IsEmptyStr(XMPP->iq_from)) {
-                                       cprintf("to=\"%s\" ", XMPP->iq_from);
+                                       cprintf("to=\"%s\" ", xmlesc(xmlbuf, XMPP->iq_from, sizeof xmlbuf));
                                }
                                if (!IsEmptyStr(XMPP->iq_to)) {
-                                       cprintf("from=\"%s\" ", XMPP->iq_to);
+                                       cprintf("from=\"%s\" ", xmlesc(xmlbuf, XMPP->iq_to, sizeof xmlbuf));
                                }
-                               cprintf("id=\"%s\"/>", XMPP->iq_id);
+                               cprintf("id=\"%s\"/>", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
                        }
 
                        /*
                         * Unknown query ... return the XML equivalent of a blank stare
                         */
                        else {
-                               CtdlLogPrintf(CTDL_DEBUG,
-                                       "Unknown query <%s> - returning <service-unavailable/>\n",
-                                       el
-                               );
-                               cprintf("<iq type=\"error\" id=\"%s\">", XMPP->iq_id);
+                               syslog(LOG_DEBUG, "xmpp: Unknown query <%s> - returning <service-unavailable/>", el);
+                               cprintf("<iq type=\"error\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
                                cprintf("<error code=\"503\" type=\"cancel\">"
                                        "<service-unavailable xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>"
                                        "</error>"
@@ -279,8 +392,7 @@ void xmpp_xml_end(void *data, const char *supplied_el) {
                        xmpp_non_sasl_authenticate(
                                XMPP->iq_id,
                                XMPP->iq_client_username,
-                               XMPP->iq_client_password,
-                               XMPP->iq_client_resource
+                               XMPP->iq_client_password
                        );
                }       
 
@@ -290,36 +402,37 @@ void xmpp_xml_end(void *data, const char *supplied_el) {
                else if (
                        (XMPP->bind_requested)
                        && (!IsEmptyStr(XMPP->iq_id))
-                       && (!IsEmptyStr(XMPP->iq_client_resource))
                        && (CC->logged_in)
-                       ) {
+               ) {
 
-                       /* Generate the "full JID" of the client resource */
+                       /* If the client has not specified a client resource, generate one */
 
-                       snprintf(XMPP->client_jid, sizeof XMPP->client_jid,
-                               "%s/%s",
-                               CC->cs_inet_email,
-                               XMPP->iq_client_resource
-                       );
+                       if (IsEmptyStr(XMPP->iq_client_resource)) {
+                               snprintf(XMPP->iq_client_resource, sizeof XMPP->iq_client_resource, "%d", CC->cs_pid);
+                       }
+
+                       /* Generate the "full JID" of the client resource */
+                       snprintf(XMPP->client_jid, sizeof XMPP->client_jid, "%s/%s", CC->cs_inet_email, XMPP->iq_client_resource);
 
                        /* Tell the client what its JID is */
 
-                       cprintf("<iq type=\"result\" id=\"%s\">", XMPP->iq_id);
+                       cprintf("<iq type=\"result\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
                        cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">");
-                       cprintf("<jid>%s</jid>", XMPP->client_jid);
+                       cprintf("<jid>%s</jid>", xmlesc(xmlbuf, XMPP->client_jid, sizeof xmlbuf));
                        cprintf("</bind>");
                        cprintf("</iq>");
                }
 
                else if (XMPP->iq_session) {
-                       cprintf("<iq type=\"result\" id=\"%s\">", XMPP->iq_id);
+                       cprintf("<iq type=\"result\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
                        cprintf("</iq>");
                }
 
                else {
-                       cprintf("<iq type=\"error\" id=\"%s\">", XMPP->iq_id);
-                       cprintf("<error></error>");
+                       cprintf("<iq type=\"error\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
+                       cprintf("<error>Don't know how to do '%s'!</error>", xmlesc(xmlbuf, XMPP->iq_type, sizeof xmlbuf));
                        cprintf("</iq>");
+                       syslog(LOG_DEBUG, "XMPP: don't know how to do iq_type='%s' with iq_query_xmlns='%s'", XMPP->iq_type, XMPP->iq_query_xmlns);
                }
 
                /* Now clear these fields out so they don't get used by a future stanza */
@@ -378,10 +491,10 @@ void xmpp_xml_end(void *data, const char *supplied_el) {
 #ifdef HAVE_OPENSSL
                cprintf("<proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
                CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
-               if (!CC->redirect_ssl) CC->kill_me = 1;
+               if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO;
 #else
                cprintf("<failure xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
-               CC->kill_me = 1;
+               CC->kill_me = KILLME_NO_CRYPTO;
 #endif
        }
 
@@ -390,14 +503,22 @@ void xmpp_xml_end(void *data, const char *supplied_el) {
        }
 
        else if (!strcasecmp(el, "stream")) {
-               CtdlLogPrintf(CTDL_DEBUG, "XMPP client shut down their stream\n");
-               /* xmpp_massacre_roster(); FIXME put this back in when it's finished */
+               syslog(LOG_DEBUG, "xmpp: client shut down their stream");
+               xmpp_massacre_roster();
                cprintf("</stream>\n");
-               CC->kill_me = 1;
+               CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
+       }
+
+       else if (!strcasecmp(el, "query")) {
+               /* already processed , no further action needed here */
+       }
+
+       else if (!strcasecmp(el, "bind")) {
+               /* already processed , no further action needed here */
        }
 
        else {
-               CtdlLogPrintf(CTDL_DEBUG, "Ignoring unknown tag <%s>\n", el);
+               syslog(LOG_DEBUG, "xmpp: ignoring unknown tag <%s>", el);
        }
 
        XMPP->chardata_len = 0;
@@ -409,7 +530,7 @@ void xmpp_xml_end(void *data, const char *supplied_el) {
 
 void xmpp_xml_chardata(void *data, const XML_Char *s, int len)
 {
-       struct citxmpp *X = XMPP;
+       citxmpp *X = XMPP;
 
        if (X->chardata_alloc == 0) {
                X->chardata_alloc = SIZ;
@@ -447,22 +568,22 @@ void xmpp_cleanup_function(void) {
 }
 
 
-
 /*
  * Here's where our XMPP session begins its happy day.
  */
 void xmpp_greeting(void) {
+       client_set_inbound_buf(4);
        strcpy(CC->cs_clientname, "XMPP session");
-       CC->session_specific_data = malloc(sizeof(struct citxmpp));
-       memset(XMPP, 0, sizeof(struct citxmpp));
+       CC->session_specific_data = malloc(sizeof(citxmpp));
+       memset(XMPP, 0, sizeof(citxmpp));
        XMPP->last_event_processed = queue_event_seq;
 
        /* XMPP does not use a greeting, but we still have to initialize some things. */
 
        XMPP->xp = XML_ParserCreateNS("UTF-8", ':');
        if (XMPP->xp == NULL) {
-               CtdlLogPrintf(CTDL_ALERT, "Cannot create XML parser!\n");
-               CC->kill_me = 1;
+               syslog(LOG_ERR, "xmpp: cannot create XML parser");
+               CC->kill_me = KILLME_XML_PARSER;
                return;
        }
 
@@ -470,6 +591,17 @@ void xmpp_greeting(void) {
        XML_SetCharacterDataHandler(XMPP->xp, xmpp_xml_chardata);
        // XML_SetUserData(XMPP->xp, something...);
 
+       /* Prevent the "billion laughs" attack against expat by disabling
+        * internal entity expansion.  With 2.x, forcibly stop the parser
+        * if an entity is declared - this is safer and a more obvious
+        * failure mode.  With older versions, simply prevent expansion
+        * of such entities. */
+#ifdef HAVE_XML_STOPPARSER
+       XML_SetEntityDeclHandler(XMPP->xp, xmpp_entity_declaration);
+#else
+       XML_SetDefaultHandler(XMPP->xp, NULL);
+#endif
+
        CC->can_receive_im = 1;         /* This protocol is capable of receiving instant messages */
 }
 
@@ -478,21 +610,19 @@ void xmpp_greeting(void) {
  * Main command loop for XMPP sessions.
  */
 void xmpp_command_loop(void) {
-       char cmdbuf[16];
-       int retval;
+       int rc;
+       StrBuf *stream_input = NewStrBuf();
 
        time(&CC->lastcmd);
-       memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
-       retval = client_read(cmdbuf, 1);
-       if (retval != 1) {
-               CtdlLogPrintf(CTDL_ERR, "Client disconnected: ending session.\r\n");
-               CC->kill_me = 1;
-               return;
+       rc = client_read_random_blob(stream_input, 30);
+       if (rc > 0) {
+               XML_Parse(XMPP->xp, ChrPtr(stream_input), rc, 0);
        }
-
-       /* FIXME ... this is woefully inefficient. */
-
-       XML_Parse(XMPP->xp, cmdbuf, 1, 0);
+       else {
+               syslog(LOG_ERR, "xmpp: client disconnected: ending session.");
+               CC->kill_me = KILLME_CLIENT_DISCONNECTED;
+       }
+       FreeStrBuf(&stream_input);
 }
 
 
@@ -522,23 +652,26 @@ void xmpp_logout_hook(void) {
 
 
 const char *CitadelServiceXMPP="XMPP";
-
+extern void xmpp_cleanup_events(void);
 CTDL_MODULE_INIT(xmpp)
 {
        if (!threading) {
-               CtdlRegisterServiceHook(config.c_xmpp_c2s_port,
+               CtdlRegisterServiceHook(CtdlGetConfigInt("c_xmpp_c2s_port"),
                                        NULL,
                                        xmpp_greeting,
                                        xmpp_command_loop,
                                        xmpp_async_loop,
-                                       CitadelServiceXMPP);
-               CtdlRegisterSessionHook(xmpp_cleanup_function, EVT_STOP);
-                CtdlRegisterSessionHook(xmpp_login_hook, EVT_LOGIN);
-                CtdlRegisterSessionHook(xmpp_logout_hook, EVT_LOGOUT);
-                CtdlRegisterSessionHook(xmpp_login_hook, EVT_UNSTEALTH);
-                CtdlRegisterSessionHook(xmpp_logout_hook, EVT_STEALTH);
+                                       CitadelServiceXMPP
+               );
+               CtdlRegisterSessionHook(xmpp_cleanup_function, EVT_STOP, PRIO_STOP + 70);
+                CtdlRegisterSessionHook(xmpp_login_hook, EVT_LOGIN, PRIO_LOGIN + 90);
+                CtdlRegisterSessionHook(xmpp_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 90);
+                CtdlRegisterSessionHook(xmpp_login_hook, EVT_UNSTEALTH, PRIO_UNSTEALTH + 1);
+                CtdlRegisterSessionHook(xmpp_logout_hook, EVT_STEALTH, PRIO_STEALTH + 1);
+               CtdlRegisterCleanupHook(xmpp_cleanup_events);
+
        }
 
-       /* return our Subversion id for the Log */
-       return "$Id$";
+       /* return our module name for the log */
+       return "xmpp";
 }