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