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