2 * XMPP (Jabber) service for the Citadel system
3 * Copyright (c) 2007-2011 by Art Cancro
5 * This program is open source software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 #include <sys/types.h>
30 #if TIME_WITH_SYS_TIME
31 # include <sys/time.h>
35 # include <sys/time.h>
45 #include <libcitadel.h>
49 #include "citserver.h"
55 #include "internet_addressing.h"
57 #include "ctdl_module.h"
58 #include "serv_xmpp.h"
60 /* XML_StopParser is present in expat 2.x */
61 #if XML_MAJOR_VERSION > 1
62 #define HAVE_XML_STOPPARSER
65 struct xmpp_event *xmpp_queue = NULL;
66 HashList *XMPP_StartHandlers = NULL;
67 HashList *XMPP_EndHandlers = NULL;
69 int XMPPSrvDebugEnable = 0;
73 #ifdef HAVE_XML_STOPPARSER
74 /* Stop the parser if an entity declaration is hit. */
75 static void xmpp_entity_declaration(void *userData, const XML_Char *entityName,
76 int is_parameter_entity, const XML_Char *value,
77 int value_length, const XML_Char *base,
78 const XML_Char *systemId, const XML_Char *publicId,
79 const XML_Char *notationName
81 XMPPM_syslog(LOG_WARNING, "Illegal entity declaration encountered; stopping parser.");
82 XML_StopParser(XMPP->xp, XML_FALSE);
86 static inline int XMPP_GetUtf8SequenceLength(const char *CharS, const char *CharE)
88 /* if this is is migrated to strbuf, remove this copy. */
90 unsigned char test = (1<<7);
92 if ((*CharS & 0xC0) != 0xC0)
96 ((test & ((unsigned char)*CharS)) != 0))
101 if ((n > 6) || ((CharE - CharS) < n))
108 * Given a source string and a target buffer, returns the string
109 * properly escaped for insertion into an XML stream. Returns a
110 * pointer to the target buffer for convenience.
112 * BUG: this does not properly handle UTF-8
114 char *xmlesc(char *buf, char *str, int bufsiz)
123 if (!buf) return(NULL);
133 for (ptr=str; *ptr; ptr++) {
136 strcpy(&buf[len], "<");
139 else if (ch == '>') {
140 strcpy(&buf[len], ">");
143 else if (ch == '&') {
144 strcpy(&buf[len], "&");
147 else if ((ch >= 0x20) && (ch <= 0x7F)) {
151 else if (ch < 0x20) {
152 /* we probably shouldn't be doing this */
159 IsUtf8Sequence = XMPP_GetUtf8SequenceLength(&buf[len], eiptr);
162 while (IsUtf8Sequence > 0){
165 if (--IsUtf8Sequence)
172 sprintf(oct, "&#%o;", ch);
173 strcpy(&buf[len], oct);
177 if ((len + 6) > bufsiz) {
186 * We have just received a <stream> tag from the client, so send them ours
188 void xmpp_stream_start(void *data, const char *supplied_el, const char **attr)
193 if (!strcasecmp(attr[0], "to")) {
194 safestrncpy(XMPP->server_name, attr[1], sizeof XMPP->server_name);
199 cprintf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
201 cprintf("<stream:stream ");
202 cprintf("from=\"%s\" ", xmlesc(xmlbuf, XMPP->server_name, sizeof xmlbuf));
203 cprintf("id=\"%08x\" ", CC->cs_pid);
204 cprintf("version=\"1.0\" ");
205 cprintf("xmlns:stream=\"http://etherx.jabber.org/streams\" ");
206 cprintf("xmlns=\"jabber:client\">");
208 /* The features of this stream are... */
209 cprintf("<stream:features>");
212 * TLS encryption (but only if it isn't already active)
215 if (!CC->redirect_ssl) {
216 cprintf("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'></starttls>");
220 if (!CC->logged_in) {
221 /* If we're not logged in yet, offer SASL as our feature set */
222 xmpp_output_auth_mechs();
224 /* Also offer non-SASL authentication */
225 cprintf("<auth xmlns=\"http://jabber.org/features/iq-auth\"/>");
228 /* Offer binding and sessions as part of our feature set */
229 cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>");
230 cprintf("<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>");
232 cprintf("</stream:features>");
234 CC->is_async = 1; /* XMPP sessions are inherently async-capable */
237 void xmpp_start_query(void *data, const char *supplied_el, const char **attr)
239 XMPP->iq_query_xmlns[0] = 0;
240 safestrncpy(XMPP->iq_query_xmlns, supplied_el, sizeof XMPP->iq_query_xmlns);
243 void xmpp_start_bind(void *data, const char *supplied_el, const char **attr)
245 XMPP->bind_requested = 1;
248 void xmpp_start_iq(void *data, const char *supplied_el, const char **attr)
251 for (i=0; attr[i] != NULL; i+=2) {
252 if (!strcasecmp(attr[i], "type")) {
253 safestrncpy(XMPP->iq_type, attr[i+1], sizeof XMPP->iq_type);
255 else if (!strcasecmp(attr[i], "id")) {
256 safestrncpy(XMPP->iq_id, attr[i+1], sizeof XMPP->iq_id);
258 else if (!strcasecmp(attr[i], "from")) {
259 safestrncpy(XMPP->iq_from, attr[i+1], sizeof XMPP->iq_from);
261 else if (!strcasecmp(attr[i], "to")) {
262 safestrncpy(XMPP->iq_to, attr[i+1], sizeof XMPP->iq_to);
267 void xmpp_start_auth(void *data, const char *supplied_el, const char **attr)
271 XMPP->sasl_auth_mech[0] = 0;
272 for (i=0; attr[i] != NULL; i+=2) {
273 if (!strcasecmp(attr[i], "mechanism")) {
274 safestrncpy(XMPP->sasl_auth_mech, attr[i+1], sizeof XMPP->sasl_auth_mech);
279 void xmpp_start_message(void *data, const char *supplied_el, const char **attr)
283 for (i=0; attr[i] != NULL; i+=2) {
284 if (!strcasecmp(attr[i], "to")) {
285 safestrncpy(XMPP->message_to, attr[i+1], sizeof XMPP->message_to);
290 void xmpp_start_html(void *data, const char *supplied_el, const char **attr)
292 ++XMPP->html_tag_level;
295 void xmpp_xml_start(void *data, const char *supplied_el, const char **attr)
303 /* Axe the namespace, we don't care about it */
304 newlen = len = safestrncpy(el, supplied_el, sizeof el);
305 while (sep = strchr(el, ':'), sep)
307 newlen -= ++sep - el;
308 memmove(el, sep, newlen + 1);
313 XMPP_syslog(LOG_DEBUG, "XMPP ELEMENT START: <%s>\n", el);
314 for (i=0; attr[i] != NULL; i+=2) {
315 XMPP_syslog(LOG_DEBUG, " Attribute '%s' = '%s'\n", attr[i], attr[i+1]);
317 uncomment for more verbosity */
319 if (GetHash(XMPP_StartHandlers, el, len, &pv))
322 h = (xmpp_handler*) pv;
323 h->Handler(data, supplied_el, attr);
328 void xmpp_end_resource(void *data, const char *supplied_el, const char **attr)
330 if (XMPP->chardata_len > 0) {
331 safestrncpy(XMPP->iq_client_resource, XMPP->chardata,
332 sizeof XMPP->iq_client_resource);
333 striplt(XMPP->iq_client_resource);
337 void xmpp_end_username(void *data, const char *supplied_el, const char **attr)
340 if (XMPP->chardata_len > 0) {
341 safestrncpy(XMPP->iq_client_username, XMPP->chardata,
342 sizeof XMPP->iq_client_username);
343 striplt(XMPP->iq_client_username);
347 void xmpp_end_password(void *data, const char *supplied_el, const char **attr)
348 { /* NON SASL ONLY */
349 if (XMPP->chardata_len > 0) {
350 safestrncpy(XMPP->iq_client_password, XMPP->chardata,
351 sizeof XMPP->iq_client_password);
352 striplt(XMPP->iq_client_password);
356 void xmpp_end_iq(void *data, const char *supplied_el, const char **attr)
360 * iq type="get" (handle queries)
362 if (!strcasecmp(XMPP->iq_type, "get"))
365 * Query on a namespace
367 if (!IsEmptyStr(XMPP->iq_query_xmlns)) {
368 xmpp_query_namespace(XMPP->iq_id, XMPP->iq_from,
369 XMPP->iq_to, XMPP->iq_query_xmlns);
373 * ping ( http://xmpp.org/extensions/xep-0199.html )
375 else if (XMPP->ping_requested) {
376 cprintf("<iq type=\"result\" ");
377 if (!IsEmptyStr(XMPP->iq_from)) {
378 cprintf("to=\"%s\" ", xmlesc(xmlbuf, XMPP->iq_from, sizeof xmlbuf));
380 if (!IsEmptyStr(XMPP->iq_to)) {
381 cprintf("from=\"%s\" ", xmlesc(xmlbuf, XMPP->iq_to, sizeof xmlbuf));
383 cprintf("id=\"%s\"/>", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
387 * Unknown query ... return the XML equivalent of a blank stare
391 XMPP_syslog(LOG_DEBUG,
392 "Unknown query <%s> - returning <service-unavailable/>\n",
396 cprintf("<iq type=\"error\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
397 cprintf("<error code=\"503\" type=\"cancel\">"
398 "<service-unavailable xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>"
406 * Non SASL authentication
409 (!strcasecmp(XMPP->iq_type, "set"))
410 && (!strcasecmp(XMPP->iq_query_xmlns, "jabber:iq:auth:query"))
413 xmpp_non_sasl_authenticate(
415 XMPP->iq_client_username,
416 XMPP->iq_client_password,
417 XMPP->iq_client_resource
422 * If this <iq> stanza was a "bind" attempt, process it ...
425 (XMPP->bind_requested)
426 && (!IsEmptyStr(XMPP->iq_id))
427 && (!IsEmptyStr(XMPP->iq_client_resource))
431 /* Generate the "full JID" of the client resource */
433 snprintf(XMPP->client_jid, sizeof XMPP->client_jid,
436 XMPP->iq_client_resource
439 /* Tell the client what its JID is */
441 cprintf("<iq type=\"result\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
442 cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">");
443 cprintf("<jid>%s</jid>", xmlesc(xmlbuf, XMPP->client_jid, sizeof xmlbuf));
448 else if (XMPP->iq_session) {
449 cprintf("<iq type=\"result\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
454 cprintf("<iq type=\"error\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
455 cprintf("<error>Don't know howto do '%s'!</error>", xmlesc(xmlbuf, XMPP->iq_type, sizeof xmlbuf));
459 /* Now clear these fields out so they don't get used by a future stanza */
461 XMPP->iq_from[0] = 0;
463 XMPP->iq_type[0] = 0;
464 XMPP->iq_client_resource[0] = 0;
465 XMPP->iq_session = 0;
466 XMPP->iq_query_xmlns[0] = 0;
467 XMPP->bind_requested = 0;
468 XMPP->ping_requested = 0;
472 void xmpp_end_auth(void *data, const char *supplied_el, const char **attr)
474 /* Try to authenticate (this function is responsible for the output stanza) */
475 xmpp_sasl_auth(XMPP->sasl_auth_mech, (XMPP->chardata != NULL ? XMPP->chardata : "") );
477 /* Now clear these fields out so they don't get used by a future stanza */
478 XMPP->sasl_auth_mech[0] = 0;
481 void xmpp_end_session(void *data, const char *supplied_el, const char **attr)
483 XMPP->iq_session = 1;
486 void xmpp_end_presence(void *data, const char *supplied_el, const char **attr)
488 /* Respond to a <presence> update by firing back with presence information
489 * on the entire wholist. Check this assumption, it's probably wrong.
491 xmpp_wholist_presence_dump();
494 void xmpp_end_body(void *data, const char *supplied_el, const char **attr)
496 if (XMPP->html_tag_level == 0)
498 if (XMPP->message_body != NULL)
500 free(XMPP->message_body);
501 XMPP->message_body = NULL;
503 if (XMPP->chardata_len > 0) {
504 XMPP->message_body = strdup(XMPP->chardata);
509 void xmpp_end_message(void *data, const char *supplied_el, const char **attr)
511 xmpp_send_message(XMPP->message_to, XMPP->message_body);
512 XMPP->html_tag_level = 0;
515 void xmpp_end_html(void *data, const char *supplied_el, const char **attr)
517 --XMPP->html_tag_level;
520 void xmpp_end_starttls(void *data, const char *supplied_el, const char **attr)
523 cprintf("<proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
524 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
525 if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO;
527 cprintf("<failure xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
528 CC->kill_me = KILLME_NO_CRYPTO;
532 void xmpp_end_ping(void *data, const char *supplied_el, const char **attr)
534 XMPP->ping_requested = 1;
537 void xmpp_end_stream(void *data, const char *supplied_el, const char **attr)
539 XMPPM_syslog(LOG_DEBUG, "XMPP client shut down their stream\n");
540 xmpp_massacre_roster();
541 cprintf("</stream>\n");
542 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
545 void xmpp_xml_end(void *data, const char *supplied_el)
553 /* Axe the namespace, we don't care about it */
554 newlen = len = safestrncpy(el, supplied_el, sizeof el);
555 while (sep = strchr(el, ':'), sep) {
557 newlen -= ++sep - el;
558 memmove(el, sep, newlen + 1);
563 XMPP_syslog(LOG_DEBUG, "XMPP ELEMENT END : <%s>\n", el);
564 if (XMPP->chardata_len > 0) {
565 XMPP_syslog(LOG_DEBUG, " chardata: %s\n", XMPP->chardata);
567 uncomment for more verbosity */
569 if (GetHash(XMPP_EndHandlers, el, len, &pv))
572 h = (xmpp_handler*) pv;
573 h->Handler(data, supplied_el, NULL);
577 XMPP_syslog(LOG_DEBUG, "Ignoring unknown tag <%s>\n", el);
580 XMPP->chardata_len = 0;
581 if (XMPP->chardata_alloc > 0) {
582 XMPP->chardata[0] = 0;
587 void xmpp_xml_chardata(void *data, const XML_Char *s, int len)
591 if (X->chardata_alloc == 0) {
592 X->chardata_alloc = SIZ;
593 X->chardata = malloc(X->chardata_alloc);
595 if ((X->chardata_len + len + 1) > X->chardata_alloc) {
596 X->chardata_alloc = X->chardata_len + len + 1024;
597 X->chardata = realloc(X->chardata, X->chardata_alloc);
599 memcpy(&X->chardata[X->chardata_len], s, len);
600 X->chardata_len += len;
601 X->chardata[X->chardata_len] = 0;
606 * This cleanup function blows away the temporary memory and files used by the XMPP service.
608 void xmpp_cleanup_function(void) {
610 /* Don't do this stuff if this is not a XMPP session! */
611 if (CC->h_command_function != xmpp_command_loop) return;
613 if (XMPP->chardata != NULL) {
614 free(XMPP->chardata);
615 XMPP->chardata = NULL;
616 XMPP->chardata_len = 0;
617 XMPP->chardata_alloc = 0;
618 if (XMPP->message_body != NULL) {
619 free(XMPP->message_body);
622 XML_ParserFree(XMPP->xp);
629 * Here's where our XMPP session begins its happy day.
631 void xmpp_greeting(void) {
632 client_set_inbound_buf(4);
633 strcpy(CC->cs_clientname, "XMPP session");
634 CC->session_specific_data = malloc(sizeof(citxmpp));
635 memset(XMPP, 0, sizeof(citxmpp));
636 XMPP->last_event_processed = queue_event_seq;
638 /* XMPP does not use a greeting, but we still have to initialize some things. */
640 XMPP->xp = XML_ParserCreateNS("UTF-8", ':');
641 if (XMPP->xp == NULL) {
642 XMPPM_syslog(LOG_ALERT, "Cannot create XML parser!\n");
643 CC->kill_me = KILLME_XML_PARSER;
647 XML_SetElementHandler(XMPP->xp, xmpp_xml_start, xmpp_xml_end);
648 XML_SetCharacterDataHandler(XMPP->xp, xmpp_xml_chardata);
649 // XML_SetUserData(XMPP->xp, something...);
651 /* Prevent the "billion laughs" attack against expat by disabling
652 * internal entity expansion. With 2.x, forcibly stop the parser
653 * if an entity is declared - this is safer and a more obvious
654 * failure mode. With older versions, simply prevent expansion
655 * of such entities. */
656 #ifdef HAVE_XML_STOPPARSER
657 XML_SetEntityDeclHandler(XMPP->xp, xmpp_entity_declaration);
659 XML_SetDefaultHandler(XMPP->xp, NULL);
662 CC->can_receive_im = 1; /* This protocol is capable of receiving instant messages */
667 * Main command loop for XMPP sessions.
669 void xmpp_command_loop(void) {
671 StrBuf *stream_input = NewStrBuf();
674 rc = client_read_random_blob(stream_input, 30);
676 XML_Parse(XMPP->xp, ChrPtr(stream_input), rc, 0);
679 XMPPM_syslog(LOG_ERR, "client disconnected: ending session.\n");
680 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
682 FreeStrBuf(&stream_input);
687 * Async loop for XMPP sessions (handles the transmission of unsolicited stanzas)
689 void xmpp_async_loop(void) {
690 xmpp_process_events();
691 xmpp_output_incoming_messages();
696 * Login hook for XMPP sessions
698 void xmpp_login_hook(void) {
699 xmpp_queue_event(XMPP_EVT_LOGIN, CC->cs_inet_email);
704 * Logout hook for XMPP sessions
706 void xmpp_logout_hook(void) {
707 xmpp_queue_event(XMPP_EVT_LOGOUT, CC->cs_inet_email);
711 void LogXMPPSrvDebugEnable(const int n)
713 XMPPSrvDebugEnable = n;
715 const char *CitadelServiceXMPP="XMPP";
716 extern void xmpp_cleanup_events(void);
720 /******************************************************************************
721 * XMPP handler registering logic *
722 ******************************************************************************/
724 void AddXMPPStartHandler(const char *key,
726 xmpp_handler_func Handler,
730 h = (xmpp_handler*) malloc(sizeof (xmpp_handler));
732 h->Handler = Handler;
733 Put(XMPP_StartHandlers, key, len, h, NULL);
736 void AddXMPPEndHandler(const char *key,
738 xmpp_handler_func Handler,
742 h = (xmpp_handler*) malloc(sizeof (xmpp_handler));
744 h->Handler = Handler;
745 Put(XMPP_EndHandlers, key, len, h, NULL);
748 CTDL_MODULE_INIT(xmpp)
751 CtdlRegisterServiceHook(config.c_xmpp_c2s_port,
759 XMPP_StartHandlers = NewHash(1, NULL);
760 XMPP_EndHandlers = NewHash(1, NULL);
762 AddXMPPEndHandler(HKEY("resource"), xmpp_end_resource, 0);
763 AddXMPPEndHandler(HKEY("username"), xmpp_end_username, 0);
764 AddXMPPEndHandler(HKEY("password"), xmpp_end_password, 0);
765 AddXMPPEndHandler(HKEY("iq"), xmpp_end_iq, 0);
766 AddXMPPEndHandler(HKEY("auth"), xmpp_end_auth, 0);
767 AddXMPPEndHandler(HKEY("session"), xmpp_end_session, 0);
768 AddXMPPEndHandler(HKEY("presence"), xmpp_end_presence, 0);
769 AddXMPPEndHandler(HKEY("body"), xmpp_end_body, 0);
770 AddXMPPEndHandler(HKEY("message"), xmpp_end_message, 0);
771 AddXMPPEndHandler(HKEY("html"), xmpp_end_html, 0);
772 AddXMPPEndHandler(HKEY("starttls"), xmpp_end_starttls, 0);
773 AddXMPPEndHandler(HKEY("ping"), xmpp_end_ping, 0);
774 AddXMPPEndHandler(HKEY("stream"), xmpp_end_stream, 0);
777 AddXMPPStartHandler(HKEY("stream"), xmpp_stream_start, 0);
778 AddXMPPStartHandler(HKEY("query"), xmpp_start_query, 0);
779 AddXMPPStartHandler(HKEY("bind"), xmpp_start_bind, 0);
780 AddXMPPStartHandler(HKEY("iq"), xmpp_start_iq, 0);
781 AddXMPPStartHandler(HKEY("auth"), xmpp_start_auth, 0);
782 AddXMPPStartHandler(HKEY("message"), xmpp_start_message, 0);
783 AddXMPPStartHandler(HKEY("html"), xmpp_start_html, 0);
786 CtdlRegisterDebugFlagHook(HKEY("serv_xmpp"), LogXMPPSrvDebugEnable, &XMPPSrvDebugEnable);
787 CtdlRegisterSessionHook(xmpp_cleanup_function, EVT_STOP, PRIO_STOP + 70);
788 CtdlRegisterSessionHook(xmpp_login_hook, EVT_LOGIN, PRIO_LOGIN + 90);
789 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 90);
790 CtdlRegisterSessionHook(xmpp_login_hook, EVT_UNSTEALTH, PRIO_UNSTEALTH + 1);
791 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_STEALTH, PRIO_STEALTH + 1);
792 CtdlRegisterCleanupHook(xmpp_cleanup_events);
796 /* return our module name for the log */