86685664d5dc65a7b5db06a59683c081594d982e
[citadel.git] / citadel / modules / xmpp / serv_xmpp.c
1 /*
2  * XMPP (Jabber) service for the Citadel system
3  * Copyright (c) 2007-2011 by Art Cancro
4  *
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.
9  *
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.
14  *
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
18  */
19
20 #include "sysdep.h"
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <stdio.h>
24 #include <fcntl.h>
25 #include <signal.h>
26 #include <pwd.h>
27 #include <errno.h>
28 #include <sys/types.h>
29
30 #if TIME_WITH_SYS_TIME
31 # include <sys/time.h>
32 # include <time.h>
33 #else
34 # if HAVE_SYS_TIME_H
35 #  include <sys/time.h>
36 # else
37 #  include <time.h>
38 # endif
39 #endif
40
41 #include <sys/wait.h>
42 #include <string.h>
43 #include <limits.h>
44 #include <ctype.h>
45 #include <libcitadel.h>
46 #include <expat.h>
47 #include "citadel.h"
48 #include "server.h"
49 #include "citserver.h"
50 #include "support.h"
51 #include "config.h"
52 #include "user_ops.h"
53 #include "database.h"
54 #include "msgbase.h"
55 #include "internet_addressing.h"
56 #include "md5.h"
57 #include "ctdl_module.h"
58 #include "serv_xmpp.h"
59
60 /* XML_StopParser is present in expat 2.x */
61 #if XML_MAJOR_VERSION > 1
62 #define HAVE_XML_STOPPARSER
63 #endif
64
65 struct xmpp_event *xmpp_queue = NULL;
66
67
68
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
76 ) {
77         syslog(LOG_WARNING, "Illegal entity declaration encountered; stopping parser.");
78         XML_StopParser(XMPP->xp, XML_FALSE);
79 }
80 #endif
81
82
83
84 /*
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.
88  *
89  * BUG: this does not properly handle UTF-8
90  */
91 char *xmlesc(char *buf, char *str, int bufsiz)
92 {
93         char *ptr;
94         unsigned char ch;
95         int len = 0;
96
97         if (!buf) return(NULL);
98         buf[0] = 0;
99         len = 0;
100         if (!str) {
101                 return(buf);
102         }
103
104         for (ptr=str; *ptr; ptr++) {
105                 ch = *ptr;
106                 if (ch == '<') {
107                         strcpy(&buf[len], "&lt;");
108                         len += 4;
109                 }
110                 else if (ch == '>') {
111                         strcpy(&buf[len], "&gt;");
112                         len += 4;
113                 }
114                 else if (ch == '&') {
115                         strcpy(&buf[len], "&amp;");
116                         len += 5;
117                 }
118                 else if ((ch >= 0x20) && (ch <= 0x7F)) {
119                         buf[len++] = ch;
120                         buf[len] = 0;
121                 }
122                 else if (ch < 0x20) {
123                         /* we probably shouldn't be doing this */
124                         buf[len++] = '_';
125                         buf[len] = 0;
126                 }
127                 else {
128                         char oct[10];
129                         sprintf(oct, "&#%o;", ch);
130                         strcpy(&buf[len], oct);
131                         len += strlen(oct);
132                 }
133                 if ((len + 6) > bufsiz) {
134                         return(buf);
135                 }
136         }
137         return(buf);
138 }
139
140
141 /*
142  * We have just received a <stream> tag from the client, so send them ours
143  */
144 void xmpp_stream_start(void *data, const char *supplied_el, const char **attr)
145 {
146         char xmlbuf[256];
147
148         while (*attr) {
149                 if (!strcasecmp(attr[0], "to")) {
150                         safestrncpy(XMPP->server_name, attr[1], sizeof XMPP->server_name);
151                 }
152                 attr += 2;
153         }
154
155         cprintf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
156
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\">");
163
164         /* The features of this stream are... */
165         cprintf("<stream:features>");
166
167         /*
168          * TLS encryption (but only if it isn't already active)
169          */ 
170 #ifdef HAVE_OPENSSL
171         if (!CC->redirect_ssl) {
172                 cprintf("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'></starttls>");
173         }
174 #endif
175
176         if (!CC->logged_in) {
177                 /* If we're not logged in yet, offer SASL as our feature set */
178                 xmpp_output_auth_mechs();
179
180                 /* Also offer non-SASL authentication */
181                 cprintf("<auth xmlns=\"http://jabber.org/features/iq-auth\"/>");
182         }
183
184         /* Offer binding and sessions as part of our feature set */
185         cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>");
186         cprintf("<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>");
187
188         cprintf("</stream:features>");
189
190         CC->is_async = 1;               /* XMPP sessions are inherently async-capable */
191 }
192
193
194 void xmpp_xml_start(void *data, const char *supplied_el, const char **attr) {
195         char el[256];
196         char *sep = NULL;
197         int i;
198
199         /* Axe the namespace, we don't care about it */
200         safestrncpy(el, supplied_el, sizeof el);
201         while (sep = strchr(el, ':'), sep) {
202                 strcpy(el, ++sep);
203         }
204
205         /*
206         syslog(LOG_DEBUG, "XMPP ELEMENT START: <%s>\n", el);
207         for (i=0; attr[i] != NULL; i+=2) {
208                 syslog(LOG_DEBUG, "                    Attribute '%s' = '%s'\n", attr[i], attr[i+1]);
209         }
210         uncomment for more verbosity */
211
212         if (!strcasecmp(el, "stream")) {
213                 xmpp_stream_start(data, supplied_el, attr);
214         }
215
216         else if (!strcasecmp(el, "query")) {
217                 XMPP->iq_query_xmlns[0] = 0;
218                 safestrncpy(XMPP->iq_query_xmlns, supplied_el, sizeof XMPP->iq_query_xmlns);
219         }
220
221         else if (!strcasecmp(el, "bind")) {
222                 XMPP->bind_requested = 1;
223         }
224
225         else if (!strcasecmp(el, "iq")) {
226                 for (i=0; attr[i] != NULL; i+=2) {
227                         if (!strcasecmp(attr[i], "type")) {
228                                 safestrncpy(XMPP->iq_type, attr[i+1], sizeof XMPP->iq_type);
229                         }
230                         else if (!strcasecmp(attr[i], "id")) {
231                                 safestrncpy(XMPP->iq_id, attr[i+1], sizeof XMPP->iq_id);
232                         }
233                         else if (!strcasecmp(attr[i], "from")) {
234                                 safestrncpy(XMPP->iq_from, attr[i+1], sizeof XMPP->iq_from);
235                         }
236                         else if (!strcasecmp(attr[i], "to")) {
237                                 safestrncpy(XMPP->iq_to, attr[i+1], sizeof XMPP->iq_to);
238                         }
239                 }
240         }
241
242         else if (!strcasecmp(el, "auth")) {
243                 XMPP->sasl_auth_mech[0] = 0;
244                 for (i=0; attr[i] != NULL; i+=2) {
245                         if (!strcasecmp(attr[i], "mechanism")) {
246                                 safestrncpy(XMPP->sasl_auth_mech, attr[i+1], sizeof XMPP->sasl_auth_mech);
247                         }
248                 }
249         }
250
251         else if (!strcasecmp(el, "message")) {
252                 for (i=0; attr[i] != NULL; i+=2) {
253                         if (!strcasecmp(attr[i], "to")) {
254                                 safestrncpy(XMPP->message_to, attr[i+1], sizeof XMPP->message_to);
255                         }
256                 }
257         }
258
259         else if (!strcasecmp(el, "html")) {
260                 ++XMPP->html_tag_level;
261         }
262 }
263
264
265
266 void xmpp_xml_end(void *data, const char *supplied_el) {
267         char el[256];
268         char *sep = NULL;
269         char xmlbuf[256];
270
271         /* Axe the namespace, we don't care about it */
272         safestrncpy(el, supplied_el, sizeof el);
273         while (sep = strchr(el, ':'), sep) {
274                 strcpy(el, ++sep);
275         }
276
277         /*
278         syslog(LOG_DEBUG, "XMPP ELEMENT END  : <%s>\n", el);
279         if (XMPP->chardata_len > 0) {
280                 syslog(LOG_DEBUG, "          chardata: %s\n", XMPP->chardata);
281         }
282         uncomment for more verbosity */
283
284         if (!strcasecmp(el, "resource")) {
285                 if (XMPP->chardata_len > 0) {
286                         safestrncpy(XMPP->iq_client_resource, XMPP->chardata,
287                                 sizeof XMPP->iq_client_resource);
288                         striplt(XMPP->iq_client_resource);
289                 }
290         }
291
292         else if (!strcasecmp(el, "username")) {         /* NON SASL ONLY */
293                 if (XMPP->chardata_len > 0) {
294                         safestrncpy(XMPP->iq_client_username, XMPP->chardata,
295                                 sizeof XMPP->iq_client_username);
296                         striplt(XMPP->iq_client_username);
297                 }
298         }
299
300         else if (!strcasecmp(el, "password")) {         /* NON SASL ONLY */
301                 if (XMPP->chardata_len > 0) {
302                         safestrncpy(XMPP->iq_client_password, XMPP->chardata,
303                                 sizeof XMPP->iq_client_password);
304                         striplt(XMPP->iq_client_password);
305                 }
306         }
307
308         else if (!strcasecmp(el, "iq")) {
309
310                 /*
311                  * iq type="get" (handle queries)
312                  */
313                 if (!strcasecmp(XMPP->iq_type, "get")) {
314
315                         /*
316                          * Query on a namespace
317                          */
318                         if (!IsEmptyStr(XMPP->iq_query_xmlns)) {
319                                 xmpp_query_namespace(XMPP->iq_id, XMPP->iq_from,
320                                                 XMPP->iq_to, XMPP->iq_query_xmlns);
321                         }
322
323                         /*
324                          * ping ( http://xmpp.org/extensions/xep-0199.html )
325                          */
326                         else if (XMPP->ping_requested) {
327                                 cprintf("<iq type=\"result\" ");
328                                 if (!IsEmptyStr(XMPP->iq_from)) {
329                                         cprintf("to=\"%s\" ", xmlesc(xmlbuf, XMPP->iq_from, sizeof xmlbuf));
330                                 }
331                                 if (!IsEmptyStr(XMPP->iq_to)) {
332                                         cprintf("from=\"%s\" ", xmlesc(xmlbuf, XMPP->iq_to, sizeof xmlbuf));
333                                 }
334                                 cprintf("id=\"%s\"/>", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
335                         }
336
337                         /*
338                          * Unknown query ... return the XML equivalent of a blank stare
339                          */
340                         else {
341                                 syslog(LOG_DEBUG,
342                                         "Unknown query <%s> - returning <service-unavailable/>\n",
343                                         el
344                                 );
345                                 cprintf("<iq type=\"error\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
346                                 cprintf("<error code=\"503\" type=\"cancel\">"
347                                         "<service-unavailable xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>"
348                                         "</error>"
349                                 );
350                                 cprintf("</iq>");
351                         }
352                 }
353
354                 /*
355                  * Non SASL authentication
356                  */
357                 else if (
358                         (!strcasecmp(XMPP->iq_type, "set"))
359                         && (!strcasecmp(XMPP->iq_query_xmlns, "jabber:iq:auth:query"))
360                         ) {
361
362                         xmpp_non_sasl_authenticate(
363                                 XMPP->iq_id,
364                                 XMPP->iq_client_username,
365                                 XMPP->iq_client_password,
366                                 XMPP->iq_client_resource
367                         );
368                 }       
369
370                 /*
371                  * If this <iq> stanza was a "bind" attempt, process it ...
372                  */
373                 else if (
374                         (XMPP->bind_requested)
375                         && (!IsEmptyStr(XMPP->iq_id))
376                         && (!IsEmptyStr(XMPP->iq_client_resource))
377                         && (CC->logged_in)
378                         ) {
379
380                         /* Generate the "full JID" of the client resource */
381
382                         snprintf(XMPP->client_jid, sizeof XMPP->client_jid,
383                                 "%s/%s",
384                                 CC->cs_inet_email,
385                                 XMPP->iq_client_resource
386                         );
387
388                         /* Tell the client what its JID is */
389
390                         cprintf("<iq type=\"result\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
391                         cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">");
392                         cprintf("<jid>%s</jid>", xmlesc(xmlbuf, XMPP->client_jid, sizeof xmlbuf));
393                         cprintf("</bind>");
394                         cprintf("</iq>");
395                 }
396
397                 else if (XMPP->iq_session) {
398                         cprintf("<iq type=\"result\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
399                         cprintf("</iq>");
400                 }
401
402                 else {
403                         cprintf("<iq type=\"error\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
404                         cprintf("<error>Don't know howto do '%s'!</error>", xmlesc(xmlbuf, XMPP->iq_type, sizeof xmlbuf));
405                         cprintf("</iq>");
406                 }
407
408                 /* Now clear these fields out so they don't get used by a future stanza */
409                 XMPP->iq_id[0] = 0;
410                 XMPP->iq_from[0] = 0;
411                 XMPP->iq_to[0] = 0;
412                 XMPP->iq_type[0] = 0;
413                 XMPP->iq_client_resource[0] = 0;
414                 XMPP->iq_session = 0;
415                 XMPP->iq_query_xmlns[0] = 0;
416                 XMPP->bind_requested = 0;
417                 XMPP->ping_requested = 0;
418         }
419
420         else if (!strcasecmp(el, "auth")) {
421
422                 /* Try to authenticate (this function is responsible for the output stanza) */
423                 xmpp_sasl_auth(XMPP->sasl_auth_mech, (XMPP->chardata != NULL ? XMPP->chardata : "") );
424
425                 /* Now clear these fields out so they don't get used by a future stanza */
426                 XMPP->sasl_auth_mech[0] = 0;
427         }
428
429         else if (!strcasecmp(el, "session")) {
430                 XMPP->iq_session = 1;
431         }
432
433         else if (!strcasecmp(el, "presence")) {
434
435                 /* Respond to a <presence> update by firing back with presence information
436                  * on the entire wholist.  Check this assumption, it's probably wrong.
437                  */
438                 xmpp_wholist_presence_dump();
439         }
440
441         else if ( (!strcasecmp(el, "body")) && (XMPP->html_tag_level == 0) ) {
442                 if (XMPP->message_body != NULL) {
443                         free(XMPP->message_body);
444                         XMPP->message_body = NULL;
445                 }
446                 if (XMPP->chardata_len > 0) {
447                         XMPP->message_body = strdup(XMPP->chardata);
448                 }
449         }
450
451         else if (!strcasecmp(el, "message")) {
452                 xmpp_send_message(XMPP->message_to, XMPP->message_body);
453                 XMPP->html_tag_level = 0;
454         }
455
456         else if (!strcasecmp(el, "html")) {
457                 --XMPP->html_tag_level;
458         }
459
460         else if (!strcasecmp(el, "starttls")) {
461 #ifdef HAVE_OPENSSL
462                 cprintf("<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;
465 #else
466                 cprintf("<failure xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
467                 CC->kill_me = KILLME_NO_CRYPTO;
468 #endif
469         }
470
471         else if (!strcasecmp(el, "ping")) {
472                 XMPP->ping_requested = 1;
473         }
474
475         else if (!strcasecmp(el, "stream")) {
476                 syslog(LOG_DEBUG, "XMPP client shut down their stream\n");
477                 xmpp_massacre_roster();
478                 cprintf("</stream>\n");
479                 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
480         }
481
482         else {
483                 syslog(LOG_DEBUG, "Ignoring unknown tag <%s>\n", el);
484         }
485
486         XMPP->chardata_len = 0;
487         if (XMPP->chardata_alloc > 0) {
488                 XMPP->chardata[0] = 0;
489         }
490 }
491
492
493 void xmpp_xml_chardata(void *data, const XML_Char *s, int len)
494 {
495         citxmpp *X = XMPP;
496
497         if (X->chardata_alloc == 0) {
498                 X->chardata_alloc = SIZ;
499                 X->chardata = malloc(X->chardata_alloc);
500         }
501         if ((X->chardata_len + len + 1) > X->chardata_alloc) {
502                 X->chardata_alloc = X->chardata_len + len + 1024;
503                 X->chardata = realloc(X->chardata, X->chardata_alloc);
504         }
505         memcpy(&X->chardata[X->chardata_len], s, len);
506         X->chardata_len += len;
507         X->chardata[X->chardata_len] = 0;
508 }
509
510
511 /*
512  * This cleanup function blows away the temporary memory and files used by the XMPP service.
513  */
514 void xmpp_cleanup_function(void) {
515
516         /* Don't do this stuff if this is not a XMPP session! */
517         if (CC->h_command_function != xmpp_command_loop) return;
518
519         if (XMPP->chardata != NULL) {
520                 free(XMPP->chardata);
521                 XMPP->chardata = NULL;
522                 XMPP->chardata_len = 0;
523                 XMPP->chardata_alloc = 0;
524                 if (XMPP->message_body != NULL) {
525                         free(XMPP->message_body);
526                 }
527         }
528         XML_ParserFree(XMPP->xp);
529         free(XMPP);
530 }
531
532
533
534 /*
535  * Here's where our XMPP session begins its happy day.
536  */
537 void xmpp_greeting(void) {
538         client_set_inbound_buf(4);
539         strcpy(CC->cs_clientname, "XMPP session");
540         CC->session_specific_data = malloc(sizeof(citxmpp));
541         memset(XMPP, 0, sizeof(citxmpp));
542         XMPP->last_event_processed = queue_event_seq;
543
544         /* XMPP does not use a greeting, but we still have to initialize some things. */
545
546         XMPP->xp = XML_ParserCreateNS("UTF-8", ':');
547         if (XMPP->xp == NULL) {
548                 syslog(LOG_ALERT, "Cannot create XML parser!\n");
549                 CC->kill_me = KILLME_XML_PARSER;
550                 return;
551         }
552
553         XML_SetElementHandler(XMPP->xp, xmpp_xml_start, xmpp_xml_end);
554         XML_SetCharacterDataHandler(XMPP->xp, xmpp_xml_chardata);
555         // XML_SetUserData(XMPP->xp, something...);
556
557         /* Prevent the "billion laughs" attack against expat by disabling
558          * internal entity expansion.  With 2.x, forcibly stop the parser
559          * if an entity is declared - this is safer and a more obvious
560          * failure mode.  With older versions, simply prevent expansion
561          * of such entities. */
562 #ifdef HAVE_XML_STOPPARSER
563         XML_SetEntityDeclHandler(XMPP->xp, xmpp_entity_declaration);
564 #else
565         XML_SetDefaultHandler(XMPP->xp, NULL);
566 #endif
567
568         CC->can_receive_im = 1;         /* This protocol is capable of receiving instant messages */
569 }
570
571
572 /* 
573  * Main command loop for XMPP sessions.
574  */
575 void xmpp_command_loop(void) {
576         int rc;
577         StrBuf *stream_input = NewStrBuf();
578
579         time(&CC->lastcmd);
580         rc = client_read_random_blob(stream_input, 30);
581         if (rc > 0) {
582                 XML_Parse(XMPP->xp, ChrPtr(stream_input), rc, 0);
583         }
584         else {
585                 syslog(LOG_ERR, "XMPP: client disconnected: ending session.\n");
586                 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
587         }
588         FreeStrBuf(&stream_input);
589 }
590
591
592 /*
593  * Async loop for XMPP sessions (handles the transmission of unsolicited stanzas)
594  */
595 void xmpp_async_loop(void) {
596         xmpp_process_events();
597         xmpp_output_incoming_messages();
598 }
599
600
601 /*
602  * Login hook for XMPP sessions
603  */
604 void xmpp_login_hook(void) {
605         xmpp_queue_event(XMPP_EVT_LOGIN, CC->cs_inet_email);
606 }
607
608
609 /*
610  * Logout hook for XMPP sessions
611  */
612 void xmpp_logout_hook(void) {
613         xmpp_queue_event(XMPP_EVT_LOGOUT, CC->cs_inet_email);
614 }
615
616
617 const char *CitadelServiceXMPP="XMPP";
618 extern void xmpp_cleanup_events(void);
619 CTDL_MODULE_INIT(xmpp)
620 {
621         if (!threading) {
622                 CtdlRegisterServiceHook(config.c_xmpp_c2s_port,
623                                         NULL,
624                                         xmpp_greeting,
625                                         xmpp_command_loop,
626                                         xmpp_async_loop,
627                                         CitadelServiceXMPP
628                 );
629                 CtdlRegisterSessionHook(xmpp_cleanup_function, EVT_STOP);
630                 CtdlRegisterSessionHook(xmpp_login_hook, EVT_LOGIN);
631                 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_LOGOUT);
632                 CtdlRegisterSessionHook(xmpp_login_hook, EVT_UNSTEALTH);
633                 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_STEALTH);
634                 CtdlRegisterCleanupHook(xmpp_cleanup_events);
635
636         }
637
638         /* return our module name for the log */
639         return "xmpp";
640 }