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