Began (but did not complete) implementation
[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
61         lprintf(CTDL_DEBUG, "New stream detected.\n");
62
63         while (*attr) {
64                 if (!strcasecmp(attr[0], "to")) {
65                         safestrncpy(XMPP->server_name, attr[1], sizeof XMPP->server_name);
66                 }
67                 attr += 2;
68         }
69
70         cprintf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
71
72         cprintf("<stream:stream ");
73         cprintf("from=\"%s\" ", XMPP->server_name);
74         cprintf("id=\"%08x\" ", CC->cs_pid);
75         cprintf("version=\"1.0\" ");
76         cprintf("xmlns:stream=\"http://etherx.jabber.org/streams\" ");
77         cprintf("xmlns=\"jabber:client\">");
78
79         /* The features of this stream are... */
80         cprintf("<stream:features>");
81
82 #ifdef HAVE_OPENSSL_XXXX_COMMENTED_OUT
83         /* TLS encryption (but only if it isn't already active) */
84         if (!CC->redirect_ssl) {
85                 cprintf("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'></starttls>");
86         }
87 #endif
88
89         if (!CC->logged_in) {
90                 /* If we're not logged in yet, offer SASL as our feature set */
91                 xmpp_output_auth_mechs();
92
93                 /* Also offer non-SASL authentication */
94                 cprintf("<auth xmlns=\"http://jabber.org/features/iq-auth\"/>");
95         }
96
97         /* Offer binding and sessions as part of our feature set */
98         cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>");
99         cprintf("<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>");
100
101         cprintf("</stream:features>");
102
103         CC->is_async = 1;               /* XMPP sessions are inherently async-capable */
104 }
105
106
107 void xmpp_xml_start(void *data, const char *supplied_el, const char **attr) {
108         char el[256];
109         char *sep = NULL;
110         int i;
111
112         /* Axe the namespace, we don't care about it */
113         safestrncpy(el, supplied_el, sizeof el);
114         while (sep = strchr(el, ':'), sep) {
115                 strcpy(el, ++sep);
116         }
117
118         lprintf(CTDL_DEBUG, "XMPP ELEMENT START: <%s>\n", el);
119
120         for (i=0; attr[i] != NULL; i+=2) {
121                 lprintf(CTDL_DEBUG, "                    Attribute '%s' = '%s'\n", attr[i], attr[i+1]);
122         }
123
124         if (!strcasecmp(el, "stream")) {
125                 xmpp_stream_start(data, supplied_el, attr);
126         }
127
128         else if (!strcasecmp(el, "query")) {
129                 XMPP->iq_query_xmlns[0] = 0;
130                 safestrncpy(XMPP->iq_query_xmlns, supplied_el, sizeof XMPP->iq_query_xmlns);
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         lprintf(CTDL_DEBUG, "XMPP ELEMENT END  : <%s>\n", el);
185         if (XMPP->chardata_len > 0) {
186                 lprintf(CTDL_DEBUG, "          chardata: %s\n", XMPP->chardata);
187         }
188
189         if (!strcasecmp(el, "resource")) {
190                 if (XMPP->chardata_len > 0) {
191                         safestrncpy(XMPP->iq_client_resource, XMPP->chardata,
192                                 sizeof XMPP->iq_client_resource);
193                 }
194         }
195
196         else if (!strcasecmp(el, "iq")) {
197
198                 /*
199                  * iq type="get" (handle queries)
200                  */
201                 if (!strcasecmp(XMPP->iq_type, "get")) {
202
203                         /*
204                          * Query on a namespace
205                          */
206                         if (!IsEmptyStr(XMPP->iq_query_xmlns)) {
207                                 xmpp_query_namespace(XMPP->iq_id, XMPP->iq_from,
208                                                 XMPP->iq_to, XMPP->iq_query_xmlns);
209                         }
210
211                         /*
212                          * Unknown queries ... return the XML equivalent of a blank stare
213                          */
214                         else {
215                                 cprintf("<iq type=\"result\" id=\"%s\">", XMPP->iq_id);
216                                 cprintf("</iq>");
217                         }
218                 }
219
220                 /*
221                  * If this <iq> stanza was a "bind" attempt, process it ...
222                  */
223                 else if ( (!IsEmptyStr(XMPP->iq_id)) && (!IsEmptyStr(XMPP->iq_client_resource)) ) {
224
225                         /* Generate the "full JID" of the client resource */
226
227                         snprintf(XMPP->client_jid, sizeof XMPP->client_jid,
228                                 "%s/%s",
229                                 CC->cs_inet_email,
230                                 XMPP->iq_client_resource
231                         );
232
233                         /* Tell the client what its JID is */
234
235                         cprintf("<iq type=\"result\" id=\"%s\">", XMPP->iq_id);
236                         cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">");
237                         cprintf("<jid>%s</jid>", XMPP->client_jid);
238                         cprintf("</bind>");
239                         cprintf("</iq>");
240                 }
241
242                 else if (XMPP->iq_session) {
243                         cprintf("<iq type=\"result\" id=\"%s\">", XMPP->iq_id);
244                         cprintf("</iq>");
245                 }
246
247                 else {
248                         cprintf("<iq type=\"error\" id=\"%s\">", XMPP->iq_id);
249                         cprintf("<error></error>");
250                         cprintf("</iq>");
251                 }
252
253                 /* Now clear these fields out so they don't get used by a future stanza */
254                 XMPP->iq_id[0] = 0;
255                 XMPP->iq_from[0] = 0;
256                 XMPP->iq_to[0] = 0;
257                 XMPP->iq_type[0] = 0;
258                 XMPP->iq_client_resource[0] = 0;
259                 XMPP->iq_session = 0;
260                 XMPP->iq_query_xmlns[0] = 0;
261         }
262
263         else if (!strcasecmp(el, "auth")) {
264
265                 /* Try to authenticate (this function is responsible for the output stanza) */
266                 xmpp_sasl_auth(XMPP->sasl_auth_mech, (XMPP->chardata != NULL ? XMPP->chardata : "") );
267
268                 /* Now clear these fields out so they don't get used by a future stanza */
269                 XMPP->sasl_auth_mech[0] = 0;
270         }
271
272         else if (!strcasecmp(el, "session")) {
273                 XMPP->iq_session = 1;
274         }
275
276         else if (!strcasecmp(el, "presence")) {
277
278                 /* Respond to a <presence> update by firing back with presence information
279                  * on the entire wholist.  Check this assumption, it's probably wrong.
280                  */
281                 jabber_wholist_presence_dump();
282         }
283
284         else if ( (!strcasecmp(el, "body")) && (XMPP->html_tag_level == 0) ) {
285                 if (XMPP->message_body != NULL) {
286                         free(XMPP->message_body);
287                         XMPP->message_body = NULL;
288                 }
289                 if (XMPP->chardata_len > 0) {
290                         XMPP->message_body = strdup(XMPP->chardata);
291                 }
292         }
293
294         else if (!strcasecmp(el, "message")) {
295                 jabber_send_message(XMPP->message_to, XMPP->message_body);
296                 XMPP->html_tag_level = 0;
297         }
298
299         else if (!strcasecmp(el, "html")) {
300                 --XMPP->html_tag_level;
301         }
302
303         else if (!strcasecmp(el, "starttls")) {
304 #ifdef HAVE_OPENSSL
305         cprintf("<proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
306         CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
307         if (!CC->redirect_ssl) CC->kill_me = 1;
308 #else
309         cprintf("<failure xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
310         CC->kill_me = 1;
311 #endif
312         }
313
314         XMPP->chardata_len = 0;
315         if (XMPP->chardata_alloc > 0) {
316                 XMPP->chardata[0] = 0;
317         }
318 }
319
320
321 void xmpp_xml_chardata(void *data, const XML_Char *s, int len)
322 {
323         struct citxmpp *X = XMPP;
324
325         if (X->chardata_alloc == 0) {
326                 X->chardata_alloc = SIZ;
327                 X->chardata = malloc(X->chardata_alloc);
328         }
329         if ((X->chardata_len + len + 1) > X->chardata_alloc) {
330                 X->chardata_alloc = X->chardata_len + len + 1024;
331                 X->chardata = realloc(X->chardata, X->chardata_alloc);
332         }
333         memcpy(&X->chardata[X->chardata_len], s, len);
334         X->chardata_len += len;
335         X->chardata[X->chardata_len] = 0;
336 }
337
338
339 /*
340  * This cleanup function blows away the temporary memory and files used by the XMPP service.
341  */
342 void xmpp_cleanup_function(void) {
343
344         /* Don't do this stuff if this is not a XMPP session! */
345         if (CC->h_command_function != xmpp_command_loop) return;
346
347         lprintf(CTDL_DEBUG, "Performing XMPP cleanup hook\n");
348         if (XMPP->chardata != NULL) {
349                 free(XMPP->chardata);
350                 XMPP->chardata = NULL;
351                 XMPP->chardata_len = 0;
352                 XMPP->chardata_alloc = 0;
353                 if (XMPP->message_body != NULL) {
354                         free(XMPP->message_body);
355                 }
356         }
357         XML_ParserFree(XMPP->xp);
358         free(XMPP);
359 }
360
361
362
363 /*
364  * Here's where our XMPP session begins its happy day.
365  */
366 void xmpp_greeting(void) {
367         strcpy(CC->cs_clientname, "Jabber session");
368         CC->session_specific_data = malloc(sizeof(struct citxmpp));
369         memset(XMPP, 0, sizeof(struct citxmpp));
370         XMPP->last_event_processed = queue_event_seq;
371
372         /* XMPP does not use a greeting, but we still have to initialize some things. */
373
374         XMPP->xp = XML_ParserCreateNS("UTF-8", ':');
375         if (XMPP->xp == NULL) {
376                 lprintf(CTDL_ALERT, "Cannot create XML parser!\n");
377                 CC->kill_me = 1;
378                 return;
379         }
380
381         XML_SetElementHandler(XMPP->xp, xmpp_xml_start, xmpp_xml_end);
382         XML_SetCharacterDataHandler(XMPP->xp, xmpp_xml_chardata);
383         // XML_SetUserData(XMPP->xp, something...);
384 }
385
386
387 /* 
388  * Main command loop for XMPP sessions.
389  */
390 void xmpp_command_loop(void) {
391         char cmdbuf[16];
392         int retval;
393
394         time(&CC->lastcmd);
395         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
396         retval = client_read(cmdbuf, 1);
397         if (retval != 1) {
398                 lprintf(CTDL_ERR, "Client disconnected: ending session.\r\n");
399                 CC->kill_me = 1;
400                 return;
401         }
402
403         /* FIXME ... this is woefully inefficient. */
404
405         XML_Parse(XMPP->xp, cmdbuf, 1, 0);
406 }
407
408
409 /*
410  * Async loop for XMPP sessions (handles the transmission of unsolicited stanzas)
411  */
412 void xmpp_async_loop(void) {
413         xmpp_process_events();
414         jabber_output_incoming_messages();
415 }
416
417
418 /*
419  * Login hook for XMPP sessions
420  */
421 void xmpp_login_hook(void) {
422         xmpp_queue_event(XMPP_EVT_LOGIN, CC->cs_inet_email);
423 }
424
425
426 /*
427  * Logout hook for XMPP sessions
428  */
429 void xmpp_logout_hook(void) {
430         xmpp_queue_event(XMPP_EVT_LOGOUT, CC->cs_inet_email);
431 }
432
433
434 const char *CitadelServiceXMPP="XMPP";
435
436 #endif  /* HAVE_EXPAT */
437
438 CTDL_MODULE_INIT(jabber)
439 {
440 #ifdef HAVE_EXPAT
441         if (!threading) {
442                 CtdlRegisterServiceHook(config.c_xmpp_c2s_port,
443                                         NULL,
444                                         xmpp_greeting,
445                                         xmpp_command_loop,
446                                         xmpp_async_loop,
447                                         CitadelServiceXMPP);
448                 CtdlRegisterSessionHook(xmpp_cleanup_function, EVT_STOP);
449                 CtdlRegisterSessionHook(xmpp_login_hook, EVT_LOGIN);
450                 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_LOGOUT);
451                 CtdlRegisterSessionHook(xmpp_login_hook, EVT_UNSTEALTH);
452                 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_STEALTH);
453         #else
454                 lprintf(CTDL_INFO, "This server is missing the Expat XML parser.  Jabber service will be disabled.\n");
455 #endif
456         }
457
458         /* return our Subversion id for the Log */
459         return "$Id$";
460 }