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