0daf9ac022886dd857636e87f26aa1d0bf5e6158
[citadel.git] / citadel / modules / xmpp / serv_xmpp.c
1 /*
2  * $Id$ 
3  *
4  * XMPP (Jabber) service for the Citadel system
5  * Copyright (c) 2007-2010 by Art Cancro
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "sysdep.h"
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <stdio.h>
26 #include <fcntl.h>
27 #include <signal.h>
28 #include <pwd.h>
29 #include <errno.h>
30 #include <sys/types.h>
31
32 #if TIME_WITH_SYS_TIME
33 # include <sys/time.h>
34 # include <time.h>
35 #else
36 # if HAVE_SYS_TIME_H
37 #  include <sys/time.h>
38 # else
39 #  include <time.h>
40 # endif
41 #endif
42
43 #include <sys/wait.h>
44 #include <string.h>
45 #include <limits.h>
46 #include <ctype.h>
47 #include <libcitadel.h>
48 #include <expat.h>
49 #include "citadel.h"
50 #include "server.h"
51 #include "citserver.h"
52 #include "support.h"
53 #include "config.h"
54 #include "user_ops.h"
55 #include "policy.h"
56 #include "database.h"
57 #include "msgbase.h"
58 #include "internet_addressing.h"
59 #include "md5.h"
60 #include "ctdl_module.h"
61 #include "serv_xmpp.h"
62
63 struct xmpp_event *xmpp_queue = NULL;
64
65 /* We have just received a <stream> tag from the client, so send them ours */
66
67 void xmpp_stream_start(void *data, const char *supplied_el, const char **attr)
68 {
69         while (*attr) {
70                 if (!strcasecmp(attr[0], "to")) {
71                         safestrncpy(XMPP->server_name, attr[1], sizeof XMPP->server_name);
72                 }
73                 attr += 2;
74         }
75
76         cprintf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
77
78         cprintf("<stream:stream ");
79         cprintf("from=\"%s\" ", XMPP->server_name);
80         cprintf("id=\"%08x\" ", CC->cs_pid);
81         cprintf("version=\"1.0\" ");
82         cprintf("xmlns:stream=\"http://etherx.jabber.org/streams\" ");
83         cprintf("xmlns=\"jabber:client\">");
84
85         /* The features of this stream are... */
86         cprintf("<stream:features>");
87
88 #ifdef HAVE_OPENSSL_XXXX_COMMENTED_OUT
89         /* TLS encryption (but only if it isn't already active) */
90         if (!CC->redirect_ssl) {
91                 cprintf("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'></starttls>");
92         }
93 #endif
94
95         if (!CC->logged_in) {
96                 /* If we're not logged in yet, offer SASL as our feature set */
97                 xmpp_output_auth_mechs();
98
99                 /* Also offer non-SASL authentication */
100                 cprintf("<auth xmlns=\"http://jabber.org/features/iq-auth\"/>");
101         }
102
103         /* Offer binding and sessions as part of our feature set */
104         cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>");
105         cprintf("<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>");
106
107         cprintf("</stream:features>");
108
109         CC->is_async = 1;               /* XMPP sessions are inherently async-capable */
110 }
111
112
113 void xmpp_xml_start(void *data, const char *supplied_el, const char **attr) {
114         char el[256];
115         char *sep = NULL;
116         int i;
117
118         /* Axe the namespace, we don't care about it */
119         safestrncpy(el, supplied_el, sizeof el);
120         while (sep = strchr(el, ':'), sep) {
121                 strcpy(el, ++sep);
122         }
123
124         /*
125         CtdlLogPrintf(CTDL_DEBUG, "XMPP ELEMENT START: <%s>\n", el);
126         for (i=0; attr[i] != NULL; i+=2) {
127                 CtdlLogPrintf(CTDL_DEBUG, "                    Attribute '%s' = '%s'\n", attr[i], attr[i+1]);
128         }
129         uncomment for more verbosity */
130
131         if (!strcasecmp(el, "stream")) {
132                 xmpp_stream_start(data, supplied_el, attr);
133         }
134
135         else if (!strcasecmp(el, "query")) {
136                 XMPP->iq_query_xmlns[0] = 0;
137                 safestrncpy(XMPP->iq_query_xmlns, supplied_el, sizeof XMPP->iq_query_xmlns);
138         }
139
140         else if (!strcasecmp(el, "bind")) {
141                 XMPP->bind_requested = 1;
142         }
143
144         else if (!strcasecmp(el, "iq")) {
145                 for (i=0; attr[i] != NULL; i+=2) {
146                         if (!strcasecmp(attr[i], "type")) {
147                                 safestrncpy(XMPP->iq_type, attr[i+1], sizeof XMPP->iq_type);
148                         }
149                         else if (!strcasecmp(attr[i], "id")) {
150                                 safestrncpy(XMPP->iq_id, attr[i+1], sizeof XMPP->iq_id);
151                         }
152                         else if (!strcasecmp(attr[i], "from")) {
153                                 safestrncpy(XMPP->iq_from, attr[i+1], sizeof XMPP->iq_from);
154                         }
155                         else if (!strcasecmp(attr[i], "to")) {
156                                 safestrncpy(XMPP->iq_to, attr[i+1], sizeof XMPP->iq_to);
157                         }
158                 }
159         }
160
161         else if (!strcasecmp(el, "auth")) {
162                 XMPP->sasl_auth_mech[0] = 0;
163                 for (i=0; attr[i] != NULL; i+=2) {
164                         if (!strcasecmp(attr[i], "mechanism")) {
165                                 safestrncpy(XMPP->sasl_auth_mech, attr[i+1], sizeof XMPP->sasl_auth_mech);
166                         }
167                 }
168         }
169
170         else if (!strcasecmp(el, "message")) {
171                 for (i=0; attr[i] != NULL; i+=2) {
172                         if (!strcasecmp(attr[i], "to")) {
173                                 safestrncpy(XMPP->message_to, attr[i+1], sizeof XMPP->message_to);
174                         }
175                 }
176         }
177
178         else if (!strcasecmp(el, "html")) {
179                 ++XMPP->html_tag_level;
180         }
181 }
182
183
184
185 void xmpp_xml_end(void *data, const char *supplied_el) {
186         char el[256];
187         char *sep = NULL;
188
189         /* Axe the namespace, we don't care about it */
190         safestrncpy(el, supplied_el, sizeof el);
191         while (sep = strchr(el, ':'), sep) {
192                 strcpy(el, ++sep);
193         }
194
195         /*
196         CtdlLogPrintf(CTDL_DEBUG, "XMPP ELEMENT END  : <%s>\n", el);
197         if (XMPP->chardata_len > 0) {
198                 CtdlLogPrintf(CTDL_DEBUG, "          chardata: %s\n", XMPP->chardata);
199         }
200         uncomment for more verbosity */
201
202         if (!strcasecmp(el, "resource")) {
203                 if (XMPP->chardata_len > 0) {
204                         safestrncpy(XMPP->iq_client_resource, XMPP->chardata,
205                                 sizeof XMPP->iq_client_resource);
206                         striplt(XMPP->iq_client_resource);
207                 }
208         }
209
210         else if (!strcasecmp(el, "username")) {         /* NON SASL ONLY */
211                 if (XMPP->chardata_len > 0) {
212                         safestrncpy(XMPP->iq_client_username, XMPP->chardata,
213                                 sizeof XMPP->iq_client_username);
214                         striplt(XMPP->iq_client_username);
215                 }
216         }
217
218         else if (!strcasecmp(el, "password")) {         /* NON SASL ONLY */
219                 if (XMPP->chardata_len > 0) {
220                         safestrncpy(XMPP->iq_client_password, XMPP->chardata,
221                                 sizeof XMPP->iq_client_password);
222                         striplt(XMPP->iq_client_password);
223                 }
224         }
225
226         else if (!strcasecmp(el, "iq")) {
227
228                 /*
229                  * iq type="get" (handle queries)
230                  */
231                 if (!strcasecmp(XMPP->iq_type, "get")) {
232
233                         /*
234                          * Query on a namespace
235                          */
236                         if (!IsEmptyStr(XMPP->iq_query_xmlns)) {
237                                 xmpp_query_namespace(XMPP->iq_id, XMPP->iq_from,
238                                                 XMPP->iq_to, XMPP->iq_query_xmlns);
239                         }
240
241                         /*
242                          * ping ( http://xmpp.org/extensions/xep-0199.html )
243                          */
244                         else if (XMPP->ping_requested) {
245                                 cprintf("<iq type=\"result\" ");
246                                 if (!IsEmptyStr(XMPP->iq_from)) {
247                                         cprintf("to=\"%s\" ", XMPP->iq_from);
248                                 }
249                                 if (!IsEmptyStr(XMPP->iq_to)) {
250                                         cprintf("from=\"%s\" ", XMPP->iq_to);
251                                 }
252                                 cprintf("id=\"%s\"/>", XMPP->iq_id);
253                         }
254
255                         /*
256                          * Unknown query ... return the XML equivalent of a blank stare
257                          */
258                         else {
259                                 CtdlLogPrintf(CTDL_DEBUG,
260                                         "Unknown query <%s> - returning <service-unavailable/>\n",
261                                         el
262                                 );
263                                 cprintf("<iq type=\"error\" id=\"%s\">", XMPP->iq_id);
264                                 cprintf("<error code=\"503\" type=\"cancel\">"
265                                         "<service-unavailable xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>"
266                                         "</error>"
267                                 );
268                                 cprintf("</iq>");
269                         }
270                 }
271
272                 /*
273                  * Non SASL authentication
274                  */
275                 else if (
276                         (!strcasecmp(XMPP->iq_type, "set"))
277                         && (!strcasecmp(XMPP->iq_query_xmlns, "jabber:iq:auth:query"))
278                         ) {
279
280                         xmpp_non_sasl_authenticate(
281                                 XMPP->iq_id,
282                                 XMPP->iq_client_username,
283                                 XMPP->iq_client_password,
284                                 XMPP->iq_client_resource
285                         );
286                 }       
287
288                 /*
289                  * If this <iq> stanza was a "bind" attempt, process it ...
290                  */
291                 else if (
292                         (XMPP->bind_requested)
293                         && (!IsEmptyStr(XMPP->iq_id))
294                         && (!IsEmptyStr(XMPP->iq_client_resource))
295                         && (CC->logged_in)
296                         ) {
297
298                         /* Generate the "full JID" of the client resource */
299
300                         snprintf(XMPP->client_jid, sizeof XMPP->client_jid,
301                                 "%s/%s",
302                                 CC->cs_inet_email,
303                                 XMPP->iq_client_resource
304                         );
305
306                         /* Tell the client what its JID is */
307
308                         cprintf("<iq type=\"result\" id=\"%s\">", XMPP->iq_id);
309                         cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">");
310                         cprintf("<jid>%s</jid>", XMPP->client_jid);
311                         cprintf("</bind>");
312                         cprintf("</iq>");
313                 }
314
315                 else if (XMPP->iq_session) {
316                         cprintf("<iq type=\"result\" id=\"%s\">", XMPP->iq_id);
317                         cprintf("</iq>");
318                 }
319
320                 else {
321                         cprintf("<iq type=\"error\" id=\"%s\">", XMPP->iq_id);
322                         cprintf("<error></error>");
323                         cprintf("</iq>");
324                 }
325
326                 /* Now clear these fields out so they don't get used by a future stanza */
327                 XMPP->iq_id[0] = 0;
328                 XMPP->iq_from[0] = 0;
329                 XMPP->iq_to[0] = 0;
330                 XMPP->iq_type[0] = 0;
331                 XMPP->iq_client_resource[0] = 0;
332                 XMPP->iq_session = 0;
333                 XMPP->iq_query_xmlns[0] = 0;
334                 XMPP->bind_requested = 0;
335                 XMPP->ping_requested = 0;
336         }
337
338         else if (!strcasecmp(el, "auth")) {
339
340                 /* Try to authenticate (this function is responsible for the output stanza) */
341                 xmpp_sasl_auth(XMPP->sasl_auth_mech, (XMPP->chardata != NULL ? XMPP->chardata : "") );
342
343                 /* Now clear these fields out so they don't get used by a future stanza */
344                 XMPP->sasl_auth_mech[0] = 0;
345         }
346
347         else if (!strcasecmp(el, "session")) {
348                 XMPP->iq_session = 1;
349         }
350
351         else if (!strcasecmp(el, "presence")) {
352
353                 /* Respond to a <presence> update by firing back with presence information
354                  * on the entire wholist.  Check this assumption, it's probably wrong.
355                  */
356                 xmpp_wholist_presence_dump();
357         }
358
359         else if ( (!strcasecmp(el, "body")) && (XMPP->html_tag_level == 0) ) {
360                 if (XMPP->message_body != NULL) {
361                         free(XMPP->message_body);
362                         XMPP->message_body = NULL;
363                 }
364                 if (XMPP->chardata_len > 0) {
365                         XMPP->message_body = strdup(XMPP->chardata);
366                 }
367         }
368
369         else if (!strcasecmp(el, "message")) {
370                 xmpp_send_message(XMPP->message_to, XMPP->message_body);
371                 XMPP->html_tag_level = 0;
372         }
373
374         else if (!strcasecmp(el, "html")) {
375                 --XMPP->html_tag_level;
376         }
377
378         else if (!strcasecmp(el, "starttls")) {
379 #ifdef HAVE_OPENSSL
380                 cprintf("<proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
381                 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
382                 if (!CC->redirect_ssl) CC->kill_me = 1;
383 #else
384                 cprintf("<failure xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
385                 CC->kill_me = 1;
386 #endif
387         }
388
389         else if (!strcasecmp(el, "ping")) {
390                 XMPP->ping_requested = 1;
391         }
392
393         else if (!strcasecmp(el, "stream")) {
394                 CtdlLogPrintf(CTDL_DEBUG, "XMPP client shut down their stream\n");
395                 /* xmpp_massacre_roster(); FIXME put this back in when it's finished */
396                 cprintf("</stream>\n");
397                 CC->kill_me = 1;
398         }
399
400         else {
401                 CtdlLogPrintf(CTDL_DEBUG, "Ignoring unknown tag <%s>\n", el);
402         }
403
404         XMPP->chardata_len = 0;
405         if (XMPP->chardata_alloc > 0) {
406                 XMPP->chardata[0] = 0;
407         }
408 }
409
410
411 void xmpp_xml_chardata(void *data, const XML_Char *s, int len)
412 {
413         struct citxmpp *X = XMPP;
414
415         if (X->chardata_alloc == 0) {
416                 X->chardata_alloc = SIZ;
417                 X->chardata = malloc(X->chardata_alloc);
418         }
419         if ((X->chardata_len + len + 1) > X->chardata_alloc) {
420                 X->chardata_alloc = X->chardata_len + len + 1024;
421                 X->chardata = realloc(X->chardata, X->chardata_alloc);
422         }
423         memcpy(&X->chardata[X->chardata_len], s, len);
424         X->chardata_len += len;
425         X->chardata[X->chardata_len] = 0;
426 }
427
428
429 /*
430  * This cleanup function blows away the temporary memory and files used by the XMPP service.
431  */
432 void xmpp_cleanup_function(void) {
433
434         /* Don't do this stuff if this is not a XMPP session! */
435         if (CC->h_command_function != xmpp_command_loop) return;
436
437         if (XMPP->chardata != NULL) {
438                 free(XMPP->chardata);
439                 XMPP->chardata = NULL;
440                 XMPP->chardata_len = 0;
441                 XMPP->chardata_alloc = 0;
442                 if (XMPP->message_body != NULL) {
443                         free(XMPP->message_body);
444                 }
445         }
446         XML_ParserFree(XMPP->xp);
447         free(XMPP);
448 }
449
450
451
452 /*
453  * Here's where our XMPP session begins its happy day.
454  */
455 void xmpp_greeting(void) {
456         strcpy(CC->cs_clientname, "XMPP session");
457         CC->session_specific_data = malloc(sizeof(struct citxmpp));
458         memset(XMPP, 0, sizeof(struct citxmpp));
459         XMPP->last_event_processed = queue_event_seq;
460
461         /* XMPP does not use a greeting, but we still have to initialize some things. */
462
463         XMPP->xp = XML_ParserCreateNS("UTF-8", ':');
464         if (XMPP->xp == NULL) {
465                 CtdlLogPrintf(CTDL_ALERT, "Cannot create XML parser!\n");
466                 CC->kill_me = 1;
467                 return;
468         }
469
470         XML_SetElementHandler(XMPP->xp, xmpp_xml_start, xmpp_xml_end);
471         XML_SetCharacterDataHandler(XMPP->xp, xmpp_xml_chardata);
472         // XML_SetUserData(XMPP->xp, something...);
473
474         CC->can_receive_im = 1;         /* This protocol is capable of receiving instant messages */
475 }
476
477
478 /* 
479  * Main command loop for XMPP sessions.
480  */
481 void xmpp_command_loop(void) {
482         char cmdbuf[16];
483         int retval;
484
485         time(&CC->lastcmd);
486         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
487         retval = client_read(cmdbuf, 1);
488         if (retval != 1) {
489                 CtdlLogPrintf(CTDL_ERR, "Client disconnected: ending session.\r\n");
490                 CC->kill_me = 1;
491                 return;
492         }
493
494         /* FIXME ... this is woefully inefficient. */
495
496         XML_Parse(XMPP->xp, cmdbuf, 1, 0);
497 }
498
499
500 /*
501  * Async loop for XMPP sessions (handles the transmission of unsolicited stanzas)
502  */
503 void xmpp_async_loop(void) {
504         xmpp_process_events();
505         xmpp_output_incoming_messages();
506 }
507
508
509 /*
510  * Login hook for XMPP sessions
511  */
512 void xmpp_login_hook(void) {
513         xmpp_queue_event(XMPP_EVT_LOGIN, CC->cs_inet_email);
514 }
515
516
517 /*
518  * Logout hook for XMPP sessions
519  */
520 void xmpp_logout_hook(void) {
521         xmpp_queue_event(XMPP_EVT_LOGOUT, CC->cs_inet_email);
522 }
523
524
525 const char *CitadelServiceXMPP="XMPP";
526
527 CTDL_MODULE_INIT(xmpp)
528 {
529         if (!threading) {
530                 CtdlRegisterServiceHook(config.c_xmpp_c2s_port,
531                                         NULL,
532                                         xmpp_greeting,
533                                         xmpp_command_loop,
534                                         xmpp_async_loop,
535                                         CitadelServiceXMPP);
536                 CtdlRegisterSessionHook(xmpp_cleanup_function, EVT_STOP);
537                 CtdlRegisterSessionHook(xmpp_login_hook, EVT_LOGIN);
538                 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_LOGOUT);
539                 CtdlRegisterSessionHook(xmpp_login_hook, EVT_UNSTEALTH);
540                 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_STEALTH);
541         }
542
543         /* return our Subversion id for the Log */
544         return "$Id$";
545 }