Debian Codegraph @

res/res_xmpp.c

raw symbols SCIP
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 2012, Digium, Inc.
5 *
6 * Joshua Colp <[email protected]>
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 <[email protected]>
24 *
25 * Iksemel http://code.google.com/p/iksemel/
26 *
27 * A reference module for interfacting Asterisk directly as a client or component with
28 * an XMPP/Jabber compliant server.
29 *
30 * This module is based upon the original res_jabber as done by Matt O'Gorman.
31 *
32 */
33
34 /*! \li \ref res_xmpp.c uses the configuration file \ref xmpp.conf
35 * \addtogroup configuration_file Configuration Files
36 */
37
38 /*!
39 * \page xmpp.conf xmpp.conf
40 * \verbinclude xmpp.conf.sample
41 */
42
43 /*** MODULEINFO
44 <depend>iksemel</depend>
45 <use type="external">openssl</use>
46 <support_level>core</support_level>
47 ***/
48
49 #include "asterisk.h"
50
51 #include <ctype.h>
52 #include <iksemel.h>
53
54 #include "asterisk/xmpp.h"
55 #include "asterisk/module.h"
56 #include "asterisk/manager.h"
57 #include "asterisk/app.h"
58 #include "asterisk/mwi.h"
59 #include "asterisk/message.h"
60 #include "asterisk/manager.h"
61 #include "asterisk/cli.h"
62 #include "asterisk/config_options.h"
63 #include "asterisk/json.h"
64
65 /*** DOCUMENTATION
66 <application name="JabberSend" language="en_US" module="res_xmpp">
67 <since>
68 <version>12.0.0</version>
69 </since>
70 <synopsis>
71 Sends an XMPP message to a buddy.
72 </synopsis>
73 <syntax>
74 <parameter name="account" required="true">
75 <para>The local named account to listen on (specified in
76 xmpp.conf)</para>
77 </parameter>
78 <parameter name="jid" required="true">
79 <para>Jabber ID of the buddy to send the message to. It can be a
80 bare JID (username@domain) or a full JID (username@domain/resource).</para>
81 </parameter>
82 <parameter name="message" required="true">
83 <para>The message to send.</para>
84 </parameter>
85 </syntax>
86 <description>
87 <para>Sends the content of <replaceable>message</replaceable> as text message
88 from the given <replaceable>account</replaceable> to the buddy identified by
89 <replaceable>jid</replaceable></para>
90 <para>The example below sends "Hello world" to
91 <replaceable>[email protected]</replaceable> as an XMPP message from the account
92 <replaceable>asterisk</replaceable>, configured in xmpp.conf.</para>
93 <example title="Send 'Hello world' to Bob">
94 same => n,JabberSend(asterisk,[email protected],Hello world)
95 </example>
96 </description>
97 <see-also>
98 <ref type="function" module="res_xmpp">JABBER_STATUS</ref>
99 <ref type="function" module="res_xmpp">JABBER_RECEIVE</ref>
100 </see-also>
101 </application>
102 <function name="JABBER_RECEIVE" language="en_US" module="res_xmpp">
103 <since>
104 <version>12.0.0</version>
105 </since>
106 <synopsis>
107 Reads XMPP messages.
108 </synopsis>
109 <syntax>
110 <parameter name="account" required="true">
111 <para>The local named account to listen on (specified in
112 xmpp.conf)</para>
113 </parameter>
114 <parameter name="jid" required="true">
115 <para>Jabber ID of the buddy to receive message from. It can be a
116 bare JID (username@domain) or a full JID (username@domain/resource).</para>
117 </parameter>
118 <parameter name="timeout">
119 <para>In seconds, defaults to <literal>20</literal>.</para>
120 </parameter>
121 </syntax>
122 <description>
123 <para>Receives a text message on the given <replaceable>account</replaceable>
124 from the buddy identified by <replaceable>jid</replaceable> and returns the contents.</para>
125 <para>The example below returns an XMPP message sent from
126 <replaceable>[email protected]</replaceable> (or nothing in case of a time out), to
127 the <replaceable>asterisk</replaceable> XMPP account configured in xmpp.conf.</para>
128 <example title="Receive a message">
129 same => n,Set(msg=${JABBER_RECEIVE(asterisk,[email protected])})
130 </example>
131 </description>
132 <see-also>
133 <ref type="function" module="res_xmpp">JABBER_STATUS</ref>
134 <ref type="application" module="res_xmpp">JabberSend</ref>
135 </see-also>
136 </function>
137 <function name="JABBER_STATUS" language="en_US" module="res_xmpp">
138 <since>
139 <version>12.0.0</version>
140 </since>
141 <synopsis>
142 Retrieves a buddy's status.
143 </synopsis>
144 <syntax>
145 <parameter name="account" required="true">
146 <para>The local named account to listen on (specified in
147 xmpp.conf)</para>
148 </parameter>
149 <parameter name="jid" required="true">
150 <para>Jabber ID of the buddy to receive message from. It can be a
151 bare JID (username@domain) or a full JID (username@domain/resource).</para>
152 </parameter>
153 </syntax>
154 <description>
155 <para>Retrieves the numeric status associated with the buddy identified
156 by <replaceable>jid</replaceable>. The return value will be one of the
157 following.</para>
158 <enumlist>
159 <enum name="1">
160 <para>Online</para>
161 </enum>
162 <enum name="2">
163 <para>Chatty</para>
164 </enum>
165 <enum name="3">
166 <para>Away</para>
167 </enum>
168 <enum name="4">
169 <para>Extended Away</para>
170 </enum>
171 <enum name="5">
172 <para>Do Not Disturb</para>
173 </enum>
174 <enum name="6">
175 <para>Offline</para>
176 </enum>
177 <enum name="7">
178 <para>Not In Roster</para>
179 </enum>
180 </enumlist>
181 </description>
182 <see-also>
183 <ref type="function" module="res_xmpp">JABBER_RECEIVE</ref>
184 <ref type="application" module="res_xmpp">JabberSend</ref>
185 </see-also>
186 </function>
187 <application name="JabberSendGroup" language="en_US" module="res_xmpp">
188 <since>
189 <version>12.0.0</version>
190 </since>
191 <synopsis>
192 Send a Jabber Message to a specified 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="Message" required="true">
202 <para>Message to be sent to the chat room.</para>
203 </parameter>
204 <parameter name="Nickname" required="false">
205 <para>The nickname Asterisk uses in the chat room.</para>
206 </parameter>
207 </syntax>
208 <description>
209 <para>Allows user to send a message to a chat room via XMPP.</para>
210 <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>
211 </description>
212 </application>
213 <application name="JabberJoin" language="en_US" module="res_xmpp">
214 <since>
215 <version>12.0.0</version>
216 </since>
217 <synopsis>
218 Join a chat room
219 </synopsis>
220 <syntax>
221 <parameter name="Jabber" required="true">
222 <para>Client or transport Asterisk uses to connect to Jabber.</para>
223 </parameter>
224 <parameter name="RoomJID" required="true">
225 <para>XMPP/Jabber JID (Name) of chat room.</para>
226 </parameter>
227 <parameter name="Nickname" required="false">
228 <para>The nickname Asterisk will use in the chat room.</para>
229 <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>
230 </parameter>
231 </syntax>
232 <description>
233 <para>Allows Asterisk to join a chat room.</para>
234 </description>
235 </application>
236 <application name="JabberLeave" language="en_US" module="res_xmpp">
237 <since>
238 <version>12.0.0</version>
239 </since>
240 <synopsis>
241 Leave a chat room
242 </synopsis>
243 <syntax>
244 <parameter name="Jabber" required="true">
245 <para>Client or transport Asterisk uses to connect to Jabber.</para>
246 </parameter>
247 <parameter name="RoomJID" required="true">
248 <para>XMPP/Jabber JID (Name) of chat room.</para>
249 </parameter>
250 <parameter name="Nickname" required="false">
251 <para>The nickname Asterisk uses in the chat room.</para>
252 </parameter>
253 </syntax>
254 <description>
255 <para>Allows Asterisk to leave a chat room.</para>
256 </description>
257 </application>
258 <manager name="JabberSend" language="en_US" module="res_xmpp">
259 <since>
260 <version>1.4.0</version>
261 </since>
262 <synopsis>
263 Sends a message to a Jabber Client.
264 </synopsis>
265 <syntax>
266 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
267 <parameter name="Jabber" required="true">
268 <para>Client or transport Asterisk uses to connect to JABBER.</para>
269 </parameter>
270 <parameter name="JID" required="true">
271 <para>XMPP/Jabber JID (Name) of recipient.</para>
272 </parameter>
273 <parameter name="Message" required="true">
274 <para>Message to be sent to the buddy.</para>
275 </parameter>
276 </syntax>
277 <description>
278 <para>Sends a message to a Jabber Client.</para>
279 </description>
280 </manager>
281 <info name="MessageDestinationInfo" language="en_US" tech="XMPP">
282 <para>Specifying a prefix of <literal>xmpp:</literal> will send the
283 message as an XMPP chat message.</para>
284 </info>
285 <info name="MessageFromInfo" language="en_US" tech="XMPP">
286 <para>Specifying a prefix of <literal>xmpp:</literal> will specify the
287 account defined in <literal>xmpp.conf</literal> to send the message from.
288 Note that this field is required for XMPP messages.</para>
289 </info>
290 <info name="MessageToInfo" language="en_US" tech="XMPP">
291 <para>Ignored</para>
292 </info>
293 <configInfo name="res_xmpp" language="en_US">
294 <synopsis>XMPP Messaging</synopsis>
295 <configFile name="xmpp.conf">
296 <configObject name="global">
297 <since>
298 <version>12.0.0</version>
299 </since>
300 <synopsis>Global configuration settings</synopsis>
301 <configOption name="debug">
302 <since>
303 <version>11.0.0</version>
304 </since>
305 <synopsis>Enable/disable XMPP message debugging</synopsis>
306 </configOption>
307 <configOption name="autoprune">
308 <since>
309 <version>11.0.0</version>
310 </since>
311 <synopsis>Auto-remove users from buddy list.</synopsis>
312 <description><para>Auto-remove users from buddy list. Depending on the setup
313 (e.g., using your personal Gtalk account for a test) this could cause loss of
314 the contact list.
315 </para></description>
316 </configOption>
317 <configOption name="autoregister">
318 <since>
319 <version>11.0.0</version>
320 </since>
321 <synopsis>Auto-register users from buddy list</synopsis>
322 </configOption>
323 <configOption name="collection_nodes">
324 <since>
325 <version>11.0.0</version>
326 </since>
327 <synopsis>Enable support for XEP-0248 for use with distributed device state</synopsis>
328 </configOption>
329 <configOption name="pubsub_autocreate">
330 <since>
331 <version>11.0.0</version>
332 </since>
333 <synopsis>Whether or not the PubSub server supports/is using auto-create for nodes</synopsis>
334 </configOption>
335 <configOption name="auth_policy">
336 <since>
337 <version>11.0.0</version>
338 </since>
339 <synopsis>Whether to automatically accept or deny users' subscription requests</synopsis>
340 </configOption>
341 </configObject>
342 <configObject name="client">
343 <since>
344 <version>12.0.0</version>
345 </since>
346 <synopsis>Configuration options for an XMPP client</synopsis>
347 <configOption name="username">
348 <since>
349 <version>11.0.0</version>
350 </since>
351 <synopsis>XMPP username with optional resource</synopsis>
352 </configOption>
353 <configOption name="secret">
354 <since>
355 <version>11.0.0</version>
356 </since>
357 <synopsis>XMPP password</synopsis>
358 </configOption>
359 <configOption name="refresh_token">
360 <since>
361 <version>13.18.0</version>
362 <version>14.7.0</version>
363 <version>15.1.0</version>
364 </since>
365 <synopsis>Google OAuth 2.0 refresh token</synopsis>
366 </configOption>
367 <configOption name="oauth_clientid">
368 <since>
369 <version>13.18.0</version>
370 <version>14.7.0</version>
371 <version>15.1.0</version>
372 </since>
373 <synopsis>Google OAuth 2.0 application's client id</synopsis>
374 </configOption>
375 <configOption name="oauth_secret">
376 <since>
377 <version>13.18.0</version>
378 <version>14.7.0</version>
379 <version>15.1.0</version>
380 </since>
381 <synopsis>Google OAuth 2.0 application's secret</synopsis>
382 </configOption>
383 <configOption name="serverhost">
384 <since>
385 <version>11.0.0</version>
386 </since>
387 <synopsis>Route to server, e.g. talk.google.com</synopsis>
388 </configOption>
389 <configOption name="statusmessage">
390 <since>
391 <version>11.0.0</version>
392 </since>
393 <synopsis>Custom status message</synopsis>
394 </configOption>
395 <configOption name="pubsub_node">
396 <since>
397 <version>11.0.0</version>
398 </since>
399 <synopsis>Node for publishing events via PubSub</synopsis>
400 </configOption>
401 <configOption name="context">
402 <since>
403 <version>11.0.0</version>
404 </since>
405 <synopsis>Dialplan context to send incoming messages to</synopsis>
406 </configOption>
407 <configOption name="priority">
408 <since>
409 <version>11.0.0</version>
410 </since>
411 <synopsis>XMPP resource priority</synopsis>
412 </configOption>
413 <configOption name="port">
414 <since>
415 <version>11.0.0</version>
416 </since>
417 <synopsis>XMPP server port</synopsis>
418 </configOption>
419 <configOption name="timeout">
420 <since>
421 <version>11.0.0</version>
422 </since>
423 <synopsis>Timeout in seconds to hold incoming messages</synopsis>
424 <description><para>Timeout (in seconds) on the message stack. Messages stored longer
425 than this value will be deleted by Asterisk. This option applies to incoming messages only
426 which are intended to be processed by the <literal>JABBER_RECEIVE</literal> dialplan function.
427 </para></description>
428 </configOption>
429 <configOption name="debug">
430 <since>
431 <version>11.0.0</version>
432 </since>
433 <synopsis>Enable debugging</synopsis>
434 </configOption>
435 <configOption name="type">
436 <since>
437 <version>11.0.0</version>
438 </since>
439 <synopsis>Connection is either a client or a component</synopsis>
440 </configOption>
441 <configOption name="distribute_events">
442 <since>
443 <version>11.0.0</version>
444 </since>
445 <synopsis>Whether or not to distribute events using this connection</synopsis>
446 </configOption>
447 <configOption name="usetls">
448 <since>
449 <version>11.0.0</version>
450 </since>
451 <synopsis>Whether to use TLS for the connection or not</synopsis>
452 </configOption>
453 <configOption name="usesasl">
454 <since>
455 <version>11.0.0</version>
456 </since>
457 <synopsis>Whether to use SASL for the connection or not</synopsis>
458 </configOption>
459 <configOption name="forceoldssl">
460 <since>
461 <version>11.0.0</version>
462 </since>
463 <synopsis>Force the use of old-style SSL for the connection</synopsis>
464 </configOption>
465 <configOption name="keepalive">
466 <since>
467 <version>11.0.0</version>
468 </since>
469 <synopsis>If enabled, periodically send an XMPP message from this client with an empty message</synopsis>
470 </configOption>
471 <configOption name="autoprune">
472 <since>
473 <version>11.18.0</version>
474 <version>13.4.0</version>
475 </since>
476 <synopsis>Auto-remove users from buddy list.</synopsis>
477 <description><para>Auto-remove users from buddy list. Depending on the setup
478 (e.g., using your personal Gtalk account for a test) this could cause loss of
479 the contact list.
480 </para></description>
481 </configOption>
482 <configOption name="autoregister">
483 <since>
484 <version>11.18.0</version>
485 <version>13.4.0</version>
486 </since>
487 <synopsis>Auto-register users bfrom buddy list</synopsis>
488 </configOption>
489 <configOption name="auth_policy">
490 <since>
491 <version>11.18.0</version>
492 <version>13.4.0</version>
493 </since>
494 <synopsis>Whether to automatically accept or deny users' subscription requests</synopsis>
495 </configOption>
496 <configOption name="sendtodialplan">
497 <since>
498 <version>11.0.0</version>
499 </since>
500 <synopsis>Send incoming messages into the dialplan</synopsis>
501 </configOption>
502 <configOption name="status">
503 <since>
504 <version>11.0.0</version>
505 </since>
506 <synopsis>Default XMPP status for the client</synopsis>
507 <description><para>Can be one of the following XMPP statuses:</para>
508 <enumlist>
509 <enum name="chat"/>
510 <enum name="available"/>
511 <enum name="away"/>
512 <enum name="xaway"/>
513 <enum name="dnd"/>
514 </enumlist>
515 </description>
516 </configOption>
517 <configOption name="buddy">
518 <since>
519 <version>11.0.0</version>
520 </since>
521 <synopsis>Manual addition of buddy to list</synopsis>
522 <description><para>
523 Manual addition of buddy to the buddy list. For distributed events, these buddies are
524 automatically added in the whitelist as 'owners' of the node(s).
525 </para></description>
526 </configOption>
527 </configObject>
528 </configFile>
529 </configInfo>
530 ***/
531
532 /*! \brief Supported general configuration flags */
533 enum {
534 XMPP_AUTOPRUNE = (1 << 0),
535 XMPP_AUTOREGISTER = (1 << 1),
536 XMPP_AUTOACCEPT = (1 << 2),
537 XMPP_DEBUG = (1 << 3),
538 XMPP_USETLS = (1 << 4),
539 XMPP_USESASL = (1 << 5),
540 XMPP_FORCESSL = (1 << 6),
541 XMPP_KEEPALIVE = (1 << 7),
542 XMPP_COMPONENT = (1 << 8),
543 XMPP_SEND_TO_DIALPLAN = (1 << 9),
544 XMPP_DISTRIBUTE_EVENTS = (1 << 10),
545 };
546
547 /*! \brief Supported pubsub configuration flags */
548 enum {
549 XMPP_XEP0248 = (1 << 0),
550 XMPP_PUBSUB = (1 << 1),
551 XMPP_PUBSUB_AUTOCREATE = (1 << 2),
552 };
553
554 /*! \brief Number of buckets for client connections */
555 #define CLIENT_BUCKETS 53
556
557 /*! \brief Number of buckets for buddies (per client) */
558 #define BUDDY_BUCKETS 53
559
560 /*! \brief Number of buckets for resources (per buddy) */
561 #define RESOURCE_BUCKETS 53
562
563 /*! \brief Namespace for TLS support */
564 #define XMPP_TLS_NS "urn:ietf:params:xml:ns:xmpp-tls"
565
566 /*! \brief Status for a disappearing buddy */
567 #define STATUS_DISAPPEAR 6
568
569 /*! \brief Global debug status */
570 static int debug;
571
572 /*! \brief XMPP Global Configuration */
573 struct ast_xmpp_global_config {
574 struct ast_flags general; /*!< General configuration options */
575 struct ast_flags pubsub; /*!< Pubsub related configuration options */
576 };
577
578 /*! \brief XMPP Client Configuration */
579 struct ast_xmpp_client_config {
580 AST_DECLARE_STRING_FIELDS(
581 AST_STRING_FIELD(name); /*!< Name of the client connection */
582 AST_STRING_FIELD(user); /*!< Username to use for authentication */
583 AST_STRING_FIELD(password); /*!< Password to use for authentication */
584 AST_STRING_FIELD(refresh_token); /*!< Refresh token to use for OAuth authentication */
585 AST_STRING_FIELD(oauth_clientid); /*!< Client ID to use for OAuth authentication */
586 AST_STRING_FIELD(oauth_secret); /*!< Secret to use for OAuth authentication */
587 AST_STRING_FIELD(server); /*!< Server hostname */
588 AST_STRING_FIELD(statusmsg); /*!< Status message for presence */
589 AST_STRING_FIELD(pubsubnode); /*!< Pubsub node */
590 AST_STRING_FIELD(context); /*!< Context for incoming messages */
591 );
592 int port; /*!< Port to use when connecting to server */
593 int message_timeout; /*!< Timeout for messages */
594 int priority; /*!< Resource priority */
595 struct ast_flags flags; /*!< Various options that have been set */
596 struct ast_flags mod_flags; /*!< Global options that have been modified */
597 enum ikshowtype status; /*!< Presence status */
598 struct ast_xmpp_client *client; /*!< Pointer to the client */
599 struct ao2_container *buddies; /*!< Configured buddies */
600 };
601
602 struct xmpp_config {
603 struct ast_xmpp_global_config *global; /*!< Global configuration options */
604 struct ao2_container *clients; /*!< Configured clients */
605 };
606
607 static AO2_GLOBAL_OBJ_STATIC(globals);
608
609 static int xmpp_client_request_tls(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node);
610 static int xmpp_client_requested_tls(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node);
611 static int xmpp_client_authenticate(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node);
612 static int xmpp_client_authenticating(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node);
613
614 static int xmpp_component_authenticate(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node);
615 static int xmpp_component_authenticating(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node);
616
617 /*! \brief Defined handlers for XMPP client states */
618 static const struct xmpp_state_handler {
619 int state;
620 int component;
621 int (*handler)(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node);
622 } xmpp_state_handlers[] = {
623 { XMPP_STATE_REQUEST_TLS, 0, xmpp_client_request_tls, },
624 { XMPP_STATE_REQUESTED_TLS, 0, xmpp_client_requested_tls, },
625 { XMPP_STATE_AUTHENTICATE, 0, xmpp_client_authenticate, },
626 { XMPP_STATE_AUTHENTICATING, 0, xmpp_client_authenticating, },
627 { XMPP_STATE_AUTHENTICATE, 1, xmpp_component_authenticate, },
628 { XMPP_STATE_AUTHENTICATING, 1, xmpp_component_authenticating, },
629 };
630
631 static int xmpp_pak_message(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, iks *node, ikspak *pak);
632 static int xmpp_pak_presence(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, iks *node, ikspak *pak);
633 static int xmpp_pak_s10n(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, iks *node, ikspak *pak);
634
635 /*! \brief Defined handlers for different PAK types */
636 static const struct xmpp_pak_handler {
637 int type;
638 int (*handler)(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, iks *node, ikspak *pak);
639 } xmpp_pak_handlers[] = {
640 { IKS_PAK_MESSAGE, xmpp_pak_message, },
641 { IKS_PAK_PRESENCE, xmpp_pak_presence, },
642 { IKS_PAK_S10N, xmpp_pak_s10n, },
643 };
644
645 static const char *app_ajisend = "JabberSend";
646 static const char *app_ajisendgroup = "JabberSendGroup";
647 static const char *app_ajistatus = "JabberStatus";
648 static const char *app_ajijoin = "JabberJoin";
649 static const char *app_ajileave = "JabberLeave";
650
651 static ast_cond_t message_received_condition;
652 static ast_mutex_t messagelock;
653
654 static int xmpp_client_config_post_apply(void *obj, void *arg, int flags);
655 static int fetch_access_token(struct ast_xmpp_client_config *cfg);
656
657 /*! \brief Destructor function for configuration */
658 static void ast_xmpp_client_config_destructor(void *obj)
659 {
660 struct ast_xmpp_client_config *cfg = obj;
661 ast_string_field_free_memory(cfg);
662 ao2_cleanup(cfg->client);
663 ao2_cleanup(cfg->buddies);
664 }
665
666 /*! \brief Destroy function for XMPP messages */
667 static void xmpp_message_destroy(struct ast_xmpp_message *message)
668 {
669 if (message->from) {
670 ast_free(message->from);
671 }
672 if (message->message) {
673 ast_free(message->message);
674 }
675
676 ast_free(message);
677 }
678
679 /*! \brief Destructor callback function for XMPP client */
680 static void xmpp_client_destructor(void *obj)
681 {
682 struct ast_xmpp_client *client = obj;
683 struct ast_xmpp_message *message;
684
685 ast_xmpp_client_disconnect(client);
686
687 ast_endpoint_shutdown(client->endpoint);
688 client->endpoint = NULL;
689
690 if (client->filter) {
691 iks_filter_delete(client->filter);
692 }
693
694 if (client->stack) {
695 iks_stack_delete(client->stack);
696 }
697
698 ao2_cleanup(client->buddies);
699
700 while ((message = AST_LIST_REMOVE_HEAD(&client->messages, list))) {
701 xmpp_message_destroy(message);
702 }
703 AST_LIST_HEAD_DESTROY(&client->messages);
704 }
705
706 /*! \brief Hashing function for XMPP buddy */
707 static int xmpp_buddy_hash(const void *obj, const int flags)
708 {
709 const struct ast_xmpp_buddy *buddy = obj;
710 const char *id = obj;
711
712 return ast_str_hash(flags & OBJ_KEY ? id : buddy->id);
713 }
714
715 /*! \brief Comparator function for XMPP buddy */
716 static int xmpp_buddy_cmp(void *obj, void *arg, int flags)
717 {
718 struct ast_xmpp_buddy *buddy1 = obj, *buddy2 = arg;
719 const char *id = arg;
720
721 return !strcmp(buddy1->id, flags & OBJ_KEY ? id : buddy2->id) ? CMP_MATCH | CMP_STOP : 0;
722 }
723
724 /*! \brief Internal function which changes the XMPP client state */
725 static void xmpp_client_change_state(struct ast_xmpp_client *client, int state)
726 {
727 if (state == client->state) {
728 return;
729 }
730 client->state = state;
731 if (client->state == XMPP_STATE_DISCONNECTED) {
732 ast_endpoint_set_state(client->endpoint, AST_ENDPOINT_OFFLINE);
733 } else if (client->state == XMPP_STATE_CONNECTED) {
734 ast_endpoint_set_state(client->endpoint, AST_ENDPOINT_ONLINE);
735 }
736 }
737
738 /*! \brief Allocator function for ast_xmpp_client */
739 static struct ast_xmpp_client *xmpp_client_alloc(const char *name)
740 {
741 struct ast_xmpp_client *client;
742
743 if (!(client = ao2_alloc(sizeof(*client), xmpp_client_destructor))) {
744 return NULL;
745 }
746
747 AST_LIST_HEAD_INIT(&client->messages);
748 client->thread = AST_PTHREADT_NULL;
749
750 client->endpoint = ast_endpoint_create("XMPP", name);
751 if (!client->endpoint) {
752 ao2_ref(client, -1);
753 return NULL;
754 }
755
756 client->buddies = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, BUDDY_BUCKETS,
757 xmpp_buddy_hash, NULL, xmpp_buddy_cmp);
758 if (!client->buddies) {
759 ast_log(LOG_ERROR, "Could not initialize buddy container for '%s'\n", name);
760 ao2_ref(client, -1);
761 return NULL;
762 }
763
764 if (ast_string_field_init(client, 512)) {
765 ast_log(LOG_ERROR, "Could not initialize stringfields for '%s'\n", name);
766 ao2_ref(client, -1);
767 return NULL;
768 }
769
770 if (!(client->stack = iks_stack_new(8192, 8192))) {
771 ast_log(LOG_ERROR, "Could not create an Iksemel stack for '%s'\n", name);
772 ao2_ref(client, -1);
773 return NULL;
774 }
775
776 ast_string_field_set(client, name, name);
777
778 client->timeout = 50;
779 xmpp_client_change_state(client, XMPP_STATE_DISCONNECTED);
780 ast_copy_string(client->mid, "aaaaa", sizeof(client->mid));
781
782 return client;
783 }
784
785 /*! \brief Find function for configuration */
786 static void *xmpp_config_find(struct ao2_container *tmp_container, const char *category)
787 {
788 return ao2_find(tmp_container, category, OBJ_KEY);
789 }
790
791 /*! \brief Look up existing client or create a new one */
792 static void *xmpp_client_find_or_create(const char *category)
793 {
794 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
795 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
796
797 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, category))) {
798 return xmpp_client_alloc(category);
799 }
800
801 ao2_ref(clientcfg->client, +1);
802 return clientcfg->client;
803 }
804
805 /*! \brief Allocator function for configuration */
806 static void *ast_xmpp_client_config_alloc(const char *cat)
807 {
808 struct ast_xmpp_client_config *cfg;
809
810 if (!(cfg = ao2_alloc(sizeof(*cfg), ast_xmpp_client_config_destructor))) {
811 return NULL;
812 }
813
814 if (ast_string_field_init(cfg, 512)) {
815 ao2_ref(cfg, -1);
816 return NULL;
817 }
818
819 if (!(cfg->client = xmpp_client_find_or_create(cat))) {
820 ao2_ref(cfg, -1);
821 return NULL;
822 }
823
824 cfg->buddies = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, BUDDY_BUCKETS,
825 xmpp_buddy_hash, NULL, xmpp_buddy_cmp);
826 if (!cfg->buddies) {
827 ao2_ref(cfg, -1);
828 return NULL;
829 }
830
831 ast_string_field_set(cfg, name, cat);
832
833 return cfg;
834 }
835
836 /*! \brief Destructor for XMPP configuration */
837 static void xmpp_config_destructor(void *obj)
838 {
839 struct xmpp_config *cfg = obj;
840 ao2_cleanup(cfg->global);
841 ao2_cleanup(cfg->clients);
842 }
843
844 /*! \brief Comparator function for configuration */
845 static int xmpp_config_cmp(void *obj, void *arg, int flags)
846 {
847 struct ast_xmpp_client_config *one = obj, *two = arg;
848 const char *match = (flags & OBJ_KEY) ? arg : two->name;
849 return strcasecmp(one->name, match) ? 0 : (CMP_MATCH | CMP_STOP);
850 }
851
852 /*! \brief Allocator for XMPP configuration */
853 static void *xmpp_config_alloc(void)
854 {
855 struct xmpp_config *cfg;
856
857 if (!(cfg = ao2_alloc(sizeof(*cfg), xmpp_config_destructor))) {
858 return NULL;
859 }
860
861 if (!(cfg->global = ao2_alloc(sizeof(*cfg->global), NULL))) {
862 goto error;
863 }
864
865 cfg->clients = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
866 NULL, xmpp_config_cmp);
867 if (!cfg->clients) {
868 goto error;
869 }
870
871 return cfg;
872 error:
873 ao2_ref(cfg, -1);
874 return NULL;
875 }
876
877 static int xmpp_config_prelink(void *newitem)
878 {
879 struct ast_xmpp_client_config *clientcfg = newitem;
880 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
881 RAII_VAR(struct ast_xmpp_client_config *, oldclientcfg, NULL, ao2_cleanup);
882
883 if (ast_strlen_zero(clientcfg->user)) {
884 ast_log(LOG_ERROR, "No user specified on client '%s'\n", clientcfg->name);
885 return -1;
886 } else if (ast_strlen_zero(clientcfg->password) && ast_strlen_zero(clientcfg->refresh_token)) {
887 ast_log(LOG_ERROR, "No password or refresh_token specified on client '%s'\n", clientcfg->name);
888 return -1;
889 } else if (ast_strlen_zero(clientcfg->server)) {
890 ast_log(LOG_ERROR, "No server specified on client '%s'\n", clientcfg->name);
891 return -1;
892 } else if (!ast_strlen_zero(clientcfg->refresh_token) &&
893 (ast_strlen_zero(clientcfg->oauth_clientid) || ast_strlen_zero(clientcfg->oauth_secret))) {
894 ast_log(LOG_ERROR, "No oauth_clientid or oauth_secret specified, so client '%s' can't be used\n", clientcfg->name);
895 return -1;
896 }
897
898 /* If this is a new connection force a reconnect */
899 if (!cfg || !cfg->clients || !(oldclientcfg = xmpp_config_find(cfg->clients, clientcfg->name))) {
900 clientcfg->client->reconnect = 1;
901 return 0;
902 }
903
904 /* If any configuration options are changing that would require reconnecting set the bit so we will do so if possible */
905 if (strcmp(clientcfg->user, oldclientcfg->user) ||
906 strcmp(clientcfg->password, oldclientcfg->password) ||
907 strcmp(clientcfg->refresh_token, oldclientcfg->refresh_token) ||
908 strcmp(clientcfg->oauth_clientid, oldclientcfg->oauth_clientid) ||
909 strcmp(clientcfg->oauth_secret, oldclientcfg->oauth_secret) ||
910 strcmp(clientcfg->server, oldclientcfg->server) ||
911 (clientcfg->port != oldclientcfg->port) ||
912 (ast_test_flag(&clientcfg->flags, XMPP_COMPONENT) != ast_test_flag(&oldclientcfg->flags, XMPP_COMPONENT)) ||
913 (clientcfg->priority != oldclientcfg->priority)) {
914 clientcfg->client->reconnect = 1;
915 } else {
916 clientcfg->client->reconnect = 0;
917 }
918
919 return 0;
920 }
921
922 static void xmpp_config_post_apply(void)
923 {
924 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
925
926 ao2_callback(cfg->clients, OBJ_NODATA | OBJ_MULTIPLE, xmpp_client_config_post_apply, NULL);
927 }
928
929 static struct aco_type global_option = {
930 .type = ACO_GLOBAL,
931 .name = "global",
932 .item_offset = offsetof(struct xmpp_config, global),
933 .category_match = ACO_WHITELIST_EXACT,
934 .category = "general",
935 };
936
937 struct aco_type *global_options[] = ACO_TYPES(&global_option);
938
939 static struct aco_type client_option = {
940 .type = ACO_ITEM,
941 .name = "client",
942 .category_match = ACO_BLACKLIST_EXACT,
943 .category = "general",
944 .item_alloc = ast_xmpp_client_config_alloc,
945 .item_find = xmpp_config_find,
946 .item_prelink = xmpp_config_prelink,
947 .item_offset = offsetof(struct xmpp_config, clients),
948 };
949
950 struct aco_type *client_options[] = ACO_TYPES(&client_option);
951
952 struct aco_file res_xmpp_conf = {
953 .filename = "xmpp.conf",
954 .alias = "jabber.conf",
955 .types = ACO_TYPES(&global_option, &client_option),
956 };
957
958 CONFIG_INFO_STANDARD(cfg_info, globals, xmpp_config_alloc,
959 .files = ACO_FILES(&res_xmpp_conf),
960 .post_apply_config = xmpp_config_post_apply,
961 );
962
963 /*! \brief Destructor callback function for XMPP resource */
964 static void xmpp_resource_destructor(void *obj)
965 {
966 struct ast_xmpp_resource *resource = obj;
967
968 if (resource->description) {
969 ast_free(resource->description);
970 }
971 }
972
973 /*! \brief Hashing function for XMPP resource */
974 static int xmpp_resource_hash(const void *obj, const int flags)
975 {
976 const struct ast_xmpp_resource *resource = obj;
977
978 return flags & OBJ_KEY ? -1 : resource->priority;
979 }
980
981 /*! \brief Comparator function for XMPP resource */
982 static int xmpp_resource_cmp(void *obj, void *arg, int flags)
983 {
984 struct ast_xmpp_resource *resource1 = obj;
985 const char *resource = arg;
986
987 return !strcmp(resource1->resource, resource) ? CMP_MATCH | CMP_STOP : 0;
988 }
989
990 /*! \brief Destructor callback function for XMPP buddy */
991 static void xmpp_buddy_destructor(void *obj)
992 {
993 struct ast_xmpp_buddy *buddy = obj;
994
995 if (buddy->resources) {
996 ao2_ref(buddy->resources, -1);
997 }
998 }
999
1000 /*! \brief Helper function which returns whether an XMPP client connection is secure or not */
1001 static int xmpp_is_secure(struct ast_xmpp_client *client)
1002 {
1003 #ifdef HAVE_OPENSSL
1004 return client->stream_flags & SECURE;
1005 #else
1006 return 0;
1007 #endif
1008 }
1009
1010 struct ast_xmpp_client *ast_xmpp_client_find(const char *name)
1011 {
1012 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1013 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
1014
1015 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, name))) {
1016 return NULL;
1017 }
1018
1019 ao2_ref(clientcfg->client, +1);
1020 return clientcfg->client;
1021 }
1022
1023 void ast_xmpp_client_unref(struct ast_xmpp_client *client)
1024 {
1025 ao2_ref(client, -1);
1026 }
1027
1028 void ast_xmpp_client_lock(struct ast_xmpp_client *client)
1029 {
1030 ao2_lock(client);
1031 }
1032
1033 void ast_xmpp_client_unlock(struct ast_xmpp_client *client)
1034 {
1035 ao2_unlock(client);
1036 }
1037
1038 /*! \brief Internal function used to send a message to a user or chatroom */
1039 static int xmpp_client_send_message(struct ast_xmpp_client *client, int group, const char *nick, const char *address, const char *message)
1040 {
1041 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1042 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
1043 int res = 0;
1044 char from[XMPP_MAX_JIDLEN];
1045 iks *message_packet;
1046
1047 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name)) ||
1048 !(message_packet = iks_make_msg(group ? IKS_TYPE_GROUPCHAT : IKS_TYPE_CHAT, address, message))) {
1049 return -1;
1050 }
1051
1052 if (!ast_strlen_zero(nick) && ast_test_flag(&clientcfg->flags, XMPP_COMPONENT)) {
1053 snprintf(from, sizeof(from), "%s@%s/%s", nick, client->jid->full, nick);
1054 } else {
1055 snprintf(from, sizeof(from), "%s", client->jid->full);
1056 }
1057
1058 iks_insert_attrib(message_packet, "from", from);
1059
1060 res = ast_xmpp_client_send(client, message_packet);
1061
1062 iks_delete(message_packet);
1063
1064 return res;
1065 }
1066
1067 int ast_xmpp_client_send_message(struct ast_xmpp_client *client, const char *user, const char *message)
1068 {
1069 return xmpp_client_send_message(client, 0, NULL, user, message);
1070 }
1071
1072 int ast_xmpp_chatroom_invite(struct ast_xmpp_client *client, const char *user, const char *room, const char *message)
1073 {
1074 int res = 0;
1075 iks *invite, *body = NULL, *namespace = NULL;
1076
1077 if (!(invite = iks_new("message")) || !(body = iks_new("body")) || !(namespace = iks_new("x"))) {
1078 res = -1;
1079 goto done;
1080 }
1081
1082 iks_insert_attrib(invite, "to", user);
1083 ast_xmpp_client_lock(client);
1084 iks_insert_attrib(invite, "id", client->mid);
1085 ast_xmpp_increment_mid(client->mid);
1086 ast_xmpp_client_unlock(client);
1087 iks_insert_cdata(body, message, 0);
1088 iks_insert_node(invite, body);
1089 iks_insert_attrib(namespace, "xmlns", "jabber:x:conference");
1090 iks_insert_attrib(namespace, "jid", room);
1091 iks_insert_node(invite, namespace);
1092
1093 res = ast_xmpp_client_send(client, invite);
1094
1095 done:
1096 iks_delete(namespace);
1097 iks_delete(body);
1098 iks_delete(invite);
1099
1100 return res;
1101 }
1102
1103 static int xmpp_client_set_group_presence(struct ast_xmpp_client *client, const char *room, int level, const char *nick)
1104 {
1105 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1106 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
1107 int res = 0;
1108 iks *presence = NULL, *x = NULL;
1109 char from[XMPP_MAX_JIDLEN], roomid[XMPP_MAX_JIDLEN];
1110
1111 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name)) ||
1112 !(presence = iks_make_pres(level, NULL)) || !(x = iks_new("x"))) {
1113 res = -1;
1114 goto done;
1115 }
1116
1117 if (ast_test_flag(&clientcfg->flags, XMPP_COMPONENT)) {
1118 snprintf(from, sizeof(from), "%s@%s/%s", nick, client->jid->full, nick);
1119 snprintf(roomid, sizeof(roomid), "%s/%s", room, nick);
1120 } else {
1121 snprintf(from, sizeof(from), "%s", client->jid->full);
1122 snprintf(roomid, sizeof(roomid), "%s/%s", room, S_OR(nick, client->jid->user));
1123 }
1124
1125 iks_insert_attrib(presence, "to", roomid);
1126 iks_insert_attrib(presence, "from", from);
1127 iks_insert_attrib(x, "xmlns", "http://jabber.org/protocol/muc");
1128 iks_insert_node(presence, x);
1129
1130 res = ast_xmpp_client_send(client, presence);
1131
1132 done:
1133 iks_delete(x);
1134 iks_delete(presence);
1135
1136 return res;
1137 }
1138
1139 int ast_xmpp_chatroom_join(struct ast_xmpp_client *client, const char *room, const char *nickname)
1140 {
1141 return xmpp_client_set_group_presence(client, room, IKS_SHOW_AVAILABLE, nickname);
1142 }
1143
1144 int ast_xmpp_chatroom_send(struct ast_xmpp_client *client, const char *nickname, const char *address, const char *message)
1145 {
1146 return xmpp_client_send_message(client, 1, nickname, address, message);
1147 }
1148
1149 int ast_xmpp_chatroom_leave(struct ast_xmpp_client *client, const char *room, const char *nickname)
1150 {
1151 return xmpp_client_set_group_presence(client, room, IKS_SHOW_UNAVAILABLE, nickname);
1152 }
1153
1154 void ast_xmpp_increment_mid(char *mid)
1155 {
1156 int i = 0;
1157
1158 for (i = strlen(mid) - 1; i >= 0; i--) {
1159 if (mid[i] != 'z') {
1160 mid[i] = mid[i] + 1;
1161 i = 0;
1162 } else {
1163 mid[i] = 'a';
1164 }
1165 }
1166 }
1167
1168 /*!
1169 * \brief Create an IQ packet
1170 * \param client the configured XMPP client we use to connect to a XMPP server
1171 * \param type the type of IQ packet to create
1172 * \return iks *
1173 */
1174 static iks* xmpp_pubsub_iq_create(struct ast_xmpp_client *client, const char *type)
1175 {
1176 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1177 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
1178 iks *request;
1179
1180 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name)) ||
1181 !(request = iks_new("iq"))) {
1182 return NULL;
1183 }
1184
1185 if (!ast_strlen_zero(clientcfg->pubsubnode)) {
1186 iks_insert_attrib(request, "to", clientcfg->pubsubnode);
1187 }
1188
1189 iks_insert_attrib(request, "from", client->jid->full);
1190 iks_insert_attrib(request, "type", type);
1191 ast_xmpp_client_lock(client);
1192 ast_xmpp_increment_mid(client->mid);
1193 iks_insert_attrib(request, "id", client->mid);
1194 ast_xmpp_client_unlock(client);
1195
1196 return request;
1197 }
1198
1199 /*!
1200 * \brief Build the skeleton of a publish
1201 * \param client the configured XMPP client we use to connect to a XMPP server
1202 * \param node Name of the node that will be published to
1203 * \param event_type, cachable
1204 * \return iks *
1205 */
1206 static iks* xmpp_pubsub_build_publish_skeleton(struct ast_xmpp_client *client, const char *node,
1207 const char *event_type, unsigned int cachable)
1208 {
1209 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1210 iks *request, *pubsub, *publish, *item;
1211
1212 if (!cfg || !cfg->global || !(request = xmpp_pubsub_iq_create(client, "set"))) {
1213 return NULL;
1214 }
1215
1216 pubsub = iks_insert(request, "pubsub");
1217 iks_insert_attrib(pubsub, "xmlns", "http://jabber.org/protocol/pubsub");
1218 publish = iks_insert(pubsub, "publish");
1219 iks_insert_attrib(publish, "node", ast_test_flag(&cfg->global->pubsub, XMPP_XEP0248) ? node : event_type);
1220 item = iks_insert(publish, "item");
1221 iks_insert_attrib(item, "id", node);
1222
1223 if (cachable == AST_DEVSTATE_NOT_CACHABLE) {
1224 iks *options, *x, *field_form_type, *field_persist;
1225
1226 options = iks_insert(pubsub, "publish-options");
1227 x = iks_insert(options, "x");
1228 iks_insert_attrib(x, "xmlns", "jabber:x:data");
1229 iks_insert_attrib(x, "type", "submit");
1230 field_form_type = iks_insert(x, "field");
1231 iks_insert_attrib(field_form_type, "var", "FORM_TYPE");
1232 iks_insert_attrib(field_form_type, "type", "hidden");
1233 iks_insert_cdata(iks_insert(field_form_type, "value"), "http://jabber.org/protocol/pubsub#publish-options", 0);
1234 field_persist = iks_insert(x, "field");
1235 iks_insert_attrib(field_persist, "var", "pubsub#persist_items");
1236 iks_insert_cdata(iks_insert(field_persist, "value"), "0", 1);
1237 }
1238
1239 return item;
1240
1241 }
1242
1243 static iks* xmpp_pubsub_build_node_config(iks *pubsub, const char *node_type, const char *collection_name)
1244 {
1245 iks *configure, *x, *field_owner, *field_node_type, *field_node_config,
1246 *field_deliver_payload, *field_persist_items, *field_access_model,
1247 *field_pubsub_collection;
1248 configure = iks_insert(pubsub, "configure");
1249 x = iks_insert(configure, "x");
1250 iks_insert_attrib(x, "xmlns", "jabber:x:data");
1251 iks_insert_attrib(x, "type", "submit");
1252 field_owner = iks_insert(x, "field");
1253 iks_insert_attrib(field_owner, "var", "FORM_TYPE");
1254 iks_insert_attrib(field_owner, "type", "hidden");
1255 iks_insert_cdata(iks_insert(field_owner, "value"),
1256 "http://jabber.org/protocol/pubsub#owner", 39);
1257 if (node_type) {
1258 field_node_type = iks_insert(x, "field");
1259 iks_insert_attrib(field_node_type, "var", "pubsub#node_type");
1260 iks_insert_cdata(iks_insert(field_node_type, "value"), node_type, strlen(node_type));
1261 }
1262 field_node_config = iks_insert(x, "field");
1263 iks_insert_attrib(field_node_config, "var", "FORM_TYPE");
1264 iks_insert_attrib(field_node_config, "type", "hidden");
1265 iks_insert_cdata(iks_insert(field_node_config, "value"),
1266 "http://jabber.org/protocol/pubsub#node_config", 45);
1267 field_deliver_payload = iks_insert(x, "field");
1268 iks_insert_attrib(field_deliver_payload, "var", "pubsub#deliver_payloads");
1269 iks_insert_cdata(iks_insert(field_deliver_payload, "value"), "1", 1);
1270 field_persist_items = iks_insert(x, "field");
1271 iks_insert_attrib(field_persist_items, "var", "pubsub#persist_items");
1272 iks_insert_cdata(iks_insert(field_persist_items, "value"), "1", 1);
1273 field_access_model = iks_insert(x, "field");
1274 iks_insert_attrib(field_access_model, "var", "pubsub#access_model");
1275 iks_insert_cdata(iks_insert(field_access_model, "value"), "whitelist", 9);
1276 if (node_type && !strcasecmp(node_type, "leaf")) {
1277 field_pubsub_collection = iks_insert(x, "field");
1278 iks_insert_attrib(field_pubsub_collection, "var", "pubsub#collection");
1279 iks_insert_cdata(iks_insert(field_pubsub_collection, "value"), collection_name,
1280 strlen(collection_name));
1281 }
1282 return configure;
1283 }
1284
1285 /*!
1286 * \brief Add Owner affiliations for pubsub node
1287 * \param client the configured XMPP client we use to connect to a XMPP server
1288 * \param node the name of the node to which to add affiliations
1289 */
1290 static void xmpp_pubsub_create_affiliations(struct ast_xmpp_client *client, const char *node)
1291 {
1292 iks *modify_affiliates = xmpp_pubsub_iq_create(client, "set");
1293 iks *pubsub, *affiliations, *affiliate;
1294 struct ao2_iterator i;
1295 struct ast_xmpp_buddy *buddy;
1296
1297 if (!modify_affiliates) {
1298 ast_log(LOG_ERROR, "Could not create IQ for creating affiliations on client '%s'\n", client->name);
1299 return;
1300 }
1301
1302 pubsub = iks_insert(modify_affiliates, "pubsub");
1303 iks_insert_attrib(pubsub, "xmlns", "http://jabber.org/protocol/pubsub#owner");
1304 affiliations = iks_insert(pubsub, "affiliations");
1305 iks_insert_attrib(affiliations, "node", node);
1306
1307 i = ao2_iterator_init(client->buddies, 0);
1308 while ((buddy = ao2_iterator_next(&i))) {
1309 affiliate = iks_insert(affiliations, "affiliation");
1310 iks_insert_attrib(affiliate, "jid", buddy->id);
1311 iks_insert_attrib(affiliate, "affiliation", "owner");
1312 ao2_ref(buddy, -1);
1313 }
1314 ao2_iterator_destroy(&i);
1315
1316 ast_xmpp_client_send(client, modify_affiliates);
1317 iks_delete(modify_affiliates);
1318 }
1319
1320 /*!
1321 * \brief Create a pubsub node
1322 * \param client the configured XMPP client we use to connect to a XMPP server
1323 * \param node_type the type of node to create
1324 * \param name the name of the node to create
1325 * \param collection_name
1326 */
1327 static void xmpp_pubsub_create_node(struct ast_xmpp_client *client, const char *node_type, const
1328 char *name, const char *collection_name)
1329 {
1330 iks *node, *pubsub, *create;
1331
1332 if (!(node = xmpp_pubsub_iq_create(client, "set"))) {
1333 return;
1334 }
1335
1336 pubsub = iks_insert(node, "pubsub");
1337 iks_insert_attrib(pubsub, "xmlns", "http://jabber.org/protocol/pubsub");
1338 create = iks_insert(pubsub, "create");
1339 iks_insert_attrib(create, "node", name);
1340 xmpp_pubsub_build_node_config(pubsub, node_type, collection_name);
1341 ast_xmpp_client_send(client, node);
1342 xmpp_pubsub_create_affiliations(client, name);
1343 iks_delete(node);
1344 }
1345
1346 /*!
1347 * \brief Delete a PubSub node
1348 * \param client the configured XMPP client we use to connect to a XMPP server
1349 * \param node_name the name of the node to delete
1350 */
1351 static void xmpp_pubsub_delete_node(struct ast_xmpp_client *client, const char *node_name)
1352 {
1353 iks *request, *pubsub, *delete;
1354
1355 if (!(request = xmpp_pubsub_iq_create(client, "set"))) {
1356 return;
1357 }
1358
1359 pubsub = iks_insert(request, "pubsub");
1360 iks_insert_attrib(pubsub, "xmlns", "http://jabber.org/protocol/pubsub#owner");
1361 delete = iks_insert(pubsub, "delete");
1362 iks_insert_attrib(delete, "node", node_name);
1363 ast_xmpp_client_send(client, request);
1364
1365 iks_delete(request);
1366 }
1367
1368 /*!
1369 * \brief Create a PubSub collection node.
1370 * \param client the configured XMPP client we use to connect to a XMPP server
1371 * \param collection_name The name to use for this collection
1372 */
1373 static void xmpp_pubsub_create_collection(struct ast_xmpp_client *client, const char *collection_name)
1374 {
1375 xmpp_pubsub_create_node(client, "collection", collection_name, NULL);
1376 }
1377
1378
1379 /*!
1380 * \brief Create a PubSub leaf node.
1381 * \param client the configured XMPP client we use to connect to a XMPP server
1382 * \param collection_name
1383 * \param leaf_name The name to use for this collection
1384 */
1385 static void xmpp_pubsub_create_leaf(struct ast_xmpp_client *client, const char *collection_name,
1386 const char *leaf_name)
1387 {
1388 xmpp_pubsub_create_node(client, "leaf", leaf_name, collection_name);
1389 }
1390
1391 /*!
1392 * \brief Publish MWI to a PubSub node
1393 * \param client the configured XMPP client we use to connect to a XMPP server
1394 * \param mailbox The mailbox identifier
1395 * \param oldmsgs Old messages
1396 * \param newmsgs New Messages
1397 */
1398 static void xmpp_pubsub_publish_mwi(struct ast_xmpp_client *client, const char *mailbox,
1399 const char *oldmsgs, const char *newmsgs)
1400 {
1401 char eid_str[20];
1402 iks *mailbox_node, *request;
1403
1404 request = xmpp_pubsub_build_publish_skeleton(client, mailbox, "message_waiting",
1405 AST_DEVSTATE_CACHABLE);
1406 if (!request) {
1407 return;
1408 }
1409
1410 ast_eid_to_str(eid_str, sizeof(eid_str), &ast_eid_default);
1411 mailbox_node = iks_insert(request, "mailbox");
1412 iks_insert_attrib(mailbox_node, "xmlns", "http://asterisk.org");
1413 iks_insert_attrib(mailbox_node, "eid", eid_str);
1414 iks_insert_cdata(iks_insert(mailbox_node, "NEWMSGS"), newmsgs, strlen(newmsgs));
1415 iks_insert_cdata(iks_insert(mailbox_node, "OLDMSGS"), oldmsgs, strlen(oldmsgs));
1416
1417 ast_xmpp_client_send(client, iks_root(request));
1418
1419 iks_delete(request);
1420 }
1421
1422 /*!
1423 * \brief Publish device state to a PubSub node
1424 * \param client the configured XMPP client we use to connect to a XMPP server
1425 * \param device the name of the device whose state to publish
1426 * \param device_state the state to publish
1427 * \param cachable
1428 */
1429 static void xmpp_pubsub_publish_device_state(struct ast_xmpp_client *client, const char *device,
1430 const char *device_state, unsigned int cachable)
1431 {
1432 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1433 iks *request, *state;
1434 char eid_str[20], cachable_str[2];
1435
1436 if (!cfg || !cfg->global || !(request = xmpp_pubsub_build_publish_skeleton(client, device, "device_state", cachable))) {
1437 return;
1438 }
1439
1440 if (ast_test_flag(&cfg->global->pubsub, XMPP_PUBSUB_AUTOCREATE)) {
1441 if (ast_test_flag(&cfg->global->pubsub, XMPP_XEP0248)) {
1442 xmpp_pubsub_create_node(client, "leaf", device, "device_state");
1443 } else {
1444 xmpp_pubsub_create_node(client, NULL, device, NULL);
1445 }
1446 }
1447
1448 ast_eid_to_str(eid_str, sizeof(eid_str), &ast_eid_default);
1449 state = iks_insert(request, "state");
1450 iks_insert_attrib(state, "xmlns", "http://asterisk.org");
1451 iks_insert_attrib(state, "eid", eid_str);
1452 snprintf(cachable_str, sizeof(cachable_str), "%u", cachable);
1453 iks_insert_attrib(state, "cachable", cachable_str);
1454 iks_insert_cdata(state, device_state, strlen(device_state));
1455 ast_xmpp_client_send(client, iks_root(request));
1456 iks_delete(request);
1457 }
1458
1459 /*!
1460 * \brief Callback function for MWI events
1461 * \param data void pointer to ast_client structure
1462 * \param sub, msg
1463 */
1464 static void xmpp_pubsub_mwi_cb(void *data, struct stasis_subscription *sub, struct stasis_message *msg)
1465 {
1466 struct ast_xmpp_client *client = data;
1467 char oldmsgs[10], newmsgs[10];
1468 struct ast_mwi_state *mwi_state;
1469
1470 if (!stasis_subscription_is_subscribed(sub) || ast_mwi_state_type() != stasis_message_type(msg)) {
1471 return;
1472 }
1473
1474 mwi_state = stasis_message_data(msg);
1475
1476 if (ast_eid_cmp(&ast_eid_default, &mwi_state->eid)) {
1477 /* If the event didn't originate from this server, don't send it back out. */
1478 return;
1479 }
1480
1481 snprintf(oldmsgs, sizeof(oldmsgs), "%d", mwi_state->old_msgs);
1482 snprintf(newmsgs, sizeof(newmsgs), "%d", mwi_state->new_msgs);
1483 xmpp_pubsub_publish_mwi(client, mwi_state->uniqueid, oldmsgs, newmsgs);
1484 }
1485
1486 /*!
1487 * \brief Callback function for device state events
1488 * \param data void pointer to ast_client structure
1489 * \param sub, msg
1490 */
1491 static void xmpp_pubsub_devstate_cb(void *data, struct stasis_subscription *sub, struct stasis_message *msg)
1492 {
1493 struct ast_xmpp_client *client = data;
1494 struct ast_device_state_message *dev_state;
1495
1496 if (!stasis_subscription_is_subscribed(sub) || ast_device_state_message_type() != stasis_message_type(msg)) {
1497 return;
1498 }
1499
1500 dev_state = stasis_message_data(msg);
1501 if (!dev_state->eid || ast_eid_cmp(&ast_eid_default, dev_state->eid)) {
1502 /* If the event is aggregate or didn't originate from this server, don't send it out. */
1503 return;
1504 }
1505
1506 xmpp_pubsub_publish_device_state(client, dev_state->device, ast_devstate_str(dev_state->state), dev_state->cachable);
1507 }
1508
1509 /*!
1510 * \brief Unsubscribe from a PubSub node
1511 * \param client the configured XMPP client we use to connect to a XMPP server
1512 * \param node the name of the node to which to unsubscribe from
1513 */
1514 static void xmpp_pubsub_unsubscribe(struct ast_xmpp_client *client, const char *node)
1515 {
1516 iks *request = xmpp_pubsub_iq_create(client, "set");
1517 iks *pubsub, *unsubscribe;
1518
1519 if (!request) {
1520 ast_log(LOG_ERROR, "Could not create IQ when creating pubsub unsubscription on client '%s'\n", client->name);
1521 return;
1522 }
1523
1524 pubsub = iks_insert(request, "pubsub");
1525 iks_insert_attrib(pubsub, "xmlns", "http://jabber.org/protocol/pubsub");
1526 unsubscribe = iks_insert(pubsub, "unsubscribe");
1527 iks_insert_attrib(unsubscribe, "jid", client->jid->partial);
1528 iks_insert_attrib(unsubscribe, "node", node);
1529
1530 ast_xmpp_client_send(client, request);
1531 iks_delete(request);
1532 }
1533
1534 /*!
1535 * \brief Subscribe to a PubSub node
1536 * \param client the configured XMPP client we use to connect to a XMPP server
1537 * \param node the name of the node to which to subscribe
1538 */
1539 static void xmpp_pubsub_subscribe(struct ast_xmpp_client *client, const char *node)
1540 {
1541 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1542 iks *request = xmpp_pubsub_iq_create(client, "set");
1543 iks *pubsub, *subscribe;
1544
1545 if (!cfg || !cfg->global || !request) {
1546 ast_log(LOG_ERROR, "Could not create IQ when creating pubsub subscription on client '%s'\n", client->name);
1547 return;
1548 }
1549
1550 pubsub = iks_insert(request, "pubsub");
1551 iks_insert_attrib(pubsub, "xmlns", "http://jabber.org/protocol/pubsub");
1552 subscribe = iks_insert(pubsub, "subscribe");
1553 iks_insert_attrib(subscribe, "jid", client->jid->partial);
1554 iks_insert_attrib(subscribe, "node", node);
1555 if (ast_test_flag(&cfg->global->pubsub, XMPP_XEP0248)) {
1556 iks *options, *x, *sub_options, *sub_type, *sub_depth, *sub_expire;
1557 options = iks_insert(pubsub, "options");
1558 x = iks_insert(options, "x");
1559 iks_insert_attrib(x, "xmlns", "jabber:x:data");
1560 iks_insert_attrib(x, "type", "submit");
1561 sub_options = iks_insert(x, "field");
1562 iks_insert_attrib(sub_options, "var", "FORM_TYPE");
1563 iks_insert_attrib(sub_options, "type", "hidden");
1564 iks_insert_cdata(iks_insert(sub_options, "value"),
1565 "http://jabber.org/protocol/pubsub#subscribe_options", 51);
1566 sub_type = iks_insert(x, "field");
1567 iks_insert_attrib(sub_type, "var", "pubsub#subscription_type");
1568 iks_insert_cdata(iks_insert(sub_type, "value"), "items", 5);
1569 sub_depth = iks_insert(x, "field");
1570 iks_insert_attrib(sub_depth, "var", "pubsub#subscription_depth");
1571 iks_insert_cdata(iks_insert(sub_depth, "value"), "all", 3);
1572 sub_expire = iks_insert(x, "field");
1573 iks_insert_attrib(sub_expire, "var", "pubsub#expire");
1574 iks_insert_cdata(iks_insert(sub_expire, "value"), "presence", 8);
1575 }
1576 ast_xmpp_client_send(client, request);
1577 iks_delete(request);
1578 }
1579
1580 /*!
1581 * \brief Callback for handling PubSub events
1582 * \param data void pointer to ast_xmpp_client structure
1583 * \param pak A pak
1584 * \retval IKS_FILTER_EAT
1585 */
1586 static int xmpp_pubsub_handle_event(void *data, ikspak *pak)
1587 {
1588 char *item_id, *device_state, *mailbox, *cachable_str;
1589 int oldmsgs, newmsgs;
1590 iks *item, *item_content;
1591 struct ast_eid pubsub_eid;
1592 unsigned int cachable = AST_DEVSTATE_CACHABLE;
1593 item = iks_find(iks_find(iks_find(pak->x, "event"), "items"), "item");
1594 if (!item) {
1595 ast_log(LOG_ERROR, "Could not parse incoming PubSub event\n");
1596 return IKS_FILTER_EAT;
1597 }
1598 item_id = iks_find_attrib(item, "id");
1599 item_content = iks_child(item);
1600 ast_str_to_eid(&pubsub_eid, iks_find_attrib(item_content, "eid"));
1601 if (!ast_eid_cmp(&ast_eid_default, &pubsub_eid)) {
1602 ast_debug(1, "Returning here, eid of incoming event matches ours!\n");
1603 return IKS_FILTER_EAT;
1604 }
1605 if (!strcasecmp(iks_name(item_content), "state")) {
1606 if ((cachable_str = iks_find_attrib(item_content, "cachable"))) {
1607 sscanf(cachable_str, "%30u", &cachable);
1608 }
1609 device_state = iks_find_cdata(item, "state");
1610 ast_publish_device_state_full(item_id,
1611 ast_devstate_val(device_state),
1612 cachable == AST_DEVSTATE_CACHABLE ? AST_DEVSTATE_CACHABLE : AST_DEVSTATE_NOT_CACHABLE,
1613 &pubsub_eid);
1614 return IKS_FILTER_EAT;
1615 } else if (!strcasecmp(iks_name(item_content), "mailbox")) {
1616 mailbox = strsep(&item_id, "@");
1617 sscanf(iks_find_cdata(item_content, "OLDMSGS"), "%10d", &oldmsgs);
1618 sscanf(iks_find_cdata(item_content, "NEWMSGS"), "%10d", &newmsgs);
1619
1620 ast_publish_mwi_state_full(mailbox, item_id, newmsgs, oldmsgs, NULL, &pubsub_eid);
1621
1622 return IKS_FILTER_EAT;
1623 } else {
1624 ast_debug(1, "Don't know how to handle PubSub event of type %s\n",
1625 iks_name(item_content));
1626 return IKS_FILTER_EAT;
1627 }
1628
1629 return IKS_FILTER_EAT;
1630 }
1631
1632 static int xmpp_pubsub_handle_error(void *data, ikspak *pak)
1633 {
1634 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1635 char *node_name, *error;
1636 int error_num;
1637 iks *orig_request, *orig_pubsub = iks_find(pak->x, "pubsub");
1638 struct ast_xmpp_client *client = data;
1639
1640 if (!cfg || !cfg->global) {
1641 ast_log(LOG_ERROR, "No global configuration available\n");
1642 return IKS_FILTER_EAT;
1643 }
1644
1645 if (!orig_pubsub) {
1646 ast_debug(1, "Error isn't a PubSub error, why are we here?\n");
1647 return IKS_FILTER_EAT;
1648 }
1649
1650 orig_request = iks_child(orig_pubsub);
1651 error = iks_find_attrib(iks_find(pak->x, "error"), "code");
1652 node_name = iks_find_attrib(orig_request, "node");
1653
1654 if (!sscanf(error, "%30d", &error_num)) {
1655 return IKS_FILTER_EAT;
1656 }
1657
1658 if (error_num > 399 && error_num < 500 && error_num != 404) {
1659 ast_log(LOG_ERROR,
1660 "Error performing operation on PubSub node %s, %s.\n", node_name, error);
1661 return IKS_FILTER_EAT;
1662 } else if (error_num > 499 && error_num < 600) {
1663 ast_log(LOG_ERROR, "PubSub Server error, %s\n", error);
1664 return IKS_FILTER_EAT;
1665 }
1666
1667 if (!strcasecmp(iks_name(orig_request), "publish")) {
1668 iks *request;
1669
1670 if (ast_test_flag(&cfg->global->pubsub, XMPP_XEP0248)) {
1671 if (iks_find(iks_find(orig_request, "item"), "state")) {
1672 xmpp_pubsub_create_leaf(client, "device_state", node_name);
1673 } else if (iks_find(iks_find(orig_request, "item"), "mailbox")) {
1674 xmpp_pubsub_create_leaf(client, "message_waiting", node_name);
1675 }
1676 } else {
1677 xmpp_pubsub_create_node(client, NULL, node_name, NULL);
1678 }
1679
1680 if ((request = xmpp_pubsub_iq_create(client, "set"))) {
1681 iks_insert_node(request, orig_pubsub);
1682 ast_xmpp_client_send(client, request);
1683 iks_delete(request);
1684 } else {
1685 ast_log(LOG_ERROR, "PubSub publish could not create IQ\n");
1686 }
1687
1688 return IKS_FILTER_EAT;
1689 } else if (!strcasecmp(iks_name(orig_request), "subscribe")) {
1690 if (ast_test_flag(&cfg->global->pubsub, XMPP_XEP0248)) {
1691 xmpp_pubsub_create_collection(client, node_name);
1692 } else {
1693 xmpp_pubsub_create_node(client, NULL, node_name, NULL);
1694 }
1695 }
1696
1697 return IKS_FILTER_EAT;
1698 }
1699
1700 static int cached_devstate_cb(void *obj, void *arg, int flags)
1701 {
1702 struct stasis_message *msg = obj;
1703 struct ast_xmpp_client *client = arg;
1704 xmpp_pubsub_devstate_cb(client, client->device_state_sub, msg);
1705 return 0;
1706 }
1707
1708 /*!
1709 * \brief Initialize collections for event distribution
1710 * \param client the configured XMPP client we use to connect to a XMPP server
1711 */
1712 static void xmpp_init_event_distribution(struct ast_xmpp_client *client)
1713 {
1714 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1715 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
1716 RAII_VAR(struct ao2_container *, cached, NULL, ao2_cleanup);
1717
1718 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name))) {
1719 return;
1720 }
1721
1722 xmpp_pubsub_unsubscribe(client, "device_state");
1723 xmpp_pubsub_unsubscribe(client, "message_waiting");
1724
1725 if (!(client->mwi_sub = stasis_subscribe_pool(ast_mwi_topic_all(), xmpp_pubsub_mwi_cb, client))) {
1726 return;
1727 }
1728 stasis_subscription_accept_message_type(client->mwi_sub, ast_mwi_state_type());
1729 stasis_subscription_set_filter(client->mwi_sub, STASIS_SUBSCRIPTION_FILTER_SELECTIVE);
1730
1731 if (!(client->device_state_sub = stasis_subscribe(ast_device_state_topic_all(), xmpp_pubsub_devstate_cb, client))) {
1732 client->mwi_sub = stasis_unsubscribe(client->mwi_sub);
1733 return;
1734 }
1735 stasis_subscription_accept_message_type(client->device_state_sub, ast_device_state_message_type());
1736 stasis_subscription_set_filter(client->device_state_sub, STASIS_SUBSCRIPTION_FILTER_SELECTIVE);
1737
1738 cached = stasis_cache_dump(ast_device_state_cache(), NULL);
1739 ao2_callback(cached, OBJ_NODATA, cached_devstate_cb, client);
1740
1741 xmpp_pubsub_subscribe(client, "device_state");
1742 xmpp_pubsub_subscribe(client, "message_waiting");
1743 iks_filter_add_rule(client->filter, xmpp_pubsub_handle_event, client, IKS_RULE_TYPE,
1744 IKS_PAK_MESSAGE, IKS_RULE_FROM, clientcfg->pubsubnode, IKS_RULE_DONE);
1745 iks_filter_add_rule(client->filter, xmpp_pubsub_handle_error, client, IKS_RULE_TYPE,
1746 IKS_PAK_IQ, IKS_RULE_SUBTYPE, IKS_TYPE_ERROR, IKS_RULE_DONE);
1747
1748 }
1749
1750 /*! \brief Internal astobj2 callback function which returns the first resource, which is the highest priority one */
1751 static int xmpp_resource_immediate(void *obj, void *arg, int flags)
1752 {
1753 return CMP_MATCH | CMP_STOP;
1754 }
1755
1756 #define BUDDY_OFFLINE 6
1757 #define BUDDY_NOT_IN_ROSTER 7
1758
1759 static int get_buddy_status(struct ast_xmpp_client_config *clientcfg, char *screenname, char *resource)
1760 {
1761 int status = BUDDY_OFFLINE;
1762 struct ast_xmpp_resource *res;
1763 struct ast_xmpp_buddy *buddy = ao2_find(clientcfg->client->buddies, screenname, OBJ_KEY);
1764
1765 if (!buddy) {
1766 return BUDDY_NOT_IN_ROSTER;
1767 }
1768
1769 res = ao2_callback(
1770 buddy->resources,
1771 0,
1772 ast_strlen_zero(resource) ? xmpp_resource_immediate : xmpp_resource_cmp,
1773 resource);
1774
1775 if (res) {
1776 status = res->status;
1777 }
1778
1779 ao2_cleanup(res);
1780 ao2_cleanup(buddy);
1781
1782 return status;
1783 }
1784
1785 /*!
1786 * \internal
1787 * \brief Dial plan funtcion to retrieve the status of a buddy.
1788 * \param chan The associated ast_channel, if there is one
1789 * \param data The account, buddy JID, and optional timeout
1790 * \param name, buf, buflen
1791 *
1792 * \retval 0 success
1793 * \retval -1 failure
1794 */
1795 static int acf_jabberstatus_read(struct ast_channel *chan, const char *name, char *data, char *buf, size_t buflen)
1796 {
1797 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1798 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
1799 AST_DECLARE_APP_ARGS(args,
1800 AST_APP_ARG(sender);
1801 AST_APP_ARG(jid);
1802 );
1803 AST_DECLARE_APP_ARGS(jid,
1804 AST_APP_ARG(screenname);
1805 AST_APP_ARG(resource);
1806 );
1807
1808 if (ast_strlen_zero(data)) {
1809 ast_log(LOG_ERROR, "Usage: JABBER_STATUS(<sender>,<jid>[/<resource>])\n");
1810 return 0;
1811 }
1812 AST_STANDARD_APP_ARGS(args, data);
1813
1814 if (args.argc != 2) {
1815 ast_log(LOG_ERROR, "JABBER_STATUS requires 2 arguments: sender and jid.\n");
1816 return -1;
1817 }
1818
1819 AST_NONSTANDARD_APP_ARGS(jid, args.jid, '/');
1820 if (jid.argc < 1 || jid.argc > 2) {
1821 ast_log(LOG_WARNING, "Wrong JID %s, exiting\n", args.jid);
1822 return -1;
1823 }
1824
1825 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, args.sender))) {
1826 ast_log(LOG_WARNING, "Could not find sender connection: '%s'\n", args.sender);
1827 return -1;
1828 }
1829
1830 snprintf(buf, buflen, "%d", get_buddy_status(clientcfg, jid.screenname, jid.resource));
1831
1832 return 0;
1833 }
1834
1835 static struct ast_custom_function jabberstatus_function = {
1836 .name = "JABBER_STATUS",
1837 .read = acf_jabberstatus_read,
1838 };
1839
1840 /*!
1841 * \brief Application to join a chat room
1842 * \param chan ast_channel
1843 * \param data Data is sender|jid|nickname.
1844 * \retval 0 success
1845 * \retval -1 error
1846 */
1847 static int xmpp_join_exec(struct ast_channel *chan, const char *data)
1848 {
1849 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1850 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
1851 char *s, nick[XMPP_MAX_RESJIDLEN];
1852 AST_DECLARE_APP_ARGS(args,
1853 AST_APP_ARG(sender);
1854 AST_APP_ARG(jid);
1855 AST_APP_ARG(nick);
1856 );
1857
1858 if (ast_strlen_zero(data)) {
1859 ast_log(LOG_ERROR, "%s requires arguments (sender,jid[,nickname])\n", app_ajijoin);
1860 return -1;
1861 }
1862 s = ast_strdupa(data);
1863
1864 AST_STANDARD_APP_ARGS(args, s);
1865 if (args.argc < 2 || args.argc > 3) {
1866 ast_log(LOG_ERROR, "%s requires arguments (sender,jid[,nickname])\n", app_ajijoin);
1867 return -1;
1868 }
1869
1870 if (strchr(args.jid, '/')) {
1871 ast_log(LOG_ERROR, "Invalid room name : resource must not be appended\n");
1872 return -1;
1873 }
1874
1875 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, args.sender))) {
1876 ast_log(LOG_ERROR, "Could not find sender connection: '%s'\n", args.sender);
1877 return -1;
1878 }
1879
1880 if (ast_strlen_zero(args.nick)) {
1881 if (ast_test_flag(&clientcfg->flags, XMPP_COMPONENT)) {
1882 snprintf(nick, sizeof(nick), "asterisk");
1883 } else {
1884 snprintf(nick, sizeof(nick), "%s", clientcfg->client->jid->user);
1885 }
1886 } else {
1887 snprintf(nick, sizeof(nick), "%s", args.nick);
1888 }
1889
1890 if (!ast_strlen_zero(args.jid) && strchr(args.jid, '@')) {
1891 ast_xmpp_chatroom_join(clientcfg->client, args.jid, nick);
1892 } else {
1893 ast_log(LOG_ERROR, "Problem with specified jid of '%s'\n", args.jid);
1894 }
1895
1896 return 0;
1897 }
1898
1899 /*!
1900 * \brief Application to leave a chat room
1901 * \param chan ast_channel
1902 * \param data Data is sender|jid|nickname.
1903 * \retval 0 success
1904 * \retval -1 error
1905 */
1906 static int xmpp_leave_exec(struct ast_channel *chan, const char *data)
1907 {
1908 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1909 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
1910 char *s, nick[XMPP_MAX_RESJIDLEN];
1911 AST_DECLARE_APP_ARGS(args,
1912 AST_APP_ARG(sender);
1913 AST_APP_ARG(jid);
1914 AST_APP_ARG(nick);
1915 );
1916
1917 if (ast_strlen_zero(data)) {
1918 ast_log(LOG_ERROR, "%s requires arguments (sender,jid[,nickname])\n", app_ajileave);
1919 return -1;
1920 }
1921 s = ast_strdupa(data);
1922
1923 AST_STANDARD_APP_ARGS(args, s);
1924 if (args.argc < 2 || args.argc > 3) {
1925 ast_log(LOG_ERROR, "%s requires arguments (sender,jid[,nickname])\n", app_ajileave);
1926 return -1;
1927 }
1928
1929 if (strchr(args.jid, '/')) {
1930 ast_log(LOG_ERROR, "Invalid room name, resource must not be appended\n");
1931 return -1;
1932 }
1933
1934 if (ast_strlen_zero(args.jid) || !strchr(args.jid, '@')) {
1935 ast_log(LOG_ERROR, "No jabber ID specified\n");
1936 return -1;
1937 }
1938
1939 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, args.sender))) {
1940 ast_log(LOG_ERROR, "Could not find sender connection: '%s'\n", args.sender);
1941 return -1;
1942 }
1943
1944 if (ast_strlen_zero(args.nick)) {
1945 if (ast_test_flag(&clientcfg->flags, XMPP_COMPONENT)) {
1946 snprintf(nick, sizeof(nick), "asterisk");
1947 } else {
1948 snprintf(nick, sizeof(nick), "%s", clientcfg->client->jid->user);
1949 }
1950 } else {
1951 snprintf(nick, sizeof(nick), "%s", args.nick);
1952 }
1953
1954 ast_xmpp_chatroom_leave(clientcfg->client, args.jid, nick);
1955
1956 return 0;
1957 }
1958
1959 /*!
1960 * \internal
1961 * \brief Dial plan function to send a message.
1962 * \param chan ast_channel
1963 * \param data Data is account,jid,message.
1964 * \retval 0 success
1965 * \retval -1 failure
1966 */
1967 static int xmpp_send_exec(struct ast_channel *chan, const char *data)
1968 {
1969 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1970 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
1971 char *s;
1972 AST_DECLARE_APP_ARGS(args,
1973 AST_APP_ARG(sender);
1974 AST_APP_ARG(recipient);
1975 AST_APP_ARG(message);
1976 );
1977
1978 if (ast_strlen_zero(data)) {
1979 ast_log(LOG_WARNING, "%s requires arguments (account,jid,message)\n", app_ajisend);
1980 return -1;
1981 }
1982 s = ast_strdupa(data);
1983
1984 AST_STANDARD_APP_ARGS(args, s);
1985
1986 if ((args.argc < 3) || ast_strlen_zero(args.message) || !strchr(args.recipient, '@')) {
1987 ast_log(LOG_WARNING, "%s requires arguments (account,jid,message)\n", app_ajisend);
1988 return -1;
1989 }
1990
1991 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, args.sender))) {
1992 ast_log(LOG_WARNING, "Could not find sender connection: '%s'\n", args.sender);
1993 return -1;
1994 }
1995
1996 ast_xmpp_client_send_message(clientcfg->client, args.recipient, args.message);
1997
1998 return 0;
1999 }
2000
2001 /*!
2002 * \brief Application to send a message to a groupchat.
2003 * \param chan ast_channel
2004 * \param data Data is sender|groupchat|message.
2005 * \retval 0 success
2006 * \retval -1 error
2007 */
2008 static int xmpp_sendgroup_exec(struct ast_channel *chan, const char *data)
2009 {
2010 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
2011 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
2012 char *s, nick[XMPP_MAX_RESJIDLEN];
2013 AST_DECLARE_APP_ARGS(args,
2014 AST_APP_ARG(sender);
2015 AST_APP_ARG(groupchat);
2016 AST_APP_ARG(message);
2017 AST_APP_ARG(nick);
2018 );
2019
2020 if (ast_strlen_zero(data)) {
2021 ast_log(LOG_ERROR, "%s requires arguments (sender,groupchatid,message[,nickname])\n", app_ajisendgroup);
2022 return -1;
2023 }
2024 s = ast_strdupa(data);
2025
2026 AST_STANDARD_APP_ARGS(args, s);
2027 if ((args.argc < 3) || (args.argc > 4) || ast_strlen_zero(args.message) || !strchr(args.groupchat, '@')) {
2028 ast_log(LOG_ERROR, "%s requires arguments (sender,groupchatid,message[,nickname])\n", app_ajisendgroup);
2029 return -1;
2030 }
2031
2032 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, args.sender))) {
2033 ast_log(LOG_ERROR, "Could not find sender connection: '%s'\n", args.sender);
2034 return -1;
2035 }
2036
2037 if (ast_strlen_zero(args.nick) || args.argc == 3) {
2038 if (ast_test_flag(&clientcfg->flags, XMPP_COMPONENT)) {
2039 snprintf(nick, sizeof(nick), "asterisk");
2040 } else {
2041 snprintf(nick, sizeof(nick), "%s", clientcfg->client->jid->user);
2042 }
2043 } else {
2044 snprintf(nick, sizeof(nick), "%s", args.nick);
2045 }
2046
2047 ast_xmpp_chatroom_send(clientcfg->client, nick, args.groupchat, args.message);
2048
2049 return 0;
2050 }
2051
2052 /*!
2053 * \internal
2054 * \brief Dial plan function to receive a message.
2055 * \param chan The associated ast_channel, if there is one
2056 * \param data The account, JID, and optional timeout
2057 * \param name, buf, buflen
2058 *
2059 * \retval 0 success
2060 * \retval -1 failure
2061 */
2062 static int acf_jabberreceive_read(struct ast_channel *chan, const char *name, char *data, char *buf, size_t buflen)
2063 {
2064 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
2065 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
2066 char *parse = NULL;
2067 int timeout, jidlen, resourcelen, found = 0;
2068 struct timeval start;
2069 long diff = 0;
2070 struct ast_xmpp_message *message;
2071 AST_DECLARE_APP_ARGS(args,
2072 AST_APP_ARG(account);
2073 AST_APP_ARG(jid);
2074 AST_APP_ARG(timeout);
2075 );
2076 AST_DECLARE_APP_ARGS(jid,
2077 AST_APP_ARG(screenname);
2078 AST_APP_ARG(resource);
2079 );
2080
2081 if (ast_strlen_zero(data)) {
2082 ast_log(LOG_WARNING, "%s requires arguments (account,jid[,timeout])\n", name);
2083 return -1;
2084 }
2085
2086 parse = ast_strdupa(data);
2087 AST_STANDARD_APP_ARGS(args, parse);
2088
2089 if (args.argc < 2 || args.argc > 3) {
2090 ast_log(LOG_WARNING, "%s requires arguments (account,jid[,timeout])\n", name);
2091 return -1;
2092 }
2093
2094 parse = ast_strdupa(args.jid);
2095 AST_NONSTANDARD_APP_ARGS(jid, parse, '/');
2096 if (jid.argc < 1 || jid.argc > 2 || strlen(args.jid) > XMPP_MAX_JIDLEN) {
2097 ast_log(LOG_WARNING, "Invalid JID : %s\n", parse);
2098 return -1;
2099 }
2100
2101 if (ast_strlen_zero(args.timeout)) {
2102 timeout = 20;
2103 } else {
2104 sscanf(args.timeout, "%d", &timeout);
2105 if (timeout <= 0) {
2106 ast_log(LOG_WARNING, "Invalid timeout specified: '%s'\n", args.timeout);
2107 return -1;
2108 }
2109 }
2110
2111 jidlen = strlen(jid.screenname);
2112 resourcelen = ast_strlen_zero(jid.resource) ? 0 : strlen(jid.resource);
2113
2114 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, args.account))) {
2115 ast_log(LOG_WARNING, "Could not find client %s, exiting\n", args.account);
2116 return -1;
2117 }
2118
2119 ast_debug(3, "Waiting for an XMPP message from %s\n", args.jid);
2120
2121 start = ast_tvnow();
2122
2123 if (chan && ast_autoservice_start(chan) < 0) {
2124 ast_log(LOG_WARNING, "Cannot start autoservice for channel %s\n", ast_channel_name(chan));
2125 return -1;
2126 }
2127
2128 /* search the messages list, grab the first message that matches with
2129 * the from JID we're expecting, and remove it from the messages list */
2130 while (diff < timeout) {
2131 struct timespec ts = { 0, };
2132 struct timeval wait;
2133 int res = 0;
2134
2135 wait = ast_tvadd(start, ast_tv(timeout, 0));
2136 ts.tv_sec = wait.tv_sec;
2137 ts.tv_nsec = wait.tv_usec * 1000;
2138
2139 /* wait up to timeout seconds for an incoming message */
2140 ast_mutex_lock(&messagelock);
2141 if (AST_LIST_EMPTY(&clientcfg->client->messages)) {
2142 res = ast_cond_timedwait(&message_received_condition, &messagelock, &ts);
2143 }
2144 ast_mutex_unlock(&messagelock);
2145 if (res == ETIMEDOUT) {
2146 ast_debug(3, "No message received from %s in %d seconds\n", args.jid, timeout);
2147 break;
2148 }
2149
2150 AST_LIST_LOCK(&clientcfg->client->messages);
2151 AST_LIST_TRAVERSE_SAFE_BEGIN(&clientcfg->client->messages, message, list) {
2152 if (jid.argc == 1) {
2153 /* no resource provided, compare bare JIDs */
2154 if (strncasecmp(jid.screenname, message->from, jidlen)) {
2155 continue;
2156 }
2157 } else {
2158 /* resource appended, compare bare JIDs and resources */
2159 char *resource = strchr(message->from, '/');
2160 if (!resource || strlen(resource) == 0) {
2161 ast_log(LOG_WARNING, "Remote JID has no resource : %s\n", message->from);
2162 if (strncasecmp(jid.screenname, message->from, jidlen)) {
2163 continue;
2164 }
2165 } else {
2166 resource ++;
2167 if (strncasecmp(jid.screenname, message->from, jidlen) || strncmp(jid.resource, resource, resourcelen)) {
2168 continue;
2169 }
2170 }
2171 }
2172 /* check if the message is not too old */
2173 if (ast_tvdiff_sec(ast_tvnow(), message->arrived) >= clientcfg->message_timeout) {
2174 ast_debug(3, "Found old message from %s, deleting it\n", message->from);
2175 AST_LIST_REMOVE_CURRENT(list);
2176 xmpp_message_destroy(message);
2177 continue;
2178 }
2179 found = 1;
2180 ast_copy_string(buf, message->message, buflen);
2181 AST_LIST_REMOVE_CURRENT(list);
2182 xmpp_message_destroy(message);
2183 break;
2184 }
2185 AST_LIST_TRAVERSE_SAFE_END;
2186 AST_LIST_UNLOCK(&clientcfg->client->messages);
2187 if (found) {
2188 break;
2189 }
2190
2191 /* check timeout */
2192 diff = ast_tvdiff_ms(ast_tvnow(), start);
2193 }
2194
2195 if (chan && ast_autoservice_stop(chan) < 0) {
2196 ast_log(LOG_WARNING, "Cannot stop autoservice for channel %s\n", ast_channel_name(chan));
2197 }
2198
2199 /* return if we timed out */
2200 if (!found) {
2201 ast_log(LOG_NOTICE, "Timed out : no message received from %s\n", args.jid);
2202 return -1;
2203 }
2204
2205 return 0;
2206 }
2207
2208 static struct ast_custom_function jabberreceive_function = {
2209 .name = "JABBER_RECEIVE",
2210 .read = acf_jabberreceive_read,
2211 };
2212
2213 /*!
2214 * \internal
2215 * \brief Delete old messages from a given JID
2216 * Messages stored during more than client->message_timeout are deleted
2217 * \param client Asterisk's XMPP client
2218 * \param from the JID we received messages from
2219 * \retval the number of deleted messages
2220 */
2221 static int delete_old_messages(struct ast_xmpp_client *client, char *from)
2222 {
2223 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
2224 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
2225 int deleted = 0, isold = 0;
2226 struct ast_xmpp_message *message = NULL;
2227
2228 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name))) {
2229 return 0;
2230 }
2231
2232 AST_LIST_LOCK(&client->messages);
2233 AST_LIST_TRAVERSE_SAFE_BEGIN(&client->messages, message, list) {
2234 if (isold) {
2235 if (!from || !strncasecmp(from, message->from, strlen(from))) {
2236 AST_LIST_REMOVE_CURRENT(list);
2237 xmpp_message_destroy(message);
2238 deleted++;
2239 }
2240 } else if (ast_tvdiff_sec(ast_tvnow(), message->arrived) >= clientcfg->message_timeout) {
2241 isold = 1;
2242 if (!from || !strncasecmp(from, message->from, strlen(from))) {
2243 AST_LIST_REMOVE_CURRENT(list);
2244 xmpp_message_destroy(message);
2245 deleted++;
2246 }
2247 }
2248 }
2249 AST_LIST_TRAVERSE_SAFE_END;
2250 AST_LIST_UNLOCK(&client->messages);
2251
2252 return deleted;
2253 }
2254
2255 static int xmpp_send_cb(const struct ast_msg *msg, const char *to, const char *from)
2256 {
2257 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
2258 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
2259 char *sender, *dest;
2260 int res;
2261
2262 sender = ast_strdupa(from);
2263 strsep(&sender, ":");
2264 dest = ast_strdupa(to);
2265 strsep(&dest, ":");
2266
2267 if (ast_strlen_zero(sender)) {
2268 ast_log(LOG_ERROR, "MESSAGE(from) of '%s' invalid for XMPP\n", from);
2269 return -1;
2270 }
2271
2272 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, sender))) {
2273 ast_log(LOG_WARNING, "Could not finder account to send from as '%s'\n", sender);
2274 return -1;
2275 }
2276
2277 ast_debug(1, "Sending message to '%s' from '%s'\n", dest, clientcfg->name);
2278
2279 if ((res = ast_xmpp_client_send_message(clientcfg->client, dest, ast_msg_get_body(msg))) != IKS_OK) {
2280 ast_log(LOG_WARNING, "Failed to send XMPP message (%d).\n", res);
2281 }
2282
2283 return res == IKS_OK ? 0 : -1;
2284 }
2285
2286 static const struct ast_msg_tech msg_tech = {
2287 .name = "xmpp",
2288 .msg_send = xmpp_send_cb,
2289 };
2290
2291 /*! \brief Internal function which creates a buddy on a client */
2292 static struct ast_xmpp_buddy *xmpp_client_create_buddy(struct ao2_container *container, const char *id)
2293 {
2294 struct ast_xmpp_buddy *buddy;
2295
2296 if (!(buddy = ao2_alloc(sizeof(*buddy), xmpp_buddy_destructor))) {
2297 return NULL;
2298 }
2299
2300 buddy->resources = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
2301 RESOURCE_BUCKETS, xmpp_resource_hash, NULL, xmpp_resource_cmp);
2302 if (!buddy->resources) {
2303 ao2_ref(buddy, -1);
2304 return NULL;
2305 }
2306
2307 ast_copy_string(buddy->id, id, sizeof(buddy->id));
2308
2309 /* Assume we need to subscribe to get their presence until proven otherwise */
2310 buddy->subscribe = 1;
2311
2312 ao2_link(container, buddy);
2313
2314 return buddy;
2315 }
2316
2317 /*! \brief Helper function which unsubscribes a user and removes them from the roster */
2318 static int xmpp_client_unsubscribe_user(struct ast_xmpp_client *client, const char *user)
2319 {
2320 iks *iq, *query = NULL, *item = NULL;
2321
2322 if (ast_xmpp_client_send(client, iks_make_s10n(IKS_TYPE_UNSUBSCRIBE, user,
2323 "Goodbye. Your status is no longer required.\n"))) {
2324 return -1;
2325 }
2326
2327 if (!(iq = iks_new("iq")) || !(query = iks_new("query")) || !(item = iks_new("item"))) {
2328 ast_log(LOG_WARNING, "Could not allocate memory for roster removal of '%s' from client '%s'\n",
2329 user, client->name);
2330 goto done;
2331 }
2332
2333 iks_insert_attrib(iq, "from", client->jid->full);
2334 iks_insert_attrib(iq, "type", "set");
2335 iks_insert_attrib(query, "xmlns", "jabber:iq:roster");
2336 iks_insert_node(iq, query);
2337 iks_insert_attrib(item, "jid", user);
2338 iks_insert_attrib(item, "subscription", "remove");
2339 iks_insert_node(query, item);
2340
2341 if (ast_xmpp_client_send(client, iq)) {
2342 ast_log(LOG_WARNING, "Could not send roster removal request of '%s' from client '%s'\n",
2343 user, client->name);
2344 }
2345
2346 done:
2347 iks_delete(item);
2348 iks_delete(query);
2349 iks_delete(iq);
2350
2351 return 0;
2352 }
2353
2354 /*! \brief Callback function which subscribes to a user if needed */
2355 static int xmpp_client_subscribe_user(void *obj, void *arg, int flags)
2356 {
2357 struct ast_xmpp_buddy *buddy = obj;
2358 struct ast_xmpp_client *client = arg;
2359
2360 if (!buddy->subscribe) {
2361 return 0;
2362 }
2363
2364 if (ast_xmpp_client_send(client, iks_make_s10n(IKS_TYPE_SUBSCRIBE, buddy->id,
2365 "Greetings! I am the Asterisk Open Source PBX and I want to subscribe to your presence\n"))) {
2366 ast_log(LOG_WARNING, "Could not send subscription for '%s' on client '%s'\n",
2367 buddy->id, client->name);
2368 }
2369
2370 buddy->subscribe = 0;
2371
2372 return 0;
2373 }
2374
2375 /*! \brief Hook function called when roster is received from server */
2376 static int xmpp_roster_hook(void *data, ikspak *pak)
2377 {
2378 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
2379 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
2380 struct ast_xmpp_client *client = data;
2381 iks *item;
2382
2383 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name))) {
2384 return IKS_FILTER_EAT;
2385 }
2386
2387 for (item = iks_child(pak->query); item; item = iks_next(item)) {
2388 struct ast_xmpp_buddy *buddy;
2389
2390 if (iks_strcmp(iks_name(item), "item")) {
2391 continue;
2392 }
2393
2394 if (!(buddy = ao2_find(client->buddies, iks_find_attrib(item, "jid"), OBJ_KEY))) {
2395 if (ast_test_flag(&clientcfg->flags, XMPP_AUTOPRUNE)) {
2396 /* The buddy has not been specified in the configuration file, we no longer
2397 * want them on our buddy list or to receive their presence. */
2398 if (xmpp_client_unsubscribe_user(client, iks_find_attrib(item, "jid"))) {
2399 ast_log(LOG_ERROR, "Could not unsubscribe user '%s' on client '%s'\n",
2400 iks_find_attrib(item, "jid"), client->name);
2401 }
2402 continue;
2403 }
2404
2405 if (!(buddy = xmpp_client_create_buddy(client->buddies, iks_find_attrib(item, "jid")))) {
2406 ast_log(LOG_ERROR, "Could not allocate buddy '%s' on client '%s'\n", iks_find_attrib(item, "jid"),
2407 client->name);
2408 continue;
2409 }
2410 }
2411
2412 /* Determine if we need to subscribe to their presence or not */
2413 if (!iks_strcmp(iks_find_attrib(item, "subscription"), "none") ||
2414 !iks_strcmp(iks_find_attrib(item, "subscription"), "from")) {
2415 buddy->subscribe = 1;
2416 } else {
2417 buddy->subscribe = 0;
2418 }
2419
2420 ao2_ref(buddy, -1);
2421 }
2422
2423 /* If autoregister is enabled we need to go through every buddy that we need to subscribe to and do so */
2424 if (ast_test_flag(&clientcfg->flags, XMPP_AUTOREGISTER)) {
2425 ao2_callback(client->buddies, OBJ_NODATA | OBJ_MULTIPLE, xmpp_client_subscribe_user, client);
2426 }
2427
2428 xmpp_client_change_state(client, XMPP_STATE_CONNECTED);
2429
2430 return IKS_FILTER_EAT;
2431 }
2432
2433 /*! \brief Internal function which changes the presence status of an XMPP client */
2434 static void xmpp_client_set_presence(struct ast_xmpp_client *client, const char *to, const char *from, int level, const char *desc)
2435 {
2436 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
2437 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
2438 iks *presence = NULL, *cnode = NULL, *priority = NULL;
2439 char priorityS[10];
2440
2441 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name)) ||
2442 !(presence = iks_make_pres(level, desc)) || !(cnode = iks_new("c")) || !(priority = iks_new("priority"))) {
2443 ast_log(LOG_ERROR, "Unable to allocate stanzas for setting presence status for client '%s'\n", client->name);
2444 goto done;
2445 }
2446
2447 if (!ast_strlen_zero(to)) {
2448 iks_insert_attrib(presence, "to", to);
2449 }
2450
2451 if (!ast_strlen_zero(from)) {
2452 iks_insert_attrib(presence, "from", from);
2453 }
2454
2455 snprintf(priorityS, sizeof(priorityS), "%d", clientcfg->priority);
2456 iks_insert_cdata(priority, priorityS, strlen(priorityS));
2457 iks_insert_node(presence, priority);
2458 iks_insert_attrib(cnode, "node", "http://www.asterisk.org/xmpp/client/caps");
2459 iks_insert_attrib(cnode, "ver", "asterisk-xmpp");
2460 iks_insert_attrib(cnode, "ext", "voice-v1 video-v1 camera-v1");
2461 iks_insert_attrib(cnode, "xmlns", "http://jabber.org/protocol/caps");
2462 iks_insert_node(presence, cnode);
2463 ast_xmpp_client_send(client, presence);
2464
2465 done:
2466 iks_delete(cnode);
2467 iks_delete(presence);
2468 iks_delete(priority);
2469 }
2470
2471 /*! \brief Hook function called when client receives a service discovery get message */
2472 static int xmpp_client_service_discovery_get_hook(void *data, ikspak *pak)
2473 {
2474 struct ast_xmpp_client *client = data;
2475 iks *iq, *disco = NULL, *ident = NULL, *google = NULL, *jingle = NULL, *ice = NULL, *rtp = NULL, *audio = NULL, *video = NULL, *query = NULL;
2476
2477 if (!(iq = iks_new("iq")) || !(query = iks_new("query")) || !(ident = iks_new("identity")) || !(disco = iks_new("feature")) ||
2478 !(google = iks_new("feature")) || !(jingle = iks_new("feature")) || !(ice = iks_new("feature")) || !(rtp = iks_new("feature")) ||
2479 !(audio = iks_new("feature")) || !(video = iks_new("feature"))) {
2480 ast_log(LOG_ERROR, "Could not allocate memory for responding to service discovery request from '%s' on client '%s'\n",
2481 pak->from->full, client->name);
2482 goto end;
2483 }
2484
2485 iks_insert_attrib(iq, "from", client->jid->full);
2486
2487 if (pak->from) {
2488 iks_insert_attrib(iq, "to", pak->from->full);
2489 }
2490
2491 iks_insert_attrib(iq, "type", "result");
2492 iks_insert_attrib(iq, "id", pak->id);
2493 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
2494 iks_insert_attrib(ident, "category", "client");
2495 iks_insert_attrib(ident, "type", "pc");
2496 iks_insert_attrib(ident, "name", "asterisk");
2497 iks_insert_attrib(disco, "var", "http://jabber.org/protocol/disco#info");
2498
2499 iks_insert_attrib(google, "var", "http://www.google.com/xmpp/protocol/voice/v1");
2500 iks_insert_attrib(jingle, "var", "urn:xmpp:jingle:1");
2501 iks_insert_attrib(ice, "var", "urn:xmpp:jingle:transports:ice-udp:1");
2502 iks_insert_attrib(rtp, "var", "urn:xmpp:jingle:apps:rtp:1");
2503 iks_insert_attrib(audio, "var", "urn:xmpp:jingle:apps:rtp:audio");
2504 iks_insert_attrib(video, "var", "urn:xmpp:jingle:apps:rtp:video");
2505 iks_insert_node(iq, query);
2506 iks_insert_node(query, ident);
2507 iks_insert_node(query, google);
2508 iks_insert_node(query, disco);
2509 iks_insert_node(query, jingle);
2510 iks_insert_node(query, ice);
2511 iks_insert_node(query, rtp);
2512 iks_insert_node(query, audio);
2513 iks_insert_node(query, video);
2514 ast_xmpp_client_send(client, iq);
2515
2516 end:
2517 iks_delete(query);
2518 iks_delete(video);
2519 iks_delete(audio);
2520 iks_delete(rtp);
2521 iks_delete(ice);
2522 iks_delete(jingle);
2523 iks_delete(google);
2524 iks_delete(ident);
2525 iks_delete(disco);
2526 iks_delete(iq);
2527
2528 return IKS_FILTER_EAT;
2529 }
2530
2531 /*! \brief Hook function called when client receives a service discovery result message */
2532 static int xmpp_client_service_discovery_result_hook(void *data, ikspak *pak)
2533 {
2534 struct ast_xmpp_client *client = data;
2535 struct ast_xmpp_buddy *buddy;
2536 struct ast_xmpp_resource *resource;
2537
2538 if (!(buddy = ao2_find(client->buddies, pak->from->partial, OBJ_KEY))) {
2539 return IKS_FILTER_EAT;
2540 }
2541
2542 if (!(resource = ao2_callback(buddy->resources, 0, xmpp_resource_cmp, pak->from->resource))) {
2543 ao2_ref(buddy, -1);
2544 return IKS_FILTER_EAT;
2545 }
2546
2547 ao2_lock(resource);
2548
2549 if (iks_find_with_attrib(pak->query, "feature", "var", "urn:xmpp:jingle:1")) {
2550 resource->caps.jingle = 1;
2551 }
2552
2553 ao2_unlock(resource);
2554
2555 ao2_ref(resource, -1);
2556 ao2_ref(buddy, -1);
2557
2558 return IKS_FILTER_EAT;
2559 }
2560
2561 /*! \brief Hook function called when client finishes authenticating with the server */
2562 static int xmpp_connect_hook(void *data, ikspak *pak)
2563 {
2564 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
2565 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
2566 struct ast_xmpp_client *client = data;
2567 iks *roster;
2568
2569 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name))) {
2570 return -1;
2571 }
2572
2573 client->jid = (iks_find_cdata(pak->query, "jid")) ? iks_id_new(client->stack, iks_find_cdata(pak->query, "jid")) : client->jid;
2574
2575 if (ast_test_flag(&clientcfg->flags, XMPP_DISTRIBUTE_EVENTS)) {
2576 xmpp_init_event_distribution(client);
2577 }
2578
2579 if (!(roster = iks_make_iq(IKS_TYPE_GET, IKS_NS_ROSTER))) {
2580 ast_log(LOG_ERROR, "Unable to allocate memory for roster request for client '%s'\n", client->name);
2581 return -1;
2582 }
2583
2584 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);
2585 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);
2586
2587 iks_insert_attrib(roster, "id", "roster");
2588 ast_xmpp_client_send(client, roster);
2589
2590 iks_filter_remove_hook(client->filter, xmpp_connect_hook);
2591 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);
2592
2593 xmpp_client_set_presence(client, NULL, client->jid->full, clientcfg->status, clientcfg->statusmsg);
2594 xmpp_client_change_state(client, XMPP_STATE_ROSTER);
2595
2596 return IKS_FILTER_EAT;
2597 }
2598
2599 /*! \brief Logging hook function */
2600 static void xmpp_log_hook(void *data, const char *xmpp, size_t size, int incoming)
2601 {
2602 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
2603 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
2604 struct ast_xmpp_client *client = data;
2605
2606 if (!debug && (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name)) || !ast_test_flag(&clientcfg->flags, XMPP_DEBUG))) {
2607 return;
2608 }
2609
2610 if (!incoming) {
2611 ast_verbose("\n<--- XMPP sent to '%s' --->\n%s\n<------------->\n", client->name, xmpp);
2612 } else {
2613 ast_verbose("\n<--- XMPP received from '%s' --->\n%s\n<------------->\n", client->name, xmpp);
2614 }
2615 }
2616
2617 /*! \brief Internal function which sends a raw message */
2618 static int xmpp_client_send_raw_message(struct ast_xmpp_client *client, const char *message)
2619 {
2620 int ret;
2621
2622 if (client->state == XMPP_STATE_DISCONNECTED) {
2623 /* iks_send_raw will crash without a connection */
2624 return IKS_NET_NOCONN;
2625 }
2626
2627 #ifdef HAVE_OPENSSL
2628 if (xmpp_is_secure(client)) {
2629 int len = strlen(message);
2630
2631 ret = SSL_write(client->ssl_session, message, len);
2632 if (ret) {
2633 /* Log the message here, because iksemel's logHook is
2634 unaccessible */
2635 xmpp_log_hook(client, message, len, 0);
2636 return IKS_OK;
2637 }
2638 }
2639 #endif
2640 /* If needed, data will be sent unencrypted, and logHook will
2641 be called inside iks_send_raw */
2642 ret = iks_send_raw(client->parser, message);
2643 if (ret != IKS_OK) {
2644 return ret;
2645 }
2646
2647 return IKS_OK;
2648 }
2649
2650 /*! \brief Helper function which sends an XMPP stream header to the server */
2651 static int xmpp_send_stream_header(struct ast_xmpp_client *client, const struct ast_xmpp_client_config *cfg, const char *to)
2652 {
2653 char *namespace = ast_test_flag(&cfg->flags, XMPP_COMPONENT) ? "jabber:component:accept" : "jabber:client";
2654 char msg[91 + strlen(namespace) + 6 + strlen(to) + 16 + 1];
2655
2656 snprintf(msg, sizeof(msg), "<?xml version='1.0'?>"
2657 "<stream:stream xmlns:stream='http://etherx.jabber.org/streams' xmlns='"
2658 "%s' to='%s' version='1.0'>", namespace, to);
2659
2660 return xmpp_client_send_raw_message(client, msg);
2661 }
2662
2663 int ast_xmpp_client_send(struct ast_xmpp_client *client, iks *stanza)
2664 {
2665 return xmpp_client_send_raw_message(client, iks_string(iks_stack(stanza), stanza));
2666 }
2667
2668 /*! \brief Internal function called when we need to request TLS support */
2669 static int xmpp_client_request_tls(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node)
2670 {
2671 /* If the client connection is already secure we can jump straight to authenticating */
2672 if (xmpp_is_secure(client)) {
2673 xmpp_client_change_state(client, XMPP_STATE_AUTHENTICATE);
2674 return 0;
2675 }
2676
2677 #ifndef HAVE_OPENSSL
2678 ast_log(LOG_ERROR, "TLS connection for client '%s' cannot be established. OpenSSL is not available.\n", client->name);
2679 return -1;
2680 #else
2681 if (iks_send_raw(client->parser, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>") == IKS_NET_TLSFAIL) {
2682 ast_log(LOG_ERROR, "TLS connection for client '%s' cannot be started.\n", client->name);
2683 return -1;
2684 }
2685
2686 client->stream_flags |= TRY_SECURE;
2687
2688 xmpp_client_change_state(client, XMPP_STATE_REQUESTED_TLS);
2689
2690 return 0;
2691 #endif
2692 }
2693
2694 #ifdef HAVE_OPENSSL
2695 static char *openssl_error_string(void)
2696 {
2697 char *buf = NULL, *ret;
2698 size_t len;
2699 BIO *bio = BIO_new(BIO_s_mem());
2700
2701 ERR_print_errors(bio);
2702 len = BIO_get_mem_data(bio, &buf);
2703 ret = ast_calloc(1, len + 1);
2704 if (ret) {
2705 memcpy(ret, buf, len);
2706 }
2707 BIO_free(bio);
2708 return ret;
2709 }
2710 #endif
2711
2712 /*! \brief Internal function called when we receive a response to our TLS initiation request */
2713 static int xmpp_client_requested_tls(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node)
2714 {
2715 #ifdef HAVE_OPENSSL
2716 int sock;
2717 long ssl_opts;
2718 char *err;
2719 #endif
2720
2721 if (!strcmp(iks_name(node), "success")) {
2722 /* TLS is up and working, we can move on to authenticating now */
2723 xmpp_client_change_state(client, XMPP_STATE_AUTHENTICATE);
2724 return 0;
2725 } else if (!strcmp(iks_name(node), "failure")) {
2726 /* TLS negotiation was a failure, close it on down! */
2727 return -1;
2728 } else if (strcmp(iks_name(node), "proceed")) {
2729 /* Ignore any other responses */
2730 return 0;
2731 }
2732
2733 #ifndef HAVE_OPENSSL
2734 ast_log(LOG_ERROR, "Somehow we managed to try to start TLS negotiation on client '%s' without OpenSSL support, disconnecting\n", client->name);
2735 return -1;
2736 #else
2737 client->ssl_method = SSLv23_method();
2738 if (!(client->ssl_context = SSL_CTX_new((SSL_METHOD *) client->ssl_method))) {
2739 goto failure;
2740 }
2741
2742 ssl_opts = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
2743 SSL_CTX_set_options(client->ssl_context, ssl_opts);
2744
2745 if (!(client->ssl_session = SSL_new(client->ssl_context))) {
2746 goto failure;
2747 }
2748
2749 sock = iks_fd(client->parser);
2750 if (!SSL_set_fd(client->ssl_session, sock)) {
2751 goto failure;
2752 }
2753
2754 if (SSL_connect(client->ssl_session) <= 0) {
2755 goto failure;
2756 }
2757
2758 client->stream_flags &= (~TRY_SECURE);
2759 client->stream_flags |= SECURE;
2760
2761 if (xmpp_send_stream_header(client, cfg, client->jid->server) != IKS_OK) {
2762 ast_log(LOG_ERROR, "TLS connection for client '%s' could not be established, failed to send stream header after negotiation\n",
2763 client->name);
2764 return -1;
2765 }
2766
2767 ast_debug(1, "TLS connection for client '%s' started with server\n", client->name);
2768
2769 xmpp_client_change_state(client, XMPP_STATE_AUTHENTICATE);
2770
2771 return 0;
2772
2773 failure:
2774 err = openssl_error_string();
2775 ast_log(LOG_ERROR, "TLS connection for client '%s' cannot be established. "
2776 "OpenSSL initialization failed: %s\n", client->name, err);
2777 ast_free(err);
2778 return -1;
2779 #endif
2780 }
2781
2782 /*! \brief Internal function called when we need to authenticate using non-SASL */
2783 static int xmpp_client_authenticate_digest(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node)
2784 {
2785 iks *iq = NULL, *query = NULL;
2786 char buf[41], sidpass[100];
2787
2788 if (!(iq = iks_new("iq")) || !(query = iks_insert(iq, "query"))) {
2789 ast_log(LOG_ERROR, "Stanzas could not be allocated for authentication on client '%s'\n", client->name);
2790 iks_delete(iq);
2791 return -1;
2792 }
2793
2794 iks_insert_attrib(iq, "type", "set");
2795 iks_insert_cdata(iks_insert(query, "username"), client->jid->user, 0);
2796 iks_insert_cdata(iks_insert(query, "resource"), client->jid->resource, 0);
2797
2798 iks_insert_attrib(query, "xmlns", "jabber:iq:auth");
2799 snprintf(sidpass, sizeof(sidpass), "%s%s", iks_find_attrib(node, "id"), cfg->password);
2800 ast_sha1_hash(buf, sidpass);
2801 iks_insert_cdata(iks_insert(query, "digest"), buf, 0);
2802
2803 ast_xmpp_client_lock(client);
2804 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);
2805 iks_insert_attrib(iq, "id", client->mid);
2806 ast_xmpp_increment_mid(client->mid);
2807 ast_xmpp_client_unlock(client);
2808
2809 iks_insert_attrib(iq, "to", client->jid->server);
2810
2811 ast_xmpp_client_send(client, iq);
2812
2813 iks_delete(iq);
2814
2815 xmpp_client_change_state(client, XMPP_STATE_AUTHENTICATING);
2816
2817 return 0;
2818 }
2819
2820 /*! \brief Internal function called when we need to authenticate using SASL */
2821 static int xmpp_client_authenticate_sasl(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node)
2822 {
2823 int features, len = strlen(client->jid->user) + strlen(cfg->password) + 3;
2824 iks *auth;
2825 char combined[len];
2826 char base64[(len + 2) * 4 / 3];
2827
2828 if (strcmp(iks_name(node), "stream:features")) {
2829 /* Ignore anything beside stream features */
2830 return 0;
2831 }
2832
2833 features = iks_stream_features(node);
2834
2835 if ((features & IKS_STREAM_SASL_MD5) && !xmpp_is_secure(client)) {
2836 if (iks_start_sasl(client->parser, IKS_SASL_DIGEST_MD5, (char*)client->jid->user, (char*)cfg->password) != IKS_OK) {
2837 ast_log(LOG_ERROR, "Tried to authenticate client '%s' using SASL DIGEST-MD5 but could not\n", client->name);
2838 return -1;
2839 }
2840
2841 xmpp_client_change_state(client, XMPP_STATE_AUTHENTICATING);
2842 return 0;
2843 }
2844
2845 /* Our only other available option is plain so if they don't support it, bail out now */
2846 if (!(features & IKS_STREAM_SASL_PLAIN)) {
2847 ast_log(LOG_ERROR, "Tried to authenticate client '%s' using SASL PLAIN but server does not support it\n", client->name);
2848 return -1;
2849 }
2850
2851 if (!(auth = iks_new("auth"))) {
2852 ast_log(LOG_ERROR, "Could not allocate memory for SASL PLAIN authentication for client '%s'\n", client->name);
2853 return -1;
2854 }
2855
2856 iks_insert_attrib(auth, "xmlns", IKS_NS_XMPP_SASL);
2857 if (!ast_strlen_zero(cfg->refresh_token)) {
2858 iks_insert_attrib(auth, "mechanism", "X-OAUTH2");
2859 iks_insert_attrib(auth, "auth:service", "oauth2");
2860 iks_insert_attrib(auth, "xmlns:auth", "http://www.google.com/talk/protocol/auth");
2861 } else {
2862 iks_insert_attrib(auth, "mechanism", "PLAIN");
2863 }
2864
2865 if (strchr(client->jid->user, '/')) {
2866 char *user = ast_strdupa(client->jid->user);
2867
2868 snprintf(combined, sizeof(combined), "%c%s%c%s", 0, strsep(&user, "/"), 0, cfg->password);
2869 } else {
2870 snprintf(combined, sizeof(combined), "%c%s%c%s", 0, client->jid->user, 0, cfg->password);
2871 }
2872
2873 ast_base64encode(base64, (const unsigned char *) combined, len - 1, (len + 2) * 4 / 3);
2874 iks_insert_cdata(auth, base64, 0);
2875
2876 ast_xmpp_client_send(client, auth);
2877
2878 iks_delete(auth);
2879
2880 xmpp_client_change_state(client, XMPP_STATE_AUTHENTICATING);
2881
2882 return 0;
2883 }
2884
2885 /*! \brief Internal function called when we need to authenticate */
2886 static int xmpp_client_authenticate(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node)
2887 {
2888 return ast_test_flag(&cfg->flags, XMPP_USESASL) ? xmpp_client_authenticate_sasl(client, cfg, type, node) : xmpp_client_authenticate_digest(client, cfg, type, node);
2889 }
2890
2891 /*! \brief Internal function called when we are authenticating */
2892 static int xmpp_client_authenticating(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node)
2893 {
2894 int features;
2895
2896 if (!strcmp(iks_name(node), "success")) {
2897 /* Authentication was a success, yay! */
2898 xmpp_send_stream_header(client, cfg, client->jid->server);
2899
2900 return 0;
2901 } else if (!strcmp(iks_name(node), "failure")) {
2902 /* Authentication was a bust, disconnect and reconnect later */
2903 return -1;
2904 } else if (strcmp(iks_name(node), "stream:features")) {
2905 /* Ignore any other responses */
2906 return 0;
2907 }
2908
2909 features = iks_stream_features(node);
2910
2911 if (features & IKS_STREAM_BIND) {
2912 iks *auth;
2913
2914 if (!(auth = iks_make_resource_bind(client->jid))) {
2915 ast_log(LOG_ERROR, "Failed to allocate memory for stream bind on client '%s'\n", client->name);
2916 return -1;
2917 }
2918
2919 ast_xmpp_client_lock(client);
2920 iks_insert_attrib(auth, "id", client->mid);
2921 ast_xmpp_increment_mid(client->mid);
2922 ast_xmpp_client_unlock(client);
2923 ast_xmpp_client_send(client, auth);
2924
2925 iks_delete(auth);
2926
2927 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);
2928 }
2929
2930 if (features & IKS_STREAM_SESSION) {
2931 iks *auth;
2932
2933 if (!(auth = iks_make_session())) {
2934 ast_log(LOG_ERROR, "Failed to allocate memory for stream session on client '%s'\n", client->name);
2935 return -1;
2936 }
2937
2938 iks_insert_attrib(auth, "id", "auth");
2939 ast_xmpp_client_lock(client);
2940 ast_xmpp_increment_mid(client->mid);
2941 ast_xmpp_client_unlock(client);
2942 ast_xmpp_client_send(client, auth);
2943
2944 iks_delete(auth);
2945
2946 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);
2947 }
2948
2949 return 0;
2950 }
2951
2952 /*! \brief Internal function called when we should authenticate as a component */
2953 static int xmpp_component_authenticate(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node)
2954 {
2955 char secret[160], shasum[320], message[344];
2956 ikspak *pak = iks_packet(node);
2957
2958 snprintf(secret, sizeof(secret), "%s%s", pak->id, cfg->password);
2959 ast_sha1_hash(shasum, secret);
2960 snprintf(message, sizeof(message), "<handshake>%s</handshake>", shasum);
2961
2962 if (xmpp_client_send_raw_message(client, message) != IKS_OK) {
2963 ast_log(LOG_ERROR, "Unable to send handshake for component '%s'\n", client->name);
2964 return -1;
2965 }
2966
2967 xmpp_client_change_state(client, XMPP_STATE_AUTHENTICATING);
2968
2969 return 0;
2970 }
2971
2972 /*! \brief Hook function called when component receives a service discovery get message */
2973 static int xmpp_component_service_discovery_get_hook(void *data, ikspak *pak)
2974 {
2975 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
2976 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
2977 struct ast_xmpp_client *client = data;
2978 iks *iq = NULL, *query = NULL, *identity = NULL, *disco = NULL, *reg = NULL, *commands = NULL, *gateway = NULL;
2979 iks *version = NULL, *vcard = NULL, *search = NULL, *item = NULL;
2980 char *node;
2981
2982 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name)) ||
2983 !(iq = iks_new("iq")) || !(query = iks_new("query")) || !(identity = iks_new("identity")) || !(disco = iks_new("feature")) ||
2984 !(reg = iks_new("feature")) || !(commands = iks_new("feature")) || !(gateway = iks_new("feature")) || !(version = iks_new("feature")) ||
2985 !(vcard = iks_new("feature")) || !(search = iks_new("search")) || !(item = iks_new("item"))) {
2986 ast_log(LOG_ERROR, "Failed to allocate stanzas for service discovery get response to '%s' on component '%s'\n",
2987 pak->from->partial, client->name);
2988 goto done;
2989 }
2990
2991 iks_insert_attrib(iq, "from", clientcfg->user);
2992 iks_insert_attrib(iq, "to", pak->from->full);
2993 iks_insert_attrib(iq, "id", pak->id);
2994 iks_insert_attrib(iq, "type", "result");
2995
2996 if (!(node = iks_find_attrib(pak->query, "node"))) {
2997 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
2998 iks_insert_attrib(identity, "category", "gateway");
2999 iks_insert_attrib(identity, "type", "pstn");
3000 iks_insert_attrib(identity, "name", "Asterisk The Open Source PBX");
3001 iks_insert_attrib(disco, "var", "http://jabber.org/protocol/disco");
3002 iks_insert_attrib(reg, "var", "jabber:iq:register");
3003 iks_insert_attrib(commands, "var", "http://jabber.org/protocol/commands");
3004 iks_insert_attrib(gateway, "var", "jabber:iq:gateway");
3005 iks_insert_attrib(version, "var", "jabber:iq:version");
3006 iks_insert_attrib(vcard, "var", "vcard-temp");
3007 iks_insert_attrib(search, "var", "jabber:iq:search");
3008
3009 iks_insert_node(iq, query);
3010 iks_insert_node(query, identity);
3011 iks_insert_node(query, disco);
3012 iks_insert_node(query, reg);
3013 iks_insert_node(query, commands);
3014 iks_insert_node(query, gateway);
3015 iks_insert_node(query, version);
3016 iks_insert_node(query, vcard);
3017 iks_insert_node(query, search);
3018 } else if (!strcasecmp(node, "http://jabber.org/protocol/commands")) {
3019 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
3020 iks_insert_attrib(query, "node", "http://jabber.org/protocol/commands");
3021 iks_insert_attrib(item, "node", "confirmaccount");
3022 iks_insert_attrib(item, "name", "Confirm account");
3023 iks_insert_attrib(item, "jid", clientcfg->user);
3024
3025 iks_insert_node(iq, query);
3026 iks_insert_node(query, item);
3027 } else if (!strcasecmp(node, "confirmaccount")) {
3028 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
3029 iks_insert_attrib(commands, "var", "http://jabber.org/protocol/commands");
3030
3031 iks_insert_node(iq, query);
3032 iks_insert_node(query, commands);
3033 } else {
3034 ast_debug(3, "Unsupported service discovery info request received with node '%s' on component '%s'\n",
3035 node, client->name);
3036 goto done;
3037 }
3038
3039 if (ast_xmpp_client_send(client, iq)) {
3040 ast_log(LOG_WARNING, "Could not send response to service discovery request on component '%s'\n",
3041 client->name);
3042 }
3043
3044 done:
3045 iks_delete(search);
3046 iks_delete(vcard);
3047 iks_delete(version);
3048 iks_delete(gateway);
3049 iks_delete(commands);
3050 iks_delete(reg);
3051 iks_delete(disco);
3052 iks_delete(identity);
3053 iks_delete(query);
3054 iks_delete(iq);
3055
3056 return IKS_FILTER_EAT;
3057 }
3058
3059 /*! \brief Hook function called when the component is queried about registration */
3060 static int xmpp_component_register_get_hook(void *data, ikspak *pak)
3061 {
3062 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
3063 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
3064 struct ast_xmpp_client *client = data;
3065 iks *iq = NULL, *query = NULL, *error = NULL, *notacceptable = NULL, *instructions = NULL;
3066 struct ast_xmpp_buddy *buddy;
3067 char *node;
3068
3069 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name)) ||
3070 !(iq = iks_new("iq")) || !(query = iks_new("query")) || !(error = iks_new("error")) || !(notacceptable = iks_new("not-acceptable")) ||
3071 !(instructions = iks_new("instructions"))) {
3072 ast_log(LOG_ERROR, "Failed to allocate stanzas for register get response to '%s' on component '%s'\n",
3073 pak->from->partial, client->name);
3074 goto done;
3075 }
3076
3077 iks_insert_attrib(iq, "from", clientcfg->user);
3078 iks_insert_attrib(iq, "to", pak->from->full);
3079 iks_insert_attrib(iq, "id", pak->id);
3080 iks_insert_attrib(iq, "type", "result");
3081 iks_insert_attrib(query, "xmlns", "jabber:iq:register");
3082 iks_insert_node(iq, query);
3083
3084 if (!(buddy = ao2_find(client->buddies, pak->from->partial, OBJ_KEY))) {
3085 iks_insert_attrib(error, "code", "406");
3086 iks_insert_attrib(error, "type", "modify");
3087 iks_insert_attrib(notacceptable, "xmlns", "urn:ietf:params:xml:ns:xmpp-stanzas");
3088
3089 iks_insert_node(iq, error);
3090 iks_insert_node(error, notacceptable);
3091
3092 ast_log(LOG_ERROR, "Received register attempt from '%s' but buddy is not configured on component '%s'\n",
3093 pak->from->partial, client->name);
3094 } else if (!(node = iks_find_attrib(pak->query, "node"))) {
3095 iks_insert_cdata(instructions, "Welcome to Asterisk - the Open Source PBX.\n", 0);
3096 iks_insert_node(query, instructions);
3097 ao2_ref(buddy, -1);
3098 } else {
3099 ast_log(LOG_WARNING, "Received register get to component '%s' using unsupported node '%s' from '%s'\n",
3100 client->name, node, pak->from->partial);
3101 ao2_ref(buddy, -1);
3102 goto done;
3103 }
3104
3105 if (ast_xmpp_client_send(client, iq)) {
3106 ast_log(LOG_WARNING, "Could not send response to '%s' for received register get on component '%s'\n",
3107 pak->from->partial, client->name);
3108 }
3109
3110 done:
3111 iks_delete(instructions);
3112 iks_delete(notacceptable);
3113 iks_delete(error);
3114 iks_delete(query);
3115 iks_delete(iq);
3116
3117 return IKS_FILTER_EAT;
3118 }
3119
3120 /*! \brief Hook function called when someone registers to the component */
3121 static int xmpp_component_register_set_hook(void *data, ikspak *pak)
3122 {
3123 struct ast_xmpp_client *client = data;
3124 iks *iq, *presence = NULL, *x = NULL;
3125
3126 if (!(iq = iks_new("iq")) || !(presence = iks_new("presence")) || !(x = iks_new("x"))) {
3127 ast_log(LOG_ERROR, "Failed to allocate stanzas for register set response to '%s' on component '%s'\n",
3128 pak->from->partial, client->name);
3129 goto done;
3130 }
3131
3132 iks_insert_attrib(iq, "from", client->jid->full);
3133 iks_insert_attrib(iq, "to", pak->from->full);
3134 iks_insert_attrib(iq, "id", pak->id);
3135 iks_insert_attrib(iq, "type", "result");
3136
3137 if (ast_xmpp_client_send(client, iq)) {
3138 ast_log(LOG_WARNING, "Could not send response to '%s' for received register set on component '%s'\n",
3139 pak->from->partial, client->name);
3140 goto done;
3141 }
3142
3143 iks_insert_attrib(presence, "from", client->jid->full);
3144 iks_insert_attrib(presence, "to", pak->from->partial);
3145 ast_xmpp_client_lock(client);
3146 iks_insert_attrib(presence, "id", client->mid);
3147 ast_xmpp_increment_mid(client->mid);
3148 ast_xmpp_client_unlock(client);
3149 iks_insert_attrib(presence, "type", "subscribe");
3150 iks_insert_attrib(x, "xmlns", "vcard-temp:x:update");
3151
3152 iks_insert_node(presence, x);
3153
3154 if (ast_xmpp_client_send(client, presence)) {
3155 ast_log(LOG_WARNING, "Could not send subscription to '%s' on component '%s'\n",
3156 pak->from->partial, client->name);
3157 }
3158
3159 done:
3160 iks_delete(x);
3161 iks_delete(presence);
3162 iks_delete(iq);
3163
3164 return IKS_FILTER_EAT;
3165 }
3166
3167 /*! \brief Hook function called when we receive a service discovery items request */
3168 static int xmpp_component_service_discovery_items_hook(void *data, ikspak *pak)
3169 {
3170 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
3171 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
3172 struct ast_xmpp_client *client = data;
3173 iks *iq = NULL, *query = NULL, *item = NULL, *feature = NULL;
3174 char *node;
3175
3176 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name)) ||
3177 !(iq = iks_new("iq")) || !(query = iks_new("query")) || !(item = iks_new("item")) || !(feature = iks_new("feature"))) {
3178 ast_log(LOG_ERROR, "Failed to allocate stanzas for service discovery items response to '%s' on component '%s'\n",
3179 pak->from->partial, client->name);
3180 goto done;
3181 }
3182
3183 iks_insert_attrib(iq, "from", clientcfg->user);
3184 iks_insert_attrib(iq, "to", pak->from->full);
3185 iks_insert_attrib(iq, "id", pak->id);
3186 iks_insert_attrib(iq, "type", "result");
3187 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
3188 iks_insert_node(iq, query);
3189
3190 if (!(node = iks_find_attrib(pak->query, "node"))) {
3191 iks_insert_attrib(item, "node", "http://jabber.org/protocol/commands");
3192 iks_insert_attrib(item, "name", "Asterisk Commands");
3193 iks_insert_attrib(item, "jid", clientcfg->user);
3194
3195 iks_insert_node(query, item);
3196 } else if (!strcasecmp(node, "http://jabber.org/protocol/commands")) {
3197 iks_insert_attrib(query, "node", "http://jabber.org/protocol/commands");
3198 } else {
3199 ast_log(LOG_WARNING, "Received service discovery items request to component '%s' using unsupported node '%s' from '%s'\n",
3200 client->name, node, pak->from->partial);
3201 goto done;
3202 }
3203
3204 if (ast_xmpp_client_send(client, iq)) {
3205 ast_log(LOG_WARNING, "Could not send response to service discovery items request from '%s' on component '%s'\n",
3206 pak->from->partial, client->name);
3207 }
3208
3209 done:
3210 iks_delete(feature);
3211 iks_delete(item);
3212 iks_delete(query);
3213 iks_delete(iq);
3214
3215 return IKS_FILTER_EAT;
3216 }
3217
3218 /*! \brief Internal function called when we authenticated as a component */
3219 static int xmpp_component_authenticating(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, int type, iks *node)
3220 {
3221 if (!strcmp(iks_name(node), "stream:features")) {
3222 return 0;
3223 }
3224
3225 if (strcmp(iks_name(node), "handshake")) {
3226 ast_log(LOG_ERROR, "Failed to authenticate component '%s'\n", client->name);
3227 return -1;
3228 }
3229
3230 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);
3231
3232 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);
3233
3234 /* This uses the client service discovery result hook on purpose, as the code is common between both */
3235 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);
3236
3237 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);
3238 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);
3239
3240 xmpp_client_change_state(client, XMPP_STATE_CONNECTED);
3241
3242 return 0;
3243 }
3244
3245 /*! \brief Internal function called when a message is received */
3246 static int xmpp_pak_message(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, iks *node, ikspak *pak)
3247 {
3248 struct ast_xmpp_message *message;
3249 char *body;
3250 int deleted = 0;
3251
3252 ast_debug(3, "XMPP client '%s' received a message\n", client->name);
3253
3254 if (!(body = iks_find_cdata(pak->x, "body"))) {
3255 /* Message contains no body, ignore it. */
3256 return 0;
3257 }
3258
3259 if (!(message = ast_calloc(1, sizeof(*message)))) {
3260 return -1;
3261 }
3262
3263 message->arrived = ast_tvnow();
3264
3265 message->message = ast_strdup(body);
3266
3267 ast_copy_string(message->id, S_OR(pak->id, ""), sizeof(message->id));
3268 message->from = !ast_strlen_zero(pak->from->full) ? ast_strdup(pak->from->full) : NULL;
3269
3270 if (ast_test_flag(&cfg->flags, XMPP_SEND_TO_DIALPLAN)) {
3271 struct ast_msg *msg;
3272 struct ast_xmpp_buddy *buddy;
3273
3274 if ((msg = ast_msg_alloc())) {
3275 int res;
3276
3277 ast_xmpp_client_lock(client);
3278
3279 buddy = ao2_find(client->buddies, pak->from->partial, OBJ_KEY | OBJ_NOLOCK);
3280
3281 res = ast_msg_set_to(msg, "xmpp:%s", cfg->user);
3282 res |= ast_msg_set_from(msg, "xmpp:%s", message->from);
3283 res |= ast_msg_set_body(msg, "%s", message->message);
3284 res |= ast_msg_set_context(msg, "%s", cfg->context);
3285 res |= ast_msg_set_tech(msg, "%s", "XMPP");
3286 res |= ast_msg_set_endpoint(msg, "%s", client->name);
3287
3288 if (buddy) {
3289 res |= ast_msg_set_var(msg, "XMPP_BUDDY", buddy->id);
3290 }
3291
3292 ao2_cleanup(buddy);
3293
3294 ast_xmpp_client_unlock(client);
3295
3296 if (res) {
3297 ast_msg_destroy(msg);
3298 } else {
3299 ast_msg_queue(msg);
3300 }
3301 }
3302 }
3303
3304 /* remove old messages received from this JID
3305 * and insert received message */
3306 deleted = delete_old_messages(client, pak->from->partial);
3307 ast_debug(3, "Deleted %d messages for client %s from JID %s\n", deleted, client->name, pak->from->partial);
3308 AST_LIST_LOCK(&client->messages);
3309 AST_LIST_INSERT_HEAD(&client->messages, message, list);
3310 AST_LIST_UNLOCK(&client->messages);
3311
3312 /* wake up threads waiting for messages */
3313 ast_mutex_lock(&messagelock);
3314 ast_cond_broadcast(&message_received_condition);
3315 ast_mutex_unlock(&messagelock);
3316
3317 return 0;
3318 }
3319
3320 /*! \brief Helper function which sends a discovery information request to a user */
3321 static int xmpp_client_send_disco_info_request(struct ast_xmpp_client *client, const char *to, const char *from)
3322 {
3323 iks *iq, *query;
3324 int res;
3325
3326 if (!(iq = iks_new("iq")) || !(query = iks_new("query"))) {
3327 iks_delete(iq);
3328 return -1;
3329 }
3330
3331 iks_insert_attrib(iq, "type", "get");
3332 iks_insert_attrib(iq, "to", to);
3333 iks_insert_attrib(iq, "from", from);
3334 ast_xmpp_client_lock(client);
3335 iks_insert_attrib(iq, "id", client->mid);
3336 ast_xmpp_increment_mid(client->mid);
3337 ast_xmpp_client_unlock(client);
3338 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
3339 iks_insert_node(iq, query);
3340
3341 res = ast_xmpp_client_send(client, iq);
3342
3343 iks_delete(query);
3344 iks_delete(iq);
3345
3346 return res;
3347 }
3348
3349 /*! \brief Callback function which returns when the resource is available */
3350 static int xmpp_resource_is_available(void *obj, void *arg, int flags)
3351 {
3352 struct ast_xmpp_resource *resource = obj;
3353
3354 return (resource->status == IKS_SHOW_AVAILABLE) ? CMP_MATCH | CMP_STOP : 0;
3355 }
3356
3357 /*! \brief Helper function which sends a ping request to a server */
3358 static int xmpp_ping_request(struct ast_xmpp_client *client, const char *to, const char *from)
3359 {
3360 iks *iq, *ping;
3361 int res;
3362
3363 ast_debug(2, "JABBER: Sending Keep-Alive Ping for client '%s'\n", client->name);
3364
3365 if (!(iq = iks_new("iq")) || !(ping = iks_new("ping"))) {
3366 iks_delete(iq);
3367 return -1;
3368 }
3369
3370 iks_insert_attrib(iq, "type", "get");
3371 iks_insert_attrib(iq, "to", to);
3372 iks_insert_attrib(iq, "from", from);
3373
3374 ast_xmpp_client_lock(client);
3375 iks_insert_attrib(iq, "id", client->mid);
3376 ast_xmpp_increment_mid(client->mid);
3377 ast_xmpp_client_unlock(client);
3378
3379 iks_insert_attrib(ping, "xmlns", "urn:xmpp:ping");
3380 iks_insert_node(iq, ping);
3381
3382 res = ast_xmpp_client_send(client, iq);
3383
3384 iks_delete(ping);
3385 iks_delete(iq);
3386
3387
3388 return res;
3389 }
3390
3391 /*! \brief Internal function called when a presence message is received */
3392 static int xmpp_pak_presence(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg, iks *node, ikspak *pak)
3393 {
3394 struct ast_xmpp_buddy *buddy;
3395 struct ast_xmpp_resource *resource;
3396 char *type = iks_find_attrib(pak->x, "type");
3397 int status = pak->show ? pak->show : STATUS_DISAPPEAR;
3398 enum ast_device_state state = AST_DEVICE_UNAVAILABLE;
3399
3400 /* If this is a component presence probe request answer immediately with our presence status */
3401 if (ast_test_flag(&cfg->flags, XMPP_COMPONENT) && !ast_strlen_zero(type) && !strcasecmp(type, "probe")) {
3402 xmpp_client_set_presence(client, pak->from->full, iks_find_attrib(pak->x, "to"), cfg->status, cfg->statusmsg);
3403 }
3404
3405 /* If no resource is available this is a general buddy presence update, which we will ignore */
3406 if (!pak->from->resource) {
3407 return 0;
3408 }
3409
3410 if (!(buddy = ao2_find(client->buddies, pak->from->partial, OBJ_KEY))) {
3411 /* Only output the message if it is not about us */
3412 if (strcmp(client->jid->partial, pak->from->partial)) {
3413 ast_log(LOG_WARNING, "Received presence information about '%s' despite not having them in roster on client '%s'\n",
3414 pak->from->partial, client->name);
3415 }
3416 return 0;
3417 }
3418
3419 ao2_lock(buddy->resources);
3420
3421 if (!(resource = ao2_callback(buddy->resources, OBJ_NOLOCK, xmpp_resource_cmp, pak->from->resource))) {
3422 /* Only create the new resource if it is not going away - in reality this should not happen */
3423 if (status != STATUS_DISAPPEAR) {
3424 if (!(resource = ao2_alloc(sizeof(*resource), xmpp_resource_destructor))) {
3425 ast_log(LOG_ERROR, "Could not allocate resource object for resource '%s' of buddy '%s' on client '%s'\n",
3426 pak->from->resource, buddy->id, client->name);
3427 ao2_unlock(buddy->resources);
3428 ao2_ref(buddy, -1);
3429 return 0;
3430 }
3431
3432 ast_copy_string(resource->resource, pak->from->resource, sizeof(resource->resource));
3433 }
3434 } else {
3435 /* We unlink the resource in case the priority changes or in case they are going away */
3436 ao2_unlink_flags(buddy->resources, resource, OBJ_NOLOCK);
3437 }
3438
3439 /* Only update the resource and add it back in if it is not going away */
3440 if (resource && (status != STATUS_DISAPPEAR)) {
3441 char *node, *ver;
3442
3443 /* Try to get the XMPP spec node, and fall back to Google if not found */
3444 if (!(node = iks_find_attrib(iks_find(pak->x, "c"), "node"))) {
3445 node = iks_find_attrib(iks_find(pak->x, "caps:c"), "node");
3446 }
3447
3448 if (!(ver = iks_find_attrib(iks_find(pak->x, "c"), "ver"))) {
3449 ver = iks_find_attrib(iks_find(pak->x, "caps:c"), "ver");
3450 }
3451
3452 if (resource->description) {
3453 ast_free(resource->description);
3454 }
3455
3456 if ((node && strcmp(resource->caps.node, node)) || (ver && strcmp(resource->caps.version, ver))) {
3457 /* For interoperability reasons, proceed even if the resource fails to provide node or version */
3458 if (node) {
3459 ast_copy_string(resource->caps.node, node, sizeof(resource->caps.node));
3460 }
3461 if (ver) {
3462 ast_copy_string(resource->caps.version, ver, sizeof(resource->caps.version));
3463 }
3464
3465 /* Google Talk places the capabilities information directly in presence, so see if it is there */
3466 if (iks_find_with_attrib(pak->x, "c", "node", "http://www.google.com/xmpp/client/caps") ||
3467 iks_find_with_attrib(pak->x, "caps:c", "node", "http://www.google.com/xmpp/client/caps") ||
3468 iks_find_with_attrib(pak->x, "c", "node", "http://www.android.com/gtalk/client/caps") ||
3469 iks_find_with_attrib(pak->x, "caps:c", "node", "http://www.android.com/gtalk/client/caps") ||
3470 iks_find_with_attrib(pak->x, "c", "node", "http://mail.google.com/xmpp/client/caps") ||
3471 iks_find_with_attrib(pak->x, "caps:c", "node", "http://mail.google.com/xmpp/client/caps")) {
3472 resource->caps.google = 1;
3473 }
3474
3475 /* To discover if the buddy supports Jingle we need to query, so do so */
3476 if (xmpp_client_send_disco_info_request(client, pak->from->full, client->jid->full)) {
3477 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);
3478 }
3479 }
3480
3481 resource->status = status;
3482 resource->description = ast_strdup(iks_find_cdata(pak->x, "status"));
3483 resource->priority = atoi((iks_find_cdata(pak->x, "priority")) ? iks_find_cdata(pak->x, "priority") : "0");
3484
3485 ao2_link_flags(buddy->resources, resource, OBJ_NOLOCK);
3486
3487 manager_event(EVENT_FLAG_USER, "JabberStatus",
3488 "Account: %s\r\nJID: %s\r\nResource: %s\r\nStatus: %d\r\nPriority: %d"
3489 "\r\nDescription: %s\r\n",
3490 client->name, pak->from->partial, resource->resource, resource->status,
3491 resource->priority, S_OR(resource->description, ""));
3492
3493 ao2_ref(resource, -1);
3494 } else {
3495 /* This will get hit by presence coming in for an unknown resource, and also when a resource goes away */
3496 if (resource) {
3497 ao2_ref(resource, -1);
3498 }
3499
3500 manager_event(EVENT_FLAG_USER, "JabberStatus",
3501 "Account: %s\r\nJID: %s\r\nStatus: %u\r\n",
3502 client->name, pak->from->partial, pak->show ? pak->show : IKS_SHOW_UNAVAILABLE);
3503 }
3504
3505 /* Determine if at least one resource is available for device state purposes */
3506 if ((resource = ao2_callback(buddy->resources, OBJ_NOLOCK, xmpp_resource_is_available, NULL))) {
3507 state = AST_DEVICE_NOT_INUSE;
3508 ao2_ref(resource, -1);
3509 }
3510
3511 ao2_unlock(buddy->resources);
3512
3513 ao2_ref(buddy, -1);
3514
3515 ast_devstate_changed(state, AST_DEVSTATE_CACHABLE, "XMPP/%s/%s", client->name, pak->from->partial);
3516
3517 return 0;
3518 }
3519
3520 /*! \brief Internal function called when a subscription message is received */
3521 static int xmpp_pak_s10n(struct ast_xmpp_client *client, struct ast_xmpp_client_config *cfg,iks *node, ikspak *pak)
3522 {
3523 struct ast_xmpp_buddy *buddy;
3524
3525 switch (pak->subtype) {
3526 case IKS_TYPE_SUBSCRIBE:
3527 if (ast_test_flag(&cfg->flags, XMPP_AUTOREGISTER)) {
3528 iks *presence, *status = NULL;
3529
3530 if ((presence = iks_new("presence")) && (status = iks_new("status"))) {
3531 iks_insert_attrib(presence, "type", "subscribed");
3532 iks_insert_attrib(presence, "to", pak->from->full);
3533 iks_insert_attrib(presence, "from", client->jid->full);
3534
3535 if (pak->id) {
3536 iks_insert_attrib(presence, "id", pak->id);
3537 }
3538
3539 iks_insert_cdata(status, "Asterisk has approved your subscription", 0);
3540 iks_insert_node(presence, status);
3541
3542 if (ast_xmpp_client_send(client, presence)) {
3543 ast_log(LOG_ERROR, "Could not send subscription acceptance to '%s' from client '%s'\n",
3544 pak->from->partial, client->name);
3545 }
3546 } else {
3547 ast_log(LOG_ERROR, "Could not allocate presence stanzas for accepting subscription from '%s' to client '%s'\n",
3548 pak->from->partial, client->name);
3549 }
3550
3551 iks_delete(status);
3552 iks_delete(presence);
3553 }
3554
3555 if (ast_test_flag(&cfg->flags, XMPP_COMPONENT)) {
3556 xmpp_client_set_presence(client, pak->from->full, iks_find_attrib(pak->x, "to"), cfg->status, cfg->statusmsg);
3557 }
3558 /* This purposely flows through so we have the subscriber amongst our buddies */
3559 case IKS_TYPE_SUBSCRIBED:
3560 ao2_lock(client->buddies);
3561
3562 if (!(buddy = ao2_find(client->buddies, pak->from->partial, OBJ_KEY | OBJ_NOLOCK))) {
3563 buddy = xmpp_client_create_buddy(client->buddies, pak->from->partial);
3564 }
3565
3566 if (!buddy) {
3567 ast_log(LOG_WARNING, "Could not find or create buddy '%s' on client '%s'\n",
3568 pak->from->partial, client->name);
3569 } else {
3570 ao2_ref(buddy, -1);
3571 }
3572
3573 ao2_unlock(client->buddies);
3574
3575 break;
3576 default:
3577 break;
3578 }
3579
3580 return 0;
3581 }
3582
3583 /*! \brief Action hook for when things occur */
3584 static int xmpp_action_hook(void *data, int type, iks *node)
3585 {
3586 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
3587 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
3588 struct ast_xmpp_client *client = data;
3589 ikspak *pak;
3590 int i;
3591
3592 if (!node) {
3593 ast_log(LOG_ERROR, "xmpp_action_hook was called without a packet\n");
3594 return IKS_HOOK;
3595 }
3596
3597 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name))) {
3598 return IKS_HOOK;
3599 }
3600
3601 /* If the client is disconnecting ignore everything */
3602 if (client->state == XMPP_STATE_DISCONNECTING) {
3603 return IKS_HOOK;
3604 }
3605
3606 pak = iks_packet(node);
3607
3608 /* work around iksemel's impossibility to recognize node names
3609 * containing a colon. Set the namespace of the corresponding
3610 * node accordingly. */
3611 if (iks_has_children(node) && strchr(iks_name(iks_child(node)), ':')) {
3612 char *node_ns = NULL;
3613 char attr[XMPP_MAX_ATTRLEN];
3614 char *node_name = iks_name(iks_child(node));
3615 char *colon = strchr(node_name, ':');
3616 snprintf(attr, sizeof(attr), "xmlns:%.*s",
3617 (int)(colon - node_name), node_name);
3618 node_ns = iks_find_attrib(iks_child(node), attr);
3619 if (node_ns) {
3620 pak->ns = node_ns;
3621 pak->query = iks_child(node);
3622 }
3623 }
3624
3625 /* Process through any state handlers */
3626 for (i = 0; i < ARRAY_LEN(xmpp_state_handlers); i++) {
3627 if ((xmpp_state_handlers[i].state == client->state) && (xmpp_state_handlers[i].component == (ast_test_flag(&clientcfg->flags, XMPP_COMPONENT) ? 1 : 0))) {
3628 if (xmpp_state_handlers[i].handler(client, clientcfg, type, node)) {
3629 /* If the handler wants us to stop now, do so */
3630 return IKS_HOOK;
3631 }
3632 break;
3633 }
3634 }
3635
3636 /* Process through any PAK handlers */
3637 for (i = 0; i < ARRAY_LEN(xmpp_pak_handlers); i++) {
3638 if (xmpp_pak_handlers[i].type == pak->type) {
3639 if (xmpp_pak_handlers[i].handler(client, clientcfg, node, pak)) {
3640 /* If the handler wants us to stop now, do so */
3641 return IKS_HOOK;
3642 }
3643 break;
3644 }
3645 }
3646
3647 /* Send the packet through the filter in case any filters want to process it */
3648 iks_filter_packet(client->filter, pak);
3649
3650 iks_delete(node);
3651
3652 return IKS_OK;
3653 }
3654
3655 int ast_xmpp_client_disconnect(struct ast_xmpp_client *client)
3656 {
3657 if ((client->thread != AST_PTHREADT_NULL) && !pthread_equal(pthread_self(), client->thread)) {
3658 xmpp_client_change_state(client, XMPP_STATE_DISCONNECTING);
3659 pthread_cancel(client->thread);
3660 pthread_join(client->thread, NULL);
3661 client->thread = AST_PTHREADT_NULL;
3662 }
3663
3664 if (client->mwi_sub) {
3665 client->mwi_sub = stasis_unsubscribe_and_join(client->mwi_sub);
3666 xmpp_pubsub_unsubscribe(client, "message_waiting");
3667 }
3668
3669 if (client->device_state_sub) {
3670 client->device_state_sub = stasis_unsubscribe_and_join(client->device_state_sub);
3671 xmpp_pubsub_unsubscribe(client, "device_state");
3672 }
3673
3674 #ifdef HAVE_OPENSSL
3675 if (client->stream_flags & SECURE) {
3676 SSL_shutdown(client->ssl_session);
3677 SSL_CTX_free(client->ssl_context);
3678 SSL_free(client->ssl_session);
3679 }
3680
3681 client->stream_flags = 0;
3682 #endif
3683
3684 if (client->parser) {
3685 iks_disconnect(client->parser);
3686 }
3687
3688 xmpp_client_change_state(client, XMPP_STATE_DISCONNECTED);
3689
3690 return 0;
3691 }
3692
3693 /*! \brief Internal function used to reconnect an XMPP client to its server */
3694 static int xmpp_client_reconnect(struct ast_xmpp_client *client)
3695 {
3696 struct timeval tv = { .tv_sec = 5, .tv_usec = 0 };
3697 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
3698 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
3699 int res = IKS_NET_NOCONN;
3700
3701 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, client->name))) {
3702 return -1;
3703 }
3704
3705 ast_xmpp_client_disconnect(client);
3706
3707 client->timeout = 50;
3708 iks_parser_reset(client->parser);
3709
3710 if (!client->filter && !(client->filter = iks_filter_new())) {
3711 ast_log(LOG_ERROR, "Could not create IKS filter for client connection '%s'\n", client->name);
3712 return -1;
3713 }
3714
3715 if (!ast_strlen_zero(clientcfg->refresh_token)) {
3716 ast_debug(2, "Obtaining OAuth access token for client '%s'\n", client->name);
3717 if (fetch_access_token(clientcfg)) {
3718 return -1;
3719 }
3720 }
3721
3722 /* If it's a component connect to user otherwise connect to server */
3723 res = iks_connect_via(client->parser, S_OR(clientcfg->server, client->jid->server), clientcfg->port,
3724 ast_test_flag(&clientcfg->flags, XMPP_COMPONENT) ? clientcfg->user : client->jid->server);
3725
3726 /* Set socket timeout options */
3727 setsockopt(iks_fd(client->parser), SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,sizeof(struct timeval));
3728
3729 if (res == IKS_NET_NOCONN) {
3730 ast_log(LOG_ERROR, "No XMPP connection available when trying to connect client '%s'\n", client->name);
3731 return -1;
3732 } else if (res == IKS_NET_NODNS) {
3733 ast_log(LOG_ERROR, "No DNS available for XMPP connection when trying to connect client '%s'\n", client->name);
3734 return -1;
3735 }
3736
3737 /* Depending on the configuration of the client we eiher jump to requesting TLS, or authenticating */
3738 xmpp_client_change_state(client, (ast_test_flag(&clientcfg->flags, XMPP_USETLS) ? XMPP_STATE_REQUEST_TLS : XMPP_STATE_AUTHENTICATE));
3739
3740 return 0;
3741 }
3742
3743 /*! \brief Internal function which polls on an XMPP client and receives data */
3744 static int xmpp_io_recv(struct ast_xmpp_client *client, char *buffer, size_t buf_len, int timeout)
3745 {
3746 struct pollfd pfd = { .events = POLLIN };
3747 int len, res;
3748
3749 #ifdef HAVE_OPENSSL
3750 if (xmpp_is_secure(client)) {
3751 pfd.fd = SSL_get_fd(client->ssl_session);
3752 if (pfd.fd < 0) {
3753 return -1;
3754 }
3755 } else
3756 #endif /* HAVE_OPENSSL */
3757 pfd.fd = iks_fd(client->parser);
3758
3759 res = ast_poll(&pfd, 1, timeout > 0 ? timeout * 1000 : -1);
3760 if (res > 0) {
3761 #ifdef HAVE_OPENSSL
3762 if (xmpp_is_secure(client)) {
3763 len = SSL_read(client->ssl_session, buffer, buf_len);
3764 } else
3765 #endif /* HAVE_OPENSSL */
3766 len = recv(pfd.fd, buffer, buf_len, 0);
3767
3768 if (len > 0) {
3769 return len;
3770 } else if (len <= 0) {
3771 return -1;
3772 }
3773 }
3774 return res;
3775 }
3776
3777 /*! \brief Internal function which receives data from the XMPP client connection */
3778 static int xmpp_client_receive(struct ast_xmpp_client *client, unsigned int timeout)
3779 {
3780 int len, ret, pos = 0, newbufpos = 0;
3781 char buf[NET_IO_BUF_SIZE - 1] = "";
3782 char newbuf[NET_IO_BUF_SIZE - 1] = "";
3783 unsigned char c;
3784
3785 while (1) {
3786 len = xmpp_io_recv(client, buf, NET_IO_BUF_SIZE - 2, timeout);
3787 if (len < 0) return IKS_NET_RWERR;
3788 if (len == 0) return IKS_NET_EXPIRED;
3789 buf[len] = '\0';
3790
3791 /* our iksemel parser won't work as expected if we feed
3792 it with XML packets that contain multiple whitespace
3793 characters between tags */
3794 while (pos < len) {
3795 c = buf[pos];
3796 /* if we stumble on the ending tag character,
3797 we skip any whitespace that follows it*/
3798 if (c == '>') {
3799 while (isspace(buf[pos+1])) {
3800 pos++;
3801 }
3802 }
3803 newbuf[newbufpos] = c;
3804 newbufpos++;
3805 pos++;
3806 }
3807 pos = 0;
3808 newbufpos = 0;
3809
3810 /* Log the message here, because iksemel's logHook is
3811 unaccessible */
3812 xmpp_log_hook(client, buf, len, 1);
3813
3814 if(buf[0] == ' ') {
3815 ast_debug(1, "JABBER: Detected Google Keep Alive. "
3816 "Sending out Ping request for client '%s'\n", client->name);
3817 /* If we just send out the ping here then we will have socket
3818 * read errors because the socket will timeout */
3819 xmpp_ping_request(client, client->jid->server, client->jid->full);
3820 }
3821
3822 /* let iksemel deal with the string length,
3823 and reset our buffer */
3824 ret = iks_parse(client->parser, newbuf, 0, 0);
3825 memset(newbuf, 0, sizeof(newbuf));
3826
3827 switch (ret) {
3828 case IKS_NOMEM:
3829 ast_log(LOG_WARNING, "Parsing failure: Out of memory.\n");
3830 break;
3831 case IKS_BADXML:
3832 ast_log(LOG_WARNING, "Parsing failure: Invalid XML.\n");
3833 break;
3834 case IKS_HOOK:
3835 ast_log(LOG_WARNING, "Parsing failure: Hook returned an error.\n");
3836 break;
3837 }
3838 if (ret != IKS_OK) {
3839 return ret;
3840 }
3841 ast_debug(3, "XML parsing successful\n");
3842 }
3843 return IKS_OK;
3844 }
3845
3846 static void sleep_with_backoff(unsigned int *sleep_time)
3847 {
3848 /* We're OK with our thread dying here */
3849 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
3850
3851 sleep(*sleep_time);
3852 *sleep_time = MIN(60, *sleep_time * 2);
3853
3854 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
3855 }
3856
3857 /*! \brief XMPP client connection thread */
3858 static void *xmpp_client_thread(void *data)
3859 {
3860 struct ast_xmpp_client *client = data;
3861 int res = IKS_NET_RWERR;
3862 unsigned int sleep_time = 1;
3863
3864 /* We only allow cancellation while sleeping */
3865 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
3866
3867 do {
3868 if (client->state == XMPP_STATE_DISCONNECTING) {
3869 ast_debug(1, "[%s] Disconnecting\n", client->name);
3870 break;
3871 }
3872
3873 if (res == IKS_NET_RWERR || client->timeout == 0) {
3874 ast_debug(3, "[%s] Connecting\n", client->name);
3875 if ((res = xmpp_client_reconnect(client)) != IKS_OK) {
3876 sleep_with_backoff(&sleep_time);
3877 res = IKS_NET_RWERR;
3878 }
3879 continue;
3880 }
3881
3882 res = xmpp_client_receive(client, 1);
3883
3884 /* Decrease timeout if no data received, and delete
3885 * old messages globally */
3886 if (res == IKS_NET_EXPIRED) {
3887 client->timeout--;
3888 }
3889
3890 if (res == IKS_HOOK) {
3891 ast_debug(2, "[%s] Got hook event\n", client->name);
3892 } else if (res == IKS_NET_TLSFAIL) {
3893 ast_log(LOG_ERROR, "[%s] TLS failure\n", client->name);
3894 } else if (!client->timeout && client->state == XMPP_STATE_CONNECTED) {
3895 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
3896 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
3897
3898 if (cfg && cfg->clients) {
3899 clientcfg = xmpp_config_find(cfg->clients, client->name);
3900 }
3901
3902 if (clientcfg && ast_test_flag(&clientcfg->flags, XMPP_KEEPALIVE)) {
3903 res = xmpp_ping_request(client, client->jid->server, client->jid->full);
3904 } else {
3905 res = IKS_OK;
3906 }
3907
3908 if (res == IKS_OK) {
3909 client->timeout = 50;
3910 } else {
3911 ast_log(LOG_WARNING, "[%s] Network timeout\n", client->name);
3912 }
3913 } else if (res == IKS_NET_RWERR) {
3914 ast_log(LOG_WARNING, "[%s] Socket read error\n", client->name);
3915 ast_xmpp_client_disconnect(client);
3916 sleep_with_backoff(&sleep_time);
3917 } else if (res == IKS_NET_NOSOCK) {
3918 ast_log(LOG_WARNING, "[%s] No socket\n", client->name);
3919 } else if (res == IKS_NET_NOCONN) {
3920 ast_log(LOG_WARNING, "[%s] No connection\n", client->name);
3921 } else if (res == IKS_NET_NODNS) {
3922 ast_log(LOG_WARNING, "[%s] No DNS\n", client->name);
3923 } else if (res == IKS_NET_NOTSUPP) {
3924 ast_log(LOG_WARNING, "[%s] Not supported\n", client->name);
3925 } else if (res == IKS_NET_DROPPED) {
3926 ast_log(LOG_WARNING, "[%s] Dropped?\n", client->name);
3927 } else if (res == IKS_NET_UNKNOWN) {
3928 ast_debug(5, "[%s] Unknown\n", client->name);
3929 } else if (res == IKS_OK) {
3930 sleep_time = 1;
3931 }
3932
3933 } while (1);
3934
3935 return NULL;
3936 }
3937
3938 static int xmpp_client_config_merge_buddies(void *obj, void *arg, int flags)
3939 {
3940 struct ast_xmpp_buddy *buddy1 = obj, *buddy2;
3941 struct ao2_container *buddies = arg;
3942
3943 /* If the buddy does not already exist link it into the client buddies container */
3944 if (!(buddy2 = ao2_find(buddies, buddy1->id, OBJ_KEY))) {
3945 ao2_link(buddies, buddy1);
3946 } else {
3947 ao2_ref(buddy2, -1);
3948 }
3949
3950 /* All buddies are unlinked from the configuration buddies container, always */
3951 return 1;
3952 }
3953
3954 static int fetch_access_token(struct ast_xmpp_client_config *cfg)
3955 {
3956 RAII_VAR(char *, cmd, NULL, ast_free);
3957 char cBuf[1024] = "";
3958 const char *url = "https://www.googleapis.com/oauth2/v3/token";
3959 struct ast_json_error error;
3960 RAII_VAR(struct ast_json *, jobj, NULL, ast_json_unref);
3961
3962 if (ast_asprintf(&cmd,
3963 "CURL(%s,client_id=%s&client_secret=%s&refresh_token=%s&grant_type=refresh_token)",
3964 url, cfg->oauth_clientid, cfg->oauth_secret, cfg->refresh_token) < 0) {
3965 return -1;
3966 }
3967
3968 ast_debug(2, "Performing OAuth 2.0 authentication for client '%s' using command: %s\n",
3969 cfg->name, cmd);
3970
3971 if (ast_func_read(NULL, cmd, cBuf, sizeof(cBuf) - 1)) {
3972 ast_log(LOG_ERROR, "CURL is unavailable. This is required for OAuth 2.0 authentication of XMPP client '%s'. Please ensure it is loaded.\n",
3973 cfg->name);
3974 return -1;
3975 }
3976
3977 ast_debug(2, "OAuth 2.0 authentication for client '%s' returned: %s\n", cfg->name, cBuf);
3978
3979 jobj = ast_json_load_string(cBuf, &error);
3980 if (jobj) {
3981 const char *token = ast_json_string_get(ast_json_object_get(jobj, "access_token"));
3982 if (token) {
3983 ast_string_field_set(cfg, password, token);
3984 return 0;
3985 }
3986 }
3987
3988 ast_log(LOG_ERROR, "An error occurred while performing OAuth 2.0 authentication for client '%s': %s\n", cfg->name, cBuf);
3989
3990 return -1;
3991 }
3992
3993 static int xmpp_client_config_post_apply(void *obj, void *arg, int flags)
3994 {
3995 struct ast_xmpp_client_config *cfg = obj;
3996 RAII_VAR(struct xmpp_config *, gcfg, ao2_global_obj_ref(globals), ao2_cleanup);
3997
3998 /* Merge global options that have not been modified */
3999 ast_copy_flags(&cfg->flags, &gcfg->global->general, ~(cfg->mod_flags.flags) & (XMPP_AUTOPRUNE | XMPP_AUTOREGISTER | XMPP_AUTOACCEPT));
4000
4001 /* Merge buddies as need be */
4002 ao2_callback(cfg->buddies, OBJ_MULTIPLE | OBJ_UNLINK, xmpp_client_config_merge_buddies, cfg->client->buddies);
4003
4004 if (cfg->client->reconnect) {
4005 /* Disconnect the existing session since our role is changing, or we are starting up */
4006 ast_xmpp_client_disconnect(cfg->client);
4007
4008 if (!(cfg->client->parser = iks_stream_new(ast_test_flag(&cfg->flags, XMPP_COMPONENT) ? "jabber:component:accept" : "jabber:client", cfg->client,
4009 xmpp_action_hook))) {
4010 ast_log(LOG_ERROR, "Iksemel stream could not be created for client '%s' - client not active\n", cfg->name);
4011 return -1;
4012 }
4013
4014 iks_set_log_hook(cfg->client->parser, xmpp_log_hook);
4015
4016 /* Create a JID based on the given user, if no resource is given use the default */
4017 if (!strchr(cfg->user, '/') && !ast_test_flag(&cfg->flags, XMPP_COMPONENT)) {
4018 char resource[strlen(cfg->user) + strlen("/asterisk-xmpp") + 1];
4019
4020 snprintf(resource, sizeof(resource), "%s/asterisk-xmpp", cfg->user);
4021 cfg->client->jid = iks_id_new(cfg->client->stack, resource);
4022 } else {
4023 cfg->client->jid = iks_id_new(cfg->client->stack, cfg->user);
4024 }
4025
4026 if (!cfg->client->jid || (ast_strlen_zero(cfg->client->jid->user) && !ast_test_flag(&cfg->flags, XMPP_COMPONENT))) {
4027 ast_log(LOG_ERROR, "Jabber identity '%s' could not be created for client '%s' - client not active\n", cfg->user, cfg->name);
4028 return -1;
4029 }
4030
4031 ast_pthread_create_background(&cfg->client->thread, NULL, xmpp_client_thread, cfg->client);
4032
4033 cfg->client->reconnect = 0;
4034 } else if (cfg->client->state == XMPP_STATE_CONNECTED) {
4035 /* If this client is connected update their presence status since it may have changed */
4036 xmpp_client_set_presence(cfg->client, NULL, cfg->client->jid->full, cfg->status, cfg->statusmsg);
4037
4038 /* Subscribe to the status of any newly added buddies */
4039 if (ast_test_flag(&cfg->flags, XMPP_AUTOREGISTER)) {
4040 ao2_callback(cfg->client->buddies, OBJ_NODATA | OBJ_MULTIPLE, xmpp_client_subscribe_user, cfg->client);
4041 }
4042 }
4043
4044 return 0;
4045 }
4046
4047 /*!
4048 * \internal
4049 * \brief Send a Jabber Message via call from the Manager
4050 * \param s mansession Manager session
4051 * \param m message Message to send
4052 * \retval 0
4053 */
4054 static int manager_jabber_send(struct mansession *s, const struct message *m)
4055 {
4056 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
4057 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
4058 const char *id = astman_get_header(m, "ActionID");
4059 const char *jabber = astman_get_header(m, "Jabber");
4060 const char *screenname = astman_get_header(m, "ScreenName");
4061 const char *message = astman_get_header(m, "Message");
4062
4063 if (ast_strlen_zero(jabber)) {
4064 astman_send_error(s, m, "No transport specified");
4065 return 0;
4066 }
4067 if (ast_strlen_zero(screenname)) {
4068 astman_send_error(s, m, "No ScreenName specified");
4069 return 0;
4070 }
4071 if (ast_strlen_zero(message)) {
4072 astman_send_error(s, m, "No Message specified");
4073 return 0;
4074 }
4075
4076 astman_send_ack(s, m, "Attempting to send Jabber Message");
4077
4078 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, jabber))) {
4079 astman_send_error(s, m, "Could not find Sender");
4080 return 0;
4081 }
4082
4083 if (strchr(screenname, '@') && !ast_xmpp_client_send_message(clientcfg->client, screenname, message)) {
4084 astman_append(s, "Response: Success\r\n");
4085 } else {
4086 astman_append(s, "Response: Error\r\n");
4087 }
4088
4089 if (!ast_strlen_zero(id)) {
4090 astman_append(s, "ActionID: %s\r\n", id);
4091 }
4092
4093 astman_append(s, "\r\n");
4094
4095 return 0;
4096 }
4097
4098 /*!
4099 * \brief Build the a node request
4100 * \param client the configured XMPP client we use to connect to a XMPP server
4101 * \param collection name of the collection for request
4102 * \return iks *
4103 */
4104 static iks* xmpp_pubsub_build_node_request(struct ast_xmpp_client *client, const char *collection)
4105 {
4106 iks *request = xmpp_pubsub_iq_create(client, "get"), *query;
4107
4108 if (!request) {
4109 return NULL;
4110 }
4111
4112 query = iks_insert(request, "query");
4113 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
4114
4115 if (collection) {
4116 iks_insert_attrib(query, "node", collection);
4117 }
4118
4119 return request;
4120 }
4121
4122 /*!
4123 * \brief Receive pubsub item lists
4124 * \param data pointer to ast_xmpp_client structure
4125 * \param pak response from pubsub diso#items query
4126 * \retval IKS_FILTER_EAT
4127 */
4128 static int xmpp_pubsub_receive_node_list(void *data, ikspak* pak)
4129 {
4130 struct ast_xmpp_client *client = data;
4131 iks *item = NULL;
4132
4133 if (iks_has_children(pak->query)) {
4134 item = iks_first_tag(pak->query);
4135 ast_verbose("Connection %s: %s\nNode name: %s\n", client->name, client->jid->partial,
4136 iks_find_attrib(item, "node"));
4137 while ((item = iks_next_tag(item))) {
4138 ast_verbose("Node name: %s\n", iks_find_attrib(item, "node"));
4139 }
4140 }
4141
4142 if (item) {
4143 iks_delete(item);
4144 }
4145
4146
4147 return IKS_FILTER_EAT;
4148 }
4149
4150 /*!
4151 * \brief Request item list from pubsub
4152 * \param client the configured XMPP client we use to connect to a XMPP server
4153 * \param collection name of the collection for request
4154 */
4155 static void xmpp_pubsub_request_nodes(struct ast_xmpp_client *client, const char *collection)
4156 {
4157 iks *request = xmpp_pubsub_build_node_request(client, collection);
4158
4159 if (!request) {
4160 ast_log(LOG_ERROR, "Could not request pubsub nodes on client '%s' - IQ could not be created\n", client->name);
4161 return;
4162 }
4163
4164 iks_filter_add_rule(client->filter, xmpp_pubsub_receive_node_list, client, IKS_RULE_TYPE,
4165 IKS_PAK_IQ, IKS_RULE_SUBTYPE, IKS_TYPE_RESULT, IKS_RULE_ID, client->mid,
4166 IKS_RULE_DONE);
4167 ast_xmpp_client_send(client, request);
4168 iks_delete(request);
4169
4170 }
4171
4172 /*!
4173 * \brief Method to expose PubSub node list via CLI.
4174 * \param e pointer to ast_cli_entry structure
4175 * \param cmd
4176 * \param a pointer to ast_cli_args structure
4177 * \return char *
4178 */
4179 static char *xmpp_cli_list_pubsub_nodes(struct ast_cli_entry *e, int cmd, struct
4180 ast_cli_args *a)
4181 {
4182 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
4183 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
4184 const char *name = NULL, *collection = NULL;
4185
4186 switch (cmd) {
4187 case CLI_INIT:
4188 e->command = "xmpp list nodes";
4189 e->usage =
4190 "Usage: xmpp list nodes <connection> [collection]\n"
4191 " Lists the user's nodes on the respective connection\n"
4192 " ([connection] as configured in xmpp.conf.)\n";
4193 return NULL;
4194 case CLI_GENERATE:
4195 return NULL;
4196 }
4197
4198 if (a->argc > 5 || a->argc < 4) {
4199 return CLI_SHOWUSAGE;
4200 } else if (a->argc == 4 || a->argc == 5) {
4201 name = a->argv[3];
4202 }
4203
4204 if (a->argc == 5) {
4205 collection = a->argv[4];
4206 }
4207
4208 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, name))) {
4209 ast_cli(a->fd, "Unable to find client '%s'!\n", name);
4210 return CLI_FAILURE;
4211 }
4212
4213 ast_cli(a->fd, "Listing pubsub nodes.\n");
4214
4215 xmpp_pubsub_request_nodes(clientcfg->client, collection);
4216
4217 return CLI_SUCCESS;
4218 }
4219
4220 /*!
4221 * \brief Delete pubsub item lists
4222 * \param data pointer to ast_xmpp_client structure
4223 * \param pak response from pubsub diso#items query
4224 * \retval IKS_FILTER_EAT
4225 */
4226 static int xmpp_pubsub_delete_node_list(void *data, ikspak* pak)
4227 {
4228 struct ast_xmpp_client *client = data;
4229 iks *item = NULL;
4230
4231 if (iks_has_children(pak->query)) {
4232 item = iks_first_tag(pak->query);
4233 ast_log(LOG_WARNING, "Connection: %s Node name: %s\n", client->jid->partial,
4234 iks_find_attrib(item, "node"));
4235 while ((item = iks_next_tag(item))) {
4236 xmpp_pubsub_delete_node(client, iks_find_attrib(item, "node"));
4237 }
4238 }
4239
4240 if (item) {
4241 iks_delete(item);
4242 }
4243
4244 return IKS_FILTER_EAT;
4245 }
4246
4247 static void xmpp_pubsub_purge_nodes(struct ast_xmpp_client *client, const char* collection_name)
4248 {
4249 iks *request = xmpp_pubsub_build_node_request(client, collection_name);
4250 ast_xmpp_client_send(client, request);
4251 iks_filter_add_rule(client->filter, xmpp_pubsub_delete_node_list, client, IKS_RULE_TYPE,
4252 IKS_PAK_IQ, IKS_RULE_SUBTYPE, IKS_TYPE_RESULT, IKS_RULE_ID, client->mid,
4253 IKS_RULE_DONE);
4254 ast_xmpp_client_send(client, request);
4255 iks_delete(request);
4256 }
4257
4258 /*!
4259 * \brief Method to purge PubSub nodes via CLI.
4260 * \param e pointer to ast_cli_entry structure
4261 * \param cmd
4262 * \param a pointer to ast_cli_args structure
4263 * \return char *
4264 */
4265 static char *xmpp_cli_purge_pubsub_nodes(struct ast_cli_entry *e, int cmd, struct
4266 ast_cli_args *a)
4267 {
4268 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
4269 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
4270 const char *name;
4271
4272 switch (cmd) {
4273 case CLI_INIT:
4274 e->command = "xmpp purge nodes";
4275 e->usage =
4276 "Usage: xmpp purge nodes <connection> <node>\n"
4277 " Purges nodes on PubSub server\n"
4278 " as configured in xmpp.conf.\n";
4279 return NULL;
4280 case CLI_GENERATE:
4281 return NULL;
4282 }
4283
4284 if (a->argc != 5) {
4285 return CLI_SHOWUSAGE;
4286 }
4287 name = a->argv[3];
4288
4289 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, name))) {
4290 ast_cli(a->fd, "Unable to find client '%s'!\n", name);
4291 return CLI_FAILURE;
4292 }
4293
4294 if (ast_test_flag(&cfg->global->pubsub, XMPP_XEP0248)) {
4295 xmpp_pubsub_purge_nodes(clientcfg->client, a->argv[4]);
4296 } else {
4297 xmpp_pubsub_delete_node(clientcfg->client, a->argv[4]);
4298 }
4299
4300 return CLI_SUCCESS;
4301 }
4302
4303 /*!
4304 * \brief Method to expose PubSub node deletion via CLI.
4305 * \param e pointer to ast_cli_entry structure
4306 * \param cmd
4307 * \param a pointer to ast_cli_args structure
4308 * \return char *
4309 */
4310 static char *xmpp_cli_delete_pubsub_node(struct ast_cli_entry *e, int cmd, struct
4311 ast_cli_args *a)
4312 {
4313 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
4314 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
4315 const char *name;
4316
4317 switch (cmd) {
4318 case CLI_INIT:
4319 e->command = "xmpp delete node";
4320 e->usage =
4321 "Usage: xmpp delete node <connection> <node>\n"
4322 " Deletes a node on PubSub server\n"
4323 " as configured in xmpp.conf.\n";
4324 return NULL;
4325 case CLI_GENERATE:
4326 return NULL;
4327 }
4328
4329 if (a->argc != 5) {
4330 return CLI_SHOWUSAGE;
4331 }
4332 name = a->argv[3];
4333
4334 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, name))) {
4335 ast_cli(a->fd, "Unable to find client '%s'!\n", name);
4336 return CLI_FAILURE;
4337 }
4338
4339 xmpp_pubsub_delete_node(clientcfg->client, a->argv[4]);
4340
4341 return CLI_SUCCESS;
4342 }
4343
4344 /*!
4345 * \brief Method to expose PubSub collection node creation via CLI.
4346 * \return char *
4347 */
4348 static char *xmpp_cli_create_collection(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4349 {
4350 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
4351 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
4352 const char *name, *collection_name;
4353
4354 switch (cmd) {
4355 case CLI_INIT:
4356 e->command = "xmpp create collection";
4357 e->usage =
4358 "Usage: xmpp create collection <connection> <collection>\n"
4359 " Creates a PubSub collection node using the account\n"
4360 " as configured in xmpp.conf.\n";
4361 return NULL;
4362 case CLI_GENERATE:
4363 return NULL;
4364 }
4365
4366 if (a->argc != 5) {
4367 return CLI_SHOWUSAGE;
4368 }
4369 name = a->argv[3];
4370 collection_name = a->argv[4];
4371
4372 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, name))) {
4373 ast_cli(a->fd, "Unable to find client '%s'!\n", name);
4374 return CLI_FAILURE;
4375 }
4376
4377 ast_cli(a->fd, "Creating test PubSub node collection.\n");
4378
4379 xmpp_pubsub_create_collection(clientcfg->client, collection_name);
4380
4381 return CLI_SUCCESS;
4382 }
4383
4384 /*!
4385 * \brief Method to expose PubSub leaf node creation via CLI.
4386 * \return char *
4387 */
4388 static char *xmpp_cli_create_leafnode(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4389 {
4390 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
4391 RAII_VAR(struct ast_xmpp_client_config *, clientcfg, NULL, ao2_cleanup);
4392 const char *name, *collection_name, *leaf_name;
4393
4394 switch (cmd) {
4395 case CLI_INIT:
4396 e->command = "xmpp create leaf";
4397 e->usage =
4398 "Usage: xmpp create leaf <connection> <collection> <leaf>\n"
4399 " Creates a PubSub leaf node using the account\n"
4400 " as configured in xmpp.conf.\n";
4401 return NULL;
4402 case CLI_GENERATE:
4403 return NULL;
4404 }
4405
4406 if (a->argc != 6) {
4407 return CLI_SHOWUSAGE;
4408 }
4409 name = a->argv[3];
4410 collection_name = a->argv[4];
4411 leaf_name = a->argv[5];
4412
4413 if (!cfg || !cfg->clients || !(clientcfg = xmpp_config_find(cfg->clients, name))) {
4414 ast_cli(a->fd, "Unable to find client '%s'!\n", name);
4415 return CLI_FAILURE;
4416 }
4417
4418 ast_cli(a->fd, "Creating test PubSub node collection.\n");
4419
4420 xmpp_pubsub_create_leaf(clientcfg->client, collection_name, leaf_name);
4421
4422 return CLI_SUCCESS;
4423 }
4424
4425 /*!
4426 * \internal
4427 * \brief Turn on/off console debugging.
4428 * \retval CLI_SUCCESS
4429 */
4430 static char *xmpp_do_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4431 {
4432 switch (cmd) {
4433 case CLI_INIT:
4434 e->command = "xmpp set debug {on|off}";
4435 e->usage =
4436 "Usage: xmpp set debug {on|off}\n"
4437 " Enables/disables dumping of XMPP/Jabber packets for debugging purposes.\n";
4438 return NULL;
4439 case CLI_GENERATE:
4440 return NULL;
4441 }
4442
4443 if (a->argc != e->args) {
4444 return CLI_SHOWUSAGE;
4445 }
4446
4447 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
4448 debug = 1;
4449 ast_cli(a->fd, "XMPP Debugging Enabled.\n");
4450 return CLI_SUCCESS;
4451 } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
4452 debug = 0;
4453 ast_cli(a->fd, "XMPP Debugging Disabled.\n");
4454 return CLI_SUCCESS;
4455 }
4456 return CLI_SHOWUSAGE; /* defaults to invalid */
4457 }
4458
4459 /*!
4460 * \internal
4461 * \brief Show client status.
4462 * \retval CLI_SUCCESS
4463 */
4464 static char *xmpp_show_clients(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4465 {
4466 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
4467 struct ao2_iterator i;
4468 struct ast_xmpp_client_config *clientcfg;
4469
4470 switch (cmd) {
4471 case CLI_INIT:
4472 e->command = "xmpp show connections";
4473 e->usage =
4474 "Usage: xmpp show connections\n"
4475 " Shows state of client and component connections\n";
4476 return NULL;
4477 case CLI_GENERATE:
4478 return NULL;
4479 }
4480
4481 if (!cfg || !cfg->clients) {
4482 return NULL;
4483 }
4484
4485 ast_cli(a->fd, "Jabber Users and their status:\n");
4486
4487 i = ao2_iterator_init(cfg->clients, 0);
4488 while ((clientcfg = ao2_iterator_next(&i))) {
4489 char *state;
4490
4491 switch (clientcfg->client->state) {
4492 case XMPP_STATE_DISCONNECTING:
4493 state = "Disconnecting";
4494 break;
4495 case XMPP_STATE_DISCONNECTED:
4496 state = "Disconnected";
4497 break;
4498 case XMPP_STATE_CONNECTING:
4499 state = "Connecting";
4500 break;
4501 case XMPP_STATE_REQUEST_TLS:
4502 state = "Waiting to request TLS";
4503 break;
4504 case XMPP_STATE_REQUESTED_TLS:
4505 state = "Requested TLS";
4506 break;
4507 case XMPP_STATE_AUTHENTICATE:
4508 state = "Waiting to authenticate";
4509 break;
4510 case XMPP_STATE_AUTHENTICATING:
4511 state = "Authenticating";
4512 break;
4513 case XMPP_STATE_ROSTER:
4514 state = "Retrieving roster";
4515 break;
4516 case XMPP_STATE_CONNECTED:
4517 state = "Connected";
4518 break;
4519 default:
4520 state = "Unknown";
4521 }
4522
4523 ast_cli(a->fd, " [%s] %s - %s\n", clientcfg->name, clientcfg->user, state);
4524
4525 ao2_ref(clientcfg, -1);
4526 }
4527 ao2_iterator_destroy(&i);
4528
4529 ast_cli(a->fd, "----\n");
4530 ast_cli(a->fd, " Number of clients: %d\n", ao2_container_count(cfg->clients));
4531
4532 return CLI_SUCCESS;
4533 }
4534
4535 /*!
4536 * \internal
4537 * \brief Show buddy lists
4538 * \retval CLI_SUCCESS
4539 */
4540 static char *xmpp_show_buddies(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4541 {
4542 RAII_VAR(struct xmpp_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
4543 struct ao2_iterator i;
4544 struct ast_xmpp_client_config *clientcfg;
4545
4546 switch (cmd) {
4547 case CLI_INIT:
4548 e->command = "xmpp show buddies";
4549 e->usage =
4550 "Usage: xmpp show buddies\n"
4551 " Shows buddy lists of our clients\n";
4552 return NULL;
4553 case CLI_GENERATE:
4554 return NULL;
4555 }
4556
4557 if (!cfg || !cfg->clients) {
4558 return NULL;
4559 }
4560
4561 ast_cli(a->fd, "XMPP buddy lists\n");
4562
4563 i = ao2_iterator_init(cfg->clients, 0);
4564 while ((clientcfg = ao2_iterator_next(&i))) {
4565 struct ao2_iterator bud;
4566 struct ast_xmpp_buddy *buddy;
4567
4568 ast_cli(a->fd, "Client: %s\n", clientcfg->name);
4569
4570 bud = ao2_iterator_init(clientcfg->client->buddies, 0);
4571 while ((buddy = ao2_iterator_next(&bud))) {
4572 struct ao2_iterator res;
4573 struct ast_xmpp_resource *resource;
4574
4575 ast_cli(a->fd, "\tBuddy:\t%s\n", buddy->id);
4576
4577 res = ao2_iterator_init(buddy->resources, 0);
4578 while ((resource = ao2_iterator_next(&res))) {
4579 ast_cli(a->fd, "\t\tResource: %s\n", resource->resource);
4580 ast_cli(a->fd, "\t\t\tnode: %s\n", resource->caps.node);
4581 ast_cli(a->fd, "\t\t\tversion: %s\n", resource->caps.version);
4582 ast_cli(a->fd, "\t\t\tGoogle Talk capable: %s\n", resource->caps.google ? "yes" : "no");
4583 ast_cli(a->fd, "\t\t\tJingle capable: %s\n", resource->caps.jingle ? "yes" : "no");
4584
4585 ao2_ref(resource, -1);
4586 }
4587 ao2_iterator_destroy(&res);
4588
4589 ao2_ref(buddy, -1);
4590 }
4591 ao2_iterator_destroy(&bud);
4592
4593 ao2_ref(clientcfg, -1);
4594 }
4595 ao2_iterator_destroy(&i);
4596
4597 return CLI_SUCCESS;
4598 }
4599
4600 static struct ast_cli_entry xmpp_cli[] = {
4601 AST_CLI_DEFINE(xmpp_do_set_debug, "Enable/Disable Jabber debug"),
4602 AST_CLI_DEFINE(xmpp_show_clients, "Show state of clients and components"),
4603 AST_CLI_DEFINE(xmpp_show_buddies, "Show buddy lists of our clients"),
4604 AST_CLI_DEFINE(xmpp_cli_create_collection, "Creates a PubSub node collection."),
4605 AST_CLI_DEFINE(xmpp_cli_list_pubsub_nodes, "Lists PubSub nodes"),
4606 AST_CLI_DEFINE(xmpp_cli_create_leafnode, "Creates a PubSub leaf node"),
4607 AST_CLI_DEFINE(xmpp_cli_delete_pubsub_node, "Deletes a PubSub node"),
4608 AST_CLI_DEFINE(xmpp_cli_purge_pubsub_nodes, "Purges PubSub nodes"),
4609 };
4610
4611 static int unload_module(void)
4612 {
4613 ast_msg_tech_unregister(&msg_tech);
4614 ast_cli_unregister_multiple(xmpp_cli, ARRAY_LEN(xmpp_cli));
4615 ast_unregister_application(app_ajisend);
4616 ast_unregister_application(app_ajisendgroup);
4617 ast_unregister_application(app_ajistatus);
4618 ast_unregister_application(app_ajijoin);
4619 ast_unregister_application(app_ajileave);
4620 ast_manager_unregister("JabberSend");
4621 ast_custom_function_unregister(&jabberstatus_function);
4622 ast_custom_function_unregister(&jabberreceive_function);
4623 aco_info_destroy(&cfg_info);
4624 ao2_global_obj_release(globals);
4625
4626 ast_cond_destroy(&message_received_condition);
4627 ast_mutex_destroy(&messagelock);
4628
4629 return 0;
4630 }
4631
4632 static int global_bitfield_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
4633 {
4634 struct ast_xmpp_global_config *global = obj;
4635
4636 if (!strcasecmp(var->name, "debug")) {
4637 debug = ast_true(var->value);
4638 } else if (!strcasecmp(var->name, "autoprune")) {
4639 ast_set2_flag(&global->general, ast_true(var->value), XMPP_AUTOPRUNE);
4640 } else if (!strcasecmp(var->name, "autoregister")) {
4641 ast_set2_flag(&global->general, ast_true(var->value), XMPP_AUTOREGISTER);
4642 } else if (!strcasecmp(var->name, "auth_policy")) {
4643 ast_set2_flag(&global->general, !strcasecmp(var->value, "accept") ? 1 : 0, XMPP_AUTOACCEPT);
4644 } else if (!strcasecmp(var->name, "collection_nodes")) {
4645 ast_set2_flag(&global->pubsub, ast_true(var->value), XMPP_XEP0248);
4646 } else if (!strcasecmp(var->name, "pubsub_autocreate")) {
4647 ast_set2_flag(&global->pubsub, ast_true(var->value), XMPP_PUBSUB_AUTOCREATE);
4648 } else {
4649 return -1;
4650 }
4651
4652 return 0;
4653 }
4654
4655 static int client_bitfield_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
4656 {
4657 struct ast_xmpp_client_config *cfg = obj;
4658
4659 if (!strcasecmp(var->name, "debug")) {
4660 ast_set2_flag(&cfg->flags, ast_true(var->value), XMPP_DEBUG);
4661 } else if (!strcasecmp(var->name, "type")) {
4662 ast_set2_flag(&cfg->flags, !strcasecmp(var->value, "component") ? 1 : 0, XMPP_COMPONENT);
4663 } else if (!strcasecmp(var->name, "distribute_events")) {
4664 ast_set2_flag(&cfg->flags, ast_true(var->value), XMPP_DISTRIBUTE_EVENTS);
4665 } else if (!strcasecmp(var->name, "usetls")) {
4666 ast_set2_flag(&cfg->flags, ast_true(var->value), XMPP_USETLS);
4667 } else if (!strcasecmp(var->name, "usesasl")) {
4668 ast_set2_flag(&cfg->flags, ast_true(var->value), XMPP_USESASL);
4669 } else if (!strcasecmp(var->name, "forceoldssl")) {
4670 ast_set2_flag(&cfg->flags, ast_true(var->value), XMPP_FORCESSL);
4671 } else if (!strcasecmp(var->name, "keepalive")) {
4672 ast_set2_flag(&cfg->flags, ast_true(var->value), XMPP_KEEPALIVE);
4673 } else if (!strcasecmp(var->name, "autoprune")) {
4674 ast_set2_flag(&cfg->flags, ast_true(var->value), XMPP_AUTOPRUNE);
4675 ast_set2_flag(&cfg->mod_flags, 1, XMPP_AUTOPRUNE);
4676 } else if (!strcasecmp(var->name, "autoregister")) {
4677 ast_set2_flag(&cfg->flags, ast_true(var->value), XMPP_AUTOREGISTER);
4678 ast_set2_flag(&cfg->mod_flags, 1, XMPP_AUTOREGISTER);
4679 } else if (!strcasecmp(var->name, "auth_policy")) {
4680 ast_set2_flag(&cfg->flags, !strcasecmp(var->value, "accept") ? 1 : 0, XMPP_AUTOACCEPT);
4681 ast_set2_flag(&cfg->mod_flags, 1, XMPP_AUTOACCEPT);
4682 } else if (!strcasecmp(var->name, "sendtodialplan")) {
4683 ast_set2_flag(&cfg->flags, ast_true(var->value), XMPP_SEND_TO_DIALPLAN);
4684 } else {
4685 return -1;
4686 }
4687
4688 return 0;
4689 }
4690
4691 static int client_status_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
4692 {
4693 struct ast_xmpp_client_config *cfg = obj;
4694
4695 if (!strcasecmp(var->value, "unavailable")) {
4696 cfg->status = IKS_SHOW_UNAVAILABLE;
4697 } else if (!strcasecmp(var->value, "available") || !strcasecmp(var->value, "online")) {
4698 cfg->status = IKS_SHOW_AVAILABLE;
4699 } else if (!strcasecmp(var->value, "chat") || !strcasecmp(var->value, "chatty")) {
4700 cfg->status = IKS_SHOW_CHAT;
4701 } else if (!strcasecmp(var->value, "away")) {
4702 cfg->status = IKS_SHOW_AWAY;
4703 } else if (!strcasecmp(var->value, "xa") || !strcasecmp(var->value, "xaway")) {
4704 cfg->status = IKS_SHOW_XA;
4705 } else if (!strcasecmp(var->value, "dnd")) {
4706 cfg->status = IKS_SHOW_DND;
4707 } else if (!strcasecmp(var->value, "invisible")) {
4708 #ifdef IKS_SHOW_INVISIBLE
4709 cfg->status = IKS_SHOW_INVISIBLE;
4710 #else
4711 cfg->status = IKS_SHOW_DND;
4712 #endif
4713 } else {
4714 return -1;
4715 }
4716
4717 return 0;
4718 }
4719
4720 static int client_buddy_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
4721 {
4722 struct ast_xmpp_client_config *cfg = obj;
4723 struct ast_xmpp_buddy *buddy;
4724
4725 if ((buddy = ao2_find(cfg->buddies, var->value, OBJ_KEY))) {
4726 ao2_ref(buddy, -1);
4727 return -1;
4728 }
4729
4730 if (!(buddy = xmpp_client_create_buddy(cfg->buddies, var->value))) {
4731 return -1;
4732 }
4733
4734 ao2_ref(buddy, -1);
4735
4736 return 0;
4737 }
4738
4739 /*!
4740 * \brief Load the module
4741 *
4742 * Module loading including tests for configuration or dependencies.
4743 * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
4744 * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
4745 * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
4746 * configuration file or other non-critical problem return
4747 * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
4748 */
4749 static int load_module(void)
4750 {
4751 if (aco_info_init(&cfg_info)) {
4752 return AST_MODULE_LOAD_DECLINE;
4753 }
4754
4755 aco_option_register_custom(&cfg_info, "debug", ACO_EXACT, global_options, "no", global_bitfield_handler, 0);
4756 aco_option_register_custom(&cfg_info, "autoprune", ACO_EXACT, global_options, "no", global_bitfield_handler, 0);
4757 aco_option_register_custom(&cfg_info, "autoregister", ACO_EXACT, global_options, "yes", global_bitfield_handler, 0);
4758 aco_option_register_custom(&cfg_info, "collection_nodes", ACO_EXACT, global_options, "no", global_bitfield_handler, 0);
4759 aco_option_register_custom(&cfg_info, "pubsub_autocreate", ACO_EXACT, global_options, "no", global_bitfield_handler, 0);
4760 aco_option_register_custom(&cfg_info, "auth_policy", ACO_EXACT, global_options, "accept", global_bitfield_handler, 0);
4761
4762 aco_option_register(&cfg_info, "username", ACO_EXACT, client_options, NULL, OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_xmpp_client_config, user));
4763 aco_option_register(&cfg_info, "secret", ACO_EXACT, client_options, NULL, OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_xmpp_client_config, password));
4764 aco_option_register(&cfg_info, "refresh_token", ACO_EXACT, client_options, NULL, OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_xmpp_client_config, refresh_token));
4765 aco_option_register(&cfg_info, "oauth_clientid", ACO_EXACT, client_options, NULL, OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_xmpp_client_config, oauth_clientid));
4766 aco_option_register(&cfg_info, "oauth_secret", ACO_EXACT, client_options, NULL, OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_xmpp_client_config, oauth_secret));
4767 aco_option_register(&cfg_info, "serverhost", ACO_EXACT, client_options, NULL, OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_xmpp_client_config, server));
4768 aco_option_register(&cfg_info, "statusmessage", ACO_EXACT, client_options, "Online and Available", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_xmpp_client_config, statusmsg));
4769 aco_option_register(&cfg_info, "pubsub_node", ACO_EXACT, client_options, NULL, OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_xmpp_client_config, pubsubnode));
4770 aco_option_register(&cfg_info, "context", ACO_EXACT, client_options, "default", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_xmpp_client_config, context));
4771 aco_option_register(&cfg_info, "priority", ACO_EXACT, client_options, "1", OPT_UINT_T, 0, FLDSET(struct ast_xmpp_client_config, priority));
4772 aco_option_register(&cfg_info, "port", ACO_EXACT, client_options, "5222", OPT_UINT_T, 0, FLDSET(struct ast_xmpp_client_config, port));
4773 aco_option_register(&cfg_info, "timeout", ACO_EXACT, client_options, "5", OPT_UINT_T, 0, FLDSET(struct ast_xmpp_client_config, message_timeout));
4774
4775 /* Global options that can be overridden per client must not specify a default */
4776 aco_option_register_custom(&cfg_info, "autoprune", ACO_EXACT, client_options, NULL, client_bitfield_handler, 0);
4777 aco_option_register_custom(&cfg_info, "autoregister", ACO_EXACT, client_options, NULL, client_bitfield_handler, 0);
4778 aco_option_register_custom(&cfg_info, "auth_policy", ACO_EXACT, client_options, NULL, client_bitfield_handler, 0);
4779
4780 aco_option_register_custom(&cfg_info, "debug", ACO_EXACT, client_options, "no", client_bitfield_handler, 0);
4781 aco_option_register_custom(&cfg_info, "type", ACO_EXACT, client_options, "client", client_bitfield_handler, 0);
4782 aco_option_register_custom(&cfg_info, "distribute_events", ACO_EXACT, client_options, "no", client_bitfield_handler, 0);
4783 aco_option_register_custom(&cfg_info, "usetls", ACO_EXACT, client_options, "yes", client_bitfield_handler, 0);
4784 aco_option_register_custom(&cfg_info, "usesasl", ACO_EXACT, client_options, "yes", client_bitfield_handler, 0);
4785 aco_option_register_custom(&cfg_info, "forceoldssl", ACO_EXACT, client_options, "no", client_bitfield_handler, 0);
4786 aco_option_register_custom(&cfg_info, "keepalive", ACO_EXACT, client_options, "yes", client_bitfield_handler, 0);
4787 aco_option_register_custom(&cfg_info, "sendtodialplan", ACO_EXACT, client_options, "no", client_bitfield_handler, 0);
4788 aco_option_register_custom(&cfg_info, "status", ACO_EXACT, client_options, "available", client_status_handler, 0);
4789 aco_option_register_custom(&cfg_info, "buddy", ACO_EXACT, client_options, NULL, client_buddy_handler, 0);
4790
4791 if (aco_process_config(&cfg_info, 0) == ACO_PROCESS_ERROR) {
4792 aco_info_destroy(&cfg_info);
4793 return AST_MODULE_LOAD_DECLINE;
4794 }
4795
4796 ast_manager_register_xml("JabberSend", EVENT_FLAG_SYSTEM, manager_jabber_send);
4797
4798 ast_register_application_xml(app_ajisend, xmpp_send_exec);
4799 ast_register_application_xml(app_ajisendgroup, xmpp_sendgroup_exec);
4800 ast_register_application_xml(app_ajijoin, xmpp_join_exec);
4801 ast_register_application_xml(app_ajileave, xmpp_leave_exec);
4802
4803 ast_cli_register_multiple(xmpp_cli, ARRAY_LEN(xmpp_cli));
4804 ast_custom_function_register(&jabberstatus_function);
4805 ast_custom_function_register(&jabberreceive_function);
4806 ast_msg_tech_register(&msg_tech);
4807
4808 ast_mutex_init(&messagelock);
4809 ast_cond_init(&message_received_condition, NULL);
4810
4811 if (ast_eid_is_empty(&ast_eid_default)) {
4812 ast_log(LOG_WARNING, "Entity ID is not set. The distributing device state or MWI will not work.\n");
4813 }
4814
4815 return AST_MODULE_LOAD_SUCCESS;
4816 }
4817
4818 static int reload(void)
4819 {
4820 if (aco_process_config(&cfg_info, 1) == ACO_PROCESS_ERROR) {
4821 return AST_MODULE_LOAD_DECLINE;
4822 }
4823
4824 return 0;
4825 }
4826
4827 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Asterisk XMPP Interface",
4828 .support_level = AST_MODULE_SUPPORT_CORE,
4829 .load = load_module,
4830 .unload = unload_module,
4831 .reload = reload,
4832 .load_pri = AST_MODPRI_CHANNEL_DEPEND,
4833 );