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