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