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