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