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 #ifdef HAVE_XML_STOPPARSER
107 /* Stop the parser if an entity declaration is hit. */
108 static void xmpp_entity_declaration(void *userData, const XML_Char *entityName,
109 int is_parameter_entity, const XML_Char *value,
110 int value_length, const XML_Char *base,
111 const XML_Char *systemId, const XML_Char *publicId,
112 const XML_Char *notationName
114 XMPPM_syslog(LOG_WARNING, "Illegal entity declaration encountered; stopping parser.");
115 XML_StopParser(XMPP->xp, XML_FALSE);
120 * We have just received a <stream> tag from the client, so send them ours
122 void xmpp_stream_start(void *data, const char *supplied_el, const char **attr)
124 citxmpp *Xmpp = XMPP;
127 if (!strcasecmp(attr[0], "to")) {
128 safestrncpy(Xmpp->server_name, attr[1], sizeof Xmpp->server_name);
133 XPUT("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
135 XPUT("<stream:stream ");
137 XPutProp(Xmpp->server_name, strlen(Xmpp->server_name));
139 XPrintf("%08x\" ", CC->cs_pid);
140 XPUT("version=\"1.0\" "
141 "xmlns:stream=\"http://etherx.jabber.org/streams\" "
142 "xmlns=\"jabber:client\">");
144 /* The features of this stream are... */
145 XPUT("<stream:features>");
148 * TLS encryption (but only if it isn't already active)
151 if (!CC->redirect_ssl) {
152 XPUT("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'></starttls>");
156 if (!CC->logged_in) {
157 /* If we're not logged in yet, offer SASL as our feature set */
158 xmpp_output_auth_mechs();
160 /* Also offer non-SASL authentication */
161 XPUT("<auth xmlns=\"http://jabber.org/features/iq-auth\"/>");
164 /* Offer binding and sessions as part of our feature set */
165 XPUT("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>"
166 "<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>"
167 "</stream:features>");
169 CC->is_async = 1; /* XMPP sessions are inherently async-capable */
172 void xmpp_start_query(void *data, const char *supplied_el, const char **attr)
174 XMPP->iq_query_xmlns[0] = 0;
175 safestrncpy(XMPP->iq_query_xmlns, supplied_el, sizeof XMPP->iq_query_xmlns);
178 void xmpp_start_bind(void *data, const char *supplied_el, const char **attr)
180 XMPP->bind_requested = 1;
183 void xmpp_start_iq(void *data, const char *supplied_el, const char **attr)
186 for (i=0; attr[i] != NULL; i+=2) {
187 if (!strcasecmp(attr[i], "type")) {
188 safestrncpy(XMPP->iq_type, attr[i+1], sizeof XMPP->iq_type);
190 else if (!strcasecmp(attr[i], "id")) {
191 safestrncpy(XMPP->iq_id, attr[i+1], sizeof XMPP->iq_id);
193 else if (!strcasecmp(attr[i], "from")) {
194 safestrncpy(XMPP->iq_from, attr[i+1], sizeof XMPP->iq_from);
196 else if (!strcasecmp(attr[i], "to")) {
197 safestrncpy(XMPP->iq_to, attr[i+1], sizeof XMPP->iq_to);
202 void xmpp_start_auth(void *data, const char *supplied_el, const char **attr)
206 XMPP->sasl_auth_mech[0] = 0;
207 for (i=0; attr[i] != NULL; i+=2) {
208 if (!strcasecmp(attr[i], "mechanism")) {
209 safestrncpy(XMPP->sasl_auth_mech, attr[i+1], sizeof XMPP->sasl_auth_mech);
214 void xmpp_start_message(void *data, const char *supplied_el, const char **attr)
218 for (i=0; attr[i] != NULL; i+=2) {
219 if (!strcasecmp(attr[i], "to")) {
220 safestrncpy(XMPP->message_to, attr[i+1], sizeof XMPP->message_to);
225 void xmpp_start_html(void *data, const char *supplied_el, const char **attr)
227 ++XMPP->html_tag_level;
230 void xmpp_xml_start(void *data, const char *supplied_el, const char **attr)
238 /* Axe the namespace, we don't care about it */
239 newlen = len = safestrncpy(el, supplied_el, sizeof el);
240 while (sep = strchr(el, ':'), sep)
242 newlen -= ++sep - el;
243 memmove(el, sep, newlen + 1);
248 XMPP_syslog(LOG_DEBUG, "XMPP ELEMENT START: <%s>\n", el);
249 for (i=0; attr[i] != NULL; i+=2) {
250 XMPP_syslog(LOG_DEBUG, " Attribute '%s' = '%s'\n", attr[i], attr[i+1]);
252 uncomment for more verbosity */
254 if (GetHash(XMPP_StartHandlers, el, len, &pv))
257 h = (xmpp_handler*) pv;
258 h->Handler(data, supplied_el, attr);
263 void xmpp_end_resource(void *data, const char *supplied_el, const char **attr)
265 if (XMPP->chardata_len > 0) {
266 safestrncpy(XMPP->iq_client_resource, XMPP->chardata,
267 sizeof XMPP->iq_client_resource);
268 striplt(XMPP->iq_client_resource);
272 void xmpp_end_username(void *data, const char *supplied_el, const char **attr)
275 if (XMPP->chardata_len > 0) {
276 safestrncpy(XMPP->iq_client_username, XMPP->chardata,
277 sizeof XMPP->iq_client_username);
278 striplt(XMPP->iq_client_username);
282 void xmpp_end_password(void *data, const char *supplied_el, const char **attr)
283 { /* NON SASL ONLY */
284 if (XMPP->chardata_len > 0) {
285 safestrncpy(XMPP->iq_client_password, XMPP->chardata,
286 sizeof XMPP->iq_client_password);
287 striplt(XMPP->iq_client_password);
291 void xmpp_end_iq(void *data, const char *supplied_el, const char **attr)
293 citxmpp *Xmpp = XMPP;
296 * iq type="get" (handle queries)
298 if (!strcasecmp(Xmpp->iq_type, "get"))
301 * Query on a namespace
303 if (!IsEmptyStr(Xmpp->iq_query_xmlns)) {
304 xmpp_query_namespace(Xmpp->iq_id, Xmpp->iq_from,
305 Xmpp->iq_to, Xmpp->iq_query_xmlns);
309 * ping ( http://xmpp.org/extensions/xep-0199.html )
311 else if (Xmpp->ping_requested) {
312 XPUT("<iq type=\"result\" ");
313 if (!IsEmptyStr(Xmpp->iq_from)) {
315 XPutProp(Xmpp->iq_from, strlen(Xmpp->iq_from));
318 if (!IsEmptyStr(Xmpp->iq_to)) {
320 XPutProp(Xmpp->iq_to, strlen(Xmpp->iq_to));
324 XPutProp(Xmpp->iq_id, strlen(Xmpp->iq_id));
329 * Unknown query ... return the XML equivalent of a blank stare
333 Xmpp_syslog(LOG_DEBUG,
334 "Unknown query <%s> - returning <service-unavailable/>\n",
338 XPUT("<iq type=\"error\" id=\"");
339 XPutProp(Xmpp->iq_id, strlen(Xmpp->iq_id));
341 "<error code=\"503\" type=\"cancel\">"
342 "<service-unavailable xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>"
349 * Non SASL authentication
352 (!strcasecmp(Xmpp->iq_type, "set"))
353 && (!strcasecmp(Xmpp->iq_query_xmlns, "jabber:iq:auth:query"))
356 xmpp_non_sasl_authenticate(
358 Xmpp->iq_client_username,
359 Xmpp->iq_client_password,
360 Xmpp->iq_client_resource
365 * If this <iq> stanza was a "bind" attempt, process it ...
368 (Xmpp->bind_requested)
369 && (!IsEmptyStr(Xmpp->iq_id))
370 && (!IsEmptyStr(Xmpp->iq_client_resource))
374 /* Generate the "full JID" of the client resource */
376 snprintf(Xmpp->client_jid, sizeof Xmpp->client_jid,
379 Xmpp->iq_client_resource
382 /* Tell the client what its JID is */
384 XPUT("<iq type=\"result\" id=\"");
385 XPutProp(Xmpp->iq_id, strlen(Xmpp->iq_id));
387 "<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">");
389 XPutBody(Xmpp->client_jid, strlen(Xmpp->client_jid));
395 else if (Xmpp->iq_session) {
396 XPUT("<iq type=\"result\" id=\"");
397 XPutProp(Xmpp->iq_id, strlen(Xmpp->iq_id));
403 XPUT("<iq type=\"error\" id=\"");
404 XPutProp(Xmpp->iq_id, strlen(Xmpp->iq_id));
406 XPUT("<error>Don't know howto do '");
407 XPutBody(Xmpp->iq_type, strlen(Xmpp->iq_type));
412 /* Now clear these fields out so they don't get used by a future stanza */
414 Xmpp->iq_from[0] = 0;
416 Xmpp->iq_type[0] = 0;
417 Xmpp->iq_client_resource[0] = 0;
418 Xmpp->iq_session = 0;
419 Xmpp->iq_query_xmlns[0] = 0;
420 Xmpp->bind_requested = 0;
421 Xmpp->ping_requested = 0;
425 void xmpp_end_auth(void *data, const char *supplied_el, const char **attr)
427 /* Try to authenticate (this function is responsible for the output stanza) */
428 xmpp_sasl_auth(XMPP->sasl_auth_mech, (XMPP->chardata != NULL ? XMPP->chardata : "") );
430 /* Now clear these fields out so they don't get used by a future stanza */
431 XMPP->sasl_auth_mech[0] = 0;
434 void xmpp_end_session(void *data, const char *supplied_el, const char **attr)
436 XMPP->iq_session = 1;
439 void xmpp_end_body(void *data, const char *supplied_el, const char **attr)
441 if (XMPP->html_tag_level == 0)
443 if (XMPP->message_body != NULL)
445 free(XMPP->message_body);
446 XMPP->message_body = NULL;
448 if (XMPP->chardata_len > 0) {
449 XMPP->message_body = strdup(XMPP->chardata);
454 void xmpp_end_html(void *data, const char *supplied_el, const char **attr)
456 --XMPP->html_tag_level;
459 void xmpp_end_starttls(void *data, const char *supplied_el, const char **attr)
462 XPUT("<proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
463 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
464 if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO;
466 XPUT("<failure xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
467 CC->kill_me = KILLME_NO_CRYPTO;
471 void xmpp_end_ping(void *data, const char *supplied_el, const char **attr)
473 XMPP->ping_requested = 1;
476 void xmpp_end_stream(void *data, const char *supplied_el, const char **attr)
478 XMPPM_syslog(LOG_DEBUG, "XMPP client shut down their stream\n");
479 xmpp_massacre_roster();
481 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
484 void xmpp_xml_end(void *data, const char *supplied_el)
492 /* Axe the namespace, we don't care about it */
493 newlen = len = safestrncpy(el, supplied_el, sizeof el);
494 while (sep = strchr(el, ':'), sep) {
496 newlen -= ++sep - el;
497 memmove(el, sep, newlen + 1);
502 XMPP_syslog(LOG_DEBUG, "XMPP ELEMENT END : <%s>\n", el);
503 if (XMPP->chardata_len > 0) {
504 XMPP_syslog(LOG_DEBUG, " chardata: %s\n", XMPP->chardata);
506 uncomment for more verbosity */
508 if (GetHash(XMPP_EndHandlers, el, len, &pv))
511 h = (xmpp_handler*) pv;
512 h->Handler(data, supplied_el, NULL);
516 XMPP_syslog(LOG_DEBUG, "Ignoring unknown tag <%s>\n", el);
519 XMPP->chardata_len = 0;
520 if (XMPP->chardata_alloc > 0) {
521 XMPP->chardata[0] = 0;
527 void xmpp_xml_chardata(void *data, const XML_Char *s, int len)
531 if (X->chardata_alloc == 0) {
532 X->chardata_alloc = SIZ;
533 X->chardata = malloc(X->chardata_alloc);
535 if ((X->chardata_len + len + 1) > X->chardata_alloc) {
536 X->chardata_alloc = X->chardata_len + len + 1024;
537 X->chardata = realloc(X->chardata, X->chardata_alloc);
539 memcpy(&X->chardata[X->chardata_len], s, len);
540 X->chardata_len += len;
541 X->chardata[X->chardata_len] = 0;
546 * This cleanup function blows away the temporary memory and files used by the XMPP service.
548 void xmpp_cleanup_function(void) {
550 /* Don't do this stuff if this is not a XMPP session! */
551 if (CC->h_command_function != xmpp_command_loop) return;
553 if (XMPP->chardata != NULL) {
554 free(XMPP->chardata);
555 XMPP->chardata = NULL;
556 XMPP->chardata_len = 0;
557 XMPP->chardata_alloc = 0;
558 if (XMPP->message_body != NULL) {
559 free(XMPP->message_body);
562 XML_ParserFree(XMPP->xp);
569 * Here's where our XMPP session begins its happy day.
571 void xmpp_greeting(void) {
572 client_set_inbound_buf(4);
573 strcpy(CC->cs_clientname, "XMPP session");
574 CC->session_specific_data = malloc(sizeof(citxmpp));
575 memset(XMPP, 0, sizeof(citxmpp));
576 XMPP->last_event_processed = queue_event_seq;
578 /* XMPP does not use a greeting, but we still have to initialize some things. */
580 XMPP->xp = XML_ParserCreateNS("UTF-8", ':');
581 if (XMPP->xp == NULL) {
582 XMPPM_syslog(LOG_ALERT, "Cannot create XML parser!\n");
583 CC->kill_me = KILLME_XML_PARSER;
587 XML_SetElementHandler(XMPP->xp, xmpp_xml_start, xmpp_xml_end);
588 XML_SetCharacterDataHandler(XMPP->xp, xmpp_xml_chardata);
589 // XML_SetUserData(XMPP->xp, something...);
591 /* Prevent the "billion laughs" attack against expat by disabling
592 * internal entity expansion. With 2.x, forcibly stop the parser
593 * if an entity is declared - this is safer and a more obvious
594 * failure mode. With older versions, simply prevent expansion
595 * of such entities. */
596 #ifdef HAVE_XML_STOPPARSER
597 XML_SetEntityDeclHandler(XMPP->xp, xmpp_entity_declaration);
599 XML_SetDefaultHandler(XMPP->xp, NULL);
602 CC->can_receive_im = 1; /* This protocol is capable of receiving instant messages */
607 * Main command loop for XMPP sessions.
609 void xmpp_command_loop(void) {
611 StrBuf *stream_input = NewStrBuf();
614 rc = client_read_random_blob(stream_input, 30);
616 XML_Parse(XMPP->xp, ChrPtr(stream_input), rc, 0);
619 XMPPM_syslog(LOG_ERR, "client disconnected: ending session.\n");
620 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
622 FreeStrBuf(&stream_input);
627 * Async loop for XMPP sessions (handles the transmission of unsolicited stanzas)
629 void xmpp_async_loop(void) {
630 xmpp_process_events();
631 xmpp_output_incoming_messages();
636 * Login hook for XMPP sessions
638 void xmpp_login_hook(void) {
639 xmpp_queue_event(XMPP_EVT_LOGIN, CC->cs_inet_email);
644 * Logout hook for XMPP sessions
646 void xmpp_logout_hook(void) {
647 xmpp_queue_event(XMPP_EVT_LOGOUT, CC->cs_inet_email);
651 void LogXMPPSrvDebugEnable(const int n)
653 XMPPSrvDebugEnable = n;
655 const char *CitadelServiceXMPP="XMPP";
656 extern void xmpp_cleanup_events(void);
660 /******************************************************************************
661 * XMPP handler registering logic *
662 ******************************************************************************/
664 void AddXMPPStartHandler(const char *key,
666 xmpp_handler_func Handler,
670 h = (xmpp_handler*) malloc(sizeof (xmpp_handler));
672 h->Handler = Handler;
673 Put(XMPP_StartHandlers, key, len, h, NULL);
676 void AddXMPPEndHandler(const char *key,
678 xmpp_handler_func Handler,
682 h = (xmpp_handler*) malloc(sizeof (xmpp_handler));
684 h->Handler = Handler;
685 Put(XMPP_EndHandlers, key, len, h, NULL);
688 CTDL_MODULE_INIT(xmpp)
691 CtdlRegisterServiceHook(config.c_xmpp_c2s_port,
699 XMPP_StartHandlers = NewHash(1, NULL);
700 XMPP_EndHandlers = NewHash(1, NULL);
702 AddXMPPEndHandler(HKEY("resource"), xmpp_end_resource, 0);
703 AddXMPPEndHandler(HKEY("username"), xmpp_end_username, 0);
704 AddXMPPEndHandler(HKEY("password"), xmpp_end_password, 0);
705 AddXMPPEndHandler(HKEY("iq"), xmpp_end_iq, 0);
706 AddXMPPEndHandler(HKEY("auth"), xmpp_end_auth, 0);
707 AddXMPPEndHandler(HKEY("session"), xmpp_end_session, 0);
708 AddXMPPEndHandler(HKEY("body"), xmpp_end_body, 0);
709 AddXMPPEndHandler(HKEY("html"), xmpp_end_html, 0);
710 AddXMPPEndHandler(HKEY("starttls"), xmpp_end_starttls, 0);
711 AddXMPPEndHandler(HKEY("ping"), xmpp_end_ping, 0);
712 AddXMPPEndHandler(HKEY("stream"), xmpp_end_stream, 0);
714 AddXMPPStartHandler(HKEY("stream"), xmpp_stream_start, 0);
715 AddXMPPStartHandler(HKEY("query"), xmpp_start_query, 0);
716 AddXMPPStartHandler(HKEY("bind"), xmpp_start_bind, 0);
717 AddXMPPStartHandler(HKEY("iq"), xmpp_start_iq, 0);
718 AddXMPPStartHandler(HKEY("auth"), xmpp_start_auth, 0);
719 AddXMPPStartHandler(HKEY("message"), xmpp_start_message, 0);
720 AddXMPPStartHandler(HKEY("html"), xmpp_start_html, 0);
723 CtdlRegisterDebugFlagHook(HKEY("serv_xmpp"), LogXMPPSrvDebugEnable, &XMPPSrvDebugEnable);
724 CtdlRegisterSessionHook(xmpp_cleanup_function, EVT_STOP, PRIO_STOP + 70);
725 CtdlRegisterSessionHook(xmpp_login_hook, EVT_LOGIN, PRIO_LOGIN + 90);
726 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 90);
727 CtdlRegisterSessionHook(xmpp_login_hook, EVT_UNSTEALTH, PRIO_UNSTEALTH + 1);
728 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_STEALTH, PRIO_STEALTH + 1);
729 CtdlRegisterCleanupHook(xmpp_cleanup_events);
733 /* return our module name for the log */