e696069a171ece7b5cac38dc2cb25abe09335231
[citadel.git] / citadel / modules / xmpp / serv_xmpp.c
1 /*
2  * XMPP (Jabber) service for the Citadel system
3  * Copyright (c) 2007-2011 by Art Cancro
4  *
5  * This program is open source 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 /* XML_StopParser is present in expat 2.x */
61 #if XML_MAJOR_VERSION > 1
62 #define HAVE_XML_STOPPARSER
63 #endif
64
65 struct xmpp_event *xmpp_queue = NULL;
66 HashList *XMPP_StartHandlers = NULL;
67 HashList *XMPP_EndHandlers = NULL;
68
69 int XMPPSrvDebugEnable = 0;
70
71
72
73 #ifdef HAVE_XML_STOPPARSER
74 /* Stop the parser if an entity declaration is hit. */
75 static void xmpp_entity_declaration(void *userData, const XML_Char *entityName,
76                                 int is_parameter_entity, const XML_Char *value,
77                                 int value_length, const XML_Char *base,
78                                 const XML_Char *systemId, const XML_Char *publicId,
79                                 const XML_Char *notationName
80 ) {
81         XMPPM_syslog(LOG_WARNING, "Illegal entity declaration encountered; stopping parser.");
82         XML_StopParser(XMPP->xp, XML_FALSE);
83 }
84 #endif
85
86 static inline int XMPP_GetUtf8SequenceLength(const char *CharS, const char *CharE)
87 {
88         /* if this is is migrated to strbuf, remove this copy. */
89         int n = 0;
90         unsigned char test = (1<<7);
91
92         if ((*CharS & 0xC0) != 0xC0) 
93                 return 1;
94
95         while ((n < 8) && 
96                ((test & ((unsigned char)*CharS)) != 0)) 
97         {
98                 test = test >> 1;
99                 n ++;
100         }
101         if ((n > 6) || ((CharE - CharS) < n))
102                 n = 0;
103         return n;
104 }
105
106
107 /*
108  * Given a source string and a target buffer, returns the string
109  * properly escaped for insertion into an XML stream.  Returns a
110  * pointer to the target buffer for convenience.
111  *
112  * BUG: this does not properly handle UTF-8
113  */
114 char *xmlesc(char *buf, char *str, int bufsiz)
115 {
116         char *ptr;
117         char *eiptr;
118         unsigned char ch;
119         int inlen;
120         int len = 0;
121         int IsUtf8Sequence;
122
123         if (!buf) return(NULL);
124         buf[0] = 0;
125         len = 0;
126         if (!str) {
127                 return(buf);
128         }
129
130         inlen = strlen(str);
131         eiptr = str + inlen;
132
133         for (ptr=str; *ptr; ptr++) {
134                 ch = *ptr;
135                 if (ch == '<') {
136                         strcpy(&buf[len], "&lt;");
137                         len += 4;
138                 }
139                 else if (ch == '>') {
140                         strcpy(&buf[len], "&gt;");
141                         len += 4;
142                 }
143                 else if (ch == '&') {
144                         strcpy(&buf[len], "&amp;");
145                         len += 5;
146                 }
147                 else if ((ch >= 0x20) && (ch <= 0x7F)) {
148                         buf[len++] = ch;
149                         buf[len] = 0;
150                 }
151                 else if (ch < 0x20) {
152                         /* we probably shouldn't be doing this */
153                         buf[len++] = '_';
154                         buf[len] = 0;
155                 }
156                 else {
157                         char oct[32];
158
159                         IsUtf8Sequence =  XMPP_GetUtf8SequenceLength(&buf[len], eiptr);
160                         if (IsUtf8Sequence)
161                         {
162                                 while (IsUtf8Sequence > 0){
163                                         buf[len] = *ptr;
164                                         len ++;
165                                         if (--IsUtf8Sequence)
166                                                 ptr++;
167                                 }
168                                 buf[len] = '\0';
169                         }
170                         else
171                         {
172                                 sprintf(oct, "&#%o;", ch);
173                                 strcpy(&buf[len], oct);
174                                 len += strlen(oct);
175                         }
176                 }
177                 if ((len + 6) > bufsiz) {
178                         return(buf);
179                 }
180         }
181         return(buf);
182 }
183
184
185 /*
186  * We have just received a <stream> tag from the client, so send them ours
187  */
188 void xmpp_stream_start(void *data, const char *supplied_el, const char **attr)
189 {
190         char xmlbuf[256];
191
192         while (*attr) {
193                 if (!strcasecmp(attr[0], "to")) {
194                         safestrncpy(XMPP->server_name, attr[1], sizeof XMPP->server_name);
195                 }
196                 attr += 2;
197         }
198
199         cprintf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
200
201         cprintf("<stream:stream ");
202         cprintf("from=\"%s\" ", xmlesc(xmlbuf, XMPP->server_name, sizeof xmlbuf));
203         cprintf("id=\"%08x\" ", CC->cs_pid);
204         cprintf("version=\"1.0\" ");
205         cprintf("xmlns:stream=\"http://etherx.jabber.org/streams\" ");
206         cprintf("xmlns=\"jabber:client\">");
207
208         /* The features of this stream are... */
209         cprintf("<stream:features>");
210
211         /*
212          * TLS encryption (but only if it isn't already active)
213          */ 
214 #ifdef HAVE_OPENSSL
215         if (!CC->redirect_ssl) {
216                 cprintf("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'></starttls>");
217         }
218 #endif
219
220         if (!CC->logged_in) {
221                 /* If we're not logged in yet, offer SASL as our feature set */
222                 xmpp_output_auth_mechs();
223
224                 /* Also offer non-SASL authentication */
225                 cprintf("<auth xmlns=\"http://jabber.org/features/iq-auth\"/>");
226         }
227
228         /* Offer binding and sessions as part of our feature set */
229         cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>");
230         cprintf("<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>");
231
232         cprintf("</stream:features>");
233
234         CC->is_async = 1;               /* XMPP sessions are inherently async-capable */
235 }
236
237 void xmpp_start_query(void *data, const char *supplied_el, const char **attr)
238 {
239         XMPP->iq_query_xmlns[0] = 0;
240         safestrncpy(XMPP->iq_query_xmlns, supplied_el, sizeof XMPP->iq_query_xmlns);
241 }
242
243 void xmpp_start_bind(void *data, const char *supplied_el, const char **attr)
244 {
245         XMPP->bind_requested = 1;
246 }
247
248 void xmpp_start_iq(void *data, const char *supplied_el, const char **attr)
249 {
250         int i;
251         for (i=0; attr[i] != NULL; i+=2) {
252                 if (!strcasecmp(attr[i], "type")) {
253                         safestrncpy(XMPP->iq_type, attr[i+1], sizeof XMPP->iq_type);
254                 }
255                 else if (!strcasecmp(attr[i], "id")) {
256                         safestrncpy(XMPP->iq_id, attr[i+1], sizeof XMPP->iq_id);
257                 }
258                 else if (!strcasecmp(attr[i], "from")) {
259                         safestrncpy(XMPP->iq_from, attr[i+1], sizeof XMPP->iq_from);
260                 }
261                 else if (!strcasecmp(attr[i], "to")) {
262                         safestrncpy(XMPP->iq_to, attr[i+1], sizeof XMPP->iq_to);
263                 }
264         }
265 }
266
267 void xmpp_start_auth(void *data, const char *supplied_el, const char **attr)
268 {
269         int i;
270
271         XMPP->sasl_auth_mech[0] = 0;
272         for (i=0; attr[i] != NULL; i+=2) {
273                 if (!strcasecmp(attr[i], "mechanism")) {
274                         safestrncpy(XMPP->sasl_auth_mech, attr[i+1], sizeof XMPP->sasl_auth_mech);
275                 }
276         }
277 }
278
279 void xmpp_start_message(void *data, const char *supplied_el, const char **attr)
280 {
281         int i;
282
283         for (i=0; attr[i] != NULL; i+=2) {
284                 if (!strcasecmp(attr[i], "to")) {
285                         safestrncpy(XMPP->message_to, attr[i+1], sizeof XMPP->message_to);
286                 }
287         }
288 }
289
290 void xmpp_start_html(void *data, const char *supplied_el, const char **attr)
291 {
292         ++XMPP->html_tag_level;
293 }
294
295 void xmpp_xml_start(void *data, const char *supplied_el, const char **attr)
296 {
297         char el[256];
298         long newlen;
299         long len;
300         char *sep = NULL;
301         void *pv;
302         
303         /* Axe the namespace, we don't care about it */
304         newlen = len = safestrncpy(el, supplied_el, sizeof el);
305         while (sep = strchr(el, ':'), sep)
306         {
307                 newlen -= ++sep - el;
308                 memmove(el, sep, newlen + 1);
309                 len = newlen;
310         }
311
312         /*
313         XMPP_syslog(LOG_DEBUG, "XMPP ELEMENT START: <%s>\n", el);
314         for (i=0; attr[i] != NULL; i+=2) {
315                 XMPP_syslog(LOG_DEBUG, "                    Attribute '%s' = '%s'\n", attr[i], attr[i+1]);
316         }
317         uncomment for more verbosity */
318
319         if (GetHash(XMPP_StartHandlers, el, len, &pv))
320         {
321                 xmpp_handler *h;
322                 h = (xmpp_handler*) pv;
323                 h->Handler(data, supplied_el, attr);
324         }
325
326 }
327
328 void xmpp_end_resource(void *data, const char *supplied_el, const char **attr)
329 {
330         if (XMPP->chardata_len > 0) {
331                 safestrncpy(XMPP->iq_client_resource, XMPP->chardata,
332                             sizeof XMPP->iq_client_resource);
333                 striplt(XMPP->iq_client_resource);
334         }
335 }
336
337 void xmpp_end_username(void *data, const char *supplied_el, const char **attr)
338 {
339         /* NON SASL ONLY */
340         if (XMPP->chardata_len > 0) {
341                 safestrncpy(XMPP->iq_client_username, XMPP->chardata,
342                             sizeof XMPP->iq_client_username);
343                 striplt(XMPP->iq_client_username);
344         }
345 }
346
347 void xmpp_end_password(void *data, const char *supplied_el, const char **attr)
348 {               /* NON SASL ONLY */
349         if (XMPP->chardata_len > 0) {
350                 safestrncpy(XMPP->iq_client_password, XMPP->chardata,
351                             sizeof XMPP->iq_client_password);
352                 striplt(XMPP->iq_client_password);
353         }
354 }
355
356 void xmpp_end_iq(void *data, const char *supplied_el, const char **attr)
357 {
358         char xmlbuf[256];
359         /*
360          * iq type="get" (handle queries)
361          */
362         if (!strcasecmp(XMPP->iq_type, "get"))
363         {
364                 /*
365                  * Query on a namespace
366                  */
367                 if (!IsEmptyStr(XMPP->iq_query_xmlns)) {
368                         xmpp_query_namespace(XMPP->iq_id, XMPP->iq_from,
369                                              XMPP->iq_to, XMPP->iq_query_xmlns);
370                 }
371                 
372                 /*
373                  * ping ( http://xmpp.org/extensions/xep-0199.html )
374                  */
375                 else if (XMPP->ping_requested) {
376                         cprintf("<iq type=\"result\" ");
377                         if (!IsEmptyStr(XMPP->iq_from)) {
378                                 cprintf("to=\"%s\" ", xmlesc(xmlbuf, XMPP->iq_from, sizeof xmlbuf));
379                         }
380                         if (!IsEmptyStr(XMPP->iq_to)) {
381                                 cprintf("from=\"%s\" ", xmlesc(xmlbuf, XMPP->iq_to, sizeof xmlbuf));
382                         }
383                         cprintf("id=\"%s\"/>", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
384                 }
385
386                 /*
387                  * Unknown query ... return the XML equivalent of a blank stare
388                  */
389                 else {
390 /*
391                         XMPP_syslog(LOG_DEBUG,
392                                     "Unknown query <%s> - returning <service-unavailable/>\n",
393                                     el
394                                 );
395 */
396                         cprintf("<iq type=\"error\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
397                         cprintf("<error code=\"503\" type=\"cancel\">"
398                                 "<service-unavailable xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>"
399                                 "</error>"
400                                 );
401                         cprintf("</iq>");
402                 }
403         }
404
405         /*
406          * Non SASL authentication
407          */
408         else if (
409                 (!strcasecmp(XMPP->iq_type, "set"))
410                 && (!strcasecmp(XMPP->iq_query_xmlns, "jabber:iq:auth:query"))
411                 ) {
412                 
413                 xmpp_non_sasl_authenticate(
414                         XMPP->iq_id,
415                         XMPP->iq_client_username,
416                         XMPP->iq_client_password,
417                         XMPP->iq_client_resource
418                         );
419         }
420
421         /*
422          * If this <iq> stanza was a "bind" attempt, process it ...
423          */
424         else if (
425                 (XMPP->bind_requested)
426                 && (!IsEmptyStr(XMPP->iq_id))
427                 && (!IsEmptyStr(XMPP->iq_client_resource))
428                 && (CC->logged_in)
429                 ) {
430
431                 /* Generate the "full JID" of the client resource */
432
433                 snprintf(XMPP->client_jid, sizeof XMPP->client_jid,
434                          "%s/%s",
435                          CC->cs_inet_email,
436                          XMPP->iq_client_resource
437                         );
438
439                 /* Tell the client what its JID is */
440
441                 cprintf("<iq type=\"result\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
442                 cprintf("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">");
443                 cprintf("<jid>%s</jid>", xmlesc(xmlbuf, XMPP->client_jid, sizeof xmlbuf));
444                 cprintf("</bind>");
445                 cprintf("</iq>");
446         }
447
448         else if (XMPP->iq_session) {
449                 cprintf("<iq type=\"result\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
450                 cprintf("</iq>");
451         }
452
453         else {
454                 cprintf("<iq type=\"error\" id=\"%s\">", xmlesc(xmlbuf, XMPP->iq_id, sizeof xmlbuf));
455                 cprintf("<error>Don't know howto do '%s'!</error>", xmlesc(xmlbuf, XMPP->iq_type, sizeof xmlbuf));
456                 cprintf("</iq>");
457         }
458
459         /* Now clear these fields out so they don't get used by a future stanza */
460         XMPP->iq_id[0] = 0;
461         XMPP->iq_from[0] = 0;
462         XMPP->iq_to[0] = 0;
463         XMPP->iq_type[0] = 0;
464         XMPP->iq_client_resource[0] = 0;
465         XMPP->iq_session = 0;
466         XMPP->iq_query_xmlns[0] = 0;
467         XMPP->bind_requested = 0;
468         XMPP->ping_requested = 0;
469 }
470
471
472 void xmpp_end_auth(void *data, const char *supplied_el, const char **attr)
473 {
474         /* Try to authenticate (this function is responsible for the output stanza) */
475         xmpp_sasl_auth(XMPP->sasl_auth_mech, (XMPP->chardata != NULL ? XMPP->chardata : "") );
476         
477         /* Now clear these fields out so they don't get used by a future stanza */
478         XMPP->sasl_auth_mech[0] = 0;
479 }
480
481 void xmpp_end_session(void *data, const char *supplied_el, const char **attr)
482 {
483         XMPP->iq_session = 1;
484 }
485
486 void xmpp_end_presence(void *data, const char *supplied_el, const char **attr)
487 {
488         /* Respond to a <presence> update by firing back with presence information
489          * on the entire wholist.  Check this assumption, it's probably wrong.
490          */
491         xmpp_wholist_presence_dump();
492 }
493
494 void xmpp_end_body(void *data, const char *supplied_el, const char **attr)
495 {
496         if (XMPP->html_tag_level == 0)
497         {
498                 if (XMPP->message_body != NULL)
499                 {
500                         free(XMPP->message_body);
501                         XMPP->message_body = NULL;
502                 }
503                 if (XMPP->chardata_len > 0) {
504                         XMPP->message_body = strdup(XMPP->chardata);
505                 }
506         }
507 }
508
509 void xmpp_end_message(void *data, const char *supplied_el, const char **attr)
510 {
511         xmpp_send_message(XMPP->message_to, XMPP->message_body);
512         XMPP->html_tag_level = 0;
513 }
514
515 void xmpp_end_html(void *data, const char *supplied_el, const char **attr)
516 {
517         --XMPP->html_tag_level;
518 }
519
520 void xmpp_end_starttls(void *data, const char *supplied_el, const char **attr)
521 {
522 #ifdef HAVE_OPENSSL
523         cprintf("<proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
524         CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
525         if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO;
526 #else
527         cprintf("<failure xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
528         CC->kill_me = KILLME_NO_CRYPTO;
529 #endif
530 }
531
532 void xmpp_end_ping(void *data, const char *supplied_el, const char **attr)
533 {
534         XMPP->ping_requested = 1;
535 }
536
537 void xmpp_end_stream(void *data, const char *supplied_el, const char **attr)
538 {
539         XMPPM_syslog(LOG_DEBUG, "XMPP client shut down their stream\n");
540         xmpp_massacre_roster();
541         cprintf("</stream>\n");
542         CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
543 }
544
545 void xmpp_xml_end(void *data, const char *supplied_el)
546 {
547         char el[256];
548         long len;
549         long newlen;
550         char *sep = NULL;
551         void *pv;
552
553         /* Axe the namespace, we don't care about it */
554         newlen = len = safestrncpy(el, supplied_el, sizeof el);
555         while (sep = strchr(el, ':'), sep) {
556
557                 newlen -= ++sep - el;
558                 memmove(el, sep, newlen + 1);
559                 len = newlen;
560         }
561
562         /*
563         XMPP_syslog(LOG_DEBUG, "XMPP ELEMENT END  : <%s>\n", el);
564         if (XMPP->chardata_len > 0) {
565                 XMPP_syslog(LOG_DEBUG, "          chardata: %s\n", XMPP->chardata);
566         }
567         uncomment for more verbosity */
568
569         if (GetHash(XMPP_EndHandlers, el, len, &pv))
570         {
571                 xmpp_handler *h;
572                 h = (xmpp_handler*) pv;
573                 h->Handler(data, supplied_el, NULL);
574         }
575         else
576         {
577                 XMPP_syslog(LOG_DEBUG, "Ignoring unknown tag <%s>\n", el);
578         }
579
580         XMPP->chardata_len = 0;
581         if (XMPP->chardata_alloc > 0) {
582                 XMPP->chardata[0] = 0;
583         }
584 }
585
586
587 void xmpp_xml_chardata(void *data, const XML_Char *s, int len)
588 {
589         citxmpp *X = XMPP;
590
591         if (X->chardata_alloc == 0) {
592                 X->chardata_alloc = SIZ;
593                 X->chardata = malloc(X->chardata_alloc);
594         }
595         if ((X->chardata_len + len + 1) > X->chardata_alloc) {
596                 X->chardata_alloc = X->chardata_len + len + 1024;
597                 X->chardata = realloc(X->chardata, X->chardata_alloc);
598         }
599         memcpy(&X->chardata[X->chardata_len], s, len);
600         X->chardata_len += len;
601         X->chardata[X->chardata_len] = 0;
602 }
603
604
605 /*
606  * This cleanup function blows away the temporary memory and files used by the XMPP service.
607  */
608 void xmpp_cleanup_function(void) {
609
610         /* Don't do this stuff if this is not a XMPP session! */
611         if (CC->h_command_function != xmpp_command_loop) return;
612
613         if (XMPP->chardata != NULL) {
614                 free(XMPP->chardata);
615                 XMPP->chardata = NULL;
616                 XMPP->chardata_len = 0;
617                 XMPP->chardata_alloc = 0;
618                 if (XMPP->message_body != NULL) {
619                         free(XMPP->message_body);
620                 }
621         }
622         XML_ParserFree(XMPP->xp);
623         free(XMPP);
624 }
625
626
627
628 /*
629  * Here's where our XMPP session begins its happy day.
630  */
631 void xmpp_greeting(void) {
632         client_set_inbound_buf(4);
633         strcpy(CC->cs_clientname, "XMPP session");
634         CC->session_specific_data = malloc(sizeof(citxmpp));
635         memset(XMPP, 0, sizeof(citxmpp));
636         XMPP->last_event_processed = queue_event_seq;
637
638         /* XMPP does not use a greeting, but we still have to initialize some things. */
639
640         XMPP->xp = XML_ParserCreateNS("UTF-8", ':');
641         if (XMPP->xp == NULL) {
642                 XMPPM_syslog(LOG_ALERT, "Cannot create XML parser!\n");
643                 CC->kill_me = KILLME_XML_PARSER;
644                 return;
645         }
646
647         XML_SetElementHandler(XMPP->xp, xmpp_xml_start, xmpp_xml_end);
648         XML_SetCharacterDataHandler(XMPP->xp, xmpp_xml_chardata);
649         // XML_SetUserData(XMPP->xp, something...);
650
651         /* Prevent the "billion laughs" attack against expat by disabling
652          * internal entity expansion.  With 2.x, forcibly stop the parser
653          * if an entity is declared - this is safer and a more obvious
654          * failure mode.  With older versions, simply prevent expansion
655          * of such entities. */
656 #ifdef HAVE_XML_STOPPARSER
657         XML_SetEntityDeclHandler(XMPP->xp, xmpp_entity_declaration);
658 #else
659         XML_SetDefaultHandler(XMPP->xp, NULL);
660 #endif
661
662         CC->can_receive_im = 1;         /* This protocol is capable of receiving instant messages */
663 }
664
665
666 /* 
667  * Main command loop for XMPP sessions.
668  */
669 void xmpp_command_loop(void) {
670         int rc;
671         StrBuf *stream_input = NewStrBuf();
672
673         time(&CC->lastcmd);
674         rc = client_read_random_blob(stream_input, 30);
675         if (rc > 0) {
676                 XML_Parse(XMPP->xp, ChrPtr(stream_input), rc, 0);
677         }
678         else {
679                 XMPPM_syslog(LOG_ERR, "client disconnected: ending session.\n");
680                 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
681         }
682         FreeStrBuf(&stream_input);
683 }
684
685
686 /*
687  * Async loop for XMPP sessions (handles the transmission of unsolicited stanzas)
688  */
689 void xmpp_async_loop(void) {
690         xmpp_process_events();
691         xmpp_output_incoming_messages();
692 }
693
694
695 /*
696  * Login hook for XMPP sessions
697  */
698 void xmpp_login_hook(void) {
699         xmpp_queue_event(XMPP_EVT_LOGIN, CC->cs_inet_email);
700 }
701
702
703 /*
704  * Logout hook for XMPP sessions
705  */
706 void xmpp_logout_hook(void) {
707         xmpp_queue_event(XMPP_EVT_LOGOUT, CC->cs_inet_email);
708 }
709
710
711 void LogXMPPSrvDebugEnable(const int n)
712 {
713         XMPPSrvDebugEnable = n;
714 }
715 const char *CitadelServiceXMPP="XMPP";
716 extern void xmpp_cleanup_events(void);
717
718
719
720 /******************************************************************************
721  *                    XMPP handler registering logic                           *
722  ******************************************************************************/
723
724 void AddXMPPStartHandler(const char *key,
725                          long len,
726                          xmpp_handler_func Handler,
727                          int Flags)
728 {
729         xmpp_handler *h;
730         h = (xmpp_handler*) malloc(sizeof (xmpp_handler));
731         h->Flags = Flags;
732         h->Handler = Handler;
733         Put(XMPP_StartHandlers, key, len, h, NULL);
734 }
735
736 void AddXMPPEndHandler(const char *key,
737                        long len,
738                        xmpp_handler_func Handler,
739                        int Flags)
740 {
741         xmpp_handler *h;
742         h = (xmpp_handler*) malloc(sizeof (xmpp_handler));
743         h->Flags = Flags;
744         h->Handler = Handler;
745         Put(XMPP_EndHandlers, key, len, h, NULL);
746 }
747
748 CTDL_MODULE_INIT(xmpp)
749 {
750         if (!threading) {
751                 CtdlRegisterServiceHook(config.c_xmpp_c2s_port,
752                                         NULL,
753                                         xmpp_greeting,
754                                         xmpp_command_loop,
755                                         xmpp_async_loop,
756                                         CitadelServiceXMPP);
757
758
759                 XMPP_StartHandlers = NewHash(1, NULL);
760                 XMPP_EndHandlers = NewHash(1, NULL);
761
762                 AddXMPPEndHandler(HKEY("resource"),      xmpp_end_resource, 0);
763                 AddXMPPEndHandler(HKEY("username"),      xmpp_end_username, 0);
764                 AddXMPPEndHandler(HKEY("password"),      xmpp_end_password, 0);
765                 AddXMPPEndHandler(HKEY("iq"),            xmpp_end_iq, 0);
766                 AddXMPPEndHandler(HKEY("auth"),          xmpp_end_auth, 0);
767                 AddXMPPEndHandler(HKEY("session"),       xmpp_end_session, 0);
768                 AddXMPPEndHandler(HKEY("presence"),      xmpp_end_presence, 0);
769                 AddXMPPEndHandler(HKEY("body"),          xmpp_end_body, 0);
770                 AddXMPPEndHandler(HKEY("message"),       xmpp_end_message, 0);
771                 AddXMPPEndHandler(HKEY("html"),          xmpp_end_html, 0);
772                 AddXMPPEndHandler(HKEY("starttls"),      xmpp_end_starttls, 0);
773                 AddXMPPEndHandler(HKEY("ping"),          xmpp_end_ping, 0);
774                 AddXMPPEndHandler(HKEY("stream"),        xmpp_end_stream, 0);
775
776
777                 AddXMPPStartHandler(HKEY("stream"),     xmpp_stream_start, 0);
778                 AddXMPPStartHandler(HKEY("query"),      xmpp_start_query, 0);
779                 AddXMPPStartHandler(HKEY("bind"),       xmpp_start_bind, 0);
780                 AddXMPPStartHandler(HKEY("iq"),         xmpp_start_iq, 0);
781                 AddXMPPStartHandler(HKEY("auth"),       xmpp_start_auth, 0);
782                 AddXMPPStartHandler(HKEY("message"),    xmpp_start_message, 0);
783                 AddXMPPStartHandler(HKEY("html"),       xmpp_start_html, 0);
784
785
786                 CtdlRegisterDebugFlagHook(HKEY("serv_xmpp"), LogXMPPSrvDebugEnable, &XMPPSrvDebugEnable);
787                 CtdlRegisterSessionHook(xmpp_cleanup_function, EVT_STOP, PRIO_STOP + 70);
788                 CtdlRegisterSessionHook(xmpp_login_hook, EVT_LOGIN, PRIO_LOGIN + 90);
789                 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_LOGOUT, PRIO_LOGOUT + 90);
790                 CtdlRegisterSessionHook(xmpp_login_hook, EVT_UNSTEALTH, PRIO_UNSTEALTH + 1);
791                 CtdlRegisterSessionHook(xmpp_logout_hook, EVT_STEALTH, PRIO_STEALTH + 1);
792                 CtdlRegisterCleanupHook(xmpp_cleanup_events);
793
794         }
795
796         /* return our module name for the log */
797         return "xmpp";
798 }