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
20 // uncomment for more verbosity
31 #include <sys/types.h>
33 #if TIME_WITH_SYS_TIME
34 # include <sys/time.h>
38 # include <sys/time.h>
48 #include <libcitadel.h>
52 #include "citserver.h"
58 #include "internet_addressing.h"
60 #include "ctdl_module.h"
61 #include "serv_xmpp.h"
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;
70 int XMPPSrvDebugEnable = 0;
74 #ifdef HAVE_XML_STOPPARSER
75 /* Stop the parser if an entity declaration is hit. */
76 static void xmpp_entity_declaration(void *userData, const XML_Char *entityName,
77 int is_parameter_entity, const XML_Char *value,
78 int value_length, const XML_Char *base,
79 const XML_Char *systemId, const XML_Char *publicId,
80 const XML_Char *notationName
82 syslog(LOG_WARNING, "Illegal entity declaration encountered; stopping parser.");
83 XML_StopParser(XMPP->xp, XML_FALSE);
87 static inline int XMPP_GetUtf8SequenceLength(const char *CharS, const char *CharE)
89 /* if this is is migrated to strbuf, remove this copy. */
91 unsigned char test = (1<<7);
93 if ((*CharS & 0xC0) != 0xC0)
97 ((test & ((unsigned char)*CharS)) != 0))
102 if ((n > 6) || ((CharE - CharS) < n))
109 * Given a source string and a target buffer, returns the string
110 * properly escaped for insertion into an XML stream. Returns a
111 * pointer to the target buffer for convenience.
113 * BUG: this does not properly handle UTF-8
115 char *xmlesc(char *buf, char *str, int bufsiz)
124 if (!buf) return(NULL);
134 for (ptr=str; *ptr; ptr++) {
137 strcpy(&buf[len], "<");
140 else if (ch == '>') {
141 strcpy(&buf[len], ">");
144 else if (ch == '&') {
145 strcpy(&buf[len], "&");
148 else if ((ch >= 0x20) && (ch <= 0x7F)) {
152 else if (ch < 0x20) {
153 /* we probably shouldn't be doing this */
160 IsUtf8Sequence = XMPP_GetUtf8SequenceLength(&buf[len], eiptr);
163 while (IsUtf8Sequence > 0){
166 if (--IsUtf8Sequence)
173 sprintf(oct, "&#%o;", ch);
174 strcpy(&buf[len], oct);
178 if ((len + 6) > bufsiz) {
187 * We have just received a <stream> tag from the client, so send them ours
189 void xmpp_stream_start(void *data, const char *supplied_el, const char **attr)
194 if (!strcasecmp(attr[0], "to")) {
195 safestrncpy(XMPP->server_name, attr[1], sizeof XMPP->server_name);
200 cprintf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
202 cprintf("<stream:stream ");
203 cprintf("from=\"%s\" ", xmlesc(xmlbuf, XMPP->server_name, sizeof xmlbuf));
204 cprintf("id=\"%08x\" ", CC->cs_pid);
205 cprintf("version=\"1.0\" ");
206 cprintf("xmlns:stream=\"http://etherx.jabber.org/streams\" ");
207 cprintf("xmlns=\"jabber:client\">");
209 /* The features of this stream are... */
210 cprintf("<stream:features>");
213 * TLS encryption (but only if it isn't already active)
216 if (!CC->redirect_ssl) {
217 cprintf("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'></starttls>");
221 if (!CC->logged_in) {
222 /* If we're not logged in yet, offer SASL as our feature set */
223 xmpp_output_auth_mechs();
225 /* Also offer non-SASL authentication */
226 cprintf("<auth xmlns=\"http://jabber.org/features/iq-auth\"/>");
229 /* Offer binding and sessions as part of our feature set */
230 cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>");
231 cprintf("<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>");
233 cprintf("</stream:features>");
235 CC->is_async = 1; /* XMPP sessions are inherently async-capable */
239 void xmpp_xml_start(void *data, const char *supplied_el, const char **attr) {
244 /* Axe the namespace, we don't care about it */
245 safestrncpy(el, supplied_el, sizeof el);
246 while (sep = strchr(el, ':'), sep) {
251 syslog(LOG_DEBUG, "XMPP ELEMENT START: <%s>\n", el);
252 for (i=0; attr[i] != NULL; i+=2) {
253 syslog(LOG_DEBUG, " Attribute '%s' = '%s'\n", attr[i], attr[i+1]);
255 #endif /* XMPP_DEBUG */
257 if (!strcasecmp(el, "stream")) {
258 xmpp_stream_start(data, supplied_el, attr);
261 else if (!strcasecmp(el, "query")) {
262 XMPP->iq_query_xmlns[0] = 0;
263 safestrncpy(XMPP->iq_query_xmlns, supplied_el, sizeof XMPP->iq_query_xmlns);
266 else if (!strcasecmp(el, "bind")) {
267 XMPP->bind_requested = 1;
270 else if (!strcasecmp(el, "iq")) {
271 for (i=0; attr[i] != NULL; i+=2) {
272 if (!strcasecmp(attr[i], "type")) {
273 safestrncpy(XMPP->iq_type, attr[i+1], sizeof XMPP->iq_type);
275 else if (!strcasecmp(attr[i], "id")) {
276 safestrncpy(XMPP->iq_id, attr[i+1], sizeof XMPP->iq_id);
278 else if (!strcasecmp(attr[i], "from")) {
279 safestrncpy(XMPP->iq_from, attr[i+1], sizeof XMPP->iq_from);
281 else if (!strcasecmp(attr[i], "to")) {
282 safestrncpy(XMPP->iq_to, attr[i+1], sizeof XMPP->iq_to);
287 else if (!strcasecmp(el, "auth")) {
288 XMPP->sasl_auth_mech[0] = 0;
289 for (i=0; attr[i] != NULL; i+=2) {
290 if (!strcasecmp(attr[i], "mechanism")) {
291 safestrncpy(XMPP->sasl_auth_mech, attr[i+1], sizeof XMPP->sasl_auth_mech);
296 else if (!strcasecmp(el, "message")) {
297 for (i=0; attr[i] != NULL; i+=2) {
298 if (!strcasecmp(attr[i], "to")) {
299 safestrncpy(XMPP->message_to, attr[i+1], sizeof XMPP->message_to);
304 else if (!strcasecmp(el, "html")) {
305 ++XMPP->html_tag_level;
311 void xmpp_xml_end(void *data, const char *supplied_el) {
316 /* Axe the namespace, we don't care about it */
317 safestrncpy(el, supplied_el, sizeof el);
318 while (sep = strchr(el, ':'), sep) {
323 syslog(LOG_DEBUG, "XMPP ELEMENT END : <%s>\n", el);
324 if (XMPP->chardata_len > 0) {
325 syslog(LOG_DEBUG, " chardata: %s\n", XMPP->chardata);
327 #endif /* XMPP_DEBUG */
329 if (!strcasecmp(el, "resource")) {
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 else if (!strcasecmp(el, "username")) { /* NON SASL ONLY */
338 if (XMPP->chardata_len > 0) {
339 safestrncpy(XMPP->iq_client_username, XMPP->chardata,
340 sizeof XMPP->iq_client_username);
341 striplt(XMPP->iq_client_username);
345 else if (!strcasecmp(el, "password")) { /* NON SASL ONLY */
346 if (XMPP->chardata_len > 0) {
347 safestrncpy(XMPP->iq_client_password, XMPP->chardata,
348 sizeof XMPP->iq_client_password);
349 striplt(XMPP->iq_client_password);
353 else if (!strcasecmp(el, "iq")) {
356 * iq type="get" (handle queries)
358 if (!strcasecmp(XMPP->iq_type, "get")) {
361 * Query on a namespace
363 if (!IsEmptyStr(XMPP->iq_query_xmlns)) {
364 xmpp_query_namespace(XMPP->iq_id, XMPP->iq_from,
365 XMPP->iq_to, XMPP->iq_query_xmlns);
369 * ping ( http://xmpp.org/extensions/xep-0199.html )
371 else if (XMPP->ping_requested) {
372 cprintf("<iq type=\"result\" ");
373 if (!IsEmptyStr(XMPP->iq_from)) {
374 cprintf("to=\"%s\" ", xmlesc(xmlbuf, XMPP->iq_from, sizeof xmlbuf));
376 if (!IsEmptyStr(XMPP->iq_to)) {
377 cprintf("from=\"%s\" ", xmlesc(xmlbuf, XMPP->iq_to, sizeof xmlbuf));
379 cprintf("id=\"%s\"/>", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
383 * Unknown query ... return the XML equivalent of a blank stare
387 "Unknown query <%s> - returning <service-unavailable/>\n",
390 cprintf("<iq type=\"error\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
391 cprintf("<error code=\"503\" type=\"cancel\">"
392 "<service-unavailable xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>"
400 * Non SASL authentication
403 (!strcasecmp(XMPP->iq_type, "set"))
404 && (!strcasecmp(XMPP->iq_query_xmlns, "jabber:iq:auth:query"))
407 xmpp_non_sasl_authenticate(
409 XMPP->iq_client_username,
410 XMPP->iq_client_password,
411 XMPP->iq_client_resource
416 * If this <iq> stanza was a "bind" attempt, process it ...
419 (XMPP->bind_requested)
420 && (!IsEmptyStr(XMPP->iq_id))
421 && (!IsEmptyStr(XMPP->iq_client_resource))
425 /* Generate the "full JID" of the client resource */
427 snprintf(XMPP->client_jid, sizeof XMPP->client_jid,
430 XMPP->iq_client_resource
433 /* Tell the client what its JID is */
435 cprintf("<iq type=\"result\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
436 cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">");
437 cprintf("<jid>%s</jid>", xmlesc(xmlbuf, XMPP->client_jid, sizeof xmlbuf));
442 else if (XMPP->iq_session) {
443 cprintf("<iq type=\"result\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
448 cprintf("<iq type=\"error\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
449 cprintf("<error>Don't know howto do '%s'!</error>", xmlesc(xmlbuf, XMPP->iq_type, sizeof xmlbuf));
453 /* Now clear these fields out so they don't get used by a future stanza */
455 XMPP->iq_from[0] = 0;
457 XMPP->iq_type[0] = 0;
458 XMPP->iq_client_resource[0] = 0;
459 XMPP->iq_session = 0;
460 XMPP->iq_query_xmlns[0] = 0;
461 XMPP->bind_requested = 0;
462 XMPP->ping_requested = 0;
465 else if (!strcasecmp(el, "auth")) {
467 /* Try to authenticate (this function is responsible for the output stanza) */
468 xmpp_sasl_auth(XMPP->sasl_auth_mech, (XMPP->chardata != NULL ? XMPP->chardata : "") );
470 /* Now clear these fields out so they don't get used by a future stanza */
471 XMPP->sasl_auth_mech[0] = 0;
474 else if (!strcasecmp(el, "session")) {
475 XMPP->iq_session = 1;
478 else if (!strcasecmp(el, "presence")) {
480 /* Respond to a <presence> update by firing back with presence information
481 * on the entire wholist. Check this assumption, it's probably wrong.
483 xmpp_wholist_presence_dump();
486 else if ( (!strcasecmp(el, "body")) && (XMPP->html_tag_level == 0) ) {
487 if (XMPP->message_body != NULL) {
488 free(XMPP->message_body);
489 XMPP->message_body = NULL;
491 if (XMPP->chardata_len > 0) {
492 XMPP->message_body = strdup(XMPP->chardata);
496 else if (!strcasecmp(el, "message")) {
497 xmpp_send_message(XMPP->message_to, XMPP->message_body);
498 XMPP->html_tag_level = 0;
501 else if (!strcasecmp(el, "html")) {
502 --XMPP->html_tag_level;
505 else if (!strcasecmp(el, "starttls")) {
507 cprintf("<proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
508 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
509 if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO;
511 cprintf("<failure xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
512 CC->kill_me = KILLME_NO_CRYPTO;
516 else if (!strcasecmp(el, "ping")) {
517 XMPP->ping_requested = 1;
520 else if (!strcasecmp(el, "stream")) {
521 syslog(LOG_DEBUG, "XMPP client shut down their stream\n");
522 xmpp_massacre_roster();
523 cprintf("</stream>\n");
524 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
527 else if (!strcasecmp(el, "query")) {
528 // no action required here, we picked up the xmlns= parameter during xmpp_xml_start()
532 syslog(LOG_DEBUG, "Ignoring unknown tag <%s>\n", el);
535 XMPP->chardata_len = 0;
536 if (XMPP->chardata_alloc > 0) {
537 XMPP->chardata[0] = 0;
542 void xmpp_xml_chardata(void *data, const XML_Char *s, int len)
546 if (X->chardata_alloc == 0) {
547 X->chardata_alloc = SIZ;
548 X->chardata = malloc(X->chardata_alloc);
550 if ((X->chardata_len + len + 1) > X->chardata_alloc) {
551 X->chardata_alloc = X->chardata_len + len + 1024;
552 X->chardata = realloc(X->chardata, X->chardata_alloc);
554 memcpy(&X->chardata[X->chardata_len], s, len);
555 X->chardata_len += len;
556 X->chardata[X->chardata_len] = 0;
561 * This cleanup function blows away the temporary memory and files used by the XMPP service.
563 void xmpp_cleanup_function(void) {
565 /* Don't do this stuff if this is not a XMPP session! */
566 if (CC->h_command_function != xmpp_command_loop) return;
568 if (XMPP->chardata != NULL) {
569 free(XMPP->chardata);
570 XMPP->chardata = NULL;
571 XMPP->chardata_len = 0;
572 XMPP->chardata_alloc = 0;
573 if (XMPP->message_body != NULL) {
574 free(XMPP->message_body);
577 XML_ParserFree(XMPP->xp);
584 * Here's where our XMPP session begins its happy day.
586 void xmpp_greeting(void) {
587 client_set_inbound_buf(4);
588 strcpy(CC->cs_clientname, "XMPP session");
589 CC->session_specific_data = malloc(sizeof(citxmpp));
590 memset(XMPP, 0, sizeof(citxmpp));
591 XMPP->last_event_processed = queue_event_seq;
593 /* XMPP does not use a greeting, but we still have to initialize some things. */
595 XMPP->xp = XML_ParserCreateNS("UTF-8", ':');
596 if (XMPP->xp == NULL) {
597 syslog(LOG_ALERT, "Cannot create XML parser!\n");
598 CC->kill_me = KILLME_XML_PARSER;
602 XML_SetElementHandler(XMPP->xp, xmpp_xml_start, xmpp_xml_end);
603 XML_SetCharacterDataHandler(XMPP->xp, xmpp_xml_chardata);
604 // XML_SetUserData(XMPP->xp, something...);
606 /* Prevent the "billion laughs" attack against expat by disabling
607 * internal entity expansion. With 2.x, forcibly stop the parser
608 * if an entity is declared - this is safer and a more obvious
609 * failure mode. With older versions, simply prevent expansion
610 * of such entities. */
611 #ifdef HAVE_XML_STOPPARSER
612 XML_SetEntityDeclHandler(XMPP->xp, xmpp_entity_declaration);
614 XML_SetDefaultHandler(XMPP->xp, NULL);
617 CC->can_receive_im = 1; /* This protocol is capable of receiving instant messages */
622 * Main command loop for XMPP sessions.
624 void xmpp_command_loop(void) {
626 StrBuf *stream_input = NewStrBuf();
629 rc = client_read_random_blob(stream_input, 30);
631 syslog(LOG_DEBUG, "\033[32m%s\033[0m", ChrPtr(stream_input));
632 XML_Parse(XMPP->xp, ChrPtr(stream_input), rc, 0);
635 syslog(LOG_ERR, "client disconnected: ending session.\n");
636 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
638 FreeStrBuf(&stream_input);
643 * Async loop for XMPP sessions (handles the transmission of unsolicited stanzas)
645 void xmpp_async_loop(void) {
646 xmpp_process_events();
647 xmpp_output_incoming_messages();
652 * Login hook for XMPP sessions
654 void xmpp_login_hook(void) {
655 xmpp_queue_event(XMPP_EVT_LOGIN, CC->cs_inet_email);
660 * Logout hook for XMPP sessions
662 void xmpp_logout_hook(void) {
663 xmpp_queue_event(XMPP_EVT_LOGOUT, CC->cs_inet_email);
667 void LogXMPPSrvDebugEnable(const int n)
669 XMPPSrvDebugEnable = n;
671 const char *CitadelServiceXMPP="XMPP";
672 extern void xmpp_cleanup_events(void);
673 CTDL_MODULE_INIT(xmpp)
676 CtdlRegisterServiceHook(config.c_xmpp_c2s_port,
683 CtdlRegisterDebugFlagHook(HKEY("serv_xmpp"), LogXMPPSrvDebugEnable, &XMPPSrvDebugEnable);
684 CtdlRegisterSessionHook(xmpp_cleanup_function, EVT_STOP, PRIO_STOP + 70);
685 CtdlRegisterSessionHook(xmpp_login_hook, EVT_LOGIN, PRIO_LOGIN + 90);
686 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 90);
687 CtdlRegisterSessionHook(xmpp_login_hook, EVT_UNSTEALTH, PRIO_UNSTEALTH + 1);
688 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_STEALTH, PRIO_STEALTH + 1);
689 CtdlRegisterCleanupHook(xmpp_cleanup_events);
693 /* return our module name for the log */