2 * XMPP (Jabber) service for the Citadel system
3 * Copyright (c) 2007-2018 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 /* uncomment for more verbosity - it will log all received XML tags */
61 #define XMPP_XML_DEBUG
63 /* XML_StopParser is present in expat 2.x */
64 #if XML_MAJOR_VERSION > 1
65 #define HAVE_XML_STOPPARSER
68 struct xmpp_event *xmpp_queue = NULL;
71 #ifdef HAVE_XML_STOPPARSER
72 /* Stop the parser if an entity declaration is hit. */
73 static void xmpp_entity_declaration(void *userData, const XML_Char *entityName,
74 int is_parameter_entity, const XML_Char *value,
75 int value_length, const XML_Char *base,
76 const XML_Char *systemId, const XML_Char *publicId,
77 const XML_Char *notationName
79 syslog(LOG_WARNING, "xmpp: illegal entity declaration encountered; stopping parser.");
80 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))
110 char *xmlesc(char *buf, char *str, int bufsiz)
118 if (!buf) return(NULL);
127 for (ptr=str; *ptr; ptr++) {
130 strcpy(&buf[len], "<");
133 else if (ch == '>') {
134 strcpy(&buf[len], ">");
137 else if (ch == '&') {
138 strcpy(&buf[len], "&");
141 else if ((ch >= 0x20) && (ch <= 0x7F)) {
145 else if (ch < 0x20) {
146 /* we probably shouldn't be doing this */
151 IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(ptr, pche);
154 while ((IsUtf8Sequence > 0) &&
165 sprintf(oct, "&#%o;", ch);
166 strcpy(&buf[len], oct);
170 if ((len + 6) > bufsiz) {
179 * We have just received a <stream> tag from the client, so send them ours
181 void xmpp_stream_start(void *data, const char *supplied_el, const char **attr)
186 if (!strcasecmp(attr[0], "to")) {
187 safestrncpy(XMPP->server_name, attr[1], sizeof XMPP->server_name);
192 cprintf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
194 cprintf("<stream:stream ");
195 cprintf("from=\"%s\" ", xmlesc(xmlbuf, XMPP->server_name, sizeof xmlbuf));
196 cprintf("id=\"%08x\" ", CC->cs_pid);
197 cprintf("version=\"1.0\" ");
198 cprintf("xmlns:stream=\"http://etherx.jabber.org/streams\" ");
199 cprintf("xmlns=\"jabber:client\">");
201 /* The features of this stream are... */
202 cprintf("<stream:features>");
205 * TLS encryption (but only if it isn't already active)
208 if (!CC->redirect_ssl) {
209 cprintf("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'></starttls>");
213 if (!CC->logged_in) {
214 /* If we're not logged in yet, offer SASL as our feature set */
215 xmpp_output_auth_mechs();
217 /* Also offer non-SASL authentication */
218 cprintf("<auth xmlns=\"http://jabber.org/features/iq-auth\"/>");
221 /* Offer binding and sessions as part of our feature set */
222 cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>");
223 cprintf("<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>");
225 cprintf("</stream:features>");
227 CC->is_async = 1; /* XMPP sessions are inherently async-capable */
231 void xmpp_xml_start(void *data, const char *supplied_el, const char **attr) {
236 /* Axe the namespace, we don't care about it */
237 safestrncpy(el, supplied_el, sizeof el);
238 while (sep = strchr(el, ':'), sep) {
242 #ifdef XMPP_XML_DEBUG
243 syslog(LOG_DEBUG, "xmpp: ELEMENT START: <%s>", el);
244 for (i=0; attr[i] != NULL; i+=2) {
245 syslog(LOG_DEBUG, "xmpp: Attribute '%s' = '%s'", attr[i], attr[i+1]);
249 if (!strcasecmp(el, "stream")) {
250 xmpp_stream_start(data, supplied_el, attr);
253 else if (!strcasecmp(el, "query")) {
254 XMPP->iq_query_xmlns[0] = 0;
255 safestrncpy(XMPP->iq_query_xmlns, supplied_el, sizeof XMPP->iq_query_xmlns);
258 else if (!strcasecmp(el, "bind")) {
259 XMPP->bind_requested = 1;
262 else if (!strcasecmp(el, "iq")) {
263 for (i=0; attr[i] != NULL; i+=2) {
264 if (!strcasecmp(attr[i], "type")) {
265 safestrncpy(XMPP->iq_type, attr[i+1], sizeof XMPP->iq_type);
267 else if (!strcasecmp(attr[i], "id")) {
268 safestrncpy(XMPP->iq_id, attr[i+1], sizeof XMPP->iq_id);
270 else if (!strcasecmp(attr[i], "from")) {
271 safestrncpy(XMPP->iq_from, attr[i+1], sizeof XMPP->iq_from);
273 else if (!strcasecmp(attr[i], "to")) {
274 safestrncpy(XMPP->iq_to, attr[i+1], sizeof XMPP->iq_to);
279 else if (!strcasecmp(el, "auth")) {
280 XMPP->sasl_auth_mech[0] = 0;
281 for (i=0; attr[i] != NULL; i+=2) {
282 if (!strcasecmp(attr[i], "mechanism")) {
283 safestrncpy(XMPP->sasl_auth_mech, attr[i+1], sizeof XMPP->sasl_auth_mech);
288 else if (!strcasecmp(el, "message")) {
289 for (i=0; attr[i] != NULL; i+=2) {
290 if (!strcasecmp(attr[i], "to")) {
291 safestrncpy(XMPP->message_to, attr[i+1], sizeof XMPP->message_to);
296 else if (!strcasecmp(el, "html")) {
297 ++XMPP->html_tag_level;
303 void xmpp_xml_end(void *data, const char *supplied_el) {
308 /* Axe the namespace, we don't care about it */
309 safestrncpy(el, supplied_el, sizeof el);
310 while (sep = strchr(el, ':'), sep) {
314 #ifdef XMPP_XML_DEBUG
315 syslog(LOG_DEBUG, "xmpp: ELEMENT END : <%s>", el);
316 if (XMPP->chardata_len > 0) {
317 syslog(LOG_DEBUG, "xmpp: chardata: %s", XMPP->chardata);
321 if (!strcasecmp(el, "resource")) {
322 if (XMPP->chardata_len > 0) {
323 safestrncpy(XMPP->iq_client_resource, XMPP->chardata, 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, sizeof XMPP->iq_client_username);
331 striplt(XMPP->iq_client_username);
335 else if (!strcasecmp(el, "password")) { /* NON SASL ONLY */
336 if (XMPP->chardata_len > 0) {
337 safestrncpy(XMPP->iq_client_password, XMPP->chardata, sizeof XMPP->iq_client_password);
338 striplt(XMPP->iq_client_password);
342 else if (!strcasecmp(el, "iq")) {
345 * iq type="get" (handle queries)
347 if (!strcasecmp(XMPP->iq_type, "get")) {
350 * Query on a namespace
352 if (!IsEmptyStr(XMPP->iq_query_xmlns)) {
353 xmpp_query_namespace(XMPP->iq_id, XMPP->iq_from, XMPP->iq_to, XMPP->iq_query_xmlns);
357 * ping ( http://xmpp.org/extensions/xep-0199.html )
359 else if (XMPP->ping_requested) {
360 cprintf("<iq type=\"result\" ");
361 if (!IsEmptyStr(XMPP->iq_from)) {
362 cprintf("to=\"%s\" ", xmlesc(xmlbuf, XMPP->iq_from, sizeof xmlbuf));
364 if (!IsEmptyStr(XMPP->iq_to)) {
365 cprintf("from=\"%s\" ", xmlesc(xmlbuf, XMPP->iq_to, sizeof xmlbuf));
367 cprintf("id=\"%s\"/>", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
371 * Unknown query ... return the XML equivalent of a blank stare
374 syslog(LOG_DEBUG, "xmpp: Unknown query <%s> - returning <service-unavailable/>", el);
375 cprintf("<iq type=\"error\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
376 cprintf("<error code=\"503\" type=\"cancel\">"
377 "<service-unavailable xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>"
385 * Non SASL authentication
388 (!strcasecmp(XMPP->iq_type, "set"))
389 && (!strcasecmp(XMPP->iq_query_xmlns, "jabber:iq:auth:query"))
392 xmpp_non_sasl_authenticate(
394 XMPP->iq_client_username,
395 XMPP->iq_client_password,
396 XMPP->iq_client_resource
401 * If this <iq> stanza was a "bind" attempt, process it ...
404 (XMPP->bind_requested)
405 && (!IsEmptyStr(XMPP->iq_id))
409 /* If the client has not specified a client resource, generate one */
411 if (IsEmptyStr(XMPP->iq_client_resource)) {
412 generate_uuid(XMPP->iq_client_resource);
415 /* Generate the "full JID" of the client resource */
416 snprintf(XMPP->client_jid, sizeof XMPP->client_jid, "%s/%s", CC->cs_inet_email, XMPP->iq_client_resource);
418 /* Tell the client what its JID is */
420 cprintf("<iq type=\"result\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
421 cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">");
422 cprintf("<jid>%s</jid>", xmlesc(xmlbuf, XMPP->client_jid, sizeof xmlbuf));
427 else if (XMPP->iq_session) {
428 cprintf("<iq type=\"result\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
433 cprintf("<iq type=\"error\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
434 cprintf("<error>Don't know how to do '%s'!</error>", xmlesc(xmlbuf, XMPP->iq_type, sizeof xmlbuf));
436 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);
439 /* Now clear these fields out so they don't get used by a future stanza */
441 XMPP->iq_from[0] = 0;
443 XMPP->iq_type[0] = 0;
444 XMPP->iq_client_resource[0] = 0;
445 XMPP->iq_session = 0;
446 XMPP->iq_query_xmlns[0] = 0;
447 XMPP->bind_requested = 0;
448 XMPP->ping_requested = 0;
451 else if (!strcasecmp(el, "auth")) {
453 /* Try to authenticate (this function is responsible for the output stanza) */
454 xmpp_sasl_auth(XMPP->sasl_auth_mech, (XMPP->chardata != NULL ? XMPP->chardata : "") );
456 /* Now clear these fields out so they don't get used by a future stanza */
457 XMPP->sasl_auth_mech[0] = 0;
460 else if (!strcasecmp(el, "session")) {
461 XMPP->iq_session = 1;
464 else if (!strcasecmp(el, "presence")) {
466 /* Respond to a <presence> update by firing back with presence information
467 * on the entire wholist. Check this assumption, it's probably wrong.
469 xmpp_wholist_presence_dump();
472 else if ( (!strcasecmp(el, "body")) && (XMPP->html_tag_level == 0) ) {
473 if (XMPP->message_body != NULL) {
474 free(XMPP->message_body);
475 XMPP->message_body = NULL;
477 if (XMPP->chardata_len > 0) {
478 XMPP->message_body = strdup(XMPP->chardata);
482 else if (!strcasecmp(el, "message")) {
483 xmpp_send_message(XMPP->message_to, XMPP->message_body);
484 XMPP->html_tag_level = 0;
487 else if (!strcasecmp(el, "html")) {
488 --XMPP->html_tag_level;
491 else if (!strcasecmp(el, "starttls")) {
493 cprintf("<proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
494 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
495 if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO;
497 cprintf("<failure xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
498 CC->kill_me = KILLME_NO_CRYPTO;
502 else if (!strcasecmp(el, "ping")) {
503 XMPP->ping_requested = 1;
506 else if (!strcasecmp(el, "stream")) {
507 syslog(LOG_DEBUG, "xmpp: client shut down their stream");
508 xmpp_massacre_roster();
509 cprintf("</stream>\n");
510 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
513 else if (!strcasecmp(el, "query")) {
514 /* already processed , no further action needed here */
517 else if (!strcasecmp(el, "bind")) {
518 /* already processed , no further action needed here */
522 syslog(LOG_DEBUG, "xmpp: ignoring unknown tag <%s>", el);
525 XMPP->chardata_len = 0;
526 if (XMPP->chardata_alloc > 0) {
527 XMPP->chardata[0] = 0;
532 void xmpp_xml_chardata(void *data, const XML_Char *s, int len)
536 if (X->chardata_alloc == 0) {
537 X->chardata_alloc = SIZ;
538 X->chardata = malloc(X->chardata_alloc);
540 if ((X->chardata_len + len + 1) > X->chardata_alloc) {
541 X->chardata_alloc = X->chardata_len + len + 1024;
542 X->chardata = realloc(X->chardata, X->chardata_alloc);
544 memcpy(&X->chardata[X->chardata_len], s, len);
545 X->chardata_len += len;
546 X->chardata[X->chardata_len] = 0;
551 * This cleanup function blows away the temporary memory and files used by the XMPP service.
553 void xmpp_cleanup_function(void) {
555 /* Don't do this stuff if this is not a XMPP session! */
556 if (CC->h_command_function != xmpp_command_loop) return;
558 if (XMPP->chardata != NULL) {
559 free(XMPP->chardata);
560 XMPP->chardata = NULL;
561 XMPP->chardata_len = 0;
562 XMPP->chardata_alloc = 0;
563 if (XMPP->message_body != NULL) {
564 free(XMPP->message_body);
567 XML_ParserFree(XMPP->xp);
573 * Here's where our XMPP session begins its happy day.
575 void xmpp_greeting(void) {
576 client_set_inbound_buf(4);
577 strcpy(CC->cs_clientname, "XMPP session");
578 CC->session_specific_data = malloc(sizeof(citxmpp));
579 memset(XMPP, 0, sizeof(citxmpp));
580 XMPP->last_event_processed = queue_event_seq;
582 /* XMPP does not use a greeting, but we still have to initialize some things. */
584 XMPP->xp = XML_ParserCreateNS("UTF-8", ':');
585 if (XMPP->xp == NULL) {
586 syslog(LOG_ERR, "xmpp: cannot create XML parser");
587 CC->kill_me = KILLME_XML_PARSER;
591 XML_SetElementHandler(XMPP->xp, xmpp_xml_start, xmpp_xml_end);
592 XML_SetCharacterDataHandler(XMPP->xp, xmpp_xml_chardata);
593 // XML_SetUserData(XMPP->xp, something...);
595 /* Prevent the "billion laughs" attack against expat by disabling
596 * internal entity expansion. With 2.x, forcibly stop the parser
597 * if an entity is declared - this is safer and a more obvious
598 * failure mode. With older versions, simply prevent expansion
599 * of such entities. */
600 #ifdef HAVE_XML_STOPPARSER
601 XML_SetEntityDeclHandler(XMPP->xp, xmpp_entity_declaration);
603 XML_SetDefaultHandler(XMPP->xp, NULL);
606 CC->can_receive_im = 1; /* This protocol is capable of receiving instant messages */
611 * Main command loop for XMPP sessions.
613 void xmpp_command_loop(void) {
615 StrBuf *stream_input = NewStrBuf();
618 rc = client_read_random_blob(stream_input, 30);
620 XML_Parse(XMPP->xp, ChrPtr(stream_input), rc, 0);
623 syslog(LOG_ERR, "xmpp: client disconnected: ending session.");
624 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
626 FreeStrBuf(&stream_input);
631 * Async loop for XMPP sessions (handles the transmission of unsolicited stanzas)
633 void xmpp_async_loop(void) {
634 xmpp_process_events();
635 xmpp_output_incoming_messages();
640 * Login hook for XMPP sessions
642 void xmpp_login_hook(void) {
643 xmpp_queue_event(XMPP_EVT_LOGIN, CC->cs_inet_email);
648 * Logout hook for XMPP sessions
650 void xmpp_logout_hook(void) {
651 xmpp_queue_event(XMPP_EVT_LOGOUT, CC->cs_inet_email);
655 const char *CitadelServiceXMPP="XMPP";
656 extern void xmpp_cleanup_events(void);
657 CTDL_MODULE_INIT(xmpp)
660 CtdlRegisterServiceHook(CtdlGetConfigInt("c_xmpp_c2s_port"),
667 CtdlRegisterSessionHook(xmpp_cleanup_function, EVT_STOP, PRIO_STOP + 70);
668 CtdlRegisterSessionHook(xmpp_login_hook, EVT_LOGIN, PRIO_LOGIN + 90);
669 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 90);
670 CtdlRegisterSessionHook(xmpp_login_hook, EVT_UNSTEALTH, PRIO_UNSTEALTH + 1);
671 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_STEALTH, PRIO_STEALTH + 1);
672 CtdlRegisterCleanupHook(xmpp_cleanup_events);
676 /* return our module name for the log */