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