988efad2910221388a8b458ad871324db26853e9
[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 <expat.h>
37 #include "citadel.h"
38 #include "server.h"
39 #include "citserver.h"
40 #include "support.h"
41 #include "config.h"
42 #include "room_ops.h"
43 #include "user_ops.h"
44 #include "policy.h"
45 #include "database.h"
46 #include "msgbase.h"
47 #include "internet_addressing.h"
48 #include "md5.h"
49 #include "ctdl_module.h"
50 #include "serv_xmpp.h"
51
52 struct xmpp_event *xmpp_queue = NULL;
53
54 /* We have just received a <stream> tag from the client, so send them ours */
55
56 void xmpp_stream_start(void *data, const char *supplied_el, const char **attr)
57 {
58         while (*attr) {
59                 if (!strcasecmp(attr[0], "to")) {
60                         safestrncpy(XMPP->server_name, attr[1], sizeof XMPP->server_name);
61                 }
62                 attr += 2;
63         }
64
65         cprintf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
66
67         cprintf("<stream:stream ");
68         cprintf("from=\"%s\" ", XMPP->server_name);
69         cprintf("id=\"%08x\" ", CC->cs_pid);
70         cprintf("version=\"1.0\" ");
71         cprintf("xmlns:stream=\"http://etherx.jabber.org/streams\" ");
72         cprintf("xmlns=\"jabber:client\">");
73
74         /* The features of this stream are... */
75         cprintf("<stream:features>");
76
77 #ifdef HAVE_OPENSSL_XXXX_COMMENTED_OUT
78         /* TLS encryption (but only if it isn't already active) */
79         if (!CC->redirect_ssl) {
80                 cprintf("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'></starttls>");
81         }
82 #endif
83
84         if (!CC->logged_in) {
85                 /* If we're not logged in yet, offer SASL as our feature set */
86                 xmpp_output_auth_mechs();
87
88                 /* Also offer non-SASL authentication */
89                 cprintf("<auth xmlns=\"http://jabber.org/features/iq-auth\"/>");
90         }
91
92         /* Offer binding and sessions as part of our feature set */
93         cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>");
94         cprintf("<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>");
95
96         cprintf("</stream:features>");
97
98         CC->is_async = 1;               /* XMPP sessions are inherently async-capable */
99 }
100
101
102 void xmpp_xml_start(void *data, const char *supplied_el, const char **attr) {
103         char el[256];
104         char *sep = NULL;
105         int i;
106
107         /* Axe the namespace, we don't care about it */
108         safestrncpy(el, supplied_el, sizeof el);
109         while (sep = strchr(el, ':'), sep) {
110                 strcpy(el, ++sep);
111         }
112
113         /*
114         CtdlLogPrintf(CTDL_DEBUG, "XMPP ELEMENT START: <%s>\n", el);
115         for (i=0; attr[i] != NULL; i+=2) {
116                 CtdlLogPrintf(CTDL_DEBUG, "                    Attribute '%s' = '%s'\n", attr[i], attr[i+1]);
117         }
118         uncomment for more verbosity */
119
120         if (!strcasecmp(el, "stream")) {
121                 xmpp_stream_start(data, supplied_el, attr);
122         }
123
124         else if (!strcasecmp(el, "query")) {
125                 XMPP->iq_query_xmlns[0] = 0;
126                 safestrncpy(XMPP->iq_query_xmlns, supplied_el, sizeof XMPP->iq_query_xmlns);
127         }
128
129         else if (!strcasecmp(el, "bind")) {
130                 XMPP->bind_requested = 1;
131         }
132
133         else if (!strcasecmp(el, "iq")) {
134                 for (i=0; attr[i] != NULL; i+=2) {
135                         if (!strcasecmp(attr[i], "type")) {
136                                 safestrncpy(XMPP->iq_type, attr[i+1], sizeof XMPP->iq_type);
137                         }
138                         else if (!strcasecmp(attr[i], "id")) {
139                                 safestrncpy(XMPP->iq_id, attr[i+1], sizeof XMPP->iq_id);
140                         }
141                         else if (!strcasecmp(attr[i], "from")) {
142                                 safestrncpy(XMPP->iq_from, attr[i+1], sizeof XMPP->iq_from);
143                         }
144                         else if (!strcasecmp(attr[i], "to")) {
145                                 safestrncpy(XMPP->iq_to, attr[i+1], sizeof XMPP->iq_to);
146                         }
147                 }
148         }
149
150         else if (!strcasecmp(el, "auth")) {
151                 XMPP->sasl_auth_mech[0] = 0;
152                 for (i=0; attr[i] != NULL; i+=2) {
153                         if (!strcasecmp(attr[i], "mechanism")) {
154                                 safestrncpy(XMPP->sasl_auth_mech, attr[i+1], sizeof XMPP->sasl_auth_mech);
155                         }
156                 }
157         }
158
159         else if (!strcasecmp(el, "message")) {
160                 for (i=0; attr[i] != NULL; i+=2) {
161                         if (!strcasecmp(attr[i], "to")) {
162                                 safestrncpy(XMPP->message_to, attr[i+1], sizeof XMPP->message_to);
163                         }
164                 }
165         }
166
167         else if (!strcasecmp(el, "html")) {
168                 ++XMPP->html_tag_level;
169         }
170 }
171
172
173
174 void xmpp_xml_end(void *data, const char *supplied_el) {
175         char el[256];
176         char *sep = NULL;
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         CtdlLogPrintf(CTDL_DEBUG, "XMPP ELEMENT END  : <%s>\n", el);
186         if (XMPP->chardata_len > 0) {
187                 CtdlLogPrintf(CTDL_DEBUG, "          chardata: %s\n", XMPP->chardata);
188         }
189         uncomment for more verbosity */
190
191         if (!strcasecmp(el, "resource")) {
192                 if (XMPP->chardata_len > 0) {
193                         safestrncpy(XMPP->iq_client_resource, XMPP->chardata,
194                                 sizeof XMPP->iq_client_resource);
195                         striplt(XMPP->iq_client_resource);
196                 }
197         }
198
199         if (!strcasecmp(el, "username")) {              /* NON SASL ONLY */
200                 if (XMPP->chardata_len > 0) {
201                         safestrncpy(XMPP->iq_client_username, XMPP->chardata,
202                                 sizeof XMPP->iq_client_username);
203                         striplt(XMPP->iq_client_username);
204                 }
205         }
206
207         if (!strcasecmp(el, "password")) {              /* NON SASL ONLY */
208                 if (XMPP->chardata_len > 0) {
209                         safestrncpy(XMPP->iq_client_password, XMPP->chardata,
210                                 sizeof XMPP->iq_client_password);
211                         striplt(XMPP->iq_client_password);
212                 }
213         }
214
215         else if (!strcasecmp(el, "iq")) {
216
217                 /*
218                  * iq type="get" (handle queries)
219                  */
220                 if (!strcasecmp(XMPP->iq_type, "get")) {
221
222                         /*
223                          * Query on a namespace
224                          */
225                         if (!IsEmptyStr(XMPP->iq_query_xmlns)) {
226                                 xmpp_query_namespace(XMPP->iq_id, XMPP->iq_from,
227                                                 XMPP->iq_to, XMPP->iq_query_xmlns);
228                         }
229
230                         /*
231                          * Unknown queries ... return the XML equivalent of a blank stare
232                          */
233                         else {
234                                 cprintf("<iq type=\"result\" id=\"%s\">", XMPP->iq_id);
235                                 cprintf("</iq>");
236                         }
237                 }
238
239                 /*
240                  * Non SASL authentication
241                  */
242                 else if (
243                         (!strcasecmp(XMPP->iq_type, "set"))
244                         && (!strcasecmp(XMPP->iq_query_xmlns, "jabber:iq:auth:query"))
245                         ) {
246
247                         jabber_non_sasl_authenticate(
248                                 XMPP->iq_id,
249                                 XMPP->iq_client_username,
250                                 XMPP->iq_client_password,
251                                 XMPP->iq_client_resource
252                         );
253                 }       
254
255                 /*
256                  * If this <iq> stanza was a "bind" attempt, process it ...
257                  */
258                 else if (
259                         (XMPP->bind_requested)
260                         && (!IsEmptyStr(XMPP->iq_id))
261                         && (!IsEmptyStr(XMPP->iq_client_resource))
262                         && (CC->logged_in)
263                         ) {
264
265                         /* Generate the "full JID" of the client resource */
266
267                         snprintf(XMPP->client_jid, sizeof XMPP->client_jid,
268                                 "%s/%s",
269                                 CC->cs_inet_email,
270                                 XMPP->iq_client_resource
271                         );
272
273                         /* Tell the client what its JID is */
274
275                         cprintf("<iq type=\"result\" id=\"%s\">", XMPP->iq_id);
276                         cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">");
277                         cprintf("<jid>%s</jid>", XMPP->client_jid);
278                         cprintf("</bind>");
279                         cprintf("</iq>");
280                 }
281
282                 else if (XMPP->iq_session) {
283                         cprintf("<iq type=\"result\" id=\"%s\">", XMPP->iq_id);
284                         cprintf("</iq>");
285                 }
286
287                 else {
288                         cprintf("<iq type=\"error\" id=\"%s\">", XMPP->iq_id);
289                         cprintf("<error></error>");
290                         cprintf("</iq>");
291                 }
292
293                 /* Now clear these fields out so they don't get used by a future stanza */
294                 XMPP->iq_id[0] = 0;
295                 XMPP->iq_from[0] = 0;
296                 XMPP->iq_to[0] = 0;
297                 XMPP->iq_type[0] = 0;
298                 XMPP->iq_client_resource[0] = 0;
299                 XMPP->iq_session = 0;
300                 XMPP->iq_query_xmlns[0] = 0;
301                 XMPP->bind_requested = 0;
302         }
303
304         else if (!strcasecmp(el, "auth")) {
305
306                 /* Try to authenticate (this function is responsible for the output stanza) */
307                 xmpp_sasl_auth(XMPP->sasl_auth_mech, (XMPP->chardata != NULL ? XMPP->chardata : "") );
308
309                 /* Now clear these fields out so they don't get used by a future stanza */
310                 XMPP->sasl_auth_mech[0] = 0;
311         }
312
313         else if (!strcasecmp(el, "session")) {
314                 XMPP->iq_session = 1;
315         }
316
317         else if (!strcasecmp(el, "presence")) {
318
319                 /* Respond to a <presence> update by firing back with presence information
320                  * on the entire wholist.  Check this assumption, it's probably wrong.
321                  */
322                 jabber_wholist_presence_dump();
323         }
324
325         else if ( (!strcasecmp(el, "body")) && (XMPP->html_tag_level == 0) ) {
326                 if (XMPP->message_body != NULL) {
327                         free(XMPP->message_body);
328                         XMPP->message_body = NULL;
329                 }
330                 if (XMPP->chardata_len > 0) {
331                         XMPP->message_body = strdup(XMPP->chardata);
332                 }
333         }
334
335         else if (!strcasecmp(el, "message")) {
336                 jabber_send_message(XMPP->message_to, XMPP->message_body);
337                 XMPP->html_tag_level = 0;
338         }
339
340         else if (!strcasecmp(el, "html")) {
341                 --XMPP->html_tag_level;
342         }
343
344         else if (!strcasecmp(el, "starttls")) {
345 #ifdef HAVE_OPENSSL
346         cprintf("<proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
347         CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
348         if (!CC->redirect_ssl) CC->kill_me = 1;
349 #else
350         cprintf("<failure xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
351         CC->kill_me = 1;
352 #endif
353         }
354
355         XMPP->chardata_len = 0;
356         if (XMPP->chardata_alloc > 0) {
357                 XMPP->chardata[0] = 0;
358         }
359 }
360
361
362 void xmpp_xml_chardata(void *data, const XML_Char *s, int len)
363 {
364         struct citxmpp *X = XMPP;
365
366         if (X->chardata_alloc == 0) {
367                 X->chardata_alloc = SIZ;
368                 X->chardata = malloc(X->chardata_alloc);
369         }
370         if ((X->chardata_len + len + 1) > X->chardata_alloc) {
371                 X->chardata_alloc = X->chardata_len + len + 1024;
372                 X->chardata = realloc(X->chardata, X->chardata_alloc);
373         }
374         memcpy(&X->chardata[X->chardata_len], s, len);
375         X->chardata_len += len;
376         X->chardata[X->chardata_len] = 0;
377 }
378
379
380 /*
381  * This cleanup function blows away the temporary memory and files used by the XMPP service.
382  */
383 void xmpp_cleanup_function(void) {
384
385         /* Don't do this stuff if this is not a XMPP session! */
386         if (CC->h_command_function != xmpp_command_loop) return;
387
388         if (XMPP->chardata != NULL) {
389                 free(XMPP->chardata);
390                 XMPP->chardata = NULL;
391                 XMPP->chardata_len = 0;
392                 XMPP->chardata_alloc = 0;
393                 if (XMPP->message_body != NULL) {
394                         free(XMPP->message_body);
395                 }
396         }
397         XML_ParserFree(XMPP->xp);
398         free(XMPP);
399 }
400
401
402
403 /*
404  * Here's where our XMPP session begins its happy day.
405  */
406 void xmpp_greeting(void) {
407         strcpy(CC->cs_clientname, "Jabber session");
408         CC->session_specific_data = malloc(sizeof(struct citxmpp));
409         memset(XMPP, 0, sizeof(struct citxmpp));
410         XMPP->last_event_processed = queue_event_seq;
411
412         /* XMPP does not use a greeting, but we still have to initialize some things. */
413
414         XMPP->xp = XML_ParserCreateNS("UTF-8", ':');
415         if (XMPP->xp == NULL) {
416                 CtdlLogPrintf(CTDL_ALERT, "Cannot create XML parser!\n");
417                 CC->kill_me = 1;
418                 return;
419         }
420
421         XML_SetElementHandler(XMPP->xp, xmpp_xml_start, xmpp_xml_end);
422         XML_SetCharacterDataHandler(XMPP->xp, xmpp_xml_chardata);
423         // XML_SetUserData(XMPP->xp, something...);
424
425         CC->can_receive_im = 1;         /* This protocol is capable of receiving instant messages */
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                 CtdlLogPrintf(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 CTDL_MODULE_INIT(jabber)
479 {
480         if (!threading) {
481                 CtdlRegisterServiceHook(config.c_xmpp_c2s_port,
482                                         NULL,
483                                         xmpp_greeting,
484                                         xmpp_command_loop,
485                                         xmpp_async_loop,
486                                         CitadelServiceXMPP);
487                 CtdlRegisterSessionHook(xmpp_cleanup_function, EVT_STOP);
488                 CtdlRegisterSessionHook(xmpp_login_hook, EVT_LOGIN);
489                 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_LOGOUT);
490                 CtdlRegisterSessionHook(xmpp_login_hook, EVT_UNSTEALTH);
491                 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_STEALTH);
492         }
493
494         /* return our Subversion id for the Log */
495         return "$Id$";
496 }