77369c487a6495e5071ad2b19f513b4820ff4207
[asterisk/asterisk.git] / res / res_xmpp.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2012, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief XMPP client and component module.
22  *
23  * \author Joshua Colp <jcolp@digium.com>
24  *
25  * Iksemel http://code.google.com/p/iksemel/
26  *
27  * A reference module for interfacting Asterisk directly as a client or component with
28  * an XMPP/Jabber compliant server.
29  *
30  * This module is based upon the original res_jabber as done by Matt O'Gorman.
31  *
32  */
33
34 /*! \li \ref res_xmpp.c uses the configuration file \ref xmpp.conf and \ref jabber.conf
35  * \addtogroup configuration_file Configuration Files
36  */
37
38 /*!
39  * \page xmpp.conf xmpp.conf
40  * \verbinclude xmpp.conf.sample
41  */
42
43 /*** MODULEINFO
44         <depend>iksemel</depend>
45         <use type="external">openssl</use>
46         <support_level>core</support_level>
47  ***/
48
49 #include "asterisk.h"
50
51 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
52
53 #include <ctype.h>
54 #include <iksemel.h>
55
56 #include "asterisk/xmpp.h"
57 #include "asterisk/module.h"
58 #include "asterisk/manager.h"
59 #include "asterisk/app.h"
60 #include "asterisk/message.h"
61 #include "asterisk/manager.h"
62 #include "asterisk/event.h"
63 #include "asterisk/cli.h"
64 #include "asterisk/config_options.h"
65
66 /*** DOCUMENTATION
67         <application name="JabberSend" language="en_US">
68                 <synopsis>
69                         Sends an XMPP message to a buddy.
70                 </synopsis>
71                 <syntax>
72                         <parameter name="account" required="true">
73                                 <para>The local named account to listen on (specified in
74                                 xmpp.conf)</para>
75                         </parameter>
76                         <parameter name="jid" required="true">
77                                 <para>Jabber ID of the buddy to send the message to. It can be a
78                                 bare JID (username@domain) or a full JID (username@domain/resource).</para>
79                         </parameter>
80                         <parameter name="message" required="true">
81                                 <para>The message to send.</para>
82                         </parameter>
83                 </syntax>
84                 <description>
85                         <para>Sends the content of <replaceable>message</replaceable> as text message
86                         from the given <replaceable>account</replaceable> to the buddy identified by
87                         <replaceable>jid</replaceable></para>
88                         <para>Example: JabberSend(asterisk,bob@domain.com,Hello world) sends "Hello world"
89                         to <replaceable>bob@domain.com</replaceable> as an XMPP message from the account
90                         <replaceable>asterisk</replaceable>, configured in xmpp.conf.</para>
91                 </description>
92                 <see-also>
93                         <ref type="function">JABBER_STATUS</ref>
94                         <ref type="function">JABBER_RECEIVE</ref>
95                 </see-also>
96         </application>
97         <function name="JABBER_RECEIVE" language="en_US">
98                 <synopsis>
99                         Reads XMPP messages.
100                 </synopsis>
101                 <syntax>
102                         <parameter name="account" required="true">
103                                 <para>The local named account to listen on (specified in
104                                 xmpp.conf)</para>
105                         </parameter>
106                         <parameter name="jid" required="true">
107                                 <para>Jabber ID of the buddy to receive message from. It can be a
108                                 bare JID (username@domain) or a full JID (username@domain/resource).</para>
109                         </parameter>
110                         <parameter name="timeout">
111                                 <para>In seconds, defaults to <literal>20</literal>.</para>
112                         </parameter>
113                 </syntax>
114                 <description>
115                         <para>Receives a text message on the given <replaceable>account</replaceable>
116                         from the buddy identified by <replaceable>jid</replaceable> and returns the contents.</para>
117                         <para>Example: ${JABBER_RECEIVE(asterisk,bob@domain.com)} returns an XMPP message
118                         sent from <replaceable>bob@domain.com</replaceable> (or nothing in case of a time out), to
119                         the <replaceable>asterisk</replaceable> XMPP account configured in xmpp.conf.</para>
120                 </description>
121                 <see-also>
122                         <ref type="function">JABBER_STATUS</ref>
123                         <ref type="application">JabberSend</ref>
124                 </see-also>
125         </function>
126         <function name="JABBER_STATUS" language="en_US">
127                 <synopsis>
128                         Retrieves a buddy's status.
129                 </synopsis>
130                 <syntax>
131                         <parameter name="account" required="true">
132                                 <para>The local named account to listen on (specified in
133                                 xmpp.conf)</para>
134                         </parameter>
135                         <parameter name="jid" required="true">
136                                 <para>Jabber ID of the buddy to receive message from. It can be a
137                                 bare JID (username@domain) or a full JID (username@domain/resource).</para>
138                         </parameter>
139                 </syntax>
140                 <description>
141                         <para>Retrieves the numeric status associated with the buddy identified
142                         by <replaceable>jid</replaceable>.
143                         If the buddy does not exist in the buddylist, returns 7.</para>
144                         <para>Status will be 1-7.</para>
145                         <para>1=Online, 2=Chatty, 3=Away, 4=XAway, 5=DND, 6=Offline</para>
146                         <para>If not in roster variable will be set to 7.</para>
147                         <para>Example: ${JABBER_STATUS(asterisk,bob@domain.com)} returns 1 if
148                         <replaceable>bob@domain.com</replaceable> is online. <replaceable>asterisk</replaceable> is
149                         the associated XMPP account configured in xmpp.conf.</para>
150                 </description>
151                 <see-also>
152                         <ref type="function">JABBER_RECEIVE</ref>
153                         <ref type="application">JabberSend</ref>
154                 </see-also>
155         </function>
156         <application name="JabberSendGroup" language="en_US">
157                 <synopsis>
158                         Send a Jabber Message to a specified chat room
159                 </synopsis>
160                 <syntax>
161                         <parameter name="Jabber" required="true">
162                                 <para>Client or transport Asterisk uses to connect to Jabber.</para>
163                         </parameter>
164                         <parameter name="RoomJID" required="true">
165                                 <para>XMPP/Jabber JID (Name) of chat room.</para>
166                         </parameter>
167                         <parameter name="Message" required="true">
168                                 <para>Message to be sent to the chat room.</para>
169                         </parameter>
170                         <parameter name="Nickname" required="false">
171                                 <para>The nickname Asterisk uses in the chat room.</para>
172                         </parameter>
173                 </syntax>
174                 <description>
175                         <para>Allows user to send a message to a chat room via XMPP.</para>
176                         <note><para>To be able to send messages to a chat room, a user must have previously joined it. Use the <replaceable>JabberJoin</replaceable> function to do so.</para></note>
177                 </description>
178         </application>
179         <application name="JabberJoin" language="en_US">
180                 <synopsis>
181                         Join a chat room
182                 </synopsis>
183                 <syntax>
184                         <parameter name="Jabber" required="true">
185                                 <para>Client or transport Asterisk uses to connect to Jabber.</para>
186                         </parameter>
187                         <parameter name="RoomJID" required="true">
188                                 <para>XMPP/Jabber JID (Name) of chat room.</para>
189                         </parameter>
190                         <parameter name="Nickname" required="false">
191                                 <para>The nickname Asterisk will use in the chat room.</para>
192                                 <note><para>If a different nickname is supplied to an already joined room, the old nick will be changed to the new one.</para></note>
193                         </parameter>
194                 </syntax>
195                 <description>
196                         <para>Allows Asterisk to join a chat room.</para>
197                 </description>
198         </application>
199         <application name="JabberLeave" language="en_US">
200                 <synopsis>
201                         Leave a chat room
202                 </synopsis>
203                 <syntax>
204                         <parameter name="Jabber" required="true">
205                                 <para>Client or transport Asterisk uses to connect to Jabber.</para>
206                         </parameter>
207                         <parameter name="RoomJID" required="true">
208                                 <para>XMPP/Jabber JID (Name) of chat room.</para>
209                         </parameter>
210                         <parameter name="Nickname" required="false">
211                                 <para>The nickname Asterisk uses in the chat room.</para>
212                         </parameter>
213                 </syntax>
214                 <description>
215                         <para>Allows Asterisk to leave a chat room.</para>
216                 </description>
217         </application>
218         <application name="JabberStatus" language="en_US">
219                 <synopsis>
220                         Retrieve the status of a jabber list member
221                 </synopsis>
222                 <syntax>
223                         <parameter name="Jabber" required="true">
224                                 <para>Client or transport Asterisk users to connect to Jabber.</para>
225                         </parameter>
226                         <parameter name="JID" required="true">
227                                 <para>XMPP/Jabber JID (Name) of recipient.</para>
228                         </parameter>
229                         <parameter name="Variable" required="true">
230                                 <para>Variable to store the status of requested user.</para>
231                         </parameter>
232                 </syntax>
233                 <description>
234                         <para>This application is deprecated. Please use the JABBER_STATUS() function instead.</para>
235                         <para>Retrieves the numeric status associated with the specified buddy <replaceable>JID</replaceable>.
236                         The return value in the <replaceable>Variable</replaceable>will be one of the following.</para>
237                         <enumlist>
238                                 <enum name="1">
239                                         <para>Online.</para>
240                                 </enum>
241                                 <enum name="2">
242                                         <para>Chatty.</para>
243                                 </enum>
244                                 <enum name="3">
245                                         <para>Away.</para>
246                                 </enum>
247                                 <enum name="4">
248                                         <para>Extended Away.</para>
249                                 </enum>
250                                 <enum name="5">
251                                         <para>Do Not Disturb.</para>
252                                 </enum>
253                                 <enum name="6">
254                                         <para>Offline.</para>
255                                 </enum>
256                                 <enum name="7">
257                                         <para>Not In Roster.</para>
258                                 </enum>
259                         </enumlist>
260                 </description>
261         </application>
262         <manager name="JabberSend" language="en_US">
263                 <synopsis>
264                         Sends a message to a Jabber Client.
265                 </synopsis>
266                 <syntax>
267                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
268                         <parameter name="Jabber" required="true">
269                                 <para>Client or transport Asterisk uses to connect to JABBER.</para>
270                         </parameter>
271                         <parameter name="JID" required="true">
272                                 <para>XMPP/Jabber JID (Name) of recipient.</para>
273                         </parameter>
274                         <parameter name="Message" required="true">
275                                 <para>Message to be sent to the buddy.</para>
276                         </parameter>
277                 </syntax>
278                 <description>
279                         <para>Sends a message to a Jabber Client.</para>
280                 </description>
281         </manager>
282         <info name="XMPPMessageToInfo" language="en_US" tech="XMPP">
283                 <para>Specifying a prefix of <literal>xmpp:</literal> will send the
284                 message as an XMPP chat message.</para>
285         </info>
286         <info name="XMPPMessageFromInfo" language="en_US" tech="XMPP">
287                 <para>Specifying a prefix of <literal>xmpp:</literal> will specify the
288                 account defined in <literal>xmpp.conf</literal> to send the message from.
289                 Note that this field is required for XMPP messages.</para>
290         </info>
291 ***/
292
293 /*! \brief Supported general configuration flags */
294 enum {
295         XMPP_AUTOPRUNE = (1 << 0),
296         XMPP_AUTOREGISTER = (1 << 1),
297         XMPP_AUTOACCEPT = (1 << 2),
298         XMPP_DEBUG = (1 << 3),
299         XMPP_USETLS = (1 << 4),
300         XMPP_USESASL = (1 << 5),
301         XMPP_FORCESSL = (1 << 6),
302         XMPP_KEEPALIVE = (1 << 7),
303         XMPP_COMPONENT = (1 << 8),
304         XMPP_SEND_TO_DIALPLAN = (1 << 9),
305         XMPP_DISTRIBUTE_EVENTS = (1 << 10),
306 };
307
308 /*! \brief Supported pubsub configuration flags */
309 enum {
310         XMPP_XEP0248 = (1 << 0),
311         XMPP_PUBSUB = (1 << 1),
312         XMPP_PUBSUB_AUTOCREATE = (1 << 2),
313 };
314
315 /*! \brief Number of buckets for client connections */
316 #define CLIENT_BUCKETS 53
317
318 /*! \brief Number of buckets for buddies (per client) */
319 #define BUDDY_BUCKETS 53
320
321 /*! \brief Number of buckets for resources (per buddy) */
322 #define RESOURCE_BUCKETS 53
323
324 /*! \brief Namespace for TLS support */
325 #define XMPP_TLS_NS "urn:ietf:params:xml:ns:xmpp-tls"
326
327 /*! \brief Status for a disappearing buddy */
328 #define STATUS_DISAPPEAR 6
329
330 /*! \brief Global debug status */
331 static int debug;
332
333 /*! \brief XMPP Global Configuration */
334 struct ast_xmpp_global_config {
335         struct ast_flags general; /*!< General configuration options */
336         struct ast_flags pubsub;  /*!< Pubsub related configuration options */
337 };
338
339 /*! \brief XMPP Client Configuration */
340 struct ast_xmpp_client_config {
341         AST_DECLARE_STRING_FIELDS(
342                 AST_STRING_FIELD(name);        /*!< Name of the client connection */
343                 AST_STRING_FIELD(user);        /*!< Username to use for authentication */
344                 AST_STRING_FIELD(password);    /*!< Password to use for authentication */
345                 AST_STRING_FIELD(server);      /*!< Server hostname */
346                 AST_STRING_FIELD(statusmsg);   /*!< Status message for presence */
347                 AST_STRING_FIELD(pubsubnode);  /*!< Pubsub node */
348                 AST_STRING_FIELD(context);     /*!< Context for incoming messages */
349                 );
350         int port;                       /*!< Port to use when connecting to server */
351         int message_timeout;            /*!< Timeout for messages */
352         int priority;                   /*!< Resource priority */
353         struct ast_flags flags;         /*!< Various options that have been set */
354         enum ikshowtype status;         /*!< Presence status */
355         struct ast_xmpp_client *client; /*!< Pointer to the client */
356         struct ao2_container *buddies;  /*!< Configured buddies */
357 };
358
359 struct xmpp_config {
360         struct ast_xmpp_global_config *global; /*!< Global configuration options */
361         struct ao2_container *clients;         /*!< Configured clients */
362 };
363
364 static AO2_GLOBAL_OBJ_STATIC(globals);
365
366 static int xmpp_client_request_tls(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node);
367 static int xmpp_client_requested_tls(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node);
368 static int xmpp_client_authenticate(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node);
369 static int xmpp_client_authenticating(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node);
370
371 static int xmpp_component_authenticate(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node);
372 static int xmpp_component_authenticating(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node);
373
374 /*! \brief Defined handlers for XMPP client states */
375 static const struct xmpp_state_handler {
376         int state;
377         int component;
378         int (*handler)(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node);
379 } xmpp_state_handlers[] = {
380         { XMPP_STATE_REQUEST_TLS, 0, xmpp_client_request_tls, },
381         { XMPP_STATE_REQUESTED_TLS, 0, xmpp_client_requested_tls, },
382         { XMPP_STATE_AUTHENTICATE, 0, xmpp_client_authenticate, },
383         { XMPP_STATE_AUTHENTICATING, 0, xmpp_client_authenticating, },
384         { XMPP_STATE_AUTHENTICATE, 1, xmpp_component_authenticate, },
385         { XMPP_STATE_AUTHENTICATING, 1, xmpp_component_authenticating, },
386 };
387
388 static int xmpp_pak_message(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, iks *node, ikspak *pak);
389 static int xmpp_pak_presence(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, iks *node, ikspak *pak);
390 static int xmpp_pak_s10n(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, iks *node, ikspak *pak);
391
392 /*! \brief Defined handlers for different PAK types */
393 static const struct xmpp_pak_handler {
394         int type;
395         int (*handler)(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, iks *node, ikspak *pak);
396 } xmpp_pak_handlers[] = {
397         { IKS_PAK_MESSAGE, xmpp_pak_message, },
398         { IKS_PAK_PRESENCE, xmpp_pak_presence, },
399         { IKS_PAK_S10N, xmpp_pak_s10n, },
400 };
401
402 static const char *app_ajisend = "JabberSend";
403 static const char *app_ajisendgroup = "JabberSendGroup";
404 static const char *app_ajistatus = "JabberStatus";
405 static const char *app_ajijoin = "JabberJoin";
406 static const char *app_ajileave = "JabberLeave";
407
408 static ast_cond_t message_received_condition;
409 static ast_mutex_t messagelock;
410
411 static int xmpp_client_config_post_apply(void *obj, void *arg, int flags);
412
413 /*! \brief Destructor function for configuration */
414 static void ast_xmpp_client_config_destructor(void *obj)
415 {
416         struct ast_xmpp_client_config *cfg = obj;
417         ast_string_field_free_memory(cfg);
418         ao2_cleanup(cfg->client);
419         ao2_cleanup(cfg->buddies);
420 }
421
422 /*! \brief Destroy function for XMPP messages */
423 static void xmpp_message_destroy(struct ast_xmpp_message *message)
424 {
425         if (message->from) {
426                 ast_free(message->from);
427         }
428         if (message->message) {
429                 ast_free(message->message);
430         }
431
432         ast_free(message);
433 }
434
435 /*! \brief Destructor callback function for XMPP client */
436 static void xmpp_client_destructor(void *obj)
437 {
438         struct ast_xmpp_client *client = obj;
439         struct ast_xmpp_message *message;
440
441         ast_xmpp_client_disconnect(client);
442
443         if (client->stack) {
444                 iks_stack_delete(client->stack);
445         }
446
447         ao2_cleanup(client->buddies);
448
449         while ((message = AST_LIST_REMOVE_HEAD(&client->messages, list))) {
450                 xmpp_message_destroy(message);
451         }
452         AST_LIST_HEAD_DESTROY(&client->messages);
453 }
454
455 /*! \brief Hashing function for XMPP buddy */
456 static int xmpp_buddy_hash(const void *obj, const int flags)
457 {
458         const struct ast_xmpp_buddy *buddy = obj;
459         const char *id = obj;
460
461         return ast_str_hash(flags & OBJ_KEY ? id : buddy->id);
462 }
463
464 /*! \brief Comparator function for XMPP buddy */
465 static int xmpp_buddy_cmp(void *obj, void *arg, int flags)
466 {
467         struct ast_xmpp_buddy *buddy1 = obj, *buddy2 = arg;
468         const char *id = arg;
469
470         return !strcmp(buddy1->id, flags & OBJ_KEY ? id : buddy2->id) ? CMP_MATCH | CMP_STOP : 0;
471 }
472
473 /*! \brief Allocator function for ast_xmpp_client */
474 static struct ast_xmpp_client *xmpp_client_alloc(const char *name)
475 {
476         struct ast_xmpp_client *client;
477
478         if (!(client = ao2_alloc(sizeof(*client), xmpp_client_destructor))) {
479                 return NULL;
480         }
481
482         AST_LIST_HEAD_INIT(&client->messages);
483         client->thread = AST_PTHREADT_NULL;
484
485         if (!(client->buddies = ao2_container_alloc(BUDDY_BUCKETS, xmpp_buddy_hash, xmpp_buddy_cmp))) {
486                 ast_log(LOG_ERROR, "Could not initialize buddy container for '%s'\n", name);
487                 ao2_ref(client, -1);
488                 return NULL;
489         }
490
491         if (ast_string_field_init(client, 512)) {
492                 ast_log(LOG_ERROR, "Could not initialize stringfields for '%s'\n", name);
493                 ao2_ref(client, -1);
494                 return NULL;
495         }
496
497         if (!(client->stack = iks_stack_new(8192, 8192))) {
498                 ast_log(LOG_ERROR, "Could not create an Iksemel stack for '%s'\n", name);
499                 ao2_ref(client, -1);
500                 return NULL;
501         }
502
503         ast_string_field_set(client, name, name);
504
505         client->timeout = 50;
506         client->state = XMPP_STATE_DISCONNECTED;
507         ast_copy_string(client->mid, "aaaaa", sizeof(client->mid));
508
509         return client;
510 }
511
512 /*! \brief Find function for configuration */
513 static void *xmpp_config_find(struct ao2_container *tmp_container, const char *category)
514 {
515         return ao2_find(tmp_container, category, OBJ_KEY);
516 }
517
518 /*! \brief Look up existing client or create a new one */
519 static void *xmpp_client_find_or_create(const char *category)
520 {
521         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
522         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
523
524         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, category))) {
525                 return xmpp_client_alloc(category);
526         }
527
528         ao2_ref(clientcfg->client, +1);
529         return clientcfg->client;
530 }
531
532 /*! \brief Allocator function for configuration */
533 static void *ast_xmpp_client_config_alloc(const char *cat)
534 {
535         struct ast_xmpp_client_config *cfg;
536
537         if (!(cfg = ao2_alloc(sizeof(*cfg), ast_xmpp_client_config_destructor))) {
538                 return NULL;
539         }
540
541         if (ast_string_field_init(cfg, 512)) {
542                 ao2_ref(cfg, -1);
543                 return NULL;
544         }
545
546         if (!(cfg->client = xmpp_client_find_or_create(cat))) {
547                 ao2_ref(cfg, -1);
548                 return NULL;
549         }
550
551         if (!(cfg->buddies = ao2_container_alloc(BUDDY_BUCKETS, xmpp_buddy_hash, xmpp_buddy_cmp))) {
552                 ao2_ref(cfg, -1);
553                 return NULL;
554         }
555
556         ast_string_field_set(cfg, name, cat);
557
558         return cfg;
559 }
560
561 /*! \brief Destructor for XMPP configuration */
562 static void xmpp_config_destructor(void *obj)
563 {
564         struct xmpp_config *cfg = obj;
565         ao2_cleanup(cfg->global);
566         ao2_cleanup(cfg->clients);
567 }
568
569 /*! \brief Hashing function for configuration */
570 static int xmpp_config_hash(const void *obj, const int flags)
571 {
572         const struct ast_xmpp_client_config *cfg = obj;
573         const char *name = (flags & OBJ_KEY) ? obj : cfg->name;
574         return ast_str_case_hash(name);
575 }
576
577 /*! \brief Comparator function for configuration */
578 static int xmpp_config_cmp(void *obj, void *arg, int flags)
579 {
580         struct ast_xmpp_client_config *one = obj, *two = arg;
581         const char *match = (flags & OBJ_KEY) ? arg : two->name;
582         return strcasecmp(one->name, match) ? 0 : (CMP_MATCH | CMP_STOP);
583 }
584
585 /*! \brief Allocator for XMPP configuration */
586 static void *xmpp_config_alloc(void)
587 {
588         struct xmpp_config *cfg;
589
590         if (!(cfg = ao2_alloc(sizeof(*cfg), xmpp_config_destructor))) {
591                 return NULL;
592         }
593
594         if (!(cfg->global = ao2_alloc(sizeof(*cfg->global), NULL))) {
595                 goto error;
596         }
597
598         ast_set_flag(&cfg->global->general, XMPP_AUTOREGISTER | XMPP_AUTOACCEPT | XMPP_USETLS | XMPP_USESASL | XMPP_KEEPALIVE);
599
600         if (!(cfg->clients = ao2_container_alloc(1, xmpp_config_hash, xmpp_config_cmp))) {
601                 goto error;
602         }
603
604         return cfg;
605 error:
606         ao2_ref(cfg, -1);
607         return NULL;
608 }
609
610 static int xmpp_config_prelink(void *newitem)
611 {
612         struct ast_xmpp_client_config *clientcfg = newitem;
613         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
614         RAII_VAR(struct ast_xmpp_client_config *, oldclientcfg, NULL, ao2_cleanup);
615
616         if (ast_strlen_zero(clientcfg->user)) {
617                 ast_log(LOG_ERROR, "No user specified on client '%s'\n", clientcfg->name);
618                 return -1;
619         } else if (ast_strlen_zero(clientcfg->password)) {
620                 ast_log(LOG_ERROR, "No password specified on client '%s'\n", clientcfg->name);
621                 return -1;
622         } else if (ast_strlen_zero(clientcfg->server)) {
623                 ast_log(LOG_ERROR, "No server specified on client '%s'\n", clientcfg->name);
624                 return -1;
625         }
626
627         /* If this is a new connection force a reconnect */
628         if (!cfg || !cfg->clients || !(oldclientcfg = xmpp_config_find(cfg->clients, clientcfg->name))) {
629                 clientcfg->client->reconnect = 1;
630                 return 0;
631         }
632
633         /* If any configuration options are changing that would require reconnecting set the bit so we will do so if possible */
634         if (strcmp(clientcfg->user, oldclientcfg->user) ||
635             strcmp(clientcfg->password, oldclientcfg->password) ||
636             strcmp(clientcfg->server, oldclientcfg->server) ||
637             (clientcfg->port != oldclientcfg->port) ||
638             (ast_test_flag(&clientcfg->flags, XMPP_COMPONENT) != ast_test_flag(&oldclientcfg->flags, XMPP_COMPONENT)) ||
639             (clientcfg->priority != oldclientcfg->priority)) {
640                 clientcfg->client->reconnect = 1;
641         } else {
642                 clientcfg->client->reconnect = 0;
643         }
644
645         return 0;
646 }
647
648 static void xmpp_config_post_apply(void)
649 {
650         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
651
652         ao2_callback(cfg->clients, OBJ_NODATA | OBJ_MULTIPLE, xmpp_client_config_post_apply, NULL);
653 }
654
655 static struct aco_type global_option = {
656         .type = ACO_GLOBAL,
657         .item_offset = offsetof(struct xmpp_config, global),
658         .category_match = ACO_WHITELIST,
659         .category = "^general$",
660 };
661
662 struct aco_type *global_options[] = ACO_TYPES(&global_option);
663
664 static struct aco_type client_option = {
665         .type = ACO_ITEM,
666         .category_match = ACO_BLACKLIST,
667         .category = "^(general)$",
668         .item_alloc = ast_xmpp_client_config_alloc,
669         .item_find = xmpp_config_find,
670         .item_prelink = xmpp_config_prelink,
671         .item_offset = offsetof(struct xmpp_config, clients),
672 };
673
674 struct aco_type *client_options[] = ACO_TYPES(&client_option);
675
676 struct aco_file res_xmpp_conf = {
677         .filename = "xmpp.conf",
678         .alias = "jabber.conf",
679         .types = ACO_TYPES(&global_option, &client_option),
680 };
681
682 CONFIG_INFO_STANDARD(cfg_info, globals, xmpp_config_alloc,
683                      .files = ACO_FILES(&res_xmpp_conf),
684                      .post_apply_config = xmpp_config_post_apply,
685         );
686
687 /*! \brief Destructor callback function for XMPP resource */
688 static void xmpp_resource_destructor(void *obj)
689 {
690         struct ast_xmpp_resource *resource = obj;
691
692         if (resource->description) {
693                 ast_free(resource->description);
694         }
695 }
696
697 /*! \brief Hashing function for XMPP resource */
698 static int xmpp_resource_hash(const void *obj, const int flags)
699 {
700         const struct ast_xmpp_resource *resource = obj;
701
702         return flags & OBJ_KEY ? -1 : resource->priority;
703 }
704
705 /*! \brief Comparator function for XMPP resource */
706 static int xmpp_resource_cmp(void *obj, void *arg, int flags)
707 {
708         struct ast_xmpp_resource *resource1 = obj, *resource2 = arg;
709         const char *resource = arg;
710
711         return !strcmp(resource1->resource, flags & OBJ_KEY ? resource : resource2->resource) ? CMP_MATCH | CMP_STOP : 0;
712 }
713
714 /*! \brief Destructor callback function for XMPP buddy */
715 static void xmpp_buddy_destructor(void *obj)
716 {
717         struct ast_xmpp_buddy *buddy = obj;
718
719         if (buddy->resources) {
720                 ao2_ref(buddy->resources, -1);
721         }
722 }
723
724 /*! \brief Helper function which returns whether an XMPP client connection is secure or not */
725 static int xmpp_is_secure(struct ast_xmpp_client *client)
726 {
727 #ifdef HAVE_OPENSSL
728         return client->stream_flags & SECURE;
729 #else
730         return 0;
731 #endif
732 }
733
734 struct ast_xmpp_client *ast_xmpp_client_find(const char *name)
735 {
736         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
737         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
738
739         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, name))) {
740                 return NULL;
741         }
742
743         ao2_ref(clientcfg->client, +1);
744         return clientcfg->client;
745 }
746
747 void ast_xmpp_client_unref(struct ast_xmpp_client *client)
748 {
749         ao2_ref(client, -1);
750 }
751
752 void ast_xmpp_client_lock(struct ast_xmpp_client *client)
753 {
754         ao2_lock(client);
755 }
756
757 void ast_xmpp_client_unlock(struct ast_xmpp_client *client)
758 {
759         ao2_unlock(client);
760 }
761
762 /*! \brief Internal function used to send a message to a user or chatroom */
763 static int xmpp_client_send_message(struct ast_xmpp_client *client, int group, const char *nick, const char *address, const char *message)
764 {
765         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
766         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
767         int res = 0;
768         char from[XMPP_MAX_JIDLEN];
769         iks *message_packet;
770
771         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name)) ||
772             !(message_packet = iks_make_msg(group ? IKS_TYPE_GROUPCHAT : IKS_TYPE_CHAT, address, message))) {
773                 return -1;
774         }
775
776         if (!ast_strlen_zero(nick) && ast_test_flag(&clientcfg->flags, XMPP_COMPONENT)) {
777                 snprintf(from, sizeof(from), "%s@%s/%s", nick, client->jid->full, nick);
778         } else {
779                 snprintf(from, sizeof(from), "%s", client->jid->full);
780         }
781
782         iks_insert_attrib(message_packet, "from", from);
783
784         res = ast_xmpp_client_send(client, message_packet);
785
786         iks_delete(message_packet);
787
788         return res;
789 }
790
791 int ast_xmpp_client_send_message(struct ast_xmpp_client *client, const char *user, const char *message)
792 {
793         return xmpp_client_send_message(client, 0, NULL, user, message);
794 }
795
796 int ast_xmpp_chatroom_invite(struct ast_xmpp_client *client, const char *user, const char *room, const char *message)
797 {
798         int res = 0;
799         iks *invite, *body = NULL, *namespace = NULL;
800
801         if (!(invite = iks_new("message")) || !(body = iks_new("body")) || !(namespace = iks_new("x"))) {
802                 res = -1;
803                 goto done;
804         }
805
806         iks_insert_attrib(invite, "to", user);
807         ast_xmpp_client_lock(client);
808         iks_insert_attrib(invite, "id", client->mid);
809         ast_xmpp_increment_mid(client->mid);
810         ast_xmpp_client_unlock(client);
811         iks_insert_cdata(body, message, 0);
812         iks_insert_node(invite, body);
813         iks_insert_attrib(namespace, "xmlns", "jabber:x:conference");
814         iks_insert_attrib(namespace, "jid", room);
815         iks_insert_node(invite, namespace);
816
817         res = ast_xmpp_client_send(client, invite);
818
819 done:
820         iks_delete(namespace);
821         iks_delete(body);
822         iks_delete(invite);
823
824         return res;
825 }
826
827 static int xmpp_client_set_group_presence(struct ast_xmpp_client *client, const char *room, int level, const char *nick)
828 {
829         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
830         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
831         int res = 0;
832         iks *presence = NULL, *x = NULL;
833         char from[XMPP_MAX_JIDLEN], roomid[XMPP_MAX_JIDLEN];
834
835         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name)) ||
836             !(presence = iks_make_pres(level, NULL)) || !(x = iks_new("x"))) {
837                 res = -1;
838                 goto done;
839         }
840
841         if (ast_test_flag(&clientcfg->flags, XMPP_COMPONENT)) {
842                 snprintf(from, sizeof(from), "%s@%s/%s", nick, client->jid->full, nick);
843                 snprintf(roomid, sizeof(roomid), "%s/%s", room, nick);
844         } else {
845                 snprintf(from, sizeof(from), "%s", client->jid->full);
846                 snprintf(roomid, sizeof(roomid), "%s/%s", room, S_OR(nick, client->jid->user));
847         }
848
849         iks_insert_attrib(presence, "to", roomid);
850         iks_insert_attrib(presence, "from", from);
851         iks_insert_attrib(x, "xmlns", "http://jabber.org/protocol/muc");
852         iks_insert_node(presence, x);
853
854         res = ast_xmpp_client_send(client, presence);
855
856 done:
857         iks_delete(x);
858         iks_delete(presence);
859
860         return res;
861 }
862
863 int ast_xmpp_chatroom_join(struct ast_xmpp_client *client, const char *room, const char *nickname)
864 {
865         return xmpp_client_set_group_presence(client, room, IKS_SHOW_AVAILABLE, nickname);
866 }
867
868 int ast_xmpp_chatroom_send(struct ast_xmpp_client *client, const char *nickname, const char *address, const char *message)
869 {
870         return xmpp_client_send_message(client, 1, nickname, address, message);
871 }
872
873 int ast_xmpp_chatroom_leave(struct ast_xmpp_client *client, const char *room, const char *nickname)
874 {
875         return xmpp_client_set_group_presence(client, room, IKS_SHOW_UNAVAILABLE, nickname);
876 }
877
878 void ast_xmpp_increment_mid(char *mid)
879 {
880         int i = 0;
881
882         for (i = strlen(mid) - 1; i >= 0; i--) {
883                 if (mid[i] != 'z') {
884                         mid[i] = mid[i] + 1;
885                         i = 0;
886                 } else {
887                         mid[i] = 'a';
888                 }
889         }
890 }
891
892 /*!
893  * \brief Create an IQ packet
894  * \param client the configured XMPP client we use to connect to a XMPP server
895  * \param type the type of IQ packet to create
896  * \return iks*
897  */
898 static iks* xmpp_pubsub_iq_create(struct ast_xmpp_client *client, const char *type)
899 {
900         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
901         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
902         iks *request;
903
904         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name)) ||
905             !(request = iks_new("iq"))) {
906                 return NULL;
907         }
908
909         if (!ast_strlen_zero(clientcfg->pubsubnode)) {
910                 iks_insert_attrib(request, "to", clientcfg->pubsubnode);
911         }
912
913         iks_insert_attrib(request, "from", client->jid->full);
914         iks_insert_attrib(request, "type", type);
915         ast_xmpp_client_lock(client);
916         ast_xmpp_increment_mid(client->mid);
917         iks_insert_attrib(request, "id", client->mid);
918         ast_xmpp_client_unlock(client);
919
920         return request;
921 }
922
923 /*!
924  * \brief Build the skeleton of a publish
925  * \param client the configured XMPP client we use to connect to a XMPP server
926  * \param node Name of the node that will be published to
927  * \param event_type
928  * \return iks *
929  */
930 static iks* xmpp_pubsub_build_publish_skeleton(struct ast_xmpp_client *client, const char *node,
931                                                const char *event_type)
932 {
933         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
934         iks *request, *pubsub, *publish, *item;
935
936         if (!cfg || !cfg->global || !(request = xmpp_pubsub_iq_create(client, "set"))) {
937                 return NULL;
938         }
939
940         pubsub = iks_insert(request, "pubsub");
941         iks_insert_attrib(pubsub, "xmlns", "http://jabber.org/protocol/pubsub");
942         publish = iks_insert(pubsub, "publish");
943         iks_insert_attrib(publish, "node", ast_test_flag(&cfg->global->pubsub, XMPP_XEP0248) ? node : event_type);
944         item = iks_insert(publish, "item");
945         iks_insert_attrib(item, "id", node);
946
947         return item;
948
949 }
950
951 static iks* xmpp_pubsub_build_node_config(iks *pubsub, const char *node_type, const char *collection_name)
952 {
953         iks *configure, *x, *field_owner, *field_node_type, *field_node_config,
954                 *field_deliver_payload, *field_persist_items, *field_access_model,
955                 *field_pubsub_collection;
956         configure = iks_insert(pubsub, "configure");
957         x = iks_insert(configure, "x");
958         iks_insert_attrib(x, "xmlns", "jabber:x:data");
959         iks_insert_attrib(x, "type", "submit");
960         field_owner = iks_insert(x, "field");
961         iks_insert_attrib(field_owner, "var", "FORM_TYPE");
962         iks_insert_attrib(field_owner, "type", "hidden");
963         iks_insert_cdata(iks_insert(field_owner, "value"),
964                          "http://jabber.org/protocol/pubsub#owner", 39);
965         if (node_type) {
966                 field_node_type = iks_insert(x, "field");
967                 iks_insert_attrib(field_node_type, "var", "pubsub#node_type");
968                 iks_insert_cdata(iks_insert(field_node_type, "value"), node_type, strlen(node_type));
969         }
970         field_node_config = iks_insert(x, "field");
971         iks_insert_attrib(field_node_config, "var", "FORM_TYPE");
972         iks_insert_attrib(field_node_config, "type", "hidden");
973         iks_insert_cdata(iks_insert(field_node_config, "value"),
974                          "http://jabber.org/protocol/pubsub#node_config", 45);
975         field_deliver_payload = iks_insert(x, "field");
976         iks_insert_attrib(field_deliver_payload, "var", "pubsub#deliver_payloads");
977         iks_insert_cdata(iks_insert(field_deliver_payload, "value"), "1", 1);
978         field_persist_items = iks_insert(x, "field");
979         iks_insert_attrib(field_persist_items, "var", "pubsub#persist_items");
980         iks_insert_cdata(iks_insert(field_persist_items, "value"), "1", 1);
981         field_access_model = iks_insert(x, "field");
982         iks_insert_attrib(field_access_model, "var", "pubsub#access_model");
983         iks_insert_cdata(iks_insert(field_access_model, "value"), "whitelist", 9);
984         if (node_type && !strcasecmp(node_type, "leaf")) {
985                 field_pubsub_collection = iks_insert(x, "field");
986                 iks_insert_attrib(field_pubsub_collection, "var", "pubsub#collection");
987                 iks_insert_cdata(iks_insert(field_pubsub_collection, "value"), collection_name,
988                                  strlen(collection_name));
989         }
990         return configure;
991 }
992
993 /*!
994  * \brief Add Owner affiliations for pubsub node
995  * \param client the configured XMPP client we use to connect to a XMPP server
996  * \param node the name of the node to which to add affiliations
997  * \return void
998  */
999 static void xmpp_pubsub_create_affiliations(struct ast_xmpp_client *client, const char *node)
1000 {
1001         iks *modify_affiliates = xmpp_pubsub_iq_create(client, "set");
1002         iks *pubsub, *affiliations, *affiliate;
1003         struct ao2_iterator i;
1004         struct ast_xmpp_buddy *buddy;
1005
1006         if (!modify_affiliates) {
1007                 ast_log(LOG_ERROR, "Could not create IQ for creating affiliations on client '%s'\n", client->name);
1008                 return;
1009         }
1010
1011         pubsub = iks_insert(modify_affiliates, "pubsub");
1012         iks_insert_attrib(pubsub, "xmlns", "http://jabber.org/protocol/pubsub#owner");
1013         affiliations = iks_insert(pubsub, "affiliations");
1014         iks_insert_attrib(affiliations, "node", node);
1015
1016         i = ao2_iterator_init(client->buddies, 0);
1017         while ((buddy = ao2_iterator_next(&i))) {
1018                 affiliate = iks_insert(affiliations, "affiliation");
1019                 iks_insert_attrib(affiliate, "jid", buddy->id);
1020                 iks_insert_attrib(affiliate, "affiliation", "owner");
1021                 ao2_ref(buddy, -1);
1022         }
1023         ao2_iterator_destroy(&i);
1024
1025         ast_xmpp_client_send(client, modify_affiliates);
1026         iks_delete(modify_affiliates);
1027 }
1028
1029 /*!
1030  * \brief Create a pubsub node
1031  * \param client the configured XMPP client we use to connect to a XMPP server
1032  * \param node_type the type of node to create
1033  * \param name the name of the node to create
1034  * \param collection_name
1035  * \return void
1036  */
1037 static void xmpp_pubsub_create_node(struct ast_xmpp_client *client, const char *node_type, const
1038                                     char *name, const char *collection_name)
1039 {
1040         iks *node, *pubsub, *create;
1041
1042         if (!(node = xmpp_pubsub_iq_create(client, "set"))) {
1043                 return;
1044         }
1045
1046         pubsub = iks_insert(node, "pubsub");
1047         iks_insert_attrib(pubsub, "xmlns", "http://jabber.org/protocol/pubsub");
1048         create = iks_insert(pubsub, "create");
1049         iks_insert_attrib(create, "node", name);
1050         xmpp_pubsub_build_node_config(pubsub, node_type, collection_name);
1051         ast_xmpp_client_send(client, node);
1052         xmpp_pubsub_create_affiliations(client, name);
1053         iks_delete(node);
1054 }
1055
1056 /*!
1057  * \brief Delete a PubSub node
1058  * \param client the configured XMPP client we use to connect to a XMPP server
1059  * \param node_name the name of the node to delete
1060  * return void
1061  */
1062 static void xmpp_pubsub_delete_node(struct ast_xmpp_client *client, const char *node_name)
1063 {
1064         iks *request, *pubsub, *delete;
1065
1066         if (!(request = xmpp_pubsub_iq_create(client, "set"))) {
1067                 return;
1068         }
1069
1070         pubsub = iks_insert(request, "pubsub");
1071         iks_insert_attrib(pubsub, "xmlns", "http://jabber.org/protocol/pubsub#owner");
1072         delete = iks_insert(pubsub, "delete");
1073         iks_insert_attrib(delete, "node", node_name);
1074         ast_xmpp_client_send(client, request);
1075
1076         iks_delete(delete);
1077         iks_delete(pubsub);
1078         iks_delete(request);
1079 }
1080
1081 /*!
1082  * \brief Create a PubSub collection node.
1083  * \param client the configured XMPP client we use to connect to a XMPP server
1084  * \param collection_name The name to use for this collection
1085  * \return void.
1086  */
1087 static void xmpp_pubsub_create_collection(struct ast_xmpp_client *client, const char *collection_name)
1088 {
1089         xmpp_pubsub_create_node(client, "collection", collection_name, NULL);
1090 }
1091
1092
1093 /*!
1094  * \brief Create a PubSub leaf node.
1095  * \param client the configured XMPP client we use to connect to a XMPP server
1096  * \param collection_name
1097  * \param leaf_name The name to use for this collection
1098  * \return void.
1099  */
1100 static void xmpp_pubsub_create_leaf(struct ast_xmpp_client *client, const char *collection_name,
1101                                     const char *leaf_name)
1102 {
1103         xmpp_pubsub_create_node(client, "leaf", leaf_name, collection_name);
1104 }
1105
1106 /*!
1107  * \brief Publish MWI to a PubSub node
1108  * \param client the configured XMPP client we use to connect to a XMPP server
1109  * \param mailbox The Mailbox
1110  * \param context The Context
1111  * \param oldmsgs Old messages
1112  * \param newmsgs New Messages
1113  * \return void
1114  */
1115 static void xmpp_pubsub_publish_mwi(struct ast_xmpp_client *client, const char *mailbox,
1116                                     const char *context, const char *oldmsgs, const char *newmsgs)
1117 {
1118         char full_mailbox[AST_MAX_EXTENSION+AST_MAX_CONTEXT], eid_str[20];
1119         iks *mailbox_node, *request;
1120
1121         snprintf(full_mailbox, sizeof(full_mailbox), "%s@%s", mailbox, context);
1122
1123         if (!(request = xmpp_pubsub_build_publish_skeleton(client, full_mailbox, "message_waiting"))) {
1124                 return;
1125         }
1126
1127         ast_eid_to_str(eid_str, sizeof(eid_str), &ast_eid_default);
1128         mailbox_node = iks_insert(request, "mailbox");
1129         iks_insert_attrib(mailbox_node, "xmlns", "http://asterisk.org");
1130         iks_insert_attrib(mailbox_node, "eid", eid_str);
1131         iks_insert_cdata(iks_insert(mailbox_node, "NEWMSGS"), newmsgs, strlen(newmsgs));
1132         iks_insert_cdata(iks_insert(mailbox_node, "OLDMSGS"), oldmsgs, strlen(oldmsgs));
1133
1134         ast_xmpp_client_send(client, iks_root(request));
1135
1136         iks_delete(request);
1137 }
1138
1139 /*!
1140  * \brief Publish device state to a PubSub node
1141  * \param client the configured XMPP client we use to connect to a XMPP server
1142  * \param device the name of the device whose state to publish
1143  * \param device_state the state to publish
1144  * \return void
1145  */
1146 static void xmpp_pubsub_publish_device_state(struct ast_xmpp_client *client, const char *device,
1147                                              const char *device_state)
1148 {
1149         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1150         iks *request, *state;
1151         char eid_str[20];
1152
1153         if (!cfg || !cfg->global || !(request = xmpp_pubsub_build_publish_skeleton(client, device, "device_state"))) {
1154                 return;
1155         }
1156
1157         if (ast_test_flag(&cfg->global->pubsub, XMPP_PUBSUB_AUTOCREATE)) {
1158                 if (ast_test_flag(&cfg->global->pubsub, XMPP_XEP0248)) {
1159                         xmpp_pubsub_create_node(client, "leaf", device, "device_state");
1160                 } else {
1161                         xmpp_pubsub_create_node(client, NULL, device, NULL);
1162                 }
1163         }
1164
1165         ast_eid_to_str(eid_str, sizeof(eid_str), &ast_eid_default);
1166         state = iks_insert(request, "state");
1167         iks_insert_attrib(state, "xmlns", "http://asterisk.org");
1168         iks_insert_attrib(state, "eid", eid_str);
1169         iks_insert_cdata(state, device_state, strlen(device_state));
1170         ast_xmpp_client_send(client, iks_root(request));
1171         iks_delete(request);
1172 }
1173
1174 /*!
1175  * \brief Callback function for MWI events
1176  * \param ast_event
1177  * \param data void pointer to ast_client structure
1178  * \return void
1179  */
1180 static void xmpp_pubsub_mwi_cb(const struct ast_event *ast_event, void *data)
1181 {
1182         struct ast_xmpp_client *client = data;
1183         const char *mailbox, *context;
1184         char oldmsgs[10], newmsgs[10];
1185
1186         if (ast_eid_cmp(&ast_eid_default, ast_event_get_ie_raw(ast_event, AST_EVENT_IE_EID))) {
1187                 /* If the event didn't originate from this server, don't send it back out. */
1188                 ast_debug(1, "Returning here\n");
1189                 return;
1190         }
1191
1192         mailbox = ast_event_get_ie_str(ast_event, AST_EVENT_IE_MAILBOX);
1193         context = ast_event_get_ie_str(ast_event, AST_EVENT_IE_CONTEXT);
1194         snprintf(oldmsgs, sizeof(oldmsgs), "%d",
1195                  ast_event_get_ie_uint(ast_event, AST_EVENT_IE_OLDMSGS));
1196         snprintf(newmsgs, sizeof(newmsgs), "%d",
1197                  ast_event_get_ie_uint(ast_event, AST_EVENT_IE_NEWMSGS));
1198         xmpp_pubsub_publish_mwi(client, mailbox, context, oldmsgs, newmsgs);
1199 }
1200
1201 /*!
1202  * \brief Callback function for device state events
1203  * \param ast_event
1204  * \param data void pointer to ast_client structure
1205  * \return void
1206  */
1207 static void xmpp_pubsub_devstate_cb(const struct ast_event *ast_event, void *data)
1208 {
1209         struct ast_xmpp_client *client = data;
1210         const char *device, *device_state;
1211
1212         if (ast_eid_cmp(&ast_eid_default, ast_event_get_ie_raw(ast_event, AST_EVENT_IE_EID))) {
1213                 /* If the event didn't originate from this server, don't send it back out. */
1214                 ast_debug(1, "Returning here\n");
1215                 return;
1216         }
1217
1218         device = ast_event_get_ie_str(ast_event, AST_EVENT_IE_DEVICE);
1219         device_state = ast_devstate_str(ast_event_get_ie_uint(ast_event, AST_EVENT_IE_STATE));
1220         xmpp_pubsub_publish_device_state(client, device, device_state);
1221 }
1222
1223 /*!
1224  * \brief Unsubscribe from a PubSub node
1225  * \param client the configured XMPP client we use to connect to a XMPP server
1226  * \param node the name of the node to which to unsubscribe from
1227  * \return void
1228  */
1229 static void xmpp_pubsub_unsubscribe(struct ast_xmpp_client *client, const char *node)
1230 {
1231         iks *request = xmpp_pubsub_iq_create(client, "set");
1232         iks *pubsub, *unsubscribe;
1233
1234         if (!request) {
1235                 ast_log(LOG_ERROR, "Could not create IQ when creating pubsub unsubscription on client '%s'\n", client->name);
1236                 return;
1237         }
1238
1239         pubsub = iks_insert(request, "pubsub");
1240         iks_insert_attrib(pubsub, "xmlns", "http://jabber.org/protocol/pubsub");
1241         unsubscribe = iks_insert(pubsub, "unsubscribe");
1242         iks_insert_attrib(unsubscribe, "jid", client->jid->partial);
1243         iks_insert_attrib(unsubscribe, "node", node);
1244
1245         ast_xmpp_client_send(client, request);
1246         iks_delete(request);
1247 }
1248
1249 /*!
1250  * \brief Subscribe to a PubSub node
1251  * \param client the configured XMPP client we use to connect to a XMPP server
1252  * \param node the name of the node to which to subscribe
1253  * \return void
1254  */
1255 static void xmpp_pubsub_subscribe(struct ast_xmpp_client *client, const char *node)
1256 {
1257         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1258         iks *request = xmpp_pubsub_iq_create(client, "set");
1259         iks *pubsub, *subscribe;
1260
1261         if (!cfg || !cfg->global || !request) {
1262                 ast_log(LOG_ERROR, "Could not create IQ when creating pubsub subscription on client '%s'\n", client->name);
1263                 return;
1264         }
1265
1266         pubsub = iks_insert(request, "pubsub");
1267         iks_insert_attrib(pubsub, "xmlns", "http://jabber.org/protocol/pubsub");
1268         subscribe = iks_insert(pubsub, "subscribe");
1269         iks_insert_attrib(subscribe, "jid", client->jid->partial);
1270         iks_insert_attrib(subscribe, "node", node);
1271         if (ast_test_flag(&cfg->global->pubsub, XMPP_XEP0248)) {
1272                 iks *options, *x, *sub_options, *sub_type, *sub_depth, *sub_expire;
1273                 options = iks_insert(pubsub, "options");
1274                 x = iks_insert(options, "x");
1275                 iks_insert_attrib(x, "xmlns", "jabber:x:data");
1276                 iks_insert_attrib(x, "type", "submit");
1277                 sub_options = iks_insert(x, "field");
1278                 iks_insert_attrib(sub_options, "var", "FORM_TYPE");
1279                 iks_insert_attrib(sub_options, "type", "hidden");
1280                 iks_insert_cdata(iks_insert(sub_options, "value"),
1281                                  "http://jabber.org/protocol/pubsub#subscribe_options", 51);
1282                 sub_type = iks_insert(x, "field");
1283                 iks_insert_attrib(sub_type, "var", "pubsub#subscription_type");
1284                 iks_insert_cdata(iks_insert(sub_type, "value"), "items", 5);
1285                 sub_depth = iks_insert(x, "field");
1286                 iks_insert_attrib(sub_depth, "var", "pubsub#subscription_depth");
1287                 iks_insert_cdata(iks_insert(sub_depth, "value"), "all", 3);
1288                 sub_expire = iks_insert(x, "field");
1289                 iks_insert_attrib(sub_expire, "var", "pubsub#expire");
1290                 iks_insert_cdata(iks_insert(sub_expire, "value"), "presence", 8);
1291         }
1292         ast_xmpp_client_send(client, request);
1293         iks_delete(request);
1294 }
1295
1296 /*!
1297  * \brief Callback for handling PubSub events
1298  * \param data void pointer to ast_xmpp_client structure
1299  * \param pak A pak
1300  * \return IKS_FILTER_EAT
1301  */
1302 static int xmpp_pubsub_handle_event(void *data, ikspak *pak)
1303 {
1304         char *item_id, *device_state, *context;
1305         int oldmsgs, newmsgs;
1306         iks *item, *item_content;
1307         struct ast_eid pubsub_eid;
1308         struct ast_event *event;
1309         item = iks_find(iks_find(iks_find(pak->x, "event"), "items"), "item");
1310         if (!item) {
1311                 ast_log(LOG_ERROR, "Could not parse incoming PubSub event\n");
1312                 return IKS_FILTER_EAT;
1313         }
1314         item_id = iks_find_attrib(item, "id");
1315         item_content = iks_child(item);
1316         ast_str_to_eid(&pubsub_eid, iks_find_attrib(item_content, "eid"));
1317         if (!ast_eid_cmp(&ast_eid_default, &pubsub_eid)) {
1318                 ast_debug(1, "Returning here, eid of incoming event matches ours!\n");
1319                 return IKS_FILTER_EAT;
1320         }
1321         if (!strcasecmp(iks_name(item_content), "state")) {
1322                 device_state = iks_find_cdata(item, "state");
1323                 if (!(event = ast_event_new(AST_EVENT_DEVICE_STATE_CHANGE,
1324                                             AST_EVENT_IE_DEVICE, AST_EVENT_IE_PLTYPE_STR, item_id, AST_EVENT_IE_STATE,
1325                                             AST_EVENT_IE_PLTYPE_UINT, ast_devstate_val(device_state), AST_EVENT_IE_EID,
1326                                             AST_EVENT_IE_PLTYPE_RAW, &pubsub_eid, sizeof(pubsub_eid),
1327                                             AST_EVENT_IE_END))) {
1328                         return IKS_FILTER_EAT;
1329                 }
1330         } else if (!strcasecmp(iks_name(item_content), "mailbox")) {
1331                 context = strsep(&item_id, "@");
1332                 sscanf(iks_find_cdata(item_content, "OLDMSGS"), "%10d", &oldmsgs);
1333                 sscanf(iks_find_cdata(item_content, "NEWMSGS"), "%10d", &newmsgs);
1334                 if (!(event = ast_event_new(AST_EVENT_MWI, AST_EVENT_IE_MAILBOX,
1335                                             AST_EVENT_IE_PLTYPE_STR, item_id, AST_EVENT_IE_CONTEXT,
1336                                             AST_EVENT_IE_PLTYPE_STR, context, AST_EVENT_IE_OLDMSGS,
1337                                             AST_EVENT_IE_PLTYPE_UINT, oldmsgs, AST_EVENT_IE_NEWMSGS,
1338                                             AST_EVENT_IE_PLTYPE_UINT, newmsgs, AST_EVENT_IE_EID, AST_EVENT_IE_PLTYPE_RAW,
1339                                             &pubsub_eid, sizeof(pubsub_eid), AST_EVENT_IE_END))) {
1340                         return IKS_FILTER_EAT;
1341                 }
1342         } else {
1343                 ast_debug(1, "Don't know how to handle PubSub event of type %s\n",
1344                           iks_name(item_content));
1345                 return IKS_FILTER_EAT;
1346         }
1347         ast_event_queue_and_cache(event);
1348         return IKS_FILTER_EAT;
1349 }
1350
1351 static int xmpp_pubsub_handle_error(void *data, ikspak *pak)
1352 {
1353         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1354         char *node_name, *error;
1355         int error_num;
1356         iks *orig_request, *orig_pubsub = iks_find(pak->x, "pubsub");
1357         struct ast_xmpp_client *client = data;
1358
1359         if (!cfg || !cfg->global) {
1360                 ast_log(LOG_ERROR, "No global configuration available\n");
1361                 return IKS_FILTER_EAT;
1362         }
1363
1364         if (!orig_pubsub) {
1365                 ast_log(LOG_ERROR, "Error isn't a PubSub error, why are we here?\n");
1366                 return IKS_FILTER_EAT;
1367         }
1368
1369         orig_request = iks_child(orig_pubsub);
1370         error = iks_find_attrib(iks_find(pak->x, "error"), "code");
1371         node_name = iks_find_attrib(orig_request, "node");
1372
1373         if (!sscanf(error, "%30d", &error_num)) {
1374                 return IKS_FILTER_EAT;
1375         }
1376
1377         if (error_num > 399 && error_num < 500 && error_num != 404) {
1378                 ast_log(LOG_ERROR,
1379                         "Error performing operation on PubSub node %s, %s.\n", node_name, error);
1380                 return IKS_FILTER_EAT;
1381         } else if (error_num > 499 && error_num < 600) {
1382                 ast_log(LOG_ERROR, "PubSub Server error, %s\n", error);
1383                 return IKS_FILTER_EAT;
1384         }
1385
1386         if (!strcasecmp(iks_name(orig_request), "publish")) {
1387                 iks *request;
1388
1389                 if (ast_test_flag(&cfg->global->pubsub, XMPP_XEP0248)) {
1390                         if (iks_find(iks_find(orig_request, "item"), "state")) {
1391                                 xmpp_pubsub_create_leaf(client, "device_state", node_name);
1392                         } else if (iks_find(iks_find(orig_request, "item"), "mailbox")) {
1393                                 xmpp_pubsub_create_leaf(client, "message_waiting", node_name);
1394                         }
1395                 } else {
1396                         xmpp_pubsub_create_node(client, NULL, node_name, NULL);
1397                 }
1398
1399                 if ((request = xmpp_pubsub_iq_create(client, "set"))) {
1400                         iks_insert_node(request, orig_pubsub);
1401                         ast_xmpp_client_send(client, request);
1402                         iks_delete(request);
1403                 } else {
1404                         ast_log(LOG_ERROR, "PubSub publish could not create IQ\n");
1405                 }
1406
1407                 return IKS_FILTER_EAT;
1408         } else if (!strcasecmp(iks_name(orig_request), "subscribe")) {
1409                 if (ast_test_flag(&cfg->global->pubsub, XMPP_XEP0248)) {
1410                         xmpp_pubsub_create_collection(client, node_name);
1411                 } else {
1412                         xmpp_pubsub_create_node(client, NULL, node_name, NULL);
1413                 }
1414         }
1415
1416         return IKS_FILTER_EAT;
1417 }
1418
1419 /*!
1420  * \brief Initialize collections for event distribution
1421  * \param client the configured XMPP client we use to connect to a XMPP server
1422  * \return void
1423  */
1424 static void xmpp_init_event_distribution(struct ast_xmpp_client *client)
1425 {
1426         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1427         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
1428
1429         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name))) {
1430                 return;
1431         }
1432
1433         xmpp_pubsub_unsubscribe(client, "device_state");
1434         xmpp_pubsub_unsubscribe(client, "message_waiting");
1435
1436         if (!(client->mwi_sub = ast_event_subscribe(AST_EVENT_MWI, xmpp_pubsub_mwi_cb, "xmpp_pubsub_mwi_subscription",
1437                                                     client, AST_EVENT_IE_END))) {
1438                 return;
1439         }
1440
1441         if (ast_enable_distributed_devstate()) {
1442                 return;
1443         }
1444         
1445
1446         if (!(client->device_state_sub = ast_event_subscribe(AST_EVENT_DEVICE_STATE_CHANGE,
1447                                                              xmpp_pubsub_devstate_cb, "xmpp_pubsub_devstate_subscription", client, AST_EVENT_IE_END))) {
1448                 ast_event_unsubscribe(client->mwi_sub);
1449                 client->mwi_sub = NULL;
1450                 return;
1451         }
1452
1453         ast_event_dump_cache(client->device_state_sub);
1454
1455         xmpp_pubsub_subscribe(client, "device_state");
1456         xmpp_pubsub_subscribe(client, "message_waiting");
1457         iks_filter_add_rule(client->filter, xmpp_pubsub_handle_event, client, IKS_RULE_TYPE,
1458                             IKS_PAK_MESSAGE, IKS_RULE_FROM, clientcfg->pubsubnode, IKS_RULE_DONE);
1459         iks_filter_add_rule(client->filter, xmpp_pubsub_handle_error, client, IKS_RULE_TYPE,
1460                             IKS_PAK_IQ, IKS_RULE_SUBTYPE, IKS_TYPE_ERROR, IKS_RULE_DONE);
1461
1462 }
1463
1464 /*! \brief Internal astobj2 callback function which returns the first resource, which is the highest priority one */
1465 static int xmpp_resource_immediate(void *obj, void *arg, int flags)
1466 {
1467         return CMP_MATCH | CMP_STOP;
1468 }
1469
1470 /*
1471  * \internal
1472  * \brief Dial plan function status(). puts the status of watched user
1473  * into a channel variable.
1474  * \param chan ast_channel
1475  * \param data
1476  * \retval 0 success
1477  * \retval -1 error
1478  */
1479 static int xmpp_status_exec(struct ast_channel *chan, const char *data)
1480 {
1481         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1482         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
1483         struct ast_xmpp_buddy *buddy;
1484         struct ast_xmpp_resource *resource;
1485         char *s = NULL, status[2];
1486         int stat = 7;
1487         static int deprecation_warning = 0;
1488         AST_DECLARE_APP_ARGS(args,
1489                              AST_APP_ARG(sender);
1490                              AST_APP_ARG(jid);
1491                              AST_APP_ARG(variable);
1492                 );
1493         AST_DECLARE_APP_ARGS(jid,
1494                              AST_APP_ARG(screenname);
1495                              AST_APP_ARG(resource);
1496                 );
1497
1498         if (deprecation_warning++ % 10 == 0) {
1499                 ast_log(LOG_WARNING, "JabberStatus is deprecated.  Please use the JABBER_STATUS dialplan function in the future.\n");
1500         }
1501
1502         if (ast_strlen_zero(data)) {
1503                 ast_log(LOG_ERROR, "Usage: JabberStatus(<sender>,<jid>[/<resource>],<varname>\n");
1504                 return 0;
1505         }
1506         s = ast_strdupa(data);
1507         AST_STANDARD_APP_ARGS(args, s);
1508
1509         if (args.argc != 3) {
1510                 ast_log(LOG_ERROR, "JabberStatus() requires 3 arguments.\n");
1511                 return -1;
1512         }
1513
1514         AST_NONSTANDARD_APP_ARGS(jid, args.jid, '/');
1515         if (jid.argc < 1 || jid.argc > 2) {
1516                 ast_log(LOG_WARNING, "Wrong JID %s, exiting\n", args.jid);
1517                 return -1;
1518         }
1519
1520         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, args.sender))) {
1521                 ast_log(LOG_WARNING, "Could not find sender connection: '%s'\n", args.sender);
1522                 return -1;
1523         }
1524
1525         if (!(buddy = ao2_find(clientcfg->client->buddies, jid.screenname, OBJ_KEY))) {
1526                 ast_log(LOG_WARNING, "Could not find buddy in list: '%s'\n", jid.screenname);
1527                 return -1;
1528         }
1529
1530         if (ast_strlen_zero(jid.resource) || !(resource = ao2_find(buddy->resources, jid.resource, OBJ_KEY))) {
1531                 resource = ao2_callback(buddy->resources, OBJ_NODATA, xmpp_resource_immediate, NULL);
1532         }
1533
1534         ao2_ref(buddy, -1);
1535
1536         if (resource) {
1537                 stat = resource->status;
1538                 ao2_ref(resource, -1);
1539         } else {
1540                 ast_log(LOG_NOTICE, "Resource '%s' of buddy '%s' was not found\n", jid.resource, jid.screenname);
1541         }
1542
1543         snprintf(status, sizeof(status), "%d", stat);
1544         pbx_builtin_setvar_helper(chan, args.variable, status);
1545
1546         return 0;
1547 }
1548
1549 /*!
1550  * \internal
1551  * \brief Dial plan funtcion to retrieve the status of a buddy.
1552  * \param channel The associated ast_channel, if there is one
1553  * \param data The account, buddy JID, and optional timeout
1554  * timeout.
1555  * \retval 0 success
1556  * \retval -1 failure
1557  */
1558 static int acf_jabberstatus_read(struct ast_channel *chan, const char *name, char *data, char *buf, size_t buflen)
1559 {
1560         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1561         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
1562         struct ast_xmpp_buddy *buddy;
1563         struct ast_xmpp_resource *resource;
1564         int stat = 7;
1565         AST_DECLARE_APP_ARGS(args,
1566                              AST_APP_ARG(sender);
1567                              AST_APP_ARG(jid);
1568                 );
1569         AST_DECLARE_APP_ARGS(jid,
1570                              AST_APP_ARG(screenname);
1571                              AST_APP_ARG(resource);
1572                 );
1573
1574         if (ast_strlen_zero(data)) {
1575                 ast_log(LOG_ERROR, "Usage: JABBER_STATUS(<sender>,<jid>[/<resource>])\n");
1576                 return 0;
1577         }
1578         AST_STANDARD_APP_ARGS(args, data);
1579
1580         if (args.argc != 2) {
1581                 ast_log(LOG_ERROR, "JABBER_STATUS requires 2 arguments: sender and jid.\n");
1582                 return -1;
1583         }
1584
1585         AST_NONSTANDARD_APP_ARGS(jid, args.jid, '/');
1586         if (jid.argc < 1 || jid.argc > 2) {
1587                 ast_log(LOG_WARNING, "Wrong JID %s, exiting\n", args.jid);
1588                 return -1;
1589         }
1590
1591         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, args.sender))) {
1592                 ast_log(LOG_WARNING, "Could not find sender connection: '%s'\n", args.sender);
1593                 return -1;
1594         }
1595
1596         if (!(buddy = ao2_find(clientcfg->client->buddies, jid.screenname, OBJ_KEY))) {
1597                 ast_log(LOG_WARNING, "Could not find buddy in list: '%s'\n", jid.screenname);
1598                 return -1;
1599         }
1600
1601         if (ast_strlen_zero(jid.resource) || !(resource = ao2_find(buddy->resources, jid.resource, OBJ_KEY))) {
1602                 resource = ao2_callback(buddy->resources, OBJ_NODATA, xmpp_resource_immediate, NULL);
1603         }
1604
1605         ao2_ref(buddy, -1);
1606
1607         if (resource) {
1608                 stat = resource->status;
1609                 ao2_ref(resource, -1);
1610         } else {
1611                 ast_log(LOG_NOTICE, "Resource %s of buddy %s was not found.\n", jid.resource, jid.screenname);
1612         }
1613
1614         snprintf(buf, buflen, "%d", stat);
1615
1616         return 0;
1617 }
1618
1619 static struct ast_custom_function jabberstatus_function = {
1620         .name = "JABBER_STATUS",
1621         .read = acf_jabberstatus_read,
1622 };
1623
1624 /*!
1625  * \brief Application to join a chat room
1626  * \param chan ast_channel
1627  * \param data  Data is sender|jid|nickname.
1628  * \retval 0 success
1629  * \retval -1 error
1630  */
1631 static int xmpp_join_exec(struct ast_channel *chan, const char *data)
1632 {
1633         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1634         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
1635         char *s, nick[XMPP_MAX_RESJIDLEN];
1636         AST_DECLARE_APP_ARGS(args,
1637                              AST_APP_ARG(sender);
1638                              AST_APP_ARG(jid);
1639                              AST_APP_ARG(nick);
1640                 );
1641
1642         if (ast_strlen_zero(data)) {
1643                 ast_log(LOG_ERROR, "%s requires arguments (sender,jid[,nickname])\n", app_ajijoin);
1644                 return -1;
1645         }
1646         s = ast_strdupa(data);
1647
1648         AST_STANDARD_APP_ARGS(args, s);
1649         if (args.argc < 2 || args.argc > 3) {
1650                 ast_log(LOG_ERROR, "%s requires arguments (sender,jid[,nickname])\n", app_ajijoin);
1651                 return -1;
1652         }
1653
1654         if (strchr(args.jid, '/')) {
1655                 ast_log(LOG_ERROR, "Invalid room name : resource must not be appended\n");
1656                 return -1;
1657         }
1658
1659         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, args.sender))) {
1660                 ast_log(LOG_ERROR, "Could not find sender connection: '%s'\n", args.sender);
1661                 return -1;
1662         }
1663
1664         if (ast_strlen_zero(args.nick)) {
1665                 if (ast_test_flag(&clientcfg->flags, XMPP_COMPONENT)) {
1666                         snprintf(nick, sizeof(nick), "asterisk");
1667                 } else {
1668                         snprintf(nick, sizeof(nick), "%s", clientcfg->client->jid->user);
1669                 }
1670         } else {
1671                 snprintf(nick, sizeof(nick), "%s", args.nick);
1672         }
1673
1674         if (!ast_strlen_zero(args.jid) && strchr(args.jid, '@')) {
1675                 ast_xmpp_chatroom_join(clientcfg->client, args.jid, nick);
1676         } else {
1677                 ast_log(LOG_ERROR, "Problem with specified jid of '%s'\n", args.jid);
1678         }
1679
1680         return 0;
1681 }
1682
1683 /*!
1684  * \brief Application to leave a chat room
1685  * \param chan ast_channel
1686  * \param data  Data is sender|jid|nickname.
1687  * \retval 0 success
1688  * \retval -1 error
1689  */
1690 static int xmpp_leave_exec(struct ast_channel *chan, const char *data)
1691 {
1692         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1693         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
1694         char *s, nick[XMPP_MAX_RESJIDLEN];
1695         AST_DECLARE_APP_ARGS(args,
1696                              AST_APP_ARG(sender);
1697                              AST_APP_ARG(jid);
1698                              AST_APP_ARG(nick);
1699                 );
1700
1701         if (ast_strlen_zero(data)) {
1702                 ast_log(LOG_ERROR, "%s requires arguments (sender,jid[,nickname])\n", app_ajileave);
1703                 return -1;
1704         }
1705         s = ast_strdupa(data);
1706
1707         AST_STANDARD_APP_ARGS(args, s);
1708         if (args.argc < 2 || args.argc > 3) {
1709                 ast_log(LOG_ERROR, "%s requires arguments (sender,jid[,nickname])\n", app_ajileave);
1710                 return -1;
1711         }
1712
1713         if (strchr(args.jid, '/')) {
1714                 ast_log(LOG_ERROR, "Invalid room name, resource must not be appended\n");
1715                 return -1;
1716         }
1717
1718         if (ast_strlen_zero(args.jid) || !strchr(args.jid, '@')) {
1719                 ast_log(LOG_ERROR, "No jabber ID specified\n");
1720                 return -1;
1721         }
1722
1723         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, args.sender))) {
1724                 ast_log(LOG_ERROR, "Could not find sender connection: '%s'\n", args.sender);
1725                 return -1;
1726         }
1727
1728         if (ast_strlen_zero(args.nick)) {
1729                 if (ast_test_flag(&clientcfg->flags, XMPP_COMPONENT)) {
1730                         snprintf(nick, sizeof(nick), "asterisk");
1731                 } else {
1732                         snprintf(nick, sizeof(nick), "%s", clientcfg->client->jid->user);
1733                 }
1734         } else {
1735                 snprintf(nick, sizeof(nick), "%s", args.nick);
1736         }
1737
1738         ast_xmpp_chatroom_leave(clientcfg->client, args.jid, nick);
1739
1740         return 0;
1741 }
1742
1743 /*!
1744  * \internal
1745  * \brief Dial plan function to send a message.
1746  * \param chan ast_channel
1747  * \param data  Data is account,jid,message.
1748  * \retval 0 success
1749  * \retval -1 failure
1750  */
1751 static int xmpp_send_exec(struct ast_channel *chan, const char *data)
1752 {
1753         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1754         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
1755         char *s;
1756         AST_DECLARE_APP_ARGS(args,
1757                              AST_APP_ARG(sender);
1758                              AST_APP_ARG(recipient);
1759                              AST_APP_ARG(message);
1760                 );
1761
1762         if (ast_strlen_zero(data)) {
1763                 ast_log(LOG_WARNING, "%s requires arguments (account,jid,message)\n", app_ajisend);
1764                 return -1;
1765         }
1766         s = ast_strdupa(data);
1767
1768         AST_STANDARD_APP_ARGS(args, s);
1769
1770         if ((args.argc < 3) || ast_strlen_zero(args.message) || !strchr(args.recipient, '@')) {
1771                 ast_log(LOG_WARNING, "%s requires arguments (account,jid,message)\n", app_ajisend);
1772                 return -1;
1773         }
1774
1775         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, args.sender))) {
1776                 ast_log(LOG_WARNING, "Could not find sender connection: '%s'\n", args.sender);
1777                 return -1;
1778         }
1779
1780         ast_xmpp_client_send_message(clientcfg->client, args.recipient, args.message);
1781
1782         return 0;
1783 }
1784
1785 /*!
1786  * \brief Application to send a message to a groupchat.
1787  * \param chan ast_channel
1788  * \param data  Data is sender|groupchat|message.
1789  * \retval 0 success
1790  * \retval -1 error
1791  */
1792 static int xmpp_sendgroup_exec(struct ast_channel *chan, const char *data)
1793 {
1794         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1795         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
1796         char *s, nick[XMPP_MAX_RESJIDLEN];
1797         AST_DECLARE_APP_ARGS(args,
1798                              AST_APP_ARG(sender);
1799                              AST_APP_ARG(groupchat);
1800                              AST_APP_ARG(message);
1801                              AST_APP_ARG(nick);
1802                 );
1803
1804         if (ast_strlen_zero(data)) {
1805                 ast_log(LOG_ERROR, "%s requires arguments (sender,groupchatid,message[,nickname])\n", app_ajisendgroup);
1806                 return -1;
1807         }
1808         s = ast_strdupa(data);
1809
1810         AST_STANDARD_APP_ARGS(args, s);
1811         if ((args.argc < 3) || (args.argc > 4) || ast_strlen_zero(args.message) || !strchr(args.groupchat, '@')) {
1812                 ast_log(LOG_ERROR, "%s requires arguments (sender,groupchatid,message[,nickname])\n", app_ajisendgroup);
1813                 return -1;
1814         }
1815
1816         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, args.sender))) {
1817                 ast_log(LOG_ERROR, "Could not find sender connection: '%s'\n", args.sender);
1818                 return -1;
1819         }
1820
1821         if (ast_strlen_zero(args.nick) || args.argc == 3) {
1822                 if (ast_test_flag(&clientcfg->flags, XMPP_COMPONENT)) {
1823                         snprintf(nick, sizeof(nick), "asterisk");
1824                 } else {
1825                         snprintf(nick, sizeof(nick), "%s", clientcfg->client->jid->user);
1826                 }
1827         } else {
1828                 snprintf(nick, sizeof(nick), "%s", args.nick);
1829         }
1830
1831         ast_xmpp_chatroom_send(clientcfg->client, nick, args.groupchat, args.message);
1832
1833         return 0;
1834 }
1835
1836 /*!
1837  * \internal
1838  * \brief Dial plan function to receive a message.
1839  * \param channel The associated ast_channel, if there is one
1840  * \param data The account, JID, and optional timeout
1841  * timeout.
1842  * \retval 0 success
1843  * \retval -1 failure
1844  */
1845 static int acf_jabberreceive_read(struct ast_channel *chan, const char *name, char *data, char *buf, size_t buflen)
1846 {
1847         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1848         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
1849         char *aux = NULL, *parse = NULL;
1850         int timeout, jidlen, resourcelen, found = 0;
1851         struct timeval start;
1852         long diff = 0;
1853         struct ast_xmpp_message *message;
1854         AST_DECLARE_APP_ARGS(args,
1855                              AST_APP_ARG(account);
1856                              AST_APP_ARG(jid);
1857                              AST_APP_ARG(timeout);
1858                 );
1859         AST_DECLARE_APP_ARGS(jid,
1860                              AST_APP_ARG(screenname);
1861                              AST_APP_ARG(resource);
1862                 );
1863
1864         if (ast_strlen_zero(data)) {
1865                 ast_log(LOG_WARNING, "%s requires arguments (account,jid[,timeout])\n", name);
1866                 return -1;
1867         }
1868
1869         parse = ast_strdupa(data);
1870         AST_STANDARD_APP_ARGS(args, parse);
1871
1872         if (args.argc < 2 || args.argc > 3) {
1873                 ast_log(LOG_WARNING, "%s requires arguments (account,jid[,timeout])\n", name);
1874                 return -1;
1875         }
1876
1877         parse = ast_strdupa(args.jid);
1878         AST_NONSTANDARD_APP_ARGS(jid, parse, '/');
1879         if (jid.argc < 1 || jid.argc > 2 || strlen(args.jid) > XMPP_MAX_JIDLEN) {
1880                 ast_log(LOG_WARNING, "Invalid JID : %s\n", parse);
1881                 return -1;
1882         }
1883
1884         if (ast_strlen_zero(args.timeout)) {
1885                 timeout = 20;
1886         } else {
1887                 sscanf(args.timeout, "%d", &timeout);
1888                 if (timeout <= 0) {
1889                         ast_log(LOG_WARNING, "Invalid timeout specified: '%s'\n", args.timeout);
1890                         return -1;
1891                 }
1892         }
1893
1894         jidlen = strlen(jid.screenname);
1895         resourcelen = ast_strlen_zero(jid.resource) ? 0 : strlen(jid.resource);
1896
1897         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, args.account))) {
1898                 ast_log(LOG_WARNING, "Could not find client %s, exiting\n", args.account);
1899                 return -1;
1900         }
1901
1902         ast_debug(3, "Waiting for an XMPP message from %s\n", args.jid);
1903
1904         start = ast_tvnow();
1905
1906         if (ast_autoservice_start(chan) < 0) {
1907                 ast_log(LOG_WARNING, "Cannot start autoservice for channel %s\n", ast_channel_name(chan));
1908                 return -1;
1909         }
1910
1911         /* search the messages list, grab the first message that matches with
1912          * the from JID we're expecting, and remove it from the messages list */
1913         while (diff < timeout) {
1914                 struct timespec ts = { 0, };
1915                 struct timeval wait;
1916                 int res = 0;
1917
1918                 wait = ast_tvadd(start, ast_tv(timeout, 0));
1919                 ts.tv_sec = wait.tv_sec;
1920                 ts.tv_nsec = wait.tv_usec * 1000;
1921
1922                 /* wait up to timeout seconds for an incoming message */
1923                 ast_mutex_lock(&messagelock);
1924                 if (AST_LIST_EMPTY(&clientcfg->client->messages)) {
1925                         res = ast_cond_timedwait(&message_received_condition, &messagelock, &ts);
1926                 }
1927                 ast_mutex_unlock(&messagelock);
1928                 if (res == ETIMEDOUT) {
1929                         ast_debug(3, "No message received from %s in %d seconds\n", args.jid, timeout);
1930                         break;
1931                 }
1932
1933                 AST_LIST_LOCK(&clientcfg->client->messages);
1934                 AST_LIST_TRAVERSE_SAFE_BEGIN(&clientcfg->client->messages, message, list) {
1935                         if (jid.argc == 1) {
1936                                 /* no resource provided, compare bare JIDs */
1937                                 if (strncasecmp(jid.screenname, message->from, jidlen)) {
1938                                         continue;
1939                                 }
1940                         } else {
1941                                 /* resource appended, compare bare JIDs and resources */
1942                                 char *resource = strchr(message->from, '/');
1943                                 if (!resource || strlen(resource) == 0) {
1944                                         ast_log(LOG_WARNING, "Remote JID has no resource : %s\n", message->from);
1945                                         if (strncasecmp(jid.screenname, message->from, jidlen)) {
1946                                                 continue;
1947                                         }
1948                                 } else {
1949                                         resource ++;
1950                                         if (strncasecmp(jid.screenname, message->from, jidlen) || strncmp(jid.resource, resource, resourcelen)) {
1951                                                 continue;
1952                                         }
1953                                 }
1954                         }
1955                         /* check if the message is not too old */
1956                         if (ast_tvdiff_sec(ast_tvnow(), message->arrived) >= clientcfg->message_timeout) {
1957                                 ast_debug(3, "Found old message from %s, deleting it\n", message->from);
1958                                 AST_LIST_REMOVE_CURRENT(list);
1959                                 xmpp_message_destroy(message);
1960                                 continue;
1961                         }
1962                         found = 1;
1963                         aux = ast_strdupa(message->message);
1964                         AST_LIST_REMOVE_CURRENT(list);
1965                         xmpp_message_destroy(message);
1966                         break;
1967                 }
1968                 AST_LIST_TRAVERSE_SAFE_END;
1969                 AST_LIST_UNLOCK(&clientcfg->client->messages);
1970                 if (found) {
1971                         break;
1972                 }
1973
1974                 /* check timeout */
1975                 diff = ast_tvdiff_ms(ast_tvnow(), start);
1976         }
1977
1978         if (ast_autoservice_stop(chan) < 0) {
1979                 ast_log(LOG_WARNING, "Cannot stop autoservice for channel %s\n", ast_channel_name(chan));
1980         }
1981
1982         /* return if we timed out */
1983         if (!found) {
1984                 ast_log(LOG_NOTICE, "Timed out : no message received from %s\n", args.jid);
1985                 return -1;
1986         }
1987         ast_copy_string(buf, aux, buflen);
1988
1989         return 0;
1990 }
1991
1992 static struct ast_custom_function jabberreceive_function = {
1993         .name = "JABBER_RECEIVE",
1994         .read = acf_jabberreceive_read,
1995 };
1996
1997 /*!
1998  * \internal
1999  * \brief Delete old messages from a given JID
2000  * Messages stored during more than client->message_timeout are deleted
2001  * \param client Asterisk's XMPP client
2002  * \param from the JID we received messages from
2003  * \retval the number of deleted messages
2004  */
2005 static int delete_old_messages(struct ast_xmpp_client *client, char *from)
2006 {
2007         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
2008         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
2009         int deleted = 0, isold = 0;
2010         struct ast_xmpp_message *message = NULL;
2011
2012         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name))) {
2013                 return 0;
2014         }
2015
2016         AST_LIST_LOCK(&client->messages);
2017         AST_LIST_TRAVERSE_SAFE_BEGIN(&client->messages, message, list) {
2018                 if (isold) {
2019                         if (!from || !strncasecmp(from, message->from, strlen(from))) {
2020                                 AST_LIST_REMOVE_CURRENT(list);
2021                                 xmpp_message_destroy(message);
2022                                 deleted++;
2023                         }
2024                 } else if (ast_tvdiff_sec(ast_tvnow(), message->arrived) >= clientcfg->message_timeout) {
2025                         isold = 1;
2026                         if (!from || !strncasecmp(from, message->from, strlen(from))) {
2027                                 AST_LIST_REMOVE_CURRENT(list);
2028                                 xmpp_message_destroy(message);
2029                                 deleted++;
2030                         }
2031                 }
2032         }
2033         AST_LIST_TRAVERSE_SAFE_END;
2034         AST_LIST_UNLOCK(&client->messages);
2035
2036         return deleted;
2037 }
2038
2039 static int xmpp_send_cb(const struct ast_msg *msg, const char *to, const char *from)
2040 {
2041         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
2042         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
2043         char *sender, *dest;
2044         int res;
2045
2046         sender = ast_strdupa(from);
2047         strsep(&sender, ":");
2048         dest = ast_strdupa(to);
2049         strsep(&dest, ":");
2050
2051         if (ast_strlen_zero(sender)) {
2052                 ast_log(LOG_ERROR, "MESSAGE(from) of '%s' invalid for XMPP\n", from);
2053                 return -1;
2054         }
2055
2056         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, sender))) {
2057                 ast_log(LOG_WARNING, "Could not finder account to send from as '%s'\n", sender);
2058                 return -1;
2059         }
2060
2061         ast_debug(1, "Sending message to '%s' from '%s'\n", dest, clientcfg->name);
2062
2063         if ((res = ast_xmpp_client_send_message(clientcfg->client, dest, ast_msg_get_body(msg))) != IKS_OK) {
2064                 ast_log(LOG_WARNING, "Failed to send XMPP message (%d).\n", res);
2065         }
2066
2067         return res == IKS_OK ? 0 : -1;
2068 }
2069
2070 static const struct ast_msg_tech msg_tech = {
2071         .name = "xmpp",
2072         .msg_send = xmpp_send_cb,
2073 };
2074
2075 /*! \brief Internal function which changes the XMPP client state */
2076 static void xmpp_client_change_state(struct ast_xmpp_client *client, int state)
2077 {
2078         client->state = state;
2079 }
2080
2081 /*! \brief Internal function which creates a buddy on a client */
2082 static struct ast_xmpp_buddy *xmpp_client_create_buddy(struct ao2_container *container, const char *id)
2083 {
2084         struct ast_xmpp_buddy *buddy;
2085
2086         if (!(buddy = ao2_alloc(sizeof(*buddy), xmpp_buddy_destructor))) {
2087                 return NULL;
2088         }
2089
2090         if (!(buddy->resources = ao2_container_alloc(RESOURCE_BUCKETS, xmpp_resource_hash, xmpp_resource_cmp))) {
2091                 ao2_ref(buddy, -1);
2092                 return NULL;
2093         }
2094
2095         ast_copy_string(buddy->id, id, sizeof(buddy->id));
2096
2097         /* Assume we need to subscribe to get their presence until proven otherwise */
2098         buddy->subscribe = 1;
2099
2100         ao2_link(container, buddy);
2101
2102         return buddy;
2103 }
2104
2105 /*! \brief Helper function which unsubscribes a user and removes them from the roster */
2106 static int xmpp_client_unsubscribe_user(struct ast_xmpp_client *client, const char *user)
2107 {
2108         iks *iq, *query = NULL, *item = NULL;
2109
2110         if (ast_xmpp_client_send(client, iks_make_s10n(IKS_TYPE_UNSUBSCRIBE, user,
2111                                                        "Goodbye. Your status is no longer required.\n"))) {
2112                 return -1;
2113         }
2114
2115         if (!(iq = iks_new("iq")) || !(query = iks_new("query")) || !(item = iks_new("item"))) {
2116                 ast_log(LOG_WARNING, "Could not allocate memory for roster removal of '%s' from client '%s'\n",
2117                         user, client->name);
2118                 goto done;
2119         }
2120
2121         iks_insert_attrib(iq, "from", client->jid->full);
2122         iks_insert_attrib(iq, "type", "set");
2123         iks_insert_attrib(query, "xmlns", "jabber:iq:roster");
2124         iks_insert_node(iq, query);
2125         iks_insert_attrib(item, "jid", user);
2126         iks_insert_attrib(item, "subscription", "remove");
2127         iks_insert_node(query, item);
2128
2129         if (ast_xmpp_client_send(client, iq)) {
2130                 ast_log(LOG_WARNING, "Could not send roster removal request of '%s' from client '%s'\n",
2131                         user, client->name);
2132         }
2133
2134 done:
2135         iks_delete(item);
2136         iks_delete(query);
2137         iks_delete(iq);
2138
2139         return 0;
2140 }
2141
2142 /*! \brief Callback function which subscribes to a user if needed */
2143 static int xmpp_client_subscribe_user(void *obj, void *arg, int flags)
2144 {
2145         struct ast_xmpp_buddy *buddy = obj;
2146         struct ast_xmpp_client *client = arg;
2147
2148         if (!buddy->subscribe) {
2149                 return 0;
2150         }
2151
2152         if (ast_xmpp_client_send(client, iks_make_s10n(IKS_TYPE_SUBSCRIBE, buddy->id,
2153                                                        "Greetings! I am the Asterisk Open Source PBX and I want to subscribe to your presence\n"))) {
2154                 ast_log(LOG_WARNING, "Could not send subscription for '%s' on client '%s'\n",
2155                         buddy->id, client->name);
2156         }
2157
2158         buddy->subscribe = 0;
2159
2160         return 0;
2161 }
2162
2163 /*! \brief Hook function called when roster is received from server */
2164 static int xmpp_roster_hook(void *data, ikspak *pak)
2165 {
2166         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
2167         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
2168         struct ast_xmpp_client *client = data;
2169         iks *item;
2170
2171         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name))) {
2172                 return IKS_FILTER_EAT;
2173         }
2174
2175         for (item = iks_child(pak->query); item; item = iks_next(item)) {
2176                 struct ast_xmpp_buddy *buddy;
2177
2178                 if (iks_strcmp(iks_name(item), "item")) {
2179                         continue;
2180                 }
2181
2182                 if (!(buddy = ao2_find(client->buddies, iks_find_attrib(item, "jid"), OBJ_KEY))) {
2183                         if (ast_test_flag(&clientcfg->flags, XMPP_AUTOPRUNE)) {
2184                                 /* The buddy has not been specified in the configuration file, we no longer
2185                                  * want them on our buddy list or to receive their presence. */
2186                                 if (xmpp_client_unsubscribe_user(client, iks_find_attrib(item, "jid"))) {
2187                                         ast_log(LOG_ERROR, "Could not unsubscribe user '%s' on client '%s'\n",
2188                                                 iks_find_attrib(item, "jid"), client->name);
2189                                 }
2190                                 continue;
2191                         }
2192
2193                         if (!(buddy = xmpp_client_create_buddy(client->buddies, iks_find_attrib(item, "jid")))) {
2194                                 ast_log(LOG_ERROR, "Could not allocate buddy '%s' on client '%s'\n", iks_find_attrib(item, "jid"),
2195                                         client->name);
2196                                 continue;
2197                         }
2198                 }
2199
2200                 /* Determine if we need to subscribe to their presence or not */
2201                 if (!iks_strcmp(iks_find_attrib(item, "subscription"), "none") ||
2202                     !iks_strcmp(iks_find_attrib(item, "subscription"), "from")) {
2203                         buddy->subscribe = 1;
2204                 } else {
2205                         buddy->subscribe = 0;
2206                 }
2207
2208                 ao2_ref(buddy, -1);
2209         }
2210
2211         /* If autoregister is enabled we need to go through every buddy that we need to subscribe to and do so */
2212         if (ast_test_flag(&clientcfg->flags, XMPP_AUTOREGISTER)) {
2213                 ao2_callback(client->buddies, OBJ_NODATA | OBJ_MULTIPLE, xmpp_client_subscribe_user, client);
2214         }
2215
2216         xmpp_client_change_state(client, XMPP_STATE_CONNECTED);
2217
2218         return IKS_FILTER_EAT;
2219 }
2220
2221 /*! \brief Internal function which changes the presence status of an XMPP client */
2222 static void xmpp_client_set_presence(struct ast_xmpp_client *client, const char *to, const char *from, int level, const char *desc)
2223 {
2224         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
2225         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
2226         iks *presence = NULL, *cnode = NULL, *priority = NULL;
2227         char priorityS[10];
2228
2229         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name)) ||
2230             !(presence = iks_make_pres(level, desc)) || !(cnode = iks_new("c")) || !(priority = iks_new("priority"))) {
2231                 ast_log(LOG_ERROR, "Unable to allocate stanzas for setting presence status for client '%s'\n", client->name);
2232                 goto done;
2233         }
2234
2235         if (!ast_strlen_zero(to)) {
2236                 iks_insert_attrib(presence, "to", to);
2237         }
2238
2239         if (!ast_strlen_zero(from)) {
2240                 iks_insert_attrib(presence, "from", from);
2241         }
2242
2243         snprintf(priorityS, sizeof(priorityS), "%d", clientcfg->priority);
2244         iks_insert_cdata(priority, priorityS, strlen(priorityS));
2245         iks_insert_node(presence, priority);
2246         iks_insert_attrib(cnode, "node", "http://www.asterisk.org/xmpp/client/caps");
2247         iks_insert_attrib(cnode, "ver", "asterisk-xmpp");
2248         iks_insert_attrib(cnode, "ext", "voice-v1 video-v1 camera-v1");
2249         iks_insert_attrib(cnode, "xmlns", "http://jabber.org/protocol/caps");
2250         iks_insert_node(presence, cnode);
2251         ast_xmpp_client_send(client, presence);
2252
2253 done:
2254         iks_delete(cnode);
2255         iks_delete(presence);
2256         iks_delete(priority);
2257 }
2258
2259 /*! \brief Hook function called when client receives a service discovery get message */
2260 static int xmpp_client_service_discovery_get_hook(void *data, ikspak *pak)
2261 {
2262         struct ast_xmpp_client *client = data;
2263         iks *iq, *disco = NULL, *ident = NULL, *google = NULL, *jingle = NULL, *ice = NULL, *rtp = NULL, *audio = NULL, *video = NULL, *query = NULL;
2264
2265         if (!(iq = iks_new("iq")) || !(query = iks_new("query")) || !(ident = iks_new("identity")) || !(disco = iks_new("feature")) ||
2266             !(google = iks_new("feature")) || !(jingle = iks_new("feature")) || !(ice = iks_new("feature")) || !(rtp = iks_new("feature")) ||
2267             !(audio = iks_new("feature")) || !(video = iks_new("feature"))) {
2268                 ast_log(LOG_ERROR, "Could not allocate memory for responding to service discovery request from '%s' on client '%s'\n",
2269                         pak->from->full, client->name);
2270                 goto end;
2271         }
2272
2273         iks_insert_attrib(iq, "from", client->jid->full);
2274
2275         if (pak->from) {
2276                 iks_insert_attrib(iq, "to", pak->from->full);
2277         }
2278
2279         iks_insert_attrib(iq, "type", "result");
2280         iks_insert_attrib(iq, "id", pak->id);
2281         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
2282         iks_insert_attrib(ident, "category", "client");
2283         iks_insert_attrib(ident, "type", "pc");
2284         iks_insert_attrib(ident, "name", "asterisk");
2285         iks_insert_attrib(disco, "var", "http://jabber.org/protocol/disco#info");
2286
2287         iks_insert_attrib(google, "var", "http://www.google.com/xmpp/protocol/voice/v1");
2288         iks_insert_attrib(jingle, "var", "urn:xmpp:jingle:1");
2289         iks_insert_attrib(ice, "var", "urn:xmpp:jingle:transports:ice-udp:1");
2290         iks_insert_attrib(rtp, "var", "urn:xmpp:jingle:apps:rtp:1");
2291         iks_insert_attrib(audio, "var", "urn:xmpp:jingle:apps:rtp:audio");
2292         iks_insert_attrib(video, "var", "urn:xmpp:jingle:apps:rtp:video");
2293         iks_insert_node(iq, query);
2294         iks_insert_node(query, ident);
2295         iks_insert_node(query, google);
2296         iks_insert_node(query, disco);
2297         iks_insert_node(query, jingle);
2298         iks_insert_node(query, ice);
2299         iks_insert_node(query, rtp);
2300         iks_insert_node(query, audio);
2301         iks_insert_node(query, video);
2302         ast_xmpp_client_send(client, iq);
2303
2304 end:
2305         iks_delete(query);
2306         iks_delete(video);
2307         iks_delete(audio);
2308         iks_delete(rtp);
2309         iks_delete(ice);
2310         iks_delete(jingle);
2311         iks_delete(google);
2312         iks_delete(ident);
2313         iks_delete(disco);
2314         iks_delete(iq);
2315
2316         return IKS_FILTER_EAT;
2317 }
2318
2319 /*! \brief Hook function called when client receives a service discovery result message */
2320 static int xmpp_client_service_discovery_result_hook(void *data, ikspak *pak)
2321 {
2322         struct ast_xmpp_client *client = data;
2323         struct ast_xmpp_buddy *buddy;
2324         struct ast_xmpp_resource *resource;
2325
2326         if (!(buddy = ao2_find(client->buddies, pak->from->partial, OBJ_KEY))) {
2327                 return IKS_FILTER_EAT;
2328         }
2329
2330         if (!(resource = ao2_find(buddy->resources, pak->from->resource, OBJ_KEY))) {
2331                 ao2_ref(buddy, -1);
2332                 return IKS_FILTER_EAT;
2333         }
2334
2335         ao2_lock(resource);
2336
2337         if (iks_find_with_attrib(pak->query, "feature", "var", "urn:xmpp:jingle:1")) {
2338                 resource->caps.jingle = 1;
2339         }
2340
2341         ao2_unlock(resource);
2342
2343         ao2_ref(resource, -1);
2344         ao2_ref(buddy, -1);
2345
2346         return IKS_FILTER_EAT;
2347 }
2348
2349 /*! \brief Hook function called when client finishes authenticating with the server */
2350 static int xmpp_connect_hook(void *data, ikspak *pak)
2351 {
2352         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
2353         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
2354         struct ast_xmpp_client *client = data;
2355         iks *roster;
2356
2357         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name))) {
2358                 return -1;
2359         }
2360
2361         client->jid = (iks_find_cdata(pak->query, "jid")) ? iks_id_new(client->stack, iks_find_cdata(pak->query, "jid")) : client->jid;
2362
2363         if (ast_test_flag(&clientcfg->flags, XMPP_DISTRIBUTE_EVENTS)) {
2364                 xmpp_init_event_distribution(client);
2365         }
2366
2367         if (!(roster = iks_make_iq(IKS_TYPE_GET, IKS_NS_ROSTER))) {
2368                 ast_log(LOG_ERROR, "Unable to allocate memory for roster request for client '%s'\n", client->name);
2369                 return -1;
2370         }
2371
2372         iks_filter_add_rule(client->filter, xmpp_client_service_discovery_get_hook, client, IKS_RULE_SUBTYPE, IKS_TYPE_GET, IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
2373         iks_filter_add_rule(client->filter, xmpp_client_service_discovery_result_hook, client, IKS_RULE_SUBTYPE, IKS_TYPE_RESULT, IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
2374
2375         iks_insert_attrib(roster, "id", "roster");
2376         ast_xmpp_client_send(client, roster);
2377
2378         iks_filter_remove_hook(client->filter, xmpp_connect_hook);
2379         iks_filter_add_rule(client->filter, xmpp_roster_hook, client, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_SUBTYPE, IKS_TYPE_RESULT, IKS_RULE_ID, "roster", IKS_RULE_DONE);
2380
2381         xmpp_client_set_presence(client, NULL, client->jid->full, clientcfg->status, clientcfg->statusmsg);
2382         xmpp_client_change_state(client, XMPP_STATE_ROSTER);
2383
2384         return IKS_FILTER_EAT;
2385 }
2386
2387 /*! \brief Logging hook function */
2388 static void xmpp_log_hook(void *data, const char *xmpp, size_t size, int incoming)
2389 {
2390         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
2391         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
2392         struct ast_xmpp_client *client = data;
2393
2394         if (!ast_strlen_zero(xmpp)) {
2395                 manager_event(EVENT_FLAG_USER, "JabberEvent", "Account: %s\r\nPacket: %s\r\n", client->name, xmpp);
2396         }
2397
2398         if (!debug && (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name)) || !ast_test_flag(&clientcfg->flags, XMPP_DEBUG))) {
2399                 return;
2400         }
2401
2402         if (!incoming) {
2403                 if (strlen(xmpp) == 1) {
2404                         if (option_debug > 2  && xmpp[0] == ' ') {
2405                                 ast_verbose("\n<--- XMPP keep alive from '%s' --->\n", client->name);
2406                         }
2407                 } else {
2408                         ast_verbose("\n<--- XMPP sent to '%s' --->\n%s\n<------------->\n", client->name, xmpp);
2409                 }
2410         } else {
2411                 ast_verbose("\n<--- XMPP received from '%s' --->\n%s\n<------------->\n", client->name, xmpp);
2412         }
2413 }
2414
2415 /*! \brief Internal function which sends a raw message */
2416 static int xmpp_client_send_raw_message(struct ast_xmpp_client *client, const char *message)
2417 {
2418         int ret;
2419 #ifdef HAVE_OPENSSL
2420         int len = strlen(message);
2421
2422         if (xmpp_is_secure(client)) {
2423                 ret = SSL_write(client->ssl_session, message, len);
2424                 if (ret) {
2425                         /* Log the message here, because iksemel's logHook is
2426                            unaccessible */
2427                         xmpp_log_hook(client, message, len, 0);
2428                         return IKS_OK;
2429                 }
2430         }
2431 #endif
2432         /* If needed, data will be sent unencrypted, and logHook will
2433            be called inside iks_send_raw */
2434         ret = iks_send_raw(client->parser, message);
2435         if (ret != IKS_OK) {
2436                 return ret;
2437         }
2438
2439         return IKS_OK;
2440 }
2441
2442 /*! \brief Helper function which sends an XMPP stream header to the server */
2443 static int xmpp_send_stream_header(struct ast_xmpp_client *client, const struct ast_xmpp_client_config *cfg, const char *to)
2444 {
2445         char *namespace = ast_test_flag(&cfg->flags, XMPP_COMPONENT) ? "jabber:component:accept" : "jabber:client";
2446         char msg[91 + strlen(namespace) + 6 + strlen(to) + 16 + 1];
2447
2448         snprintf(msg, sizeof(msg), "<?xml version='1.0'?>"
2449                  "<stream:stream xmlns:stream='http://etherx.jabber.org/streams' xmlns='"
2450                  "%s' to='%s' version='1.0'>", namespace, to);
2451
2452         return xmpp_client_send_raw_message(client, msg);
2453 }
2454
2455 int ast_xmpp_client_send(struct ast_xmpp_client *client, iks *stanza)
2456 {
2457         return xmpp_client_send_raw_message(client, iks_string(iks_stack(stanza), stanza));
2458 }
2459
2460 /*! \brief Internal function called when we need to request TLS support */
2461 static int xmpp_client_request_tls(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node)
2462 {
2463         /* If the client connection is already secure we can jump straight to authenticating */
2464         if (xmpp_is_secure(client)) {
2465                 xmpp_client_change_state(client, XMPP_STATE_AUTHENTICATE);
2466                 return 0;
2467         }
2468
2469 #ifndef HAVE_OPENSSL
2470         ast_log(LOG_ERROR, "TLS connection for client '%s' cannot be established. OpenSSL is not available.\n", client->name);
2471         return -1;
2472 #else
2473         if (iks_send_raw(client->parser, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>") == IKS_NET_TLSFAIL) {
2474                 ast_log(LOG_ERROR, "TLS connection for client '%s' cannot be started.\n", client->name);
2475                 return -1;
2476         }
2477
2478         client->stream_flags |= TRY_SECURE;
2479
2480         xmpp_client_change_state(client, XMPP_STATE_REQUESTED_TLS);
2481
2482         return 0;
2483 #endif
2484 }
2485
2486 /*! \brief Internal function called when we receive a response to our TLS initiation request */
2487 static int xmpp_client_requested_tls(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node)
2488 {
2489 #ifdef HAVE_OPENSSL
2490         int sock;
2491 #endif
2492
2493         if (!strcmp(iks_name(node), "success")) {
2494                 /* TLS is up and working, we can move on to authenticating now */
2495                 xmpp_client_change_state(client, XMPP_STATE_AUTHENTICATE);
2496                 return 0;
2497         } else if (!strcmp(iks_name(node), "failure")) {
2498                 /* TLS negotiation was a failure, close it on down! */
2499                 return -1;
2500         } else if (strcmp(iks_name(node), "proceed")) {
2501                 /* Ignore any other responses */
2502                 return 0;
2503         }
2504
2505 #ifndef HAVE_OPENSSL
2506         ast_log(LOG_ERROR, "Somehow we managed to try to start TLS negotiation on client '%s' without OpenSSL support, disconnecting\n", client->name);
2507         return -1;
2508 #else
2509         client->ssl_method = SSLv3_method();
2510         if (!(client->ssl_context = SSL_CTX_new((SSL_METHOD *) client->ssl_method))) {
2511                 goto failure;
2512         }
2513
2514         if (!(client->ssl_session = SSL_new(client->ssl_context))) {
2515                 goto failure;
2516         }
2517
2518         sock = iks_fd(client->parser);
2519         if (!SSL_set_fd(client->ssl_session, sock)) {
2520                 goto failure;
2521         }
2522
2523         if (!SSL_connect(client->ssl_session)) {
2524                 goto failure;
2525         }
2526
2527         client->stream_flags &= (~TRY_SECURE);
2528         client->stream_flags |= SECURE;
2529
2530         if (xmpp_send_stream_header(client, cfg, client->jid->server) != IKS_OK) {
2531                 ast_log(LOG_ERROR, "TLS connection for client '%s' could not be established, failed to send stream header after negotiation\n",
2532                         client->name);
2533                 return -1;
2534         }
2535
2536         ast_debug(1, "TLS connection for client '%s' started with server\n", client->name);
2537
2538         xmpp_client_change_state(client, XMPP_STATE_AUTHENTICATE);
2539
2540         return 0;
2541
2542 failure:
2543         ast_log(LOG_ERROR, "TLS connection for client '%s' cannot be established. OpenSSL initialization failed.\n", client->name);
2544         return -1;
2545 #endif
2546 }
2547
2548 /*! \brief Internal function called when we need to authenticate using non-SASL */
2549 static int xmpp_client_authenticate_digest(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node)
2550 {
2551         iks *iq = NULL, *query = NULL;
2552         char buf[41], sidpass[100];
2553
2554         if (!(iq = iks_new("iq")) || !(query = iks_insert(iq, "query"))) {
2555                 ast_log(LOG_ERROR, "Stanzas could not be allocated for authentication on client '%s'\n", client->name);
2556                 iks_delete(iq);
2557                 return -1;
2558         }
2559
2560         iks_insert_attrib(iq, "type", "set");
2561         iks_insert_cdata(iks_insert(query, "username"), client->jid->user, 0);
2562         iks_insert_cdata(iks_insert(query, "resource"), client->jid->resource, 0);
2563
2564         iks_insert_attrib(query, "xmlns", "jabber:iq:auth");
2565         snprintf(sidpass, sizeof(sidpass), "%s%s", iks_find_attrib(node, "id"), cfg->password);
2566         ast_sha1_hash(buf, sidpass);
2567         iks_insert_cdata(iks_insert(query, "digest"), buf, 0);
2568
2569         ast_xmpp_client_lock(client);
2570         iks_filter_add_rule(client->filter, xmpp_connect_hook, client, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_SUBTYPE, IKS_TYPE_RESULT, IKS_RULE_ID, client->mid, IKS_RULE_DONE);
2571         iks_insert_attrib(iq, "id", client->mid);
2572         ast_xmpp_increment_mid(client->mid);
2573         ast_xmpp_client_unlock(client);
2574
2575         iks_insert_attrib(iq, "to", client->jid->server);
2576
2577         ast_xmpp_client_send(client, iq);
2578
2579         iks_delete(iq);
2580
2581         xmpp_client_change_state(client, XMPP_STATE_AUTHENTICATING);
2582
2583         return 0;
2584 }
2585
2586 /*! \brief Internal function called when we need to authenticate using SASL */
2587 static int xmpp_client_authenticate_sasl(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node)
2588 {
2589         int features, len = strlen(client->jid->user) + strlen(cfg->password) + 3;
2590         iks *auth;
2591         char combined[len];
2592         char base64[(len + 2) * 4 / 3];
2593
2594         if (strcmp(iks_name(node), "stream:features")) {
2595                 /* Ignore anything beside stream features */
2596                 return 0;
2597         }
2598
2599         features = iks_stream_features(node);
2600
2601         if ((features & IKS_STREAM_SASL_MD5) && !xmpp_is_secure(client)) {
2602                 if (iks_start_sasl(client->parser, IKS_SASL_DIGEST_MD5, (char*)client->jid->user, (char*)cfg->password) != IKS_OK) {
2603                         ast_log(LOG_ERROR, "Tried to authenticate client '%s' using SASL DIGEST-MD5 but could not\n", client->name);
2604                         return -1;
2605                 }
2606
2607                 xmpp_client_change_state(client, XMPP_STATE_AUTHENTICATING);
2608                 return 0;
2609         }
2610
2611         /* Our only other available option is plain so if they don't support it, bail out now */
2612         if (!(features & IKS_STREAM_SASL_PLAIN)) {
2613                 ast_log(LOG_ERROR, "Tried to authenticate client '%s' using SASL PLAIN but server does not support it\n", client->name);
2614                 return -1;
2615         }
2616
2617         if (!(auth = iks_new("auth"))) {
2618                 ast_log(LOG_ERROR, "Could not allocate memory for SASL PLAIN authentication for client '%s'\n", client->name);
2619                 return -1;
2620         }
2621
2622         iks_insert_attrib(auth, "xmlns", IKS_NS_XMPP_SASL);
2623         iks_insert_attrib(auth, "mechanism", "PLAIN");
2624
2625         if (strchr(client->jid->user, '/')) {
2626                 char *user = ast_strdupa(client->jid->user);
2627
2628                 snprintf(combined, sizeof(combined), "%c%s%c%s", 0, strsep(&user, "/"), 0, cfg->password);
2629         } else {
2630                 snprintf(combined, sizeof(combined), "%c%s%c%s", 0, client->jid->user, 0, cfg->password);
2631         }
2632
2633         ast_base64encode(base64, (const unsigned char *) combined, len - 1, (len + 2) * 4 / 3);
2634         iks_insert_cdata(auth, base64, 0);
2635
2636         ast_xmpp_client_send(client, auth);
2637
2638         iks_delete(auth);
2639
2640         xmpp_client_change_state(client, XMPP_STATE_AUTHENTICATING);
2641
2642         return 0;
2643 }
2644
2645 /*! \brief Internal function called when we need to authenticate */
2646 static int xmpp_client_authenticate(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node)
2647 {
2648         return ast_test_flag(&cfg->flags, XMPP_USESASL) ? xmpp_client_authenticate_sasl(client, cfg, type, node) : xmpp_client_authenticate_digest(client, cfg, type, node);
2649 }
2650
2651 /*! \brief Internal function called when we are authenticating */
2652 static int xmpp_client_authenticating(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node)
2653 {
2654         int features;
2655
2656         if (!strcmp(iks_name(node), "success")) {
2657                 /* Authentication was a success, yay! */
2658                 xmpp_send_stream_header(client, cfg, client->jid->server);
2659
2660                 return 0;
2661         } else if (!strcmp(iks_name(node), "failure")) {
2662                 /* Authentication was a bust, disconnect and reconnect later */
2663                 return -1;
2664         } else if (strcmp(iks_name(node), "stream:features")) {
2665                 /* Ignore any other responses */
2666                 return 0;
2667         }
2668
2669         features = iks_stream_features(node);
2670
2671         if (features & IKS_STREAM_BIND) {
2672                 iks *auth;
2673
2674                 if (!(auth = iks_make_resource_bind(client->jid))) {
2675                         ast_log(LOG_ERROR, "Failed to allocate memory for stream bind on client '%s'\n", client->name);
2676                         return -1;
2677                 }
2678
2679                 ast_xmpp_client_lock(client);
2680                 iks_insert_attrib(auth, "id", client->mid);
2681                 ast_xmpp_increment_mid(client->mid);
2682                 ast_xmpp_client_unlock(client);
2683                 ast_xmpp_client_send(client, auth);
2684
2685                 iks_delete(auth);
2686
2687                 iks_filter_add_rule(client->filter, xmpp_connect_hook, client, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_SUBTYPE, IKS_TYPE_RESULT, IKS_RULE_DONE);
2688         }
2689
2690         if (features & IKS_STREAM_SESSION) {
2691                 iks *auth;
2692
2693                 if (!(auth = iks_make_session())) {
2694                         ast_log(LOG_ERROR, "Failed to allocate memory for stream session on client '%s'\n", client->name);
2695                         return -1;
2696                 }
2697
2698                 iks_insert_attrib(auth, "id", "auth");
2699                 ast_xmpp_client_lock(client);
2700                 ast_xmpp_increment_mid(client->mid);
2701                 ast_xmpp_client_unlock(client);
2702                 ast_xmpp_client_send(client, auth);
2703
2704                 iks_delete(auth);
2705
2706                 iks_filter_add_rule(client->filter, xmpp_connect_hook, client, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_SUBTYPE, IKS_TYPE_RESULT, IKS_RULE_ID, "auth", IKS_RULE_DONE);
2707         }
2708
2709         return 0;
2710 }
2711
2712 /*! \brief Internal function called when we should authenticate as a component */
2713 static int xmpp_component_authenticate(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node)
2714 {
2715         char secret[160], shasum[320], message[344];
2716         ikspak *pak = iks_packet(node);
2717
2718         snprintf(secret, sizeof(secret), "%s%s", pak->id, cfg->password);
2719         ast_sha1_hash(shasum, secret);
2720         snprintf(message, sizeof(message), "<handshake>%s</handshake>", shasum);
2721
2722         if (xmpp_client_send_raw_message(client, message) != IKS_OK) {
2723                 ast_log(LOG_ERROR, "Unable to send handshake for component '%s'\n", client->name);
2724                 return -1;
2725         }
2726
2727         xmpp_client_change_state(client, XMPP_STATE_AUTHENTICATING);
2728
2729         return 0;
2730 }
2731
2732 /*! \brief Hook function called when component receives a service discovery get message */
2733 static int xmpp_component_service_discovery_get_hook(void *data, ikspak *pak)
2734 {
2735         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
2736         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
2737         struct ast_xmpp_client *client = data;
2738         iks *iq = NULL, *query = NULL, *identity = NULL, *disco = NULL, *reg = NULL, *commands = NULL, *gateway = NULL;
2739         iks *version = NULL, *vcard = NULL, *search = NULL, *item = NULL;
2740         char *node;
2741
2742         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name)) ||
2743             !(iq = iks_new("iq")) || !(query = iks_new("query")) || !(identity = iks_new("identity")) || !(disco = iks_new("feature")) ||
2744             !(reg = iks_new("feature")) || !(commands = iks_new("feature")) || !(gateway = iks_new("feature")) || !(version = iks_new("feature")) ||
2745             !(vcard = iks_new("feature")) || !(search = iks_new("search")) || !(item = iks_new("item"))) {
2746                 ast_log(LOG_ERROR, "Failed to allocate stanzas for service discovery get response to '%s' on component '%s'\n",
2747                         pak->from->partial, client->name);
2748                 goto done;
2749         }
2750
2751         iks_insert_attrib(iq, "from", clientcfg->user);
2752         iks_insert_attrib(iq, "to", pak->from->full);
2753         iks_insert_attrib(iq, "id", pak->id);
2754         iks_insert_attrib(iq, "type", "result");
2755
2756         if (!(node = iks_find_attrib(pak->query, "node"))) {
2757                 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
2758                 iks_insert_attrib(identity, "category", "gateway");
2759                 iks_insert_attrib(identity, "type", "pstn");
2760                 iks_insert_attrib(identity, "name", "Asterisk The Open Source PBX");
2761                 iks_insert_attrib(disco, "var", "http://jabber.org/protocol/disco");
2762                 iks_insert_attrib(reg, "var", "jabber:iq:register");
2763                 iks_insert_attrib(commands, "var", "http://jabber.org/protocol/commands");
2764                 iks_insert_attrib(gateway, "var", "jabber:iq:gateway");
2765                 iks_insert_attrib(version, "var", "jabber:iq:version");
2766                 iks_insert_attrib(vcard, "var", "vcard-temp");
2767                 iks_insert_attrib(search, "var", "jabber:iq:search");
2768
2769                 iks_insert_node(iq, query);
2770                 iks_insert_node(query, identity);
2771                 iks_insert_node(query, disco);
2772                 iks_insert_node(query, reg);
2773                 iks_insert_node(query, commands);
2774                 iks_insert_node(query, gateway);
2775                 iks_insert_node(query, version);
2776                 iks_insert_node(query, vcard);
2777                 iks_insert_node(query, search);
2778         } else if (!strcasecmp(node, "http://jabber.org/protocol/commands")) {
2779                 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
2780                 iks_insert_attrib(query, "node", "http://jabber.org/protocol/commands");
2781                 iks_insert_attrib(item, "node", "confirmaccount");
2782                 iks_insert_attrib(item, "name", "Confirm account");
2783                 iks_insert_attrib(item, "jid", clientcfg->user);
2784
2785                 iks_insert_node(iq, query);
2786                 iks_insert_node(query, item);
2787         } else if (!strcasecmp(node, "confirmaccount")) {
2788                 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
2789                 iks_insert_attrib(commands, "var", "http://jabber.org/protocol/commands");
2790
2791                 iks_insert_node(iq, query);
2792                 iks_insert_node(query, commands);
2793         } else {
2794                 ast_debug(3, "Unsupported service discovery info request received with node '%s' on component '%s'\n",
2795                           node, client->name);
2796                 goto done;
2797         }
2798
2799         if (ast_xmpp_client_send(client, iq)) {
2800                 ast_log(LOG_WARNING, "Could not send response to service discovery request on component '%s'\n",
2801                         client->name);
2802         }
2803
2804 done:
2805         iks_delete(search);
2806         iks_delete(vcard);
2807         iks_delete(version);
2808         iks_delete(gateway);
2809         iks_delete(commands);
2810         iks_delete(reg);
2811         iks_delete(disco);
2812         iks_delete(identity);
2813         iks_delete(query);
2814         iks_delete(iq);
2815
2816         return IKS_FILTER_EAT;
2817 }
2818
2819 /*! \brief Hook function called when the component is queried about registration */
2820 static int xmpp_component_register_get_hook(void *data, ikspak *pak)
2821 {
2822         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
2823         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
2824         struct ast_xmpp_client *client = data;
2825         iks *iq = NULL, *query = NULL, *error = NULL, *notacceptable = NULL, *instructions = NULL;
2826         struct ast_xmpp_buddy *buddy;
2827         char *node;
2828
2829         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name)) ||
2830             !(iq = iks_new("iq")) || !(query = iks_new("query")) || !(error = iks_new("error")) || !(notacceptable = iks_new("not-acceptable")) ||
2831             !(instructions = iks_new("instructions"))) {
2832                 ast_log(LOG_ERROR, "Failed to allocate stanzas for register get response to '%s' on component '%s'\n",
2833                         pak->from->partial, client->name);
2834                 goto done;
2835         }
2836
2837         iks_insert_attrib(iq, "from", clientcfg->user);
2838         iks_insert_attrib(iq, "to", pak->from->full);
2839         iks_insert_attrib(iq, "id", pak->id);
2840         iks_insert_attrib(iq, "type", "result");
2841         iks_insert_attrib(query, "xmlns", "jabber:iq:register");
2842         iks_insert_node(iq, query);
2843
2844         if (!(buddy = ao2_find(client->buddies, pak->from->partial, OBJ_KEY))) {
2845                 iks_insert_attrib(error, "code", "406");
2846                 iks_insert_attrib(error, "type", "modify");
2847                 iks_insert_attrib(notacceptable, "xmlns", "urn:ietf:params:xml:ns:xmpp-stanzas");
2848
2849                 iks_insert_node(iq, error);
2850                 iks_insert_node(error, notacceptable);
2851
2852                 ast_log(LOG_ERROR, "Received register attempt from '%s' but buddy is not configured on component '%s'\n",
2853                         pak->from->partial, client->name);
2854         } else if (!(node = iks_find_attrib(pak->query, "node"))) {
2855                 iks_insert_cdata(instructions, "Welcome to Asterisk - the Open Source PBX.\n", 0);
2856                 iks_insert_node(query, instructions);
2857                 ao2_ref(buddy, -1);
2858         } else {
2859                 ast_log(LOG_WARNING, "Received register get to component '%s' using unsupported node '%s' from '%s'\n",
2860                         client->name, node, pak->from->partial);
2861                 ao2_ref(buddy, -1);
2862                 goto done;
2863         }
2864
2865         if (ast_xmpp_client_send(client, iq)) {
2866                 ast_log(LOG_WARNING, "Could not send response to '%s' for received register get on component '%s'\n",
2867                         pak->from->partial, client->name);
2868         }
2869
2870 done:
2871         iks_delete(instructions);
2872         iks_delete(notacceptable);
2873         iks_delete(error);
2874         iks_delete(query);
2875         iks_delete(iq);
2876
2877         return IKS_FILTER_EAT;
2878 }
2879
2880 /*! \brief Hook function called when someone registers to the component */
2881 static int xmpp_component_register_set_hook(void *data, ikspak *pak)
2882 {
2883         struct ast_xmpp_client *client = data;
2884         iks *iq, *presence = NULL, *x = NULL;
2885
2886         if (!(iq = iks_new("iq")) || !(presence = iks_new("presence")) || !(x = iks_new("x"))) {
2887                 ast_log(LOG_ERROR, "Failed to allocate stanzas for register set response to '%s' on component '%s'\n",
2888                         pak->from->partial, client->name);
2889                 goto done;
2890         }
2891
2892         iks_insert_attrib(iq, "from", client->jid->full);
2893         iks_insert_attrib(iq, "to", pak->from->full);
2894         iks_insert_attrib(iq, "id", pak->id);
2895         iks_insert_attrib(iq, "type", "result");
2896
2897         if (ast_xmpp_client_send(client, iq)) {
2898                 ast_log(LOG_WARNING, "Could not send response to '%s' for received register set on component '%s'\n",
2899                         pak->from->partial, client->name);
2900                 goto done;
2901         }
2902
2903         iks_insert_attrib(presence, "from", client->jid->full);
2904         iks_insert_attrib(presence, "to", pak->from->partial);
2905         ast_xmpp_client_lock(client);
2906         iks_insert_attrib(presence, "id", client->mid);
2907         ast_xmpp_increment_mid(client->mid);
2908         ast_xmpp_client_unlock(client);
2909         iks_insert_attrib(presence, "type", "subscribe");
2910         iks_insert_attrib(x, "xmlns", "vcard-temp:x:update");
2911
2912         iks_insert_node(presence, x);
2913
2914         if (ast_xmpp_client_send(client, presence)) {
2915                 ast_log(LOG_WARNING, "Could not send subscription to '%s' on component '%s'\n",
2916                         pak->from->partial, client->name);
2917         }
2918
2919 done:
2920         iks_delete(x);
2921         iks_delete(presence);
2922         iks_delete(iq);
2923
2924         return IKS_FILTER_EAT;
2925 }
2926
2927 /*! \brief Hook function called when we receive a service discovery items request */
2928 static int xmpp_component_service_discovery_items_hook(void *data, ikspak *pak)
2929 {
2930         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
2931         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
2932         struct ast_xmpp_client *client = data;
2933         iks *iq = NULL, *query = NULL, *item = NULL, *feature = NULL;
2934         char *node;
2935
2936         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name)) ||
2937             !(iq = iks_new("iq")) || !(query = iks_new("query")) || !(item = iks_new("item")) || !(feature = iks_new("feature"))) {
2938                 ast_log(LOG_ERROR, "Failed to allocate stanzas for service discovery items response to '%s' on component '%s'\n",
2939                         pak->from->partial, client->name);
2940                 goto done;
2941         }
2942
2943         iks_insert_attrib(iq, "from", clientcfg->user);
2944         iks_insert_attrib(iq, "to", pak->from->full);
2945         iks_insert_attrib(iq, "id", pak->id);
2946         iks_insert_attrib(iq, "type", "result");
2947         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
2948         iks_insert_node(iq, query);
2949
2950         if (!(node = iks_find_attrib(pak->query, "node"))) {
2951                 iks_insert_attrib(item, "node", "http://jabber.org/protocol/commands");
2952                 iks_insert_attrib(item, "name", "Asterisk Commands");
2953                 iks_insert_attrib(item, "jid", clientcfg->user);
2954
2955                 iks_insert_node(query, item);
2956         } else if (!strcasecmp(node, "http://jabber.org/protocol/commands")) {
2957                 iks_insert_attrib(query, "node", "http://jabber.org/protocol/commands");
2958         } else {
2959                 ast_log(LOG_WARNING, "Received service discovery items request to component '%s' using unsupported node '%s' from '%s'\n",
2960                         client->name, node, pak->from->partial);
2961                 goto done;
2962         }
2963
2964         if (ast_xmpp_client_send(client, iq)) {
2965                 ast_log(LOG_WARNING, "Could not send response to service discovery items request from '%s' on component '%s'\n",
2966                         pak->from->partial, client->name);
2967         }
2968
2969 done:
2970         iks_delete(feature);
2971         iks_delete(item);
2972         iks_delete(query);
2973         iks_delete(iq);
2974
2975         return IKS_FILTER_EAT;
2976 }
2977
2978 /*! \brief Internal function called when we authenticated as a component */
2979 static int xmpp_component_authenticating(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node)
2980 {
2981         if (strcmp(iks_name(node), "handshake")) {
2982                 ast_log(LOG_ERROR, "Failed to authenticate component '%s'\n", client->name);
2983                 return -1;
2984         }
2985
2986         iks_filter_add_rule(client->filter, xmpp_component_service_discovery_items_hook, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#items", IKS_RULE_DONE);
2987
2988         iks_filter_add_rule(client->filter, xmpp_component_service_discovery_get_hook, client, IKS_RULE_SUBTYPE, IKS_TYPE_GET, IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
2989
2990         /* This uses the client service discovery result hook on purpose, as the code is common between both */
2991         iks_filter_add_rule(client->filter, xmpp_client_service_discovery_result_hook, client, IKS_RULE_SUBTYPE, IKS_TYPE_RESULT, IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
2992
2993         iks_filter_add_rule(client->filter, xmpp_component_register_get_hook, client, IKS_RULE_SUBTYPE, IKS_TYPE_GET, IKS_RULE_NS, "jabber:iq:register", IKS_RULE_DONE);
2994         iks_filter_add_rule(client->filter, xmpp_component_register_set_hook, client, IKS_RULE_SUBTYPE, IKS_TYPE_SET, IKS_RULE_NS, "jabber:iq:register", IKS_RULE_DONE);
2995
2996         xmpp_client_change_state(client, XMPP_STATE_CONNECTED);
2997
2998         return 0;
2999 }
3000
3001 /*! \brief Internal function called when a message is received */
3002 static int xmpp_pak_message(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, iks *node, ikspak *pak)
3003 {
3004         struct ast_xmpp_message *message;
3005         char *body;
3006         int deleted = 0;
3007
3008         ast_debug(3, "XMPP client '%s' received a message\n", client->name);
3009
3010         if (!(body = iks_find_cdata(pak->x, "body"))) {
3011                 /* Message contains no body, ignore it. */
3012                 return 0;
3013         }
3014
3015         if (!(message = ast_calloc(1, sizeof(*message)))) {
3016                 return -1;
3017         }
3018
3019         message->arrived = ast_tvnow();
3020
3021         message->message = ast_strdup(body);
3022
3023         ast_copy_string(message->id, S_OR(pak->id, ""), sizeof(message->id));
3024         message->from = !ast_strlen_zero(pak->from->full) ? ast_strdup(pak->from->full) : NULL;
3025
3026         if (ast_test_flag(&cfg->flags, XMPP_SEND_TO_DIALPLAN)) {
3027                 struct ast_msg *msg;
3028
3029                 if ((msg = ast_msg_alloc())) {
3030                         int res;
3031
3032                         ast_xmpp_client_lock(client);
3033
3034                         res = ast_msg_set_to(msg, "xmpp:%s", cfg->user);
3035                         res |= ast_msg_set_from(msg, "xmpp:%s", message->from);
3036                         res |= ast_msg_set_body(msg, "%s", message->message);
3037                         res |= ast_msg_set_context(msg, "%s", cfg->context);
3038
3039                         ast_xmpp_client_unlock(client);
3040
3041                         if (res) {
3042                                 ast_msg_destroy(msg);
3043                         } else {
3044                                 ast_msg_queue(msg);
3045                         }
3046                 }
3047         }
3048
3049         /* remove old messages received from this JID
3050          * and insert received message */
3051         deleted = delete_old_messages(client, pak->from->partial);
3052         ast_debug(3, "Deleted %d messages for client %s from JID %s\n", deleted, client->name, pak->from->partial);
3053         AST_LIST_LOCK(&client->messages);
3054         AST_LIST_INSERT_HEAD(&client->messages, message, list);
3055         AST_LIST_UNLOCK(&client->messages);
3056
3057         /* wake up threads waiting for messages */
3058         ast_mutex_lock(&messagelock);
3059         ast_cond_broadcast(&message_received_condition);
3060         ast_mutex_unlock(&messagelock);
3061
3062         return 0;
3063 }
3064
3065 /*! \brief Helper function which sends a discovery information request to a user */
3066 static int xmpp_client_send_disco_info_request(struct ast_xmpp_client *client, const char *to, const char *from)
3067 {
3068         iks *iq, *query;
3069         int res;
3070
3071         if (!(iq = iks_new("iq")) || !(query = iks_new("query"))) {
3072                 iks_delete(iq);
3073                 return -1;
3074         }
3075
3076         iks_insert_attrib(iq, "type", "get");
3077         iks_insert_attrib(iq, "to", to);
3078         iks_insert_attrib(iq, "from", from);
3079         ast_xmpp_client_lock(client);
3080         iks_insert_attrib(iq, "id", client->mid);
3081         ast_xmpp_increment_mid(client->mid);
3082         ast_xmpp_client_unlock(client);
3083         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
3084         iks_insert_node(iq, query);
3085
3086         res = ast_xmpp_client_send(client, iq);
3087
3088         iks_delete(query);
3089         iks_delete(iq);
3090
3091         return res;
3092 }
3093
3094 /*! \brief Internal function called when a presence message is received */
3095 static int xmpp_pak_presence(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, iks *node, ikspak *pak)
3096 {
3097         struct ast_xmpp_buddy *buddy;
3098         struct ast_xmpp_resource *resource;
3099         char *type = iks_find_attrib(pak->x, "type");
3100         int status = pak->show ? pak->show : STATUS_DISAPPEAR;
3101
3102         /* If no resource is available this is a general buddy presence update, which we will ignore */
3103         if (!pak->from->resource) {
3104                 return 0;
3105         }
3106
3107         if (!(buddy = ao2_find(client->buddies, pak->from->partial, OBJ_KEY))) {
3108                 /* Only output the message if it is not about us */
3109                 if (strcmp(client->jid->partial, pak->from->partial)) {
3110                         ast_log(LOG_WARNING, "Received presence information about '%s' despite not having them in roster on client '%s'\n",
3111                                 pak->from->partial, client->name);
3112                 }
3113                 return 0;
3114         }
3115
3116         /* If this is a component presence probe request answer immediately with our presence status */
3117         if (ast_test_flag(&cfg->flags, XMPP_COMPONENT) && !ast_strlen_zero(type) && !strcasecmp(type, "probe")) {
3118                 xmpp_client_set_presence(client, pak->from->full, iks_find_attrib(pak->x, "to"), cfg->status, cfg->statusmsg);
3119         }
3120
3121         ao2_lock(buddy->resources);
3122
3123         if (!(resource = ao2_find(buddy->resources, pak->from->resource, OBJ_KEY | OBJ_NOLOCK))) {
3124                 /* Only create the new resource if it is not going away - in reality this should not happen */
3125                 if (status != STATUS_DISAPPEAR) {
3126                         if (!(resource = ao2_alloc(sizeof(*resource), xmpp_resource_destructor))) {
3127                                 ast_log(LOG_ERROR, "Could not allocate resource object for resource '%s' of buddy '%s' on client '%s'\n",
3128                                         pak->from->resource, buddy->id, client->name);
3129                                 ao2_unlock(buddy->resources);
3130                                 ao2_ref(buddy, -1);
3131                                 return 0;
3132                         }
3133
3134                         ast_copy_string(resource->resource, pak->from->resource, sizeof(resource->resource));
3135                 }
3136         } else {
3137                 /* We unlink the resource in case the priority changes or in case they are going away */
3138                 ao2_unlink_flags(buddy->resources, resource, OBJ_NOLOCK);
3139         }
3140
3141         /* Only update the resource and add it back in if it is not going away */
3142         if (resource && (status != STATUS_DISAPPEAR)) {
3143                 char *node, *ver;
3144
3145                 /* Try to get the XMPP spec node, and fall back to Google if not found */
3146                 if (!(node = iks_find_attrib(iks_find(pak->x, "c"), "node"))) {
3147                         node = iks_find_attrib(iks_find(pak->x, "caps:c"), "node");
3148                 }
3149
3150                 if (!(ver = iks_find_attrib(iks_find(pak->x, "c"), "ver"))) {
3151                         ver = iks_find_attrib(iks_find(pak->x, "caps:c"), "ver");
3152                 }
3153
3154                 if (resource->description) {
3155                         ast_free(resource->description);
3156                 }
3157
3158                 if ((node && strcmp(resource->caps.node, node)) || (ver && strcmp(resource->caps.version, ver))) {
3159                         /* For interoperability reasons, proceed even if the resource fails to provide node or version */
3160                         if (node) {
3161                                 ast_copy_string(resource->caps.node, node, sizeof(resource->caps.node));
3162                         }
3163                         if (ver) {
3164                                 ast_copy_string(resource->caps.version, ver, sizeof(resource->caps.version));
3165                         }
3166
3167                         /* Google Talk places the capabilities information directly in presence, so see if it is there */
3168                         if (iks_find_with_attrib(pak->x, "c", "node", "http://www.google.com/xmpp/client/caps") ||
3169                             iks_find_with_attrib(pak->x, "caps:c", "node", "http://www.google.com/xmpp/client/caps") ||
3170                             iks_find_with_attrib(pak->x, "c", "node", "http://www.android.com/gtalk/client/caps") ||
3171                             iks_find_with_attrib(pak->x, "caps:c", "node", "http://www.android.com/gtalk/client/caps") ||
3172                             iks_find_with_attrib(pak->x, "c", "node", "http://mail.google.com/xmpp/client/caps") ||
3173                             iks_find_with_attrib(pak->x, "caps:c", "node", "http://mail.google.com/xmpp/client/caps")) {
3174                                 resource->caps.google = 1;
3175                         }
3176
3177                         /* To discover if the buddy supports Jingle we need to query, so do so */
3178                         if (xmpp_client_send_disco_info_request(client, pak->from->full, client->jid->full)) {
3179                                 ast_log(LOG_WARNING, "Could not send discovery information request to resource '%s' of buddy '%s' on client '%s', capabilities may be incomplete\n", resource->resource, buddy->id, client->name);
3180                         }
3181                 }
3182
3183                 resource->status = status;
3184                 resource->description = ast_strdup(iks_find_cdata(pak->x, "status"));
3185                 resource->priority = atoi((iks_find_cdata(pak->x, "priority")) ? iks_find_cdata(pak->x, "priority") : "0");
3186
3187                 ao2_link_flags(buddy->resources, resource, OBJ_NOLOCK);
3188
3189                 manager_event(EVENT_FLAG_USER, "JabberStatus",
3190                               "Account: %s\r\nJID: %s\r\nResource: %s\r\nStatus: %d\r\nPriority: %d"
3191                               "\r\nDescription: %s\r\n",
3192                               client->name, pak->from->partial, resource->resource, resource->status,
3193                               resource->priority, S_OR(resource->description, ""));
3194
3195                 ao2_ref(resource, -1);
3196         } else {
3197                 /* This will get hit by presence coming in for an unknown resource, and also when a resource goes away */
3198                 if (resource) {
3199                         ao2_ref(resource, -1);
3200                 }
3201
3202                 manager_event(EVENT_FLAG_USER, "JabberStatus",
3203                               "Account: %s\r\nJID: %s\r\nStatus: %d\r\n",
3204                               client->name, pak->from->partial, pak->show ? pak->show : IKS_SHOW_UNAVAILABLE);
3205         }
3206
3207         ao2_unlock(buddy->resources);
3208
3209         ao2_ref(buddy, -1);
3210
3211         return 0;
3212 }
3213
3214 /*! \brief Internal function called when a subscription message is received */
3215 static int xmpp_pak_s10n(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg,iks *node, ikspak *pak)
3216 {
3217         struct ast_xmpp_buddy *buddy;
3218
3219         switch (pak->subtype) {
3220         case IKS_TYPE_SUBSCRIBE:
3221                 if (ast_test_flag(&cfg->flags, XMPP_AUTOREGISTER)) {
3222                         iks *presence, *status = NULL;
3223
3224                         if ((presence = iks_new("presence")) && (status = iks_new("status"))) {
3225                                 iks_insert_attrib(presence, "type", "subscribed");
3226                                 iks_insert_attrib(presence, "to", pak->from->full);
3227                                 iks_insert_attrib(presence, "from", client->jid->full);
3228
3229                                 if (pak->id) {
3230                                         iks_insert_attrib(presence, "id", pak->id);
3231                                 }
3232
3233                                 iks_insert_cdata(status, "Asterisk has approved your subscription", 0);
3234                                 iks_insert_node(presence, status);
3235
3236                                 if (ast_xmpp_client_send(client, presence)) {
3237                                         ast_log(LOG_ERROR, "Could not send subscription acceptance to '%s' from client '%s'\n",
3238                                                 pak->from->partial, client->name);
3239                                 }
3240                         } else {
3241                                 ast_log(LOG_ERROR, "Could not allocate presence stanzas for accepting subscription from '%s' to client '%s'\n",
3242                                         pak->from->partial, client->name);
3243                         }
3244
3245                         iks_delete(status);
3246                         iks_delete(presence);
3247                 }
3248
3249                 if (ast_test_flag(&cfg->flags, XMPP_COMPONENT)) {
3250                         xmpp_client_set_presence(client, pak->from->full, iks_find_attrib(pak->x, "to"), cfg->status, cfg->statusmsg);
3251                 }
3252                 /* This purposely flows through so we have the subscriber amongst our buddies */
3253         case IKS_TYPE_SUBSCRIBED:
3254                 ao2_lock(client->buddies);
3255
3256                 if (!(buddy = ao2_find(client->buddies, pak->from->partial, OBJ_KEY | OBJ_NOLOCK))) {
3257                         buddy = xmpp_client_create_buddy(client->buddies, pak->from->partial);
3258                 }
3259
3260                 if (!buddy) {
3261                         ast_log(LOG_WARNING, "Could not find or create buddy '%s' on client '%s'\n",
3262                                 pak->from->partial, client->name);
3263                 } else {
3264                         ao2_ref(buddy, -1);
3265                 }
3266
3267                 ao2_unlock(client->buddies);
3268
3269                 break;
3270         default:
3271                 break;
3272         }
3273
3274         return 0;
3275 }
3276
3277 /*! \brief Action hook for when things occur */
3278 static int xmpp_action_hook(void *data, int type, iks *node)
3279 {
3280         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
3281         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
3282         struct ast_xmpp_client *client = data;
3283         ikspak *pak;
3284         int i;
3285
3286         if (!node) {
3287                 ast_log(LOG_ERROR, "xmpp_action_hook was called without a packet\n");
3288                 return IKS_HOOK;
3289         }
3290
3291         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name))) {
3292                 return IKS_HOOK;
3293         }
3294
3295         /* If the client is disconnecting ignore everything */
3296         if (client->state == XMPP_STATE_DISCONNECTING) {
3297                 return IKS_HOOK;
3298         }
3299
3300         pak = iks_packet(node);
3301
3302         /* work around iksemel's impossibility to recognize node names
3303          * containing a colon. Set the namespace of the corresponding
3304          * node accordingly. */
3305         if (iks_has_children(node) && strchr(iks_name(iks_child(node)), ':')) {
3306                 char *node_ns = NULL;
3307                 char attr[XMPP_MAX_ATTRLEN];
3308                 char *node_name = iks_name(iks_child(node));
3309                 char *aux = strchr(node_name, ':') + 1;
3310                 snprintf(attr, strlen("xmlns:") + (strlen(node_name) - strlen(aux)), "xmlns:%s", node_name);
3311                 node_ns = iks_find_attrib(iks_child(node), attr);
3312                 if (node_ns) {
3313                         pak->ns = node_ns;
3314                         pak->query = iks_child(node);
3315                 }
3316         }
3317
3318         /* Process through any state handlers */
3319         for (i = 0; i < ARRAY_LEN(xmpp_state_handlers); i++) {
3320                 if ((xmpp_state_handlers[i].state == client->state) && (xmpp_state_handlers[i].component == (ast_test_flag(&clientcfg->flags, XMPP_COMPONENT) ? 1 : 0))) {
3321                         if (xmpp_state_handlers[i].handler(client, clientcfg, type, node)) {
3322                                 /* If the handler wants us to stop now, do so */
3323                                 return IKS_HOOK;
3324                         }
3325                         break;
3326                 }
3327         }
3328
3329         /* Process through any PAK handlers */
3330         for (i = 0; i < ARRAY_LEN(xmpp_pak_handlers); i++) {
3331                 if (xmpp_pak_handlers[i].type == pak->type) {
3332                         if (xmpp_pak_handlers[i].handler(client, clientcfg, node, pak)) {
3333                                 /* If the handler wants us to stop now, do so */
3334                                 return IKS_HOOK;
3335                         }
3336                         break;
3337                 }
3338         }
3339
3340         /* Send the packet through the filter in case any filters want to process it */
3341         iks_filter_packet(client->filter, pak);
3342
3343         iks_delete(node);
3344
3345         return IKS_OK;
3346 }
3347
3348 int ast_xmpp_client_disconnect(struct ast_xmpp_client *client)
3349 {
3350         if ((client->thread != AST_PTHREADT_NULL) && !pthread_equal(pthread_self(), client->thread)) {
3351                 client->state = XMPP_STATE_DISCONNECTING;
3352                 pthread_join(client->thread, NULL);
3353                 client->thread = AST_PTHREADT_NULL;
3354         }
3355
3356         if (client->mwi_sub) {
3357                 ast_event_unsubscribe(client->mwi_sub);
3358                 client->mwi_sub = NULL;
3359                 xmpp_pubsub_unsubscribe(client, "message_waiting");
3360         }
3361
3362         if (client->device_state_sub) {
3363                 ast_event_unsubscribe(client->device_state_sub);
3364                 client->device_state_sub = NULL;
3365                 xmpp_pubsub_unsubscribe(client, "device_state");
3366         }
3367
3368 #ifdef HAVE_OPENSSL
3369         if (client->stream_flags & SECURE) {
3370                 SSL_shutdown(client->ssl_session);
3371                 SSL_CTX_free(client->ssl_context);
3372                 SSL_free(client->ssl_session);
3373         }
3374
3375         client->stream_flags = 0;
3376 #endif
3377
3378         if (client->parser) {
3379                 iks_disconnect(client->parser);
3380         }
3381
3382         /* Disconnecting the parser and going back to a disconnected state means any hooks should no longer be present */
3383         if (client->filter) {
3384                 iks_filter_delete(client->filter);
3385                 client->filter = NULL;
3386         }
3387
3388         client->state = XMPP_STATE_DISCONNECTED;
3389
3390         return 0;
3391 }
3392
3393 /*! \brief Internal function used to reconnect an XMPP client to its server */
3394 static int xmpp_client_reconnect(struct ast_xmpp_client *client)
3395 {
3396         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
3397         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
3398         int res = IKS_NET_NOCONN;
3399
3400         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name))) {
3401                 return -1;
3402         }
3403
3404         ast_xmpp_client_disconnect(client);
3405
3406         client->timeout = 50;
3407         iks_parser_reset(client->parser);
3408
3409         if (!client->filter && !(client->filter = iks_filter_new())) {
3410                 ast_log(LOG_ERROR, "Could not create IKS filter for client connection '%s'\n", client->name);
3411                 return -1;
3412         }
3413
3414         /* If it's a component connect to user otherwise connect to server */
3415         res = iks_connect_via(client->parser, S_OR(clientcfg->server, client->jid->server), clientcfg->port,
3416                               ast_test_flag(&clientcfg->flags, XMPP_COMPONENT) ? clientcfg->user : client->jid->server);
3417
3418         if (res == IKS_NET_NOCONN) {
3419                 ast_log(LOG_ERROR, "No XMPP connection available when trying to connect client '%s'\n", client->name);
3420                 return -1;
3421         } else if (res == IKS_NET_NODNS) {
3422                 ast_log(LOG_ERROR, "No DNS available for XMPP connection when trying to connect client '%s'\n", client->name);
3423                 return -1;
3424         }
3425
3426         /* Depending on the configuration of the client we eiher jump to requesting TLS, or authenticating */
3427         xmpp_client_change_state(client, (ast_test_flag(&clientcfg->flags, XMPP_USETLS) ? XMPP_STATE_REQUEST_TLS : XMPP_STATE_AUTHENTICATE));
3428
3429         return 0;
3430 }
3431
3432 /*! \brief Internal function which polls on an XMPP client and receives data */
3433 static int xmpp_io_recv(struct ast_xmpp_client *client, char *buffer, size_t buf_len, int timeout)
3434 {
3435         struct pollfd pfd = { .events = POLLIN };
3436         int len, res;
3437
3438 #ifdef HAVE_OPENSSL
3439         if (xmpp_is_secure(client)) {
3440                 pfd.fd = SSL_get_fd(client->ssl_session);
3441                 if (pfd.fd < 0) {
3442                         return -1;
3443                 }
3444         } else
3445 #endif /* HAVE_OPENSSL */
3446                 pfd.fd = iks_fd(client->parser);
3447
3448         res = ast_poll(&pfd, 1, timeout > 0 ? timeout * 1000 : -1);
3449         if (res > 0) {
3450 #ifdef HAVE_OPENSSL
3451                 if (xmpp_is_secure(client)) {
3452                         len = SSL_read(client->ssl_session, buffer, buf_len);
3453                 } else
3454 #endif /* HAVE_OPENSSL */
3455                         len = recv(pfd.fd, buffer, buf_len, 0);
3456
3457                 if (len > 0) {
3458                         return len;
3459                 } else if (len <= 0) {
3460                         return -1;
3461                 }
3462         }
3463         return res;
3464 }
3465
3466 /*! \brief Internal function which receives data from the XMPP client connection */
3467 static int xmpp_client_receive(struct ast_xmpp_client *client, unsigned int timeout)
3468 {
3469         int len, ret, pos = 0, newbufpos = 0;
3470         char buf[NET_IO_BUF_SIZE - 1] = "";
3471         char newbuf[NET_IO_BUF_SIZE - 1] = "";
3472         unsigned char c;
3473
3474         while (1) {
3475                 len = xmpp_io_recv(client, buf, NET_IO_BUF_SIZE - 2, timeout);
3476                 if (len < 0) return IKS_NET_RWERR;
3477                 if (len == 0) return IKS_NET_EXPIRED;
3478                 buf[len] = '\0';
3479
3480                 /* our iksemel parser won't work as expected if we feed
3481                    it with XML packets that contain multiple whitespace
3482                    characters between tags */
3483                 while (pos < len) {
3484                         c = buf[pos];
3485                         /* if we stumble on the ending tag character,
3486                            we skip any whitespace that follows it*/
3487                         if (c == '>') {
3488                                 while (isspace(buf[pos+1])) {
3489                                         pos++;
3490                                 }
3491                         }
3492                         newbuf[newbufpos] = c;
3493                         newbufpos++;
3494                         pos++;
3495                 }
3496                 pos = 0;
3497                 newbufpos = 0;
3498
3499                 /* Log the message here, because iksemel's logHook is
3500                    unaccessible */
3501                 xmpp_log_hook(client, buf, len, 1);
3502
3503                 /* let iksemel deal with the string length,
3504                    and reset our buffer */
3505                 ret = iks_parse(client->parser, newbuf, 0, 0);
3506                 memset(newbuf, 0, sizeof(newbuf));
3507
3508                 switch (ret) {
3509                 case IKS_NOMEM:
3510                         ast_log(LOG_WARNING, "Parsing failure: Out of memory.\n");
3511                         break;
3512                 case IKS_BADXML:
3513                         ast_log(LOG_WARNING, "Parsing failure: Invalid XML.\n");
3514                         break;
3515                 case IKS_HOOK:
3516                         ast_log(LOG_WARNING, "Parsing failure: Hook returned an error.\n");
3517                         break;
3518                 }
3519                 if (ret != IKS_OK) {
3520                         return ret;
3521                 }
3522                 ast_debug(3, "XML parsing successful\n");
3523         }
3524         return IKS_OK;
3525 }
3526
3527 /*! \brief XMPP client connection thread */
3528 static void *xmpp_client_thread(void *data)
3529 {
3530         struct ast_xmpp_client *client = data;
3531         int res = IKS_NET_RWERR;
3532
3533         do {
3534                 if (client->state == XMPP_STATE_DISCONNECTING) {
3535                         break;
3536                 }
3537
3538                 if (res == IKS_NET_RWERR || client->timeout == 0) {
3539                         ast_debug(3, "Connecting client '%s'\n", client->name);
3540                         if ((res = xmpp_client_reconnect(client)) != IKS_OK) {
3541                                 sleep(4);
3542                                 res = IKS_NET_RWERR;
3543                         }
3544                         continue;
3545                 }
3546
3547                 res = xmpp_client_receive(client, 1);
3548
3549                 /* Decrease timeout if no data received, and delete
3550                  * old messages globally */
3551                 if (res == IKS_NET_EXPIRED) {
3552                         client->timeout--;
3553                 }
3554
3555                 if (res == IKS_HOOK) {
3556                         ast_debug(2, "JABBER: Got hook event.\n");
3557                 } else if (res == IKS_NET_TLSFAIL) {
3558                         ast_log(LOG_ERROR, "JABBER:  Failure in TLS.\n");
3559                 } else if (!client->timeout && client->state == XMPP_STATE_CONNECTED) {
3560                         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
3561                         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
3562
3563                         if (cfg && cfg->clients && (clientcfg = xmpp_config_find(cfg->clients, client->name))) {
3564                                 res = ast_test_flag(&clientcfg->flags, XMPP_KEEPALIVE) ? xmpp_client_send_raw_message(client, " ") : IKS_OK;
3565                         } else {
3566                                 res = IKS_OK;
3567                         }
3568
3569                         if (res == IKS_OK) {
3570                                 client->timeout = 50;
3571                         } else {
3572                                 ast_log(LOG_WARNING, "JABBER: Network Timeout\n");
3573                         }
3574                 } else if (res == IKS_NET_RWERR) {
3575                         ast_log(LOG_WARNING, "JABBER: socket read error\n");
3576                 }
3577
3578         } while (1);
3579
3580         return NULL;
3581 }
3582
3583 static int xmpp_client_config_merge_buddies(void *obj, void *arg, int flags)
3584 {
3585         struct ast_xmpp_buddy *buddy1 = obj, *buddy2;
3586         struct ao2_container *buddies = arg;
3587
3588         /* If the buddy does not already exist link it into the client buddies container */
3589         if (!(buddy2 = ao2_find(buddies, buddy1->id, OBJ_KEY))) {
3590                 ao2_link(buddies, buddy1);
3591         } else {
3592                 ao2_ref(buddy2, -1);
3593         }
3594
3595         /* All buddies are unlinked from the configuration buddies container, always */
3596         return 1;
3597 }
3598
3599 static int xmpp_client_config_post_apply(void *obj, void *arg, int flags)
3600 {
3601         struct ast_xmpp_client_config *cfg = obj;
3602
3603         /* Merge buddies as need be */
3604         ao2_callback(cfg->buddies, OBJ_MULTIPLE | OBJ_UNLINK, xmpp_client_config_merge_buddies, cfg->client->buddies);
3605
3606         if (cfg->client->reconnect) {
3607                 /* Disconnect the existing session since our role is changing, or we are starting up */
3608                 ast_xmpp_client_disconnect(cfg->client);
3609
3610                 if (!(cfg->client->parser = iks_stream_new(ast_test_flag(&cfg->flags, XMPP_COMPONENT) ? "jabber:component:accept" : "jabber:client", cfg->client,
3611                                                            xmpp_action_hook))) {
3612                         ast_log(LOG_ERROR, "Iksemel stream could not be created for client '%s' - client not active\n", cfg->name);
3613                         return -1;
3614                 }
3615
3616                 iks_set_log_hook(cfg->client->parser, xmpp_log_hook);
3617
3618                 /* Create a JID based on the given user, if no resource is given use the default */
3619                 if (!strchr(cfg->user, '/') && !ast_test_flag(&cfg->flags, XMPP_COMPONENT)) {
3620                         char resource[strlen(cfg->user) + strlen("/asterisk-xmpp") + 1];
3621
3622                         snprintf(resource, sizeof(resource), "%s/asterisk-xmpp", cfg->user);
3623                         cfg->client->jid = iks_id_new(cfg->client->stack, resource);
3624                 } else {
3625                         cfg->client->jid = iks_id_new(cfg->client->stack, cfg->user);
3626                 }
3627
3628                 if (!cfg->client->jid) {
3629                         ast_log(LOG_ERROR, "Jabber identity could not be created for client '%s' - client not active\n", cfg->name);
3630                         return -1;
3631                 }
3632
3633                 ast_pthread_create_background(&cfg->client->thread, NULL, xmpp_client_thread, cfg->client);
3634
3635                 cfg->client->reconnect = 0;
3636         } else if (cfg->client->state == XMPP_STATE_CONNECTED) {
3637                 /* If this client is connected update their presence status since it may have changed */
3638                 xmpp_client_set_presence(cfg->client, NULL, cfg->client->jid->full, cfg->status, cfg->statusmsg);
3639
3640                 /* Subscribe to the status of any newly added buddies */
3641                 if (ast_test_flag(&cfg->flags, XMPP_AUTOREGISTER)) {
3642                         ao2_callback(cfg->client->buddies, OBJ_NODATA | OBJ_MULTIPLE, xmpp_client_subscribe_user, cfg->client);
3643                 }
3644         }
3645
3646         return 0;
3647 }
3648
3649 /*!
3650  * \internal
3651  * \brief  Send a Jabber Message via call from the Manager
3652  * \param s mansession Manager session
3653  * \param m message Message to send
3654  * \return  0
3655  */
3656 static int manager_jabber_send(struct mansession *s, const struct message *m)
3657 {
3658         RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
3659         RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
3660         const char *id = astman_get_header(m, "ActionID");
3661         const char *jabber = astman_get_header(m, "Jabber");
3662         const char *screenname = astman_get_header(m, "ScreenName");
3663         const char *message = astman_get_header(m, "Message");
3664
3665         if (ast_strlen_zero(jabber)) {
3666                 astman_send_error(s, m, "No transport specified");
3667                 return 0;
3668         }
3669         if (ast_strlen_zero(screenname)) {
3670                 astman_send_error(s, m, "No ScreenName specified");
3671                 return 0;
3672         }
3673         if (ast_strlen_zero(message)) {
3674                 astman_send_error(s, m, "No Message specified");
3675                 return 0;
3676         }
3677
3678         astman_send_ack(s, m, "Attempting to send Jabber Message");
3679
3680         if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, jabber))) {
3681                 astman_send_error(s, m, "Could not find Sender");
3682                 return 0;
3683         }
3684
3685         if (strchr(screenname, '@') && !ast_xmpp_client_send_message(clientcfg->client, screenname, message)) {
3686                 astman_append(s, "Response: Success\r\n");
3687         } else {
3688                 astman_append(s, "Response: Error\r\n");
3689         }
3690
3691         if (!ast_strlen_zero(id)) {
3692                 astman_append(s, "ActionID: %s\r\n", id);
3693         }
3694
3695         astman_append(s, "\r\n");
3696
3697         return 0;
3698 }
3699
3700 /*!
3701  * \brief Build the a node request
3702  * \param client the configured XMPP client we use to connect to a XMPP server
3703  * \param collection name of the collection for request
3704  * \return iks*
3705  */
3706 static iks* xmpp_pubsub_build_node_request(struct ast_xmpp_client *client, const char *collection)
3707 {
3708         iks *request = xmpp_pubsub_iq_create(client, "get"), *query;
3709
3710         if (!request) {
3711                 return NULL;
3712         }
3713
3714         query = iks_insert(request, "query");
3715         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
3716
3717         if (collection) {
3718                 iks_insert_attrib(query, "node", collection);
3719         }
3720
3721         return request;
3722 }
3723
3724 /*!
3725  * \brief Receive pubsub item lists
3726  * \param data pointer to ast_xmpp_client structure
3727  * \param pak response from pubsub diso#items query
3728  * \return IKS_FILTER_EAT
3729  */
3730 static int xmpp_pubsub_receive_node_list(void *data, ikspak* pak)
3731 {
3732         struct ast_xmpp_client *client = data;
3733         iks *item = NULL;
3734
3735         if (iks_has_children(pak->query)) {
3736                 item = iks_first_tag(pak->query);
3737                 ast_verbose("Connection %s: %s\nNode name: %s\n", client->name, client->jid->partial,
3738                             iks_find_attrib(item, "node"));
3739                 while ((item = iks_next_tag(item))) {
3740                         ast_verbose("Node name: %s\n", iks_find_attrib(item, "node"));
3741                 }
3742         }
3743
3744         if (item) {
3745                 iks_delete(item);
3746         }
3747
3748
3749         return IKS_FILTER_EAT;
3750 }
3751
3752 /*!
3753 * \brief Request item list from pubsub
3754 * \param client the configured XMPP client we use to connect to a XMPP server
3755 * \param collection name of the collection for request
3756 * \return void
3757 */
3758 static void xmpp_pubsub_request_nodes(struct ast_xmpp_client *client, const char *collection)
3759 {
3760         iks *request = xmpp_pubsub_build_node_request(client, collection);
3761
3762         if (!request) {
3763                 ast_log(LOG_ERROR, "Could not request pubsub nodes on client '%s' - IQ could not be&nbs