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
29 #include <sys/types.h>
31 #if TIME_WITH_SYS_TIME
32 # include <sys/time.h>
36 # include <sys/time.h>
46 #define SHOW_ME_VAPPEND_PRINTF
47 #include <libcitadel.h>
51 #include "citserver.h"
57 #include "internet_addressing.h"
59 #include "ctdl_module.h"
60 #include "serv_xmpp.h"
62 /* XML_StopParser is present in expat 2.x */
63 #if XML_MAJOR_VERSION > 1
64 #define HAVE_XML_STOPPARSER
67 struct xmpp_event *xmpp_queue = NULL;
68 HashList *XMPP_StartHandlers = NULL;
69 HashList *XMPP_EndHandlers = NULL;
71 int XMPPSrvDebugEnable = 0;
77 cputbuf(Xmpp->OutBuf);
78 FlushStrBuf(Xmpp->OutBuf);
81 void XPutBody(const char *Str, long Len)
83 StrBufXMLEscAppend(XMPP->OutBuf, NULL, Str, Len, 0);
86 void XPutProp(const char *Str, long Len)
88 StrEscAppend(XMPP->OutBuf, NULL, Str, 0, 1);
91 void XPut(const char *Str, long Len)
93 StrBufAppendBufPlain(XMPP->OutBuf, Str, Len, 0);
95 #define XPUT(CONSTSTR) XPut(CONSTSTR, sizeof(CONSTSTR) -1)
97 void XPrintf(const char *Format, ...)
100 va_start(arg_ptr, Format);
101 StrBufVAppendPrintf(XMPP->OutBuf, Format, arg_ptr);
106 void XPrint(const char *Token, long tlen,
123 va_start(arg_ptr, Flags);
126 ArgType = va_arg(arg_ptr, int);
130 PName = va_arg(arg_ptr, char*);
131 PLen = va_arg(arg_ptr, long);
132 Val = va_arg(arg_ptr, char*);
133 VLen = va_arg(arg_ptr, long);
141 PName = va_arg(arg_ptr, char*);
142 PLen = va_arg(arg_ptr, long);
143 Val = va_arg(arg_ptr, char*);
144 VLen = va_arg(arg_ptr, long);
155 PName = va_arg(arg_ptr, char*);
156 PLen = va_arg(arg_ptr, long);
157 VLen = va_arg(arg_ptr, long);
161 XPrintf("%ld", VLen);
167 Val = va_arg(arg_ptr, char*);
168 VLen = va_arg(arg_ptr, long);
176 if (Flags == XCLOSED)
196 #ifdef HAVE_XML_STOPPARSER
197 /* Stop the parser if an entity declaration is hit. */
198 static void xmpp_entity_declaration(void *userData, const XML_Char *entityName,
199 int is_parameter_entity, const XML_Char *value,
200 int value_length, const XML_Char *base,
201 const XML_Char *systemId, const XML_Char *publicId,
202 const XML_Char *notationName
204 XMPPM_syslog(LOG_WARNING, "Illegal entity declaration encountered; stopping parser.");
205 XML_StopParser(XMPP->xp, XML_FALSE);
210 * We have just received a <stream> tag from the client, so send them ours
212 void xmpp_stream_start(void *data, const char *supplied_el, const char **attr)
214 citxmpp *Xmpp = XMPP;
217 if (!strcasecmp(attr[0], "to")) {
218 safestrncpy(Xmpp->server_name, attr[1], sizeof Xmpp->server_name);
223 XPUT("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
225 XPUT("<stream:stream ");
227 XPutProp(Xmpp->server_name, strlen(Xmpp->server_name));
229 XPrintf("%08x\" ", CC->cs_pid);
230 XPUT("version=\"1.0\" "
231 "xmlns:stream=\"http://etherx.jabber.org/streams\" "
232 "xmlns=\"jabber:client\">"
233 /* The features of this stream are... */
234 "<stream:features>");
237 * TLS encryption (but only if it isn't already active)
240 if (!CC->redirect_ssl) {
241 XPUT("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'></starttls>");
245 if (!CC->logged_in) {
246 /* If we're not logged in yet, offer SASL as our feature set */
247 xmpp_output_auth_mechs();
249 /* Also offer non-SASL authentication */
250 XPUT("<auth xmlns=\"http://jabber.org/features/iq-auth\"/>");
253 /* Offer binding and sessions as part of our feature set */
254 XPUT("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>"
255 "<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>"
256 "</stream:features>");
258 CC->is_async = 1; /* XMPP sessions are inherently async-capable */
261 void xmpp_start_query(void *data, const char *supplied_el, const char **attr)
263 XMPP->iq_query_xmlns[0] = 0;
264 safestrncpy(XMPP->iq_query_xmlns, supplied_el, sizeof XMPP->iq_query_xmlns);
267 void xmpp_start_bind(void *data, const char *supplied_el, const char **attr)
269 XMPP->bind_requested = 1;
272 void xmpp_start_iq(void *data, const char *supplied_el, const char **attr)
275 for (i=0; attr[i] != NULL; i+=2) {
276 if (!strcasecmp(attr[i], "type")) {
277 safestrncpy(XMPP->iq_type, attr[i+1], sizeof XMPP->iq_type);
279 else if (!strcasecmp(attr[i], "id")) {
280 safestrncpy(XMPP->iq_id, attr[i+1], sizeof XMPP->iq_id);
282 else if (!strcasecmp(attr[i], "from")) {
283 safestrncpy(XMPP->iq_from, attr[i+1], sizeof XMPP->iq_from);
285 else if (!strcasecmp(attr[i], "to")) {
286 safestrncpy(XMPP->iq_to, attr[i+1], sizeof XMPP->iq_to);
291 void xmpp_start_auth(void *data, const char *supplied_el, const char **attr)
295 XMPP->sasl_auth_mech[0] = 0;
296 for (i=0; attr[i] != NULL; i+=2) {
297 if (!strcasecmp(attr[i], "mechanism")) {
298 safestrncpy(XMPP->sasl_auth_mech, attr[i+1], sizeof XMPP->sasl_auth_mech);
303 void xmpp_start_message(void *data, const char *supplied_el, const char **attr)
307 for (i=0; attr[i] != NULL; i+=2) {
308 if (!strcasecmp(attr[i], "to")) {
309 safestrncpy(XMPP->message_to, attr[i+1], sizeof XMPP->message_to);
314 void xmpp_start_html(void *data, const char *supplied_el, const char **attr)
316 ++XMPP->html_tag_level;
319 void xmpp_xml_start(void *data, const char *supplied_el, const char **attr)
327 /* Axe the namespace, we don't care about it */
328 newlen = len = safestrncpy(el, supplied_el, sizeof el);
329 while (sep = strchr(el, ':'), sep)
331 newlen -= ++sep - el;
332 memmove(el, sep, newlen + 1);
337 XMPP_syslog(LOG_DEBUG, "XMPP ELEMENT START: <%s>\n", el);
338 for (i=0; attr[i] != NULL; i+=2) {
339 XMPP_syslog(LOG_DEBUG, " Attribute '%s' = '%s'\n", attr[i], attr[i+1]);
341 uncomment for more verbosity */
343 if (GetHash(XMPP_StartHandlers, el, len, &pv))
346 h = (xmpp_handler*) pv;
347 h->Handler(data, supplied_el, attr);
351 void xmpp_end_resource(void *data, const char *supplied_el, const char **attr)
353 if (XMPP->chardata_len > 0) {
354 safestrncpy(XMPP->iq_client_resource, XMPP->chardata,
355 sizeof XMPP->iq_client_resource);
356 striplt(XMPP->iq_client_resource);
360 void xmpp_end_username(void *data, const char *supplied_el, const char **attr)
363 if (XMPP->chardata_len > 0) {
364 safestrncpy(XMPP->iq_client_username, XMPP->chardata,
365 sizeof XMPP->iq_client_username);
366 striplt(XMPP->iq_client_username);
370 void xmpp_end_password(void *data, const char *supplied_el, const char **attr)
371 { /* NON SASL ONLY */
372 if (XMPP->chardata_len > 0) {
373 safestrncpy(XMPP->iq_client_password, XMPP->chardata,
374 sizeof XMPP->iq_client_password);
375 striplt(XMPP->iq_client_password);
379 void xmpp_end_iq(void *data, const char *supplied_el, const char **attr)
381 citxmpp *Xmpp = XMPP;
384 * iq type="get" (handle queries)
386 if (!strcasecmp(Xmpp->iq_type, "get"))
389 * Query on a namespace
391 if (!IsEmptyStr(Xmpp->iq_query_xmlns)) {
392 xmpp_query_namespace(Xmpp->iq_id, Xmpp->iq_from,
393 Xmpp->iq_to, Xmpp->iq_query_xmlns);
397 * ping ( http://xmpp.org/extensions/xep-0199.html )
399 else if (Xmpp->ping_requested) {
400 XPUT("<iq type=\"result\" ");
401 if (!IsEmptyStr(Xmpp->iq_from)) {
403 XPutProp(Xmpp->iq_from, strlen(Xmpp->iq_from));
406 if (!IsEmptyStr(Xmpp->iq_to)) {
408 XPutProp(Xmpp->iq_to, strlen(Xmpp->iq_to));
412 XPutProp(Xmpp->iq_id, strlen(Xmpp->iq_id));
417 * Unknown query ... return the XML equivalent of a blank stare
421 Xmpp_syslog(LOG_DEBUG,
422 "Unknown query <%s> - returning <service-unavailable/>\n",
426 XPUT("<iq type=\"error\" id=\"");
427 XPutProp(Xmpp->iq_id, strlen(Xmpp->iq_id));
429 "<error code=\"503\" type=\"cancel\">"
430 "<service-unavailable xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>"
437 * Non SASL authentication
440 (!strcasecmp(Xmpp->iq_type, "set"))
441 && (!strcasecmp(Xmpp->iq_query_xmlns, "jabber:iq:auth:query"))
444 xmpp_non_sasl_authenticate(
446 Xmpp->iq_client_username,
447 Xmpp->iq_client_password,
448 Xmpp->iq_client_resource
453 * If this <iq> stanza was a "bind" attempt, process it ...
456 (Xmpp->bind_requested)
457 && (!IsEmptyStr(Xmpp->iq_id))
458 && (!IsEmptyStr(Xmpp->iq_client_resource))
462 /* Generate the "full JID" of the client resource */
464 snprintf(Xmpp->client_jid, sizeof Xmpp->client_jid,
467 Xmpp->iq_client_resource
470 /* Tell the client what its JID is */
472 XPUT("<iq type=\"result\" id=\"");
473 XPutProp(Xmpp->iq_id, strlen(Xmpp->iq_id));
475 "<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">");
477 XPutBody(Xmpp->client_jid, strlen(Xmpp->client_jid));
483 else if (Xmpp->iq_session) {
484 XPUT("<iq type=\"result\" id=\"");
485 XPutProp(Xmpp->iq_id, strlen(Xmpp->iq_id));
491 XPUT("<iq type=\"error\" id=\"");
492 XPutProp(Xmpp->iq_id, strlen(Xmpp->iq_id));
494 XPUT("<error>Don't know howto do '");
495 XPutBody(Xmpp->iq_type, strlen(Xmpp->iq_type));
500 /* Now clear these fields out so they don't get used by a future stanza */
502 Xmpp->iq_from[0] = 0;
504 Xmpp->iq_type[0] = 0;
505 Xmpp->iq_client_resource[0] = 0;
506 Xmpp->iq_session = 0;
507 Xmpp->iq_query_xmlns[0] = 0;
508 Xmpp->bind_requested = 0;
509 Xmpp->ping_requested = 0;
513 void xmpp_end_auth(void *data, const char *supplied_el, const char **attr)
515 /* Try to authenticate (this function is responsible for the output stanza) */
516 xmpp_sasl_auth(XMPP->sasl_auth_mech, (XMPP->chardata != NULL ? XMPP->chardata : "") );
518 /* Now clear these fields out so they don't get used by a future stanza */
519 XMPP->sasl_auth_mech[0] = 0;
522 void xmpp_end_session(void *data, const char *supplied_el, const char **attr)
524 XMPP->iq_session = 1;
527 void xmpp_end_body(void *data, const char *supplied_el, const char **attr)
529 if (XMPP->html_tag_level == 0)
531 if (XMPP->message_body != NULL)
533 free(XMPP->message_body);
534 XMPP->message_body = NULL;
536 if (XMPP->chardata_len > 0) {
537 XMPP->message_body = strdup(XMPP->chardata);
542 void xmpp_end_html(void *data, const char *supplied_el, const char **attr)
544 --XMPP->html_tag_level;
547 void xmpp_end_starttls(void *data, const char *supplied_el, const char **attr)
550 XPUT("<proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
552 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
553 if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO;
555 XPUT("<failure xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
556 CC->kill_me = KILLME_NO_CRYPTO;
560 void xmpp_end_ping(void *data, const char *supplied_el, const char **attr)
562 XMPP->ping_requested = 1;
565 void xmpp_end_stream(void *data, const char *supplied_el, const char **attr)
567 XMPPM_syslog(LOG_DEBUG, "XMPP client shut down their stream\n");
568 xmpp_massacre_roster();
570 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
573 void xmpp_xml_end(void *data, const char *supplied_el)
581 /* Axe the namespace, we don't care about it */
582 newlen = len = safestrncpy(el, supplied_el, sizeof el);
583 while (sep = strchr(el, ':'), sep) {
585 newlen -= ++sep - el;
586 memmove(el, sep, newlen + 1);
591 XMPP_syslog(LOG_DEBUG, "XMPP ELEMENT END : <%s>\n", el);
592 if (XMPP->chardata_len > 0) {
593 XMPP_syslog(LOG_DEBUG, " chardata: %s\n", XMPP->chardata);
595 uncomment for more verbosity */
597 if (GetHash(XMPP_EndHandlers, el, len, &pv))
600 h = (xmpp_handler*) pv;
601 h->Handler(data, supplied_el, NULL);
605 XMPP_syslog(LOG_DEBUG, "Ignoring unknown tag <%s>\n", el);
608 XMPP->chardata_len = 0;
609 if (XMPP->chardata_alloc > 0) {
610 XMPP->chardata[0] = 0;
615 void xmpp_xml_chardata(void *data, const XML_Char *s, int len)
619 if (X->chardata_alloc == 0) {
620 X->chardata_alloc = SIZ;
621 X->chardata = malloc(X->chardata_alloc);
623 if ((X->chardata_len + len + 1) > X->chardata_alloc) {
624 X->chardata_alloc = X->chardata_len + len + 1024;
625 X->chardata = realloc(X->chardata, X->chardata_alloc);
627 memcpy(&X->chardata[X->chardata_len], s, len);
628 X->chardata_len += len;
629 X->chardata[X->chardata_len] = 0;
634 * This cleanup function blows away the temporary memory and files used by the XMPP service.
636 void xmpp_cleanup_function(void) {
638 /* Don't do this stuff if this is not a XMPP session! */
639 if (CC->h_command_function != xmpp_command_loop) return;
641 if (XMPP->chardata != NULL) {
642 free(XMPP->chardata);
643 XMPP->chardata = NULL;
644 XMPP->chardata_len = 0;
645 XMPP->chardata_alloc = 0;
646 if (XMPP->message_body != NULL) {
647 free(XMPP->message_body);
650 XML_ParserFree(XMPP->xp);
651 FreeStrBuf(&XMPP->OutBuf);
658 * Here's where our XMPP session begins its happy day.
660 void xmpp_greeting(void) {
661 client_set_inbound_buf(4);
662 strcpy(CC->cs_clientname, "XMPP session");
663 CC->session_specific_data = malloc(sizeof(citxmpp));
664 memset(XMPP, 0, sizeof(citxmpp));
665 XMPP->last_event_processed = queue_event_seq;
666 XMPP->OutBuf = NewStrBufPlain(NULL, SIZ);
667 /* XMPP does not use a greeting, but we still have to initialize some things. */
669 XMPP->xp = XML_ParserCreateNS("UTF-8", ':');
670 if (XMPP->xp == NULL) {
671 XMPPM_syslog(LOG_ALERT, "Cannot create XML parser!\n");
672 CC->kill_me = KILLME_XML_PARSER;
676 XML_SetElementHandler(XMPP->xp, xmpp_xml_start, xmpp_xml_end);
677 XML_SetCharacterDataHandler(XMPP->xp, xmpp_xml_chardata);
678 // XML_SetUserData(XMPP->xp, something...);
680 /* Prevent the "billion laughs" attack against expat by disabling
681 * internal entity expansion. With 2.x, forcibly stop the parser
682 * if an entity is declared - this is safer and a more obvious
683 * failure mode. With older versions, simply prevent expansion
684 * of such entities. */
685 #ifdef HAVE_XML_STOPPARSER
686 XML_SetEntityDeclHandler(XMPP->xp, xmpp_entity_declaration);
688 XML_SetDefaultHandler(XMPP->xp, NULL);
691 CC->can_receive_im = 1; /* This protocol is capable of receiving instant messages */
697 * Main command loop for XMPP sessions.
699 void xmpp_command_loop(void) {
701 StrBuf *stream_input = NewStrBuf();
704 rc = client_read_random_blob(stream_input, 30);
706 XML_Parse(XMPP->xp, ChrPtr(stream_input), rc, 0);
709 XMPPM_syslog(LOG_ERR, "client disconnected: ending session.\n");
710 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
712 FreeStrBuf(&stream_input);
718 * Async loop for XMPP sessions (handles the transmission of unsolicited stanzas)
720 void xmpp_async_loop(void) {
721 xmpp_process_events();
722 xmpp_output_incoming_messages();
727 * Login hook for XMPP sessions
729 void xmpp_login_hook(void) {
730 xmpp_queue_event(XMPP_EVT_LOGIN, CC->cs_inet_email);
735 * Logout hook for XMPP sessions
737 void xmpp_logout_hook(void) {
738 xmpp_queue_event(XMPP_EVT_LOGOUT, CC->cs_inet_email);
742 void LogXMPPSrvDebugEnable(const int n)
744 XMPPSrvDebugEnable = n;
746 const char *CitadelServiceXMPP="XMPP";
747 extern void xmpp_cleanup_events(void);
751 /******************************************************************************
752 * XMPP handler registering logic *
753 ******************************************************************************/
755 void AddXMPPStartHandler(const char *key,
757 xmpp_handler_func Handler,
761 h = (xmpp_handler*) malloc(sizeof (xmpp_handler));
763 h->Handler = Handler;
764 Put(XMPP_StartHandlers, key, len, h, NULL);
767 void AddXMPPEndHandler(const char *key,
769 xmpp_handler_func Handler,
773 h = (xmpp_handler*) malloc(sizeof (xmpp_handler));
775 h->Handler = Handler;
776 Put(XMPP_EndHandlers, key, len, h, NULL);
779 CTDL_MODULE_INIT(xmpp)
782 CtdlRegisterServiceHook(config.c_xmpp_c2s_port,
790 XMPP_StartHandlers = NewHash(1, NULL);
791 XMPP_EndHandlers = NewHash(1, NULL);
793 AddXMPPEndHandler(HKEY("resource"), xmpp_end_resource, 0);
794 AddXMPPEndHandler(HKEY("username"), xmpp_end_username, 0);
795 AddXMPPEndHandler(HKEY("password"), xmpp_end_password, 0);
796 AddXMPPEndHandler(HKEY("iq"), xmpp_end_iq, 0);
797 AddXMPPEndHandler(HKEY("auth"), xmpp_end_auth, 0);
798 AddXMPPEndHandler(HKEY("session"), xmpp_end_session, 0);
799 AddXMPPEndHandler(HKEY("body"), xmpp_end_body, 0);
800 AddXMPPEndHandler(HKEY("html"), xmpp_end_html, 0);
801 AddXMPPEndHandler(HKEY("starttls"), xmpp_end_starttls, 0);
802 AddXMPPEndHandler(HKEY("ping"), xmpp_end_ping, 0);
803 AddXMPPEndHandler(HKEY("stream"), xmpp_end_stream, 0);
805 AddXMPPStartHandler(HKEY("stream"), xmpp_stream_start, 0);
806 AddXMPPStartHandler(HKEY("query"), xmpp_start_query, 0);
807 AddXMPPStartHandler(HKEY("bind"), xmpp_start_bind, 0);
808 AddXMPPStartHandler(HKEY("iq"), xmpp_start_iq, 0);
809 AddXMPPStartHandler(HKEY("auth"), xmpp_start_auth, 0);
810 AddXMPPStartHandler(HKEY("message"), xmpp_start_message, 0);
811 AddXMPPStartHandler(HKEY("html"), xmpp_start_html, 0);
814 CtdlRegisterDebugFlagHook(HKEY("serv_xmpp"), LogXMPPSrvDebugEnable, &XMPPSrvDebugEnable);
815 CtdlRegisterSessionHook(xmpp_cleanup_function, EVT_STOP, PRIO_STOP + 70);
816 CtdlRegisterSessionHook(xmpp_login_hook, EVT_LOGIN, PRIO_LOGIN + 90);
817 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 90);
818 CtdlRegisterSessionHook(xmpp_login_hook, EVT_UNSTEALTH, PRIO_UNSTEALTH + 1);
819 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_STEALTH, PRIO_STEALTH + 1);
820 CtdlRegisterCleanupHook(xmpp_cleanup_events);
824 /* return our module name for the log */