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
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 #if XML_MAJOR_VERSION > 0
61 /* XML_StopParser is present in expat 2.x */
62 #define HAVE_XML_STOPPARSER
65 struct xmpp_event *xmpp_queue = NULL;
69 #ifdef HAVE_XML_STOPPARSER
70 /* Stop the parser if an entity declaration is hit. */
71 static void xmpp_entity_declaration(void *userData, const XML_Char *entityName,
72 int is_parameter_entity, const XML_Char *value,
73 int value_length, const XML_Char *base,
74 const XML_Char *systemId, const XML_Char *publicId,
75 const XML_Char *notationName
77 syslog(LOG_WARNING, "Illegal entity declaration encountered; stopping parser.");
78 XML_StopParser(XMPP->xp, XML_FALSE);
85 * Given a source string and a target buffer, returns the string
86 * properly escaped for insertion into an XML stream. Returns a
87 * pointer to the target buffer for convenience.
89 * BUG: this does not properly handle UTF-8
91 char *xmlesc(char *buf, char *str, int bufsiz)
97 if (!buf) return(NULL);
104 for (ptr=str; *ptr; ptr++) {
107 strcpy(&buf[len], "<");
110 else if (ch == '>') {
111 strcpy(&buf[len], ">");
114 else if (ch == '&') {
115 strcpy(&buf[len], "&");
118 else if ((ch >= 0x20) && (ch <= 0x7F)) {
122 else if (ch < 0x20) {
123 /* we probably shouldn't be doing this */
129 sprintf(oct, "&#%o;", ch);
130 strcpy(&buf[len], oct);
133 if ((len + 6) > bufsiz) {
142 * We have just received a <stream> tag from the client, so send them ours
144 void xmpp_stream_start(void *data, const char *supplied_el, const char **attr)
149 if (!strcasecmp(attr[0], "to")) {
150 safestrncpy(XMPP->server_name, attr[1], sizeof XMPP->server_name);
155 cprintf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
157 cprintf("<stream:stream ");
158 cprintf("from=\"%s\" ", xmlesc(xmlbuf, XMPP->server_name, sizeof xmlbuf));
159 cprintf("id=\"%08x\" ", CC->cs_pid);
160 cprintf("version=\"1.0\" ");
161 cprintf("xmlns:stream=\"http://etherx.jabber.org/streams\" ");
162 cprintf("xmlns=\"jabber:client\">");
164 /* The features of this stream are... */
165 cprintf("<stream:features>");
168 /* TLS encryption (but only if it isn't already active) */
169 if (!CC->redirect_ssl) {
170 cprintf("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'></starttls>");
174 if (!CC->logged_in) {
175 /* If we're not logged in yet, offer SASL as our feature set */
176 xmpp_output_auth_mechs();
178 /* Also offer non-SASL authentication */
179 cprintf("<auth xmlns=\"http://jabber.org/features/iq-auth\"/>");
182 /* Offer binding and sessions as part of our feature set */
183 cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>");
184 cprintf("<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>");
186 cprintf("</stream:features>");
188 CC->is_async = 1; /* XMPP sessions are inherently async-capable */
192 void xmpp_xml_start(void *data, const char *supplied_el, const char **attr) {
197 /* Axe the namespace, we don't care about it */
198 safestrncpy(el, supplied_el, sizeof el);
199 while (sep = strchr(el, ':'), sep) {
204 CtdlLogPrintf(CTDL_DEBUG, "XMPP ELEMENT START: <%s>\n", el);
205 for (i=0; attr[i] != NULL; i+=2) {
206 CtdlLogPrintf(CTDL_DEBUG, " Attribute '%s' = '%s'\n", attr[i], attr[i+1]);
208 uncomment for more verbosity */
210 if (!strcasecmp(el, "stream")) {
211 xmpp_stream_start(data, supplied_el, attr);
214 else if (!strcasecmp(el, "query")) {
215 XMPP->iq_query_xmlns[0] = 0;
216 safestrncpy(XMPP->iq_query_xmlns, supplied_el, sizeof XMPP->iq_query_xmlns);
219 else if (!strcasecmp(el, "bind")) {
220 XMPP->bind_requested = 1;
223 else if (!strcasecmp(el, "iq")) {
224 for (i=0; attr[i] != NULL; i+=2) {
225 if (!strcasecmp(attr[i], "type")) {
226 safestrncpy(XMPP->iq_type, attr[i+1], sizeof XMPP->iq_type);
228 else if (!strcasecmp(attr[i], "id")) {
229 safestrncpy(XMPP->iq_id, attr[i+1], sizeof XMPP->iq_id);
231 else if (!strcasecmp(attr[i], "from")) {
232 safestrncpy(XMPP->iq_from, attr[i+1], sizeof XMPP->iq_from);
234 else if (!strcasecmp(attr[i], "to")) {
235 safestrncpy(XMPP->iq_to, attr[i+1], sizeof XMPP->iq_to);
240 else if (!strcasecmp(el, "auth")) {
241 XMPP->sasl_auth_mech[0] = 0;
242 for (i=0; attr[i] != NULL; i+=2) {
243 if (!strcasecmp(attr[i], "mechanism")) {
244 safestrncpy(XMPP->sasl_auth_mech, attr[i+1], sizeof XMPP->sasl_auth_mech);
249 else if (!strcasecmp(el, "message")) {
250 for (i=0; attr[i] != NULL; i+=2) {
251 if (!strcasecmp(attr[i], "to")) {
252 safestrncpy(XMPP->message_to, attr[i+1], sizeof XMPP->message_to);
257 else if (!strcasecmp(el, "html")) {
258 ++XMPP->html_tag_level;
264 void xmpp_xml_end(void *data, const char *supplied_el) {
269 /* Axe the namespace, we don't care about it */
270 safestrncpy(el, supplied_el, sizeof el);
271 while (sep = strchr(el, ':'), sep) {
276 CtdlLogPrintf(CTDL_DEBUG, "XMPP ELEMENT END : <%s>\n", el);
277 if (XMPP->chardata_len > 0) {
278 CtdlLogPrintf(CTDL_DEBUG, " chardata: %s\n", XMPP->chardata);
280 uncomment for more verbosity */
282 if (!strcasecmp(el, "resource")) {
283 if (XMPP->chardata_len > 0) {
284 safestrncpy(XMPP->iq_client_resource, XMPP->chardata,
285 sizeof XMPP->iq_client_resource);
286 striplt(XMPP->iq_client_resource);
290 else if (!strcasecmp(el, "username")) { /* NON SASL ONLY */
291 if (XMPP->chardata_len > 0) {
292 safestrncpy(XMPP->iq_client_username, XMPP->chardata,
293 sizeof XMPP->iq_client_username);
294 striplt(XMPP->iq_client_username);
298 else if (!strcasecmp(el, "password")) { /* NON SASL ONLY */
299 if (XMPP->chardata_len > 0) {
300 safestrncpy(XMPP->iq_client_password, XMPP->chardata,
301 sizeof XMPP->iq_client_password);
302 striplt(XMPP->iq_client_password);
306 else if (!strcasecmp(el, "iq")) {
309 * iq type="get" (handle queries)
311 if (!strcasecmp(XMPP->iq_type, "get")) {
314 * Query on a namespace
316 if (!IsEmptyStr(XMPP->iq_query_xmlns)) {
317 xmpp_query_namespace(XMPP->iq_id, XMPP->iq_from,
318 XMPP->iq_to, XMPP->iq_query_xmlns);
322 * ping ( http://xmpp.org/extensions/xep-0199.html )
324 else if (XMPP->ping_requested) {
325 cprintf("<iq type=\"result\" ");
326 if (!IsEmptyStr(XMPP->iq_from)) {
327 cprintf("to=\"%s\" ", xmlesc(xmlbuf, XMPP->iq_from, sizeof xmlbuf));
329 if (!IsEmptyStr(XMPP->iq_to)) {
330 cprintf("from=\"%s\" ", xmlesc(xmlbuf, XMPP->iq_to, sizeof xmlbuf));
332 cprintf("id=\"%s\"/>", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
336 * Unknown query ... return the XML equivalent of a blank stare
339 CtdlLogPrintf(CTDL_DEBUG,
340 "Unknown query <%s> - returning <service-unavailable/>\n",
343 cprintf("<iq type=\"error\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
344 cprintf("<error code=\"503\" type=\"cancel\">"
345 "<service-unavailable xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>"
353 * Non SASL authentication
356 (!strcasecmp(XMPP->iq_type, "set"))
357 && (!strcasecmp(XMPP->iq_query_xmlns, "jabber:iq:auth:query"))
360 xmpp_non_sasl_authenticate(
362 XMPP->iq_client_username,
363 XMPP->iq_client_password,
364 XMPP->iq_client_resource
369 * If this <iq> stanza was a "bind" attempt, process it ...
372 (XMPP->bind_requested)
373 && (!IsEmptyStr(XMPP->iq_id))
374 && (!IsEmptyStr(XMPP->iq_client_resource))
378 /* Generate the "full JID" of the client resource */
380 snprintf(XMPP->client_jid, sizeof XMPP->client_jid,
383 XMPP->iq_client_resource
386 /* Tell the client what its JID is */
388 cprintf("<iq type=\"result\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
389 cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">");
390 cprintf("<jid>%s</jid>", xmlesc(xmlbuf, XMPP->client_jid, sizeof xmlbuf));
395 else if (XMPP->iq_session) {
396 cprintf("<iq type=\"result\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
401 cprintf("<iq type=\"error\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
402 cprintf("<error>Don't know howto do '%s'!</error>", xmlesc(xmlbuf, XMPP->iq_type, sizeof xmlbuf));
406 /* Now clear these fields out so they don't get used by a future stanza */
408 XMPP->iq_from[0] = 0;
410 XMPP->iq_type[0] = 0;
411 XMPP->iq_client_resource[0] = 0;
412 XMPP->iq_session = 0;
413 XMPP->iq_query_xmlns[0] = 0;
414 XMPP->bind_requested = 0;
415 XMPP->ping_requested = 0;
418 else if (!strcasecmp(el, "auth")) {
420 /* Try to authenticate (this function is responsible for the output stanza) */
421 xmpp_sasl_auth(XMPP->sasl_auth_mech, (XMPP->chardata != NULL ? XMPP->chardata : "") );
423 /* Now clear these fields out so they don't get used by a future stanza */
424 XMPP->sasl_auth_mech[0] = 0;
427 else if (!strcasecmp(el, "session")) {
428 XMPP->iq_session = 1;
431 else if (!strcasecmp(el, "presence")) {
433 /* Respond to a <presence> update by firing back with presence information
434 * on the entire wholist. Check this assumption, it's probably wrong.
436 xmpp_wholist_presence_dump();
439 else if ( (!strcasecmp(el, "body")) && (XMPP->html_tag_level == 0) ) {
440 if (XMPP->message_body != NULL) {
441 free(XMPP->message_body);
442 XMPP->message_body = NULL;
444 if (XMPP->chardata_len > 0) {
445 XMPP->message_body = strdup(XMPP->chardata);
449 else if (!strcasecmp(el, "message")) {
450 xmpp_send_message(XMPP->message_to, XMPP->message_body);
451 XMPP->html_tag_level = 0;
454 else if (!strcasecmp(el, "html")) {
455 --XMPP->html_tag_level;
458 else if (!strcasecmp(el, "starttls")) {
460 cprintf("<proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
461 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
462 if (!CC->redirect_ssl) CC->kill_me = 1;
464 cprintf("<failure xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
469 else if (!strcasecmp(el, "ping")) {
470 XMPP->ping_requested = 1;
473 else if (!strcasecmp(el, "stream")) {
474 CtdlLogPrintf(CTDL_DEBUG, "XMPP client shut down their stream\n");
475 xmpp_massacre_roster();
476 cprintf("</stream>\n");
481 CtdlLogPrintf(CTDL_DEBUG, "Ignoring unknown tag <%s>\n", el);
484 XMPP->chardata_len = 0;
485 if (XMPP->chardata_alloc > 0) {
486 XMPP->chardata[0] = 0;
491 void xmpp_xml_chardata(void *data, const XML_Char *s, int len)
495 if (X->chardata_alloc == 0) {
496 X->chardata_alloc = SIZ;
497 X->chardata = malloc(X->chardata_alloc);
499 if ((X->chardata_len + len + 1) > X->chardata_alloc) {
500 X->chardata_alloc = X->chardata_len + len + 1024;
501 X->chardata = realloc(X->chardata, X->chardata_alloc);
503 memcpy(&X->chardata[X->chardata_len], s, len);
504 X->chardata_len += len;
505 X->chardata[X->chardata_len] = 0;
510 * This cleanup function blows away the temporary memory and files used by the XMPP service.
512 void xmpp_cleanup_function(void) {
514 /* Don't do this stuff if this is not a XMPP session! */
515 if (CC->h_command_function != xmpp_command_loop) return;
517 if (XMPP->chardata != NULL) {
518 free(XMPP->chardata);
519 XMPP->chardata = NULL;
520 XMPP->chardata_len = 0;
521 XMPP->chardata_alloc = 0;
522 if (XMPP->message_body != NULL) {
523 free(XMPP->message_body);
526 XML_ParserFree(XMPP->xp);
533 * Here's where our XMPP session begins its happy day.
535 void xmpp_greeting(void) {
536 client_set_inbound_buf(4);
537 strcpy(CC->cs_clientname, "XMPP session");
538 CC->session_specific_data = malloc(sizeof(citxmpp));
539 memset(XMPP, 0, sizeof(citxmpp));
540 XMPP->last_event_processed = queue_event_seq;
542 /* XMPP does not use a greeting, but we still have to initialize some things. */
544 XMPP->xp = XML_ParserCreateNS("UTF-8", ':');
545 if (XMPP->xp == NULL) {
546 CtdlLogPrintf(CTDL_ALERT, "Cannot create XML parser!\n");
551 XML_SetElementHandler(XMPP->xp, xmpp_xml_start, xmpp_xml_end);
552 XML_SetCharacterDataHandler(XMPP->xp, xmpp_xml_chardata);
553 // XML_SetUserData(XMPP->xp, something...);
555 /* Prevent the "billion laughs" attack against expat by disabling
556 * internal entity expansion. With 2.x, forcibly stop the parser
557 * if an entity is declared - this is safer and a more obvious
558 * failure mode. With older versions, simply prevent expansion
559 * of such entities. */
560 #ifdef HAVE_XML_STOPPARSER
561 XML_SetEntityDeclHandler(XMPP->xp, xmpp_entity_declaration);
563 XML_SetDefaultHandler(XMPP->xp, NULL);
566 CC->can_receive_im = 1; /* This protocol is capable of receiving instant messages */
571 * Main command loop for XMPP sessions.
573 void xmpp_command_loop(void) {
575 StrBuf *stream_input = NewStrBuf();
578 rc = client_read_random_blob(stream_input, 30);
580 XML_Parse(XMPP->xp, ChrPtr(stream_input), rc, 0);
583 CtdlLogPrintf(CTDL_ERR, "Client disconnected: ending session.\n");
586 FreeStrBuf(&stream_input);
591 * Async loop for XMPP sessions (handles the transmission of unsolicited stanzas)
593 void xmpp_async_loop(void) {
594 xmpp_process_events();
595 xmpp_output_incoming_messages();
600 * Login hook for XMPP sessions
602 void xmpp_login_hook(void) {
603 xmpp_queue_event(XMPP_EVT_LOGIN, CC->cs_inet_email);
608 * Logout hook for XMPP sessions
610 void xmpp_logout_hook(void) {
611 xmpp_queue_event(XMPP_EVT_LOGOUT, CC->cs_inet_email);
615 const char *CitadelServiceXMPP="XMPP";
617 CTDL_MODULE_INIT(xmpp)
620 CtdlRegisterServiceHook(config.c_xmpp_c2s_port,
627 CtdlRegisterSessionHook(xmpp_cleanup_function, EVT_STOP);
628 CtdlRegisterSessionHook(xmpp_login_hook, EVT_LOGIN);
629 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_LOGOUT);
630 CtdlRegisterSessionHook(xmpp_login_hook, EVT_UNSTEALTH);
631 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_STEALTH);
634 /* return our Subversion id for the Log */