2 * XMPP (Jabber) service for the Citadel system
3 * Copyright (c) 2007-2017 by Art Cancro and citadel.org
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;
70 #ifdef HAVE_XML_STOPPARSER
71 /* Stop the parser if an entity declaration is hit. */
72 static void xmpp_entity_declaration(void *userData, const XML_Char *entityName,
73 int is_parameter_entity, const XML_Char *value,
74 int value_length, const XML_Char *base,
75 const XML_Char *systemId, const XML_Char *publicId,
76 const XML_Char *notationName
78 syslog(LOG_WARNING, "xmpp: illegal entity declaration encountered; stopping parser.");
79 XML_StopParser(XMPP->xp, XML_FALSE);
86 * Given a source string and a target buffer, returns the string
87 * properly escaped for insertion into an XML stream. Returns a
88 * pointer to the target buffer for convenience.
90 static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
93 unsigned char test = (1<<7);
95 if ((*CharS & 0xC0) != 0xC0)
99 ((test & ((unsigned char)*CharS)) != 0))
104 if ((n > 6) || ((CharE - CharS) < n))
109 char *xmlesc(char *buf, char *str, int bufsiz)
117 if (!buf) return(NULL);
126 for (ptr=str; *ptr; ptr++) {
129 strcpy(&buf[len], "<");
132 else if (ch == '>') {
133 strcpy(&buf[len], ">");
136 else if (ch == '&') {
137 strcpy(&buf[len], "&");
140 else if ((ch >= 0x20) && (ch <= 0x7F)) {
144 else if (ch < 0x20) {
145 /* we probably shouldn't be doing this */
150 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(ptr, pche);
153 while ((IsUtf8Sequence > 0) &&
164 sprintf(oct, "&#%o;", ch);
165 strcpy(&buf[len], oct);
169 if ((len + 6) > bufsiz) {
178 * We have just received a <stream> tag from the client, so send them ours
180 void xmpp_stream_start(void *data, const char *supplied_el, const char **attr)
185 if (!strcasecmp(attr[0], "to")) {
186 safestrncpy(XMPP->server_name, attr[1], sizeof XMPP->server_name);
191 cprintf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
193 cprintf("<stream:stream ");
194 cprintf("from=\"%s\" ", xmlesc(xmlbuf, XMPP->server_name, sizeof xmlbuf));
195 cprintf("id=\"%08x\" ", CC->cs_pid);
196 cprintf("version=\"1.0\" ");
197 cprintf("xmlns:stream=\"http://etherx.jabber.org/streams\" ");
198 cprintf("xmlns=\"jabber:client\">");
200 /* The features of this stream are... */
201 cprintf("<stream:features>");
204 * TLS encryption (but only if it isn't already active)
207 if (!CC->redirect_ssl) {
208 cprintf("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'></starttls>");
212 if (!CC->logged_in) {
213 /* If we're not logged in yet, offer SASL as our feature set */
214 xmpp_output_auth_mechs();
216 /* Also offer non-SASL authentication */
217 cprintf("<auth xmlns=\"http://jabber.org/features/iq-auth\"/>");
220 /* Offer binding and sessions as part of our feature set */
221 cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>");
222 cprintf("<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>");
224 cprintf("</stream:features>");
226 CC->is_async = 1; /* XMPP sessions are inherently async-capable */
230 void xmpp_xml_start(void *data, const char *supplied_el, const char **attr) {
235 /* Axe the namespace, we don't care about it */
236 safestrncpy(el, supplied_el, sizeof el);
237 while (sep = strchr(el, ':'), sep) {
242 syslog(LOG_DEBUG, "xmpp: ELEMENT START: <%s>", el);
243 for (i=0; attr[i] != NULL; i+=2) {
244 syslog(LOG_DEBUG, "xmpp: Attribute '%s' = '%s'", attr[i], attr[i+1]);
246 uncomment for more verbosity */
248 if (!strcasecmp(el, "stream")) {
249 xmpp_stream_start(data, supplied_el, attr);
252 else if (!strcasecmp(el, "query")) {
253 XMPP->iq_query_xmlns[0] = 0;
254 safestrncpy(XMPP->iq_query_xmlns, supplied_el, sizeof XMPP->iq_query_xmlns);
257 else if (!strcasecmp(el, "bind")) {
258 XMPP->bind_requested = 1;
261 else if (!strcasecmp(el, "iq")) {
262 for (i=0; attr[i] != NULL; i+=2) {
263 if (!strcasecmp(attr[i], "type")) {
264 safestrncpy(XMPP->iq_type, attr[i+1], sizeof XMPP->iq_type);
266 else if (!strcasecmp(attr[i], "id")) {
267 safestrncpy(XMPP->iq_id, attr[i+1], sizeof XMPP->iq_id);
269 else if (!strcasecmp(attr[i], "from")) {
270 safestrncpy(XMPP->iq_from, attr[i+1], sizeof XMPP->iq_from);
272 else if (!strcasecmp(attr[i], "to")) {
273 safestrncpy(XMPP->iq_to, attr[i+1], sizeof XMPP->iq_to);
278 else if (!strcasecmp(el, "auth")) {
279 XMPP->sasl_auth_mech[0] = 0;
280 for (i=0; attr[i] != NULL; i+=2) {
281 if (!strcasecmp(attr[i], "mechanism")) {
282 safestrncpy(XMPP->sasl_auth_mech, attr[i+1], sizeof XMPP->sasl_auth_mech);
287 else if (!strcasecmp(el, "message")) {
288 for (i=0; attr[i] != NULL; i+=2) {
289 if (!strcasecmp(attr[i], "to")) {
290 safestrncpy(XMPP->message_to, attr[i+1], sizeof XMPP->message_to);
295 else if (!strcasecmp(el, "html")) {
296 ++XMPP->html_tag_level;
302 void xmpp_xml_end(void *data, const char *supplied_el) {
307 /* Axe the namespace, we don't care about it */
308 safestrncpy(el, supplied_el, sizeof el);
309 while (sep = strchr(el, ':'), sep) {
314 syslog(LOG_DEBUG, "xmpp: ELEMENT END : <%s>", el);
315 if (XMPP->chardata_len > 0) {
316 syslog(LOG_DEBUG, "xmpp: chardata: %s", XMPP->chardata);
318 uncomment for more verbosity */
320 if (!strcasecmp(el, "resource")) {
321 if (XMPP->chardata_len > 0) {
322 safestrncpy(XMPP->iq_client_resource, XMPP->chardata,
323 sizeof XMPP->iq_client_resource);
324 striplt(XMPP->iq_client_resource);
328 else if (!strcasecmp(el, "username")) { /* NON SASL ONLY */
329 if (XMPP->chardata_len > 0) {
330 safestrncpy(XMPP->iq_client_username, XMPP->chardata,
331 sizeof XMPP->iq_client_username);
332 striplt(XMPP->iq_client_username);
336 else if (!strcasecmp(el, "password")) { /* NON SASL ONLY */
337 if (XMPP->chardata_len > 0) {
338 safestrncpy(XMPP->iq_client_password, XMPP->chardata,
339 sizeof XMPP->iq_client_password);
340 striplt(XMPP->iq_client_password);
344 else if (!strcasecmp(el, "iq")) {
347 * iq type="get" (handle queries)
349 if (!strcasecmp(XMPP->iq_type, "get")) {
352 * Query on a namespace
354 if (!IsEmptyStr(XMPP->iq_query_xmlns)) {
355 xmpp_query_namespace(XMPP->iq_id, XMPP->iq_from,
356 XMPP->iq_to, XMPP->iq_query_xmlns);
360 * ping ( http://xmpp.org/extensions/xep-0199.html )
362 else if (XMPP->ping_requested) {
363 cprintf("<iq type=\"result\" ");
364 if (!IsEmptyStr(XMPP->iq_from)) {
365 cprintf("to=\"%s\" ", xmlesc(xmlbuf, XMPP->iq_from, sizeof xmlbuf));
367 if (!IsEmptyStr(XMPP->iq_to)) {
368 cprintf("from=\"%s\" ", xmlesc(xmlbuf, XMPP->iq_to, sizeof xmlbuf));
370 cprintf("id=\"%s\"/>", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
374 * Unknown query ... return the XML equivalent of a blank stare
377 syslog(LOG_DEBUG, "xmpp: Unknown query <%s> - returning <service-unavailable/>", el);
378 cprintf("<iq type=\"error\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
379 cprintf("<error code=\"503\" type=\"cancel\">"
380 "<service-unavailable xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>"
388 * Non SASL authentication
391 (!strcasecmp(XMPP->iq_type, "set"))
392 && (!strcasecmp(XMPP->iq_query_xmlns, "jabber:iq:auth:query"))
395 xmpp_non_sasl_authenticate(
397 XMPP->iq_client_username,
398 XMPP->iq_client_password,
399 XMPP->iq_client_resource
404 * If this <iq> stanza was a "bind" attempt, process it ...
407 (XMPP->bind_requested)
408 && (!IsEmptyStr(XMPP->iq_id))
409 && (!IsEmptyStr(XMPP->iq_client_resource))
413 /* Generate the "full JID" of the client resource */
415 snprintf(XMPP->client_jid, sizeof XMPP->client_jid,
418 XMPP->iq_client_resource
421 /* Tell the client what its JID is */
423 cprintf("<iq type=\"result\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
424 cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">");
425 cprintf("<jid>%s</jid>", xmlesc(xmlbuf, XMPP->client_jid, sizeof xmlbuf));
430 else if (XMPP->iq_session) {
431 cprintf("<iq type=\"result\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
436 cprintf("<iq type=\"error\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
437 cprintf("<error>Don't know howto do '%s'!</error>", xmlesc(xmlbuf, XMPP->iq_type, sizeof xmlbuf));
441 /* Now clear these fields out so they don't get used by a future stanza */
443 XMPP->iq_from[0] = 0;
445 XMPP->iq_type[0] = 0;
446 XMPP->iq_client_resource[0] = 0;
447 XMPP->iq_session = 0;
448 XMPP->iq_query_xmlns[0] = 0;
449 XMPP->bind_requested = 0;
450 XMPP->ping_requested = 0;
453 else if (!strcasecmp(el, "auth")) {
455 /* Try to authenticate (this function is responsible for the output stanza) */
456 xmpp_sasl_auth(XMPP->sasl_auth_mech, (XMPP->chardata != NULL ? XMPP->chardata : "") );
458 /* Now clear these fields out so they don't get used by a future stanza */
459 XMPP->sasl_auth_mech[0] = 0;
462 else if (!strcasecmp(el, "session")) {
463 XMPP->iq_session = 1;
466 else if (!strcasecmp(el, "presence")) {
468 /* Respond to a <presence> update by firing back with presence information
469 * on the entire wholist. Check this assumption, it's probably wrong.
471 xmpp_wholist_presence_dump();
474 else if ( (!strcasecmp(el, "body")) && (XMPP->html_tag_level == 0) ) {
475 if (XMPP->message_body != NULL) {
476 free(XMPP->message_body);
477 XMPP->message_body = NULL;
479 if (XMPP->chardata_len > 0) {
480 XMPP->message_body = strdup(XMPP->chardata);
484 else if (!strcasecmp(el, "message")) {
485 xmpp_send_message(XMPP->message_to, XMPP->message_body);
486 XMPP->html_tag_level = 0;
489 else if (!strcasecmp(el, "html")) {
490 --XMPP->html_tag_level;
493 else if (!strcasecmp(el, "starttls")) {
495 cprintf("<proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
496 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
497 if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO;
499 cprintf("<failure xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
500 CC->kill_me = KILLME_NO_CRYPTO;
504 else if (!strcasecmp(el, "ping")) {
505 XMPP->ping_requested = 1;
508 else if (!strcasecmp(el, "stream")) {
509 syslog(LOG_DEBUG, "xmpp: client shut down their stream");
510 xmpp_massacre_roster();
511 cprintf("</stream>\n");
512 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
515 else if (!strcasecmp(el, "query")) {
516 /* already processed , no further action needed here */
519 else if (!strcasecmp(el, "bind")) {
520 /* already processed , no further action needed here */
524 syslog(LOG_DEBUG, "xmpp: ignoring unknown tag <%s>", el);
527 XMPP->chardata_len = 0;
528 if (XMPP->chardata_alloc > 0) {
529 XMPP->chardata[0] = 0;
534 void xmpp_xml_chardata(void *data, const XML_Char *s, int len)
538 if (X->chardata_alloc == 0) {
539 X->chardata_alloc = SIZ;
540 X->chardata = malloc(X->chardata_alloc);
542 if ((X->chardata_len + len + 1) > X->chardata_alloc) {
543 X->chardata_alloc = X->chardata_len + len + 1024;
544 X->chardata = realloc(X->chardata, X->chardata_alloc);
546 memcpy(&X->chardata[X->chardata_len], s, len);
547 X->chardata_len += len;
548 X->chardata[X->chardata_len] = 0;
553 * This cleanup function blows away the temporary memory and files used by the XMPP service.
555 void xmpp_cleanup_function(void) {
557 /* Don't do this stuff if this is not a XMPP session! */
558 if (CC->h_command_function != xmpp_command_loop) return;
560 if (XMPP->chardata != NULL) {
561 free(XMPP->chardata);
562 XMPP->chardata = NULL;
563 XMPP->chardata_len = 0;
564 XMPP->chardata_alloc = 0;
565 if (XMPP->message_body != NULL) {
566 free(XMPP->message_body);
569 XML_ParserFree(XMPP->xp);
576 * Here's where our XMPP session begins its happy day.
578 void xmpp_greeting(void) {
579 client_set_inbound_buf(4);
580 strcpy(CC->cs_clientname, "XMPP session");
581 CC->session_specific_data = malloc(sizeof(citxmpp));
582 memset(XMPP, 0, sizeof(citxmpp));
583 XMPP->last_event_processed = queue_event_seq;
585 /* XMPP does not use a greeting, but we still have to initialize some things. */
587 XMPP->xp = XML_ParserCreateNS("UTF-8", ':');
588 if (XMPP->xp == NULL) {
589 syslog(LOG_ERR, "xmpp: cannot create XML parser");
590 CC->kill_me = KILLME_XML_PARSER;
594 XML_SetElementHandler(XMPP->xp, xmpp_xml_start, xmpp_xml_end);
595 XML_SetCharacterDataHandler(XMPP->xp, xmpp_xml_chardata);
596 // XML_SetUserData(XMPP->xp, something...);
598 /* Prevent the "billion laughs" attack against expat by disabling
599 * internal entity expansion. With 2.x, forcibly stop the parser
600 * if an entity is declared - this is safer and a more obvious
601 * failure mode. With older versions, simply prevent expansion
602 * of such entities. */
603 #ifdef HAVE_XML_STOPPARSER
604 XML_SetEntityDeclHandler(XMPP->xp, xmpp_entity_declaration);
606 XML_SetDefaultHandler(XMPP->xp, NULL);
609 CC->can_receive_im = 1; /* This protocol is capable of receiving instant messages */
614 * Main command loop for XMPP sessions.
616 void xmpp_command_loop(void) {
618 StrBuf *stream_input = NewStrBuf();
621 rc = client_read_random_blob(stream_input, 30);
623 XML_Parse(XMPP->xp, ChrPtr(stream_input), rc, 0);
626 syslog(LOG_ERR, "xmpp: client disconnected: ending session.");
627 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
629 FreeStrBuf(&stream_input);
634 * Async loop for XMPP sessions (handles the transmission of unsolicited stanzas)
636 void xmpp_async_loop(void) {
637 xmpp_process_events();
638 xmpp_output_incoming_messages();
643 * Login hook for XMPP sessions
645 void xmpp_login_hook(void) {
646 xmpp_queue_event(XMPP_EVT_LOGIN, CC->cs_inet_email);
651 * Logout hook for XMPP sessions
653 void xmpp_logout_hook(void) {
654 xmpp_queue_event(XMPP_EVT_LOGOUT, CC->cs_inet_email);
658 const char *CitadelServiceXMPP="XMPP";
659 extern void xmpp_cleanup_events(void);
660 CTDL_MODULE_INIT(xmpp)
663 CtdlRegisterServiceHook(CtdlGetConfigInt("c_xmpp_c2s_port"),
670 CtdlRegisterSessionHook(xmpp_cleanup_function, EVT_STOP, PRIO_STOP + 70);
671 CtdlRegisterSessionHook(xmpp_login_hook, EVT_LOGIN, PRIO_LOGIN + 90);
672 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 90);
673 CtdlRegisterSessionHook(xmpp_login_hook, EVT_UNSTEALTH, PRIO_UNSTEALTH + 1);
674 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_STEALTH, PRIO_STEALTH + 1);
675 CtdlRegisterCleanupHook(xmpp_cleanup_events);
679 /* return our module name for the log */