7ca0bf81e6871c90b902d62a8db0c953e2b61619
[asterisk/asterisk.git] / res / res_jabber.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2010, Digium, Inc.
5  *
6  * Matt O'Gorman <mogorman@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  * \brief A resource for interfacing Asterisk directly as a client
21  * or a component to a XMPP/Jabber compliant server.
22  *
23  * References:
24  * - http://www.xmpp.org - The XMPP standards foundation
25  *
26  * Iksemel http://code.google.com/p/iksemel/
27  *
28  * \todo If you unload this module, chan_gtalk/jingle will be dead. How do we handle that?
29  * \todo Dialplan applications need RETURN variable, like JABBERSENDSTATUS
30  *
31  */
32
33 /*! \li \ref res_jabber.c uses the configuration file \ref jabber.conf
34  * \addtogroup configuration_file Configuration Files
35  */
36
37 /*! 
38  * \page jabber.conf jabber.conf
39  * \verbinclude jabber.conf.sample
40  */
41
42 /*** MODULEINFO
43         <defaultenabled>no</defaultenabled>
44         <depend>iksemel</depend>
45         <use type="external">openssl</use>
46         <support_level>deprecated</support_level>
47         <replacement>res_xmpp</replacement>
48  ***/
49
50 #include "asterisk.h"
51
52 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
53
54 #include <ctype.h>
55 #include <iksemel.h>
56
57 #include "asterisk/channel.h"
58 #include "asterisk/jabber.h"
59 #include "asterisk/file.h"
60 #include "asterisk/config.h"
61 #include "asterisk/callerid.h"
62 #include "asterisk/lock.h"
63 #include "asterisk/cli.h"
64 #include "asterisk/app.h"
65 #include "asterisk/pbx.h"
66 #include "asterisk/md5.h"
67 #include "asterisk/acl.h"
68 #include "asterisk/utils.h"
69 #include "asterisk/module.h"
70 #include "asterisk/astobj.h"
71 #include "asterisk/astdb.h"
72 #include "asterisk/manager.h"
73 #include "asterisk/event.h"
74 #include "asterisk/devicestate.h"
75 #include "asterisk/message.h"
76
77 /*** DOCUMENTATION
78         <application name="JabberSend" language="en_US" module="res_jabber">
79                 <synopsis>
80                         Sends an XMPP message to a buddy.
81                 </synopsis>
82                 <syntax>
83                         <parameter name="account" required="true">
84                                 <para>The local named account to listen on (specified in
85                                 jabber.conf)</para>
86                         </parameter>
87                         <parameter name="jid" required="true">
88                                 <para>Jabber ID of the buddy to send the message to. It can be a
89                                 bare JID (username@domain) or a full JID (username@domain/resource).</para>
90                         </parameter>
91                         <parameter name="message" required="true">
92                                 <para>The message to send.</para>
93                         </parameter>
94                 </syntax>
95                 <description>
96                         <para>Sends the content of <replaceable>message</replaceable> as text message
97                         from the given <replaceable>account</replaceable> to the buddy identified by
98                         <replaceable>jid</replaceable></para>
99                         <para>Example: JabberSend(asterisk,bob@domain.com,Hello world) sends "Hello world"
100                         to <replaceable>bob@domain.com</replaceable> as an XMPP message from the account
101                         <replaceable>asterisk</replaceable>, configured in jabber.conf.</para>
102                 </description>
103                 <see-also>
104                         <ref type="function" module="res_jabber">JABBER_STATUS</ref>
105                         <ref type="function" module="res_jabber">JABBER_RECEIVE</ref>
106                 </see-also>
107         </application>
108         <function name="JABBER_RECEIVE" language="en_US" module="res_jabber">
109                 <synopsis>
110                         Reads XMPP messages.
111                 </synopsis>
112                 <syntax>
113                         <parameter name="account" required="true">
114                                 <para>The local named account to listen on (specified in
115                                 jabber.conf)</para>
116                         </parameter>
117                         <parameter name="jid" required="true">
118                                 <para>Jabber ID of the buddy to receive message from. It can be a
119                                 bare JID (username@domain) or a full JID (username@domain/resource).</para>
120                         </parameter>
121                         <parameter name="timeout">
122                                 <para>In seconds, defaults to <literal>20</literal>.</para>
123                         </parameter>
124                 </syntax>
125                 <description>
126                         <para>Receives a text message on the given <replaceable>account</replaceable>
127                         from the buddy identified by <replaceable>jid</replaceable> and returns the contents.</para>
128                         <para>Example: ${JABBER_RECEIVE(asterisk,bob@domain.com)} returns an XMPP message
129                         sent from <replaceable>bob@domain.com</replaceable> (or nothing in case of a time out), to
130                         the <replaceable>asterisk</replaceable> XMPP account configured in jabber.conf.</para>
131                 </description>
132                 <see-also>
133                         <ref type="function" module="res_jabber">JABBER_STATUS</ref>
134                         <ref type="application" module="res_jabber">JabberSend</ref>
135                 </see-also>
136         </function>
137         <function name="JABBER_STATUS" language="en_US" module="res_jabber">
138                 <synopsis>
139                         Retrieves a buddy's status.
140                 </synopsis>
141                 <syntax>
142                         <parameter name="account" required="true">
143                                 <para>The local named account to listen on (specified in
144                                 jabber.conf)</para>
145                         </parameter>
146                         <parameter name="jid" required="true">
147                                 <para>Jabber ID of the buddy to receive message from. It can be a
148                                 bare JID (username@domain) or a full JID (username@domain/resource).</para>
149                         </parameter>
150                 </syntax>
151                 <description>
152                         <para>Retrieves the numeric status associated with the buddy identified
153                         by <replaceable>jid</replaceable>.
154                         If the buddy does not exist in the buddylist, returns 7.</para>
155                         <para>Status will be 1-7.</para>
156                         <para>1=Online, 2=Chatty, 3=Away, 4=XAway, 5=DND, 6=Offline</para>
157                         <para>If not in roster variable will be set to 7.</para>
158                         <para>Example: ${JABBER_STATUS(asterisk,bob@domain.com)} returns 1 if
159                         <replaceable>bob@domain.com</replaceable> is online. <replaceable>asterisk</replaceable> is
160                         the associated XMPP account configured in jabber.conf.</para>
161                 </description>
162                 <see-also>
163                         <ref type="function" module="res_jabber">JABBER_RECEIVE</ref>
164                         <ref type="application" module="res_jabber">JabberSend</ref>
165                 </see-also>
166         </function>
167         <application name="JabberSendGroup" language="en_US" module="res_jabber">
168                 <synopsis>
169                         Send a Jabber Message to a specified chat room
170                 </synopsis>
171                 <syntax>
172                         <parameter name="Jabber" required="true">
173                                 <para>Client or transport Asterisk uses to connect to Jabber.</para>
174                         </parameter>
175                         <parameter name="RoomJID" required="true">
176                                 <para>XMPP/Jabber JID (Name) of chat room.</para>
177                         </parameter>
178                         <parameter name="Message" required="true">
179                                 <para>Message to be sent to the chat room.</para>
180                         </parameter>
181                         <parameter name="Nickname" required="false">
182                                 <para>The nickname Asterisk uses in the chat room.</para>
183                         </parameter>
184                 </syntax>
185                 <description>
186                         <para>Allows user to send a message to a chat room via XMPP.</para>
187                         <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>
188                 </description>
189         </application>
190         <application name="JabberJoin" language="en_US" module="res_jabber">
191                 <synopsis>
192                         Join a chat room
193                 </synopsis>
194                 <syntax>
195                         <parameter name="Jabber" required="true">
196                                 <para>Client or transport Asterisk uses to connect to Jabber.</para>
197                         </parameter>
198                         <parameter name="RoomJID" required="true">
199                                 <para>XMPP/Jabber JID (Name) of chat room.</para>
200                         </parameter>
201                         <parameter name="Nickname" required="false">
202                                 <para>The nickname Asterisk will use in the chat room.</para>
203                                 <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>
204                         </parameter>
205                 </syntax>
206                 <description>
207                         <para>Allows Asterisk to join a chat room.</para>
208                 </description>
209         </application>
210         <application name="JabberLeave" language="en_US" module="res_jabber">
211                 <synopsis>
212                         Leave a chat room
213                 </synopsis>
214                 <syntax>
215                         <parameter name="Jabber" required="true">
216                                 <para>Client or transport Asterisk uses to connect to Jabber.</para>
217                         </parameter>
218                         <parameter name="RoomJID" required="true">
219                                 <para>XMPP/Jabber JID (Name) of chat room.</para>
220                         </parameter>
221                         <parameter name="Nickname" required="false">
222                                 <para>The nickname Asterisk uses in the chat room.</para>
223                         </parameter>
224                 </syntax>
225                 <description>
226                         <para>Allows Asterisk to leave a chat room.</para>
227                 </description>
228         </application>
229         <application name="JabberStatus" language="en_US" module="res_jabber">
230                 <synopsis>
231                         Retrieve the status of a jabber list member
232                 </synopsis>
233                 <syntax>
234                         <parameter name="Jabber" required="true">
235                                 <para>Client or transport Asterisk users to connect to Jabber.</para>
236                         </parameter>
237                         <parameter name="JID" required="true">
238                                 <para>XMPP/Jabber JID (Name) of recipient.</para>
239                         </parameter>
240                         <parameter name="Variable" required="true">
241                                 <para>Variable to store the status of requested user.</para>
242                         </parameter>
243                 </syntax>
244                 <description>
245                         <para>This application is deprecated. Please use the JABBER_STATUS() function instead.</para>
246                         <para>Retrieves the numeric status associated with the specified buddy <replaceable>JID</replaceable>.
247                         The return value in the <replaceable>Variable</replaceable>will be one of the following.</para>
248                         <enumlist>
249                                 <enum name="1">
250                                         <para>Online.</para>
251                                 </enum>
252                                 <enum name="2">
253                                         <para>Chatty.</para>
254                                 </enum>
255                                 <enum name="3">
256                                         <para>Away.</para>
257                                 </enum>
258                                 <enum name="4">
259                                         <para>Extended Away.</para>
260                                 </enum>
261                                 <enum name="5">
262                                         <para>Do Not Disturb.</para>
263                                 </enum>
264                                 <enum name="6">
265                                         <para>Offline.</para>
266                                 </enum>
267                                 <enum name="7">
268                                         <para>Not In Roster.</para>
269                                 </enum>
270                         </enumlist>
271                 </description>
272         </application>
273         <manager name="JabberSend" language="en_US" module="res_jabber">
274                 <synopsis>
275                         Sends a message to a Jabber Client.
276                 </synopsis>
277                 <syntax>
278                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
279                         <parameter name="Jabber" required="true">
280                                 <para>Client or transport Asterisk uses to connect to JABBER.</para>
281                         </parameter>
282                         <parameter name="JID" required="true">
283                                 <para>XMPP/Jabber JID (Name) of recipient.</para>
284                         </parameter>
285                         <parameter name="Message" required="true">
286                                 <para>Message to be sent to the buddy.</para>
287                         </parameter>
288                 </syntax>
289                 <description>
290                         <para>Sends a message to a Jabber Client.</para>
291                 </description>
292         </manager>
293  ***/
294
295 /*!\todo This should really be renamed to xmpp.conf. For backwards compatibility, we
296  * need to read both files */
297 #define JABBER_CONFIG "jabber.conf"
298
299 /*-- Forward declarations */
300 static void aji_message_destroy(struct aji_message *obj);
301 static int aji_is_secure(struct aji_client *client);
302 #ifdef HAVE_OPENSSL
303 static int aji_start_tls(struct aji_client *client);
304 static int aji_tls_handshake(struct aji_client *client);
305 #endif
306 static int aji_io_recv(struct aji_client *client, char *buffer, size_t buf_len, int timeout);
307 static int aji_recv(struct aji_client *client, int timeout);
308 static int aji_send_header(struct aji_client *client, const char *to);
309 static int aji_send_raw(struct aji_client *client, const char *xmlstr);
310 static void aji_log_hook(void *data, const char *xmpp, size_t size, int is_incoming);
311 static int aji_start_sasl(struct aji_client *client, enum ikssasltype type, char *username, char *pass);
312 static int aji_act_hook(void *data, int type, iks *node);
313 static void aji_handle_iq(struct aji_client *client, iks *node);
314 static void aji_handle_message(struct aji_client *client, ikspak *pak);
315 static void aji_handle_presence(struct aji_client *client, ikspak *pak);
316 static void aji_handle_subscribe(struct aji_client *client, ikspak *pak);
317 static int aji_send_raw_chat(struct aji_client *client, int groupchat, const char *nick, const char *address, const char *message);
318 static void *aji_recv_loop(void *data);
319 static int aji_initialize(struct aji_client *client);
320 static int aji_client_connect(void *data, ikspak *pak);
321 static void aji_set_presence(struct aji_client *client, char *to, char *from, int level, char *desc);
322 static int aji_set_group_presence(struct aji_client *client, char *room, int level, char *nick, char *desc);
323 static char *aji_do_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
324 static char *aji_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
325 static char *aji_show_clients(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
326 static char *aji_show_buddies(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
327 static int aji_create_client(char *label, struct ast_variable *var, int debug);
328 static int aji_create_buddy(char *label, struct aji_client *client);
329 static int aji_reload(int reload);
330 static int aji_load_config(int reload);
331 static void aji_pruneregister(struct aji_client *client);
332 static int aji_filter_roster(void *data, ikspak *pak);
333 static int aji_get_roster(struct aji_client *client);
334 static int aji_client_info_handler(void *data, ikspak *pak);
335 static int aji_dinfo_handler(void *data, ikspak *pak);
336 static int aji_ditems_handler(void *data, ikspak *pak);
337 static int aji_register_query_handler(void *data, ikspak *pak);
338 static int aji_register_approve_handler(void *data, ikspak *pak);
339 static int aji_reconnect(struct aji_client *client);
340 static char *aji_cli_create_collection(struct ast_cli_entry *e, int cmd,
341         struct ast_cli_args *a);
342 static char *aji_cli_list_pubsub_nodes(struct ast_cli_entry *e, int cmd,
343         struct ast_cli_args *a);
344 static char *aji_cli_delete_pubsub_node(struct ast_cli_entry *e, int cmd, struct
345         ast_cli_args *a);
346 static char *aji_cli_purge_pubsub_nodes(struct ast_cli_entry *e, int cmd, struct
347                 ast_cli_args *a);
348 static iks *jabber_make_auth(iksid * id, const char *pass, const char *sid);
349 static int aji_receive_node_list(void *data, ikspak* pak);
350 static void aji_init_event_distribution(struct aji_client *client);
351 static iks* aji_create_pubsub_node(struct aji_client *client, const char *node_type,
352         const char *name, const char *collection_name);
353 static iks* aji_build_node_config(iks *pubsub, const char *node_type,
354         const char *collection_name);
355 static void aji_create_pubsub_collection(struct aji_client *client,
356         const char *collection_name);
357 static void aji_create_pubsub_leaf(struct aji_client *client, const char *collection_name,
358    const char *leaf_name);
359 static char *aji_cli_create_leafnode(struct ast_cli_entry *e, int cmd,
360         struct ast_cli_args *a);
361 static void aji_create_affiliations(struct aji_client *client, const char *node);
362 static iks* aji_pubsub_iq_create(struct aji_client *client, const char *type);
363 static void aji_publish_device_state(struct aji_client *client, const char * device,
364                                      const char *device_state, unsigned int cachable);
365 static int aji_handle_pubsub_error(void *data, ikspak *pak);
366 static int aji_handle_pubsub_event(void *data, ikspak *pak);
367 static void aji_pubsub_subscribe(struct aji_client *client, const char *node);
368 static void aji_delete_pubsub_node(struct aji_client *client, const char *node_name);
369 static iks* aji_build_node_request(struct aji_client *client, const char *collection);
370 static int aji_delete_node_list(void *data, ikspak* pak);
371 static void aji_pubsub_purge_nodes(struct aji_client *client,
372         const char* collection_name);
373 static void aji_publish_mwi(struct aji_client *client, const char *mailbox,
374         const char *context, const char *oldmsgs, const char *newmsgs);
375 static void aji_devstate_cb(void *data, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *msg);
376 static void aji_mwi_cb(void *data, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *msg);
377 static iks* aji_build_publish_skeleton(struct aji_client *client, const char *node,
378                                        const char *event_type, unsigned int cachable);
379 /* No transports in this version */
380 /*
381 static int aji_create_transport(char *label, struct aji_client *client);
382 static int aji_register_transport(void *data, ikspak *pak);
383 static int aji_register_transport2(void *data, ikspak *pak);
384 */
385
386 static int msg_send_cb(const struct ast_msg *msg, const char *to, const char *from);
387
388 static const struct ast_msg_tech msg_tech = {
389         .name = "xmpp",
390         .msg_send = msg_send_cb,
391 };
392
393 static struct ast_cli_entry aji_cli[] = {
394         AST_CLI_DEFINE(aji_do_set_debug, "Enable/Disable Jabber debug"),
395         AST_CLI_DEFINE(aji_do_reload, "Reload Jabber configuration"),
396         AST_CLI_DEFINE(aji_show_clients, "Show state of clients and components"),
397         AST_CLI_DEFINE(aji_show_buddies, "Show buddy lists of our clients"),
398         AST_CLI_DEFINE(aji_cli_create_collection, "Creates a PubSub node collection."),
399         AST_CLI_DEFINE(aji_cli_list_pubsub_nodes, "Lists PubSub nodes"),
400         AST_CLI_DEFINE(aji_cli_create_leafnode, "Creates a PubSub leaf node"),
401         AST_CLI_DEFINE(aji_cli_delete_pubsub_node, "Deletes a PubSub node"),
402         AST_CLI_DEFINE(aji_cli_purge_pubsub_nodes, "Purges PubSub nodes"),
403 };
404
405 static char *app_ajisend = "JabberSend";
406 static char *app_ajisendgroup = "JabberSendGroup";
407 static char *app_ajistatus = "JabberStatus";
408 static char *app_ajijoin = "JabberJoin";
409 static char *app_ajileave = "JabberLeave";
410
411 static struct aji_client_container clients;
412 static struct aji_capabilities *capabilities = NULL;
413 static struct stasis_subscription *mwi_sub = NULL;
414 static struct stasis_subscription *device_state_sub = NULL;
415 static ast_cond_t message_received_condition;
416 static ast_mutex_t messagelock;
417
418 /*! \brief Global flags, initialized to default values */
419 static struct ast_flags globalflags = { AJI_AUTOREGISTER | AJI_AUTOACCEPT };
420
421 /*! \brief PubSub flags, initialized to default values */
422 static struct ast_flags pubsubflags = { 0 };
423 /*!
424  * \internal
425  * \brief Deletes the aji_client data structure.
426  * \param obj aji_client The structure we will delete.
427  * \return void.
428  */
429 void ast_aji_client_destroy(struct aji_client *obj)
430 {
431         struct aji_message *tmp;
432         ASTOBJ_CONTAINER_DESTROYALL(&obj->buddies, ast_aji_buddy_destroy);
433         ASTOBJ_CONTAINER_DESTROY(&obj->buddies);
434         iks_filter_delete(obj->f);
435         iks_parser_delete(obj->p);
436         iks_stack_delete(obj->stack);
437         AST_LIST_LOCK(&obj->messages);
438         while ((tmp = AST_LIST_REMOVE_HEAD(&obj->messages, list))) {
439                 aji_message_destroy(tmp);
440         }
441         AST_LIST_HEAD_DESTROY(&obj->messages);
442         ast_free(obj);
443 }
444
445 /*!
446  * \internal
447  * \brief Deletes the aji_buddy data structure.
448  * \param obj aji_buddy The structure we will delete.
449  * \return void.
450  */
451 void ast_aji_buddy_destroy(struct aji_buddy *obj)
452 {
453         struct aji_resource *tmp;
454
455         while ((tmp = obj->resources)) {
456                 obj->resources = obj->resources->next;
457                 ast_free(tmp->description);
458                 ast_free(tmp);
459         }
460
461         ast_free(obj);
462 }
463
464 /*!
465  * \internal
466  * \brief Deletes the aji_message data structure.
467  * \param obj aji_message The structure we will delete.
468  * \return void.
469  */
470 static void aji_message_destroy(struct aji_message *obj)
471 {
472         if (obj->from) {
473                 ast_free(obj->from);
474         }
475         if (obj->message) {
476                 ast_free(obj->message);
477         }
478         ast_free(obj);
479 }
480
481 /*!
482  * \internal
483  * \brief Find version in XML stream and populate our capabilities list
484  * \param node the node attribute in the caps element we'll look for or add to
485  * our list
486  * \param version the version attribute in the caps element we'll look for or
487  * add to our list
488  * \param pak struct The XML stanza we're processing
489  * \return a pointer to the added or found aji_version structure
490  */
491 static struct aji_version *aji_find_version(char *node, char *version, ikspak *pak)
492 {
493         struct aji_capabilities *list = NULL;
494         struct aji_version *res = NULL;
495
496         list = capabilities;
497
498         if (!node) {
499                 node = pak->from->full;
500         }
501         if (!version) {
502                 version = "none supplied.";
503         }
504         while (list) {
505                 if (!strcasecmp(list->node, node)) {
506                         res = list->versions;
507                         while(res) {
508                                 if (!strcasecmp(res->version, version)) {
509                                         return res;
510                                 }
511                                 res = res->next;
512                         }
513                         /* Specified version not found. Let's add it to
514                            this node in our capabilities list */
515                         if (!res) {
516                                 res = ast_malloc(sizeof(*res));
517                                 if (!res) {
518                                         ast_log(LOG_ERROR, "Out of memory!\n");
519                                         return NULL;
520                                 }
521                                 res->jingle = 0;
522                                 res->parent = list;
523                                 ast_copy_string(res->version, version, sizeof(res->version));
524                                 res->next = list->versions;
525                                 list->versions = res;
526                                 return res;
527                         }
528                 }
529                 list = list->next;
530         }
531         /* Specified node not found. Let's add it our capabilities list */
532         if (!list) {
533                 list = ast_malloc(sizeof(*list));
534                 if (!list) {
535                         ast_log(LOG_ERROR, "Out of memory!\n");
536                         return NULL;
537                 }
538                 res = ast_malloc(sizeof(*res));
539                 if (!res) {
540                         ast_log(LOG_ERROR, "Out of memory!\n");
541                         ast_free(list);
542                         return NULL;
543                 }
544                 ast_copy_string(list->node, node, sizeof(list->node));
545                 ast_copy_string(res->version, version, sizeof(res->version));
546                 res->jingle = 0;
547                 res->parent = list;
548                 res->next = NULL;
549                 list->versions = res;
550                 list->next = capabilities;
551                 capabilities = list;
552         }
553         return res;
554 }
555
556 /*!
557  * \internal
558  * \brief Find the aji_resource we want
559  * \param buddy aji_buddy A buddy
560  * \param name
561  * \return aji_resource object
562 */
563 static struct aji_resource *aji_find_resource(struct aji_buddy *buddy, char *name)
564 {
565         struct aji_resource *res = NULL;
566         if (!buddy || !name) {
567                 return res;
568         }
569         res = buddy->resources;
570         while (res) {
571                 if (!strcasecmp(res->resource, name)) {
572                         break;
573                 }
574                 res = res->next;
575         }
576         return res;
577 }
578
579 /*!
580  * \internal
581  * \brief Jabber GTalk function
582  * \param node iks
583  * \return 1 on success, 0 on failure.
584 */
585 static int gtalk_yuck(iks *node)
586 {
587         if (iks_find_with_attrib(node, "c", "node", "http://www.google.com/xmpp/client/caps")) {
588                 ast_debug(1, "Found resource with Googletalk voice capabilities\n");
589                 return 1;
590         } else if (iks_find_with_attrib(node, "caps:c", "ext", "pmuc-v1 sms-v1 camera-v1 video-v1 voice-v1")) {
591                 ast_debug(1, "Found resource with Gmail voice/video chat capabilities\n");
592                 return 1;
593         } else if (iks_find_with_attrib(node, "caps:c", "ext", "pmuc-v1 sms-v1 video-v1 voice-v1")) {
594                 ast_debug(1, "Found resource with Gmail voice/video chat capabilities (no camera)\n");
595                 return 1;
596         }
597
598         return 0;
599 }
600
601 /*!
602  * \internal
603  * \brief Setup the authentication struct
604  * \param id iksid 
605  * \param pass password
606  * \param sid
607  * \return x iks
608 */
609 static iks *jabber_make_auth(iksid * id, const char *pass, const char *sid)
610 {
611         iks *x, *y;
612         x = iks_new("iq");
613         iks_insert_attrib(x, "type", "set");
614         y = iks_insert(x, "query");
615         iks_insert_attrib(y, "xmlns", IKS_NS_AUTH);
616         iks_insert_cdata(iks_insert(y, "username"), id->user, 0);
617         iks_insert_cdata(iks_insert(y, "resource"), id->resource, 0);
618         if (sid) {
619                 char buf[41];
620                 char sidpass[100];
621                 snprintf(sidpass, sizeof(sidpass), "%s%s", sid, pass);
622                 ast_sha1_hash(buf, sidpass);
623                 iks_insert_cdata(iks_insert(y, "digest"), buf, 0);
624         } else {
625                 iks_insert_cdata(iks_insert(y, "password"), pass, 0);
626         }
627         return x;
628 }
629
630 /*!
631  * \internal
632  * \brief Dial plan function status(). puts the status of watched user 
633  * into a channel variable.
634  * \param chan ast_channel
635  * \param data
636  * \retval 0 success
637  * \retval -1 error
638  */
639 static int aji_status_exec(struct ast_channel *chan, const char *data)
640 {
641         struct aji_client *client = NULL;
642         struct aji_buddy *buddy = NULL;
643         struct aji_resource *r = NULL;
644         char *s = NULL;
645         int stat = 7;
646         char status[2];
647         static int deprecation_warning = 0;
648         AST_DECLARE_APP_ARGS(args,
649                 AST_APP_ARG(sender);
650                 AST_APP_ARG(jid);
651                 AST_APP_ARG(variable);
652         );
653         AST_DECLARE_APP_ARGS(jid,
654                 AST_APP_ARG(screenname);
655                 AST_APP_ARG(resource);
656         );
657
658         if (deprecation_warning++ % 10 == 0) {
659                 ast_log(LOG_WARNING, "JabberStatus is deprecated.  Please use the JABBER_STATUS dialplan function in the future.\n");
660         }
661
662         if (!data) {
663                 ast_log(LOG_ERROR, "Usage: JabberStatus(<sender>,<jid>[/<resource>],<varname>\n");
664                 return 0;
665         }
666         s = ast_strdupa(data);
667         AST_STANDARD_APP_ARGS(args, s);
668
669         if (args.argc != 3) {
670                 ast_log(LOG_ERROR, "JabberStatus() requires 3 arguments.\n");
671                 return -1;
672         }
673
674         AST_NONSTANDARD_APP_ARGS(jid, args.jid, '/');
675         if (jid.argc < 1 || jid.argc > 2) {
676                 ast_log(LOG_WARNING, "Wrong JID %s, exiting\n", args.jid);
677                 return -1;
678         }
679
680         if (!(client = ast_aji_get_client(args.sender))) {
681                 ast_log(LOG_WARNING, "Could not find sender connection: '%s'\n", args.sender);
682                 return -1;
683         }
684         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, jid.screenname);
685         if (!buddy) {
686                 ast_log(LOG_WARNING, "Could not find buddy in list: '%s'\n", jid.screenname);
687                 ASTOBJ_UNREF(client, ast_aji_client_destroy);
688                 return -1;
689         }
690         r = aji_find_resource(buddy, jid.resource);
691         if (!r && buddy->resources) {
692                 r = buddy->resources;
693         }
694         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
695         ASTOBJ_UNREF(client, ast_aji_client_destroy);
696         if (!r) {
697                 ast_log(LOG_NOTICE, "Resource '%s' of buddy '%s' was not found\n", jid.resource, jid.screenname);
698         } else {
699                 stat = r->status;
700         }
701         snprintf(status, sizeof(status), "%d", stat);
702         pbx_builtin_setvar_helper(chan, args.variable, status);
703         return 0;
704 }
705
706 /*!
707  * \internal
708  * \brief Dial plan funtcion to retrieve the status of a buddy.
709  * \param channel The associated ast_channel, if there is one
710  * \param data The account, buddy JID, and optional timeout
711  * timeout.
712  * \retval 0 success
713  * \retval -1 failure
714  */
715 static int acf_jabberstatus_read(struct ast_channel *chan, const char *name, char *data, char *buf, size_t buflen)
716 {
717         struct aji_client *client = NULL;
718         struct aji_buddy *buddy = NULL;
719         struct aji_resource *r = NULL;
720         int stat = 7;
721         AST_DECLARE_APP_ARGS(args,
722                 AST_APP_ARG(sender);
723                 AST_APP_ARG(jid);
724         );
725         AST_DECLARE_APP_ARGS(jid,
726                 AST_APP_ARG(screenname);
727                 AST_APP_ARG(resource);
728         );
729
730         if (!data) {
731                 ast_log(LOG_ERROR, "Usage: JABBER_STATUS(<sender>,<jid>[/<resource>])\n");
732                 return 0;
733         }
734         AST_STANDARD_APP_ARGS(args, data);
735
736         if (args.argc != 2) {
737                 ast_log(LOG_ERROR, "JABBER_STATUS requires 2 arguments: sender and jid.\n");
738                 return -1;
739         }
740
741         AST_NONSTANDARD_APP_ARGS(jid, args.jid, '/');
742         if (jid.argc < 1 || jid.argc > 2) {
743                 ast_log(LOG_WARNING, "Wrong JID %s, exiting\n", args.jid);
744                 return -1;
745         }
746
747         if (!(client = ast_aji_get_client(args.sender))) {
748                 ast_log(LOG_WARNING, "Could not find sender connection: '%s'\n", args.sender);
749                 return -1;
750         }
751         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, jid.screenname);
752         if (!buddy) {
753                 ast_log(LOG_WARNING, "Could not find buddy in list: '%s'\n", jid.screenname);
754                 ASTOBJ_UNREF(client, ast_aji_client_destroy);
755                 return -1;
756         }
757         r = aji_find_resource(buddy, jid.resource);
758         if (!r && buddy->resources) {
759                 r = buddy->resources;
760         }
761         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
762         ASTOBJ_UNREF(client, ast_aji_client_destroy);
763         if (!r) {
764                 ast_log(LOG_NOTICE, "Resource %s of buddy %s was not found.\n", jid.resource, jid.screenname);
765         } else {
766                 stat = r->status;
767         }
768         snprintf(buf, buflen, "%d", stat);
769         return 0;
770 }
771
772 static struct ast_custom_function jabberstatus_function = {
773         .name = "JABBER_STATUS",
774         .read = acf_jabberstatus_read,
775 };
776
777 /*!
778  * \internal
779  * \brief Dial plan function to receive a message.
780  * \param channel The associated ast_channel, if there is one
781  * \param data The account, JID, and optional timeout
782  * timeout.
783  * \retval 0 success
784  * \retval -1 failure
785  */
786 static int acf_jabberreceive_read(struct ast_channel *chan, const char *name, char *data, char *buf, size_t buflen)
787 {
788         char *parse = NULL;
789         int timeout;
790         int jidlen, resourcelen;
791         struct timeval start;
792         long diff = 0;
793         struct aji_client *client = NULL;
794         int found = 0;
795         struct aji_message *tmp = NULL;
796         AST_DECLARE_APP_ARGS(args,
797                         AST_APP_ARG(account);
798                         AST_APP_ARG(jid);
799                         AST_APP_ARG(timeout);
800                         );
801         AST_DECLARE_APP_ARGS(jid,
802                         AST_APP_ARG(screenname);
803                         AST_APP_ARG(resource);
804         );
805
806         if (ast_strlen_zero(data)) {
807                 ast_log(LOG_WARNING, "%s requires arguments (account,jid[,timeout])\n", name);
808                 return -1;
809         }
810
811         parse = ast_strdupa(data);
812         AST_STANDARD_APP_ARGS(args, parse);
813
814         if (args.argc < 2 || args.argc > 3) {
815                 ast_log(LOG_WARNING, "%s requires arguments (account,jid[,timeout])\n", name);
816                 return -1;
817         }
818
819         parse = ast_strdupa(args.jid);
820         AST_NONSTANDARD_APP_ARGS(jid, parse, '/');
821         if (jid.argc < 1 || jid.argc > 2 || strlen(args.jid) > AJI_MAX_JIDLEN) {
822                 ast_log(LOG_WARNING, "Invalid JID : %s\n", parse);
823                 return -1;
824         }
825
826         if (ast_strlen_zero(args.timeout)) {
827                 timeout = 20;
828         } else {
829                 sscanf(args.timeout, "%d", &timeout);
830                 if (timeout <= 0) {
831                         ast_log(LOG_WARNING, "Invalid timeout specified: '%s'\n", args.timeout);
832                         return -1;
833                 }
834         }
835
836         jidlen = strlen(jid.screenname);
837         resourcelen = ast_strlen_zero(jid.resource) ? 0 : strlen(jid.resource);
838
839         client = ast_aji_get_client(args.account);
840         if (!client) {
841                 ast_log(LOG_WARNING, "Could not find client %s, exiting\n", args.account);
842                 return -1;
843         }
844
845         ast_debug(3, "Waiting for an XMPP message from %s\n", args.jid);
846
847         start = ast_tvnow();
848
849         if (ast_autoservice_start(chan) < 0) {
850                 ast_log(LOG_WARNING, "Cannot start autoservice for channel %s\n", ast_channel_name(chan));
851                 ASTOBJ_UNREF(client, ast_aji_client_destroy);
852                 return -1;
853         }
854
855         /* search the messages list, grab the first message that matches with
856          * the from JID we're expecting, and remove it from the messages list */
857         while (diff < timeout) {
858                 struct timespec ts = { 0, };
859                 struct timeval wait;
860                 int res;
861
862                 wait = ast_tvadd(start, ast_tv(timeout, 0));
863                 ts.tv_sec = wait.tv_sec;
864                 ts.tv_nsec = wait.tv_usec * 1000;
865
866                 /* wait up to timeout seconds for an incoming message */
867                 ast_mutex_lock(&messagelock);
868                 res = ast_cond_timedwait(&message_received_condition, &messagelock, &ts);
869                 ast_mutex_unlock(&messagelock);
870                 if (res == ETIMEDOUT) {
871                         ast_debug(3, "No message received from %s in %d seconds\n", args.jid, timeout);
872                         break;
873                 }
874
875                 AST_LIST_LOCK(&client->messages);
876                 AST_LIST_TRAVERSE_SAFE_BEGIN(&client->messages, tmp, list) {
877                         if (jid.argc == 1) {
878                                 /* no resource provided, compare bare JIDs */
879                                 if (strncasecmp(jid.screenname, tmp->from, jidlen)) {
880                                         continue;
881                                 }
882                         } else {
883                                 /* resource appended, compare bare JIDs and resources */
884                                 char *resource = strchr(tmp->from, '/');
885                                 if (!resource || strlen(resource) == 0) {
886                                         ast_log(LOG_WARNING, "Remote JID has no resource : %s\n", tmp->from);
887                                         if (strncasecmp(jid.screenname, tmp->from, jidlen)) {
888                                                 continue;
889                                         }
890                                 } else {
891                                         resource ++;
892                                         if (strncasecmp(jid.screenname, tmp->from, jidlen) || strncmp(jid.resource, resource, resourcelen)) {
893                                                 continue;
894                                         }
895                                 }
896                         }
897                         /* check if the message is not too old */
898                         if (ast_tvdiff_sec(ast_tvnow(), tmp->arrived) >= client->message_timeout) {
899                                 ast_debug(3, "Found old message from %s, deleting it\n", tmp->from);
900                                 AST_LIST_REMOVE_CURRENT(list);
901                                 aji_message_destroy(tmp);
902                                 continue;
903                         }
904                         found = 1;
905                         ast_copy_string(buf, tmp->message, buflen);
906                         AST_LIST_REMOVE_CURRENT(list);
907                         aji_message_destroy(tmp);
908                         break;
909                 }
910                 AST_LIST_TRAVERSE_SAFE_END;
911                 AST_LIST_UNLOCK(&client->messages);
912                 if (found) {
913                         break;
914                 }
915
916                 /* check timeout */
917                 diff = ast_tvdiff_ms(ast_tvnow(), start);
918         }
919
920         ASTOBJ_UNREF(client, ast_aji_client_destroy);
921         if (ast_autoservice_stop(chan) < 0) {
922                 ast_log(LOG_WARNING, "Cannot stop autoservice for channel %s\n", ast_channel_name(chan));
923         }
924
925         /* return if we timed out */
926         if (!found) {
927                 ast_log(LOG_NOTICE, "Timed out : no message received from %s\n", args.jid);
928                 return -1;
929         }
930
931         return 0;
932 }
933
934 static struct ast_custom_function jabberreceive_function = {
935         .name = "JABBER_RECEIVE",
936         .read = acf_jabberreceive_read,
937 };
938
939 /*!
940  * \internal
941  * \brief Delete old messages from a given JID
942  * Messages stored during more than client->message_timeout are deleted
943  * \param client Asterisk's XMPP client
944  * \param from the JID we received messages from
945  * \retval the number of deleted messages
946  * \retval -1 failure
947  */
948 static int delete_old_messages(struct aji_client *client, char *from)
949 {
950         int deleted = 0;
951         int isold = 0;
952         struct aji_message *tmp = NULL;
953         if (!client) {
954                 ast_log(LOG_ERROR, "Cannot find our XMPP client\n");
955                 return -1;
956         }
957
958         /* remove old messages */
959         AST_LIST_LOCK(&client->messages);
960         if (AST_LIST_EMPTY(&client->messages)) {
961                 AST_LIST_UNLOCK(&client->messages);
962                 return 0;
963         }
964
965         AST_LIST_TRAVERSE_SAFE_BEGIN(&client->messages, tmp, list) {
966                 if (isold) {
967                         if (!from || !strncasecmp(from, tmp->from, strlen(from))) {
968                                 AST_LIST_REMOVE_CURRENT(list);
969                                 aji_message_destroy(tmp);
970                                 deleted ++;
971                         }
972                 } else if (ast_tvdiff_sec(ast_tvnow(), tmp->arrived) >= client->message_timeout) {
973                         isold = 1;
974                         if (!from || !strncasecmp(from, tmp->from, strlen(from))) {
975                                 AST_LIST_REMOVE_CURRENT(list);
976                                 aji_message_destroy(tmp);
977                                 deleted ++;
978                         }
979                 }
980         }
981         AST_LIST_TRAVERSE_SAFE_END;
982         AST_LIST_UNLOCK(&client->messages);
983
984         return deleted;
985 }
986
987 /*!
988  * \internal
989  * \brief Delete old messages
990  * Messages stored during more than client->message_timeout are deleted
991  * \param client Asterisk's XMPP client
992  * \retval the number of deleted messages
993  * \retval -1 failure
994  */
995 static int delete_old_messages_all(struct aji_client *client)
996 {
997         return delete_old_messages(client, NULL);
998 }
999
1000 /*!
1001 * \brief Application to join a chat room
1002 * \param chan ast_channel
1003 * \param data  Data is sender|jid|nickname.
1004 * \retval 0 success
1005 * \retval -1 error
1006 */
1007 static int aji_join_exec(struct ast_channel *chan, const char *data)
1008 {
1009         struct aji_client *client = NULL;
1010         char *s;
1011         char nick[AJI_MAX_RESJIDLEN];
1012
1013         AST_DECLARE_APP_ARGS(args,
1014                 AST_APP_ARG(sender);
1015                 AST_APP_ARG(jid);
1016                 AST_APP_ARG(nick);
1017         );
1018
1019         if (!data) {
1020                 ast_log(LOG_ERROR, "%s requires arguments (sender,jid[,nickname])\n", app_ajijoin);
1021                 return -1;
1022         }
1023         s = ast_strdupa(data);
1024
1025         AST_STANDARD_APP_ARGS(args, s);
1026         if (args.argc < 2 || args.argc > 3) {
1027                 ast_log(LOG_ERROR, "%s requires arguments (sender,jid[,nickname])\n", app_ajijoin);
1028                 return -1;
1029         }
1030
1031         if (strchr(args.jid, '/')) {
1032                 ast_log(LOG_ERROR, "Invalid room name : resource must not be appended\n");
1033                 return -1;
1034         }
1035
1036         if (!(client = ast_aji_get_client(args.sender))) {
1037                 ast_log(LOG_ERROR, "Could not find sender connection: '%s'\n", args.sender);
1038                 return -1;
1039         }
1040
1041         if (!ast_strlen_zero(args.nick)) {
1042                 snprintf(nick, AJI_MAX_RESJIDLEN, "%s", args.nick);
1043         } else {
1044                 if (client->component) {
1045                         sprintf(nick, "asterisk");
1046                 } else {
1047                         snprintf(nick, AJI_MAX_RESJIDLEN, "%s", client->jid->user);
1048                 }
1049         }
1050
1051         if (!ast_strlen_zero(args.jid) && strchr(args.jid, '@')) {
1052                 ast_aji_join_chat(client, args.jid, nick);
1053         } else {
1054                 ast_log(LOG_ERROR, "Problem with specified jid of '%s'\n", args.jid);
1055         }
1056
1057         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1058         return 0;
1059 }
1060
1061 /*!
1062 * \brief Application to leave a chat room
1063 * \param chan ast_channel
1064 * \param data  Data is sender|jid|nickname.
1065 * \retval 0 success
1066 * \retval -1 error
1067 */
1068 static int aji_leave_exec(struct ast_channel *chan, const char *data)
1069 {
1070         struct aji_client *client = NULL;
1071         char *s;
1072         char nick[AJI_MAX_RESJIDLEN];
1073         AST_DECLARE_APP_ARGS(args,
1074                 AST_APP_ARG(sender);
1075                 AST_APP_ARG(jid);
1076                 AST_APP_ARG(nick);
1077         );
1078
1079         if (!data) {
1080                 ast_log(LOG_ERROR, "%s requires arguments (sender,jid[,nickname])\n", app_ajileave);
1081                 return -1;
1082         }
1083         s = ast_strdupa(data);
1084
1085         AST_STANDARD_APP_ARGS(args, s);
1086         if (args.argc < 2 || args.argc > 3) {
1087                 ast_log(LOG_ERROR, "%s requires arguments (sender,jid[,nickname])\n", app_ajileave);
1088                 return -1;
1089         }
1090
1091         if (strchr(args.jid, '/')) {
1092                 ast_log(LOG_ERROR, "Invalid room name, resource must not be appended\n");
1093                 return -1;
1094         }
1095
1096         if (!(client = ast_aji_get_client(args.sender))) {
1097                 ast_log(LOG_ERROR, "Could not find sender connection: '%s'\n", args.sender);
1098                 return -1;
1099         }
1100
1101         if (!ast_strlen_zero(args.nick)) {
1102                 snprintf(nick, AJI_MAX_RESJIDLEN, "%s", args.nick);
1103         } else {
1104                 if (client->component) {
1105                         sprintf(nick, "asterisk");
1106                 } else {
1107                         snprintf(nick, AJI_MAX_RESJIDLEN, "%s", client->jid->user);
1108                 }
1109         }
1110
1111         if (!ast_strlen_zero(args.jid) && strchr(args.jid, '@')) {
1112                 ast_aji_leave_chat(client, args.jid, nick);
1113         }
1114         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1115         return 0;
1116 }
1117
1118 /*!
1119  * \internal
1120  * \brief Dial plan function to send a message.
1121  * \param chan ast_channel
1122  * \param data  Data is account,jid,message.
1123  * \retval 0 success
1124  * \retval -1 failure
1125  */
1126 static int aji_send_exec(struct ast_channel *chan, const char *data)
1127 {
1128         struct aji_client *client = NULL;
1129         char *s;
1130         AST_DECLARE_APP_ARGS(args,
1131                 AST_APP_ARG(sender);
1132                 AST_APP_ARG(recipient);
1133                 AST_APP_ARG(message);
1134         );
1135
1136         if (!data) {
1137                 ast_log(LOG_WARNING, "%s requires arguments (account,jid,message)\n", app_ajisend);
1138                 return -1;
1139         }
1140         s = ast_strdupa(data);
1141
1142         AST_STANDARD_APP_ARGS(args, s);
1143         if (args.argc < 3) {
1144                 ast_log(LOG_WARNING, "%s requires arguments (account,jid,message)\n", app_ajisend);
1145                 return -1;
1146         }
1147
1148         if (!(client = ast_aji_get_client(args.sender))) {
1149                 ast_log(LOG_WARNING, "Could not find sender connection: '%s'\n", args.sender);
1150                 return -1;
1151         }
1152         if (strchr(args.recipient, '@') && !ast_strlen_zero(args.message)) {
1153                 ast_aji_send_chat(client, args.recipient, args.message);
1154         }
1155         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1156         return 0;
1157 }
1158
1159 static int msg_send_cb(const struct ast_msg *msg, const char *to, const char *from)
1160 {
1161         struct aji_client *client;
1162         char *sender;
1163         char *dest;
1164         int res;
1165
1166         sender = ast_strdupa(from);
1167         strsep(&sender, ":");
1168         dest = ast_strdupa(to);
1169         strsep(&dest, ":");
1170
1171         if (ast_strlen_zero(sender)) {
1172                 ast_log(LOG_ERROR, "MESSAGE(from) of '%s' invalid for xmpp\n", from);
1173                 return -1;
1174         }
1175
1176         if (!(client = ast_aji_get_client(sender))) {
1177                 ast_log(LOG_WARNING, "Could not finder account to send from as '%s'\n", sender);
1178                 return -1;
1179         }
1180
1181         ast_debug(1, "Sending message to '%s' from '%s'\n", dest, client->name);
1182
1183         res = ast_aji_send_chat(client, dest, ast_msg_get_body(msg));
1184         if (res != IKS_OK) {
1185                 ast_log(LOG_WARNING, "Failed to send xmpp message (%d).\n", res);
1186         }
1187
1188         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1189         return res == IKS_OK ? 0 : -1;
1190 }
1191
1192 /*!
1193 * \brief Application to send a message to a groupchat.
1194 * \param chan ast_channel
1195 * \param data  Data is sender|groupchat|message.
1196 * \retval 0 success
1197 * \retval -1 error
1198 */
1199 static int aji_sendgroup_exec(struct ast_channel *chan, const char *data)
1200 {
1201         struct aji_client *client = NULL;
1202         char *s;
1203         char nick[AJI_MAX_RESJIDLEN];
1204         int res = 0;
1205         AST_DECLARE_APP_ARGS(args,
1206                 AST_APP_ARG(sender);
1207                 AST_APP_ARG(groupchat);
1208                 AST_APP_ARG(message);
1209                 AST_APP_ARG(nick);
1210         );
1211
1212         if (!data) {
1213                 ast_log(LOG_ERROR, "%s requires arguments (sender,groupchatid,message[,nickname])\n", app_ajisendgroup);
1214                 return -1;
1215         }
1216         s = ast_strdupa(data);
1217
1218         AST_STANDARD_APP_ARGS(args, s);
1219         if (args.argc < 3 || args.argc > 4) {
1220                 ast_log(LOG_ERROR, "%s requires arguments (sender,groupchatid,message[,nickname])\n", app_ajisendgroup);
1221                 return -1;
1222         }
1223
1224         if (!(client = ast_aji_get_client(args.sender))) {
1225                 ast_log(LOG_ERROR, "Could not find sender connection: '%s'\n", args.sender);
1226                 return -1;
1227         }
1228
1229         if (ast_strlen_zero(args.nick) || args.argc == 3) {
1230                 if (client->component) {
1231                         sprintf(nick, "asterisk");
1232                 } else {
1233                         snprintf(nick, AJI_MAX_RESJIDLEN, "%s", client->jid->user);
1234                 }
1235         } else {
1236                 snprintf(nick, AJI_MAX_RESJIDLEN, "%s", args.nick);
1237         }
1238
1239         if (strchr(args.groupchat, '@') && !ast_strlen_zero(args.message)) {
1240                 res = ast_aji_send_groupchat(client, nick, args.groupchat, args.message);
1241         }
1242
1243         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1244         if (res != IKS_OK) {
1245                 return -1;
1246         }
1247         return 0;
1248 }
1249
1250 /*!
1251  * \internal
1252  * \brief Tests whether the connection is secured or not
1253  * \return 0 if the connection is not secured
1254  */
1255 static int aji_is_secure(struct aji_client *client)
1256 {
1257 #ifdef HAVE_OPENSSL
1258         return client->stream_flags & SECURE;
1259 #else
1260         return 0;
1261 #endif
1262 }
1263
1264 #ifdef HAVE_OPENSSL
1265 /*!
1266  * \internal
1267  * \brief Starts the TLS procedure
1268  * \param client the configured XMPP client we use to connect to a XMPP server
1269  * \return IKS_OK on success, an error code if sending failed, IKS_NET_TLSFAIL
1270  * if OpenSSL is not installed
1271  */
1272 static int aji_start_tls(struct aji_client *client)
1273 {
1274         int ret;
1275
1276         /* This is sent not encrypted */
1277         if ((ret = iks_send_raw(client->p, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>"))) {
1278                 return ret;
1279         }
1280
1281         client->stream_flags |= TRY_SECURE;
1282         return IKS_OK;
1283 }
1284
1285 /*!
1286  * \internal
1287  * \brief TLS handshake, OpenSSL initialization
1288  * \param client the configured XMPP client we use to connect to a XMPP server
1289  * \return IKS_OK on success, IKS_NET_TLSFAIL on failure
1290  */
1291 static int aji_tls_handshake(struct aji_client *client)
1292 {
1293         int sock;
1294
1295         ast_debug(1, "Starting TLS handshake\n");
1296
1297         /* Choose an SSL/TLS protocol version, create SSL_CTX */
1298         client->ssl_method = SSLv3_method();
1299         if (!(client->ssl_context = SSL_CTX_new((SSL_METHOD *) client->ssl_method))) {
1300                 return IKS_NET_TLSFAIL;
1301         }
1302
1303         /* Create new SSL session */
1304         if (!(client->ssl_session = SSL_new(client->ssl_context))) {
1305                 return IKS_NET_TLSFAIL;
1306         }
1307
1308         /* Enforce TLS on our XMPP connection */
1309         sock = iks_fd(client->p);
1310         if (!SSL_set_fd(client->ssl_session, sock)) {
1311                 return IKS_NET_TLSFAIL;
1312         }
1313
1314         /* Perform SSL handshake */
1315         if (!SSL_connect(client->ssl_session)) {
1316                 return IKS_NET_TLSFAIL;
1317         }
1318
1319         client->stream_flags &= (~TRY_SECURE);
1320         client->stream_flags |= SECURE;
1321
1322         /* Sent over the established TLS connection */
1323         if (aji_send_header(client, client->jid->server) != IKS_OK) {
1324                 return IKS_NET_TLSFAIL;
1325         }
1326
1327         ast_debug(1, "TLS started with server\n");
1328
1329         return IKS_OK;
1330 }
1331 #endif /* HAVE_OPENSSL */
1332
1333 /*!
1334  * \internal
1335  * \brief Secured or unsecured IO socket receiving function
1336  * \param client the configured XMPP client we use to connect to a XMPP server
1337  * \param buffer the reception buffer
1338  * \param buf_len the size of the buffer
1339  * \param timeout the select timer
1340  * \retval the number of read bytes
1341  * \retval 0 timeout expiration
1342  * \retval -1 error
1343  */
1344 static int aji_io_recv(struct aji_client *client, char *buffer, size_t buf_len, int timeout)
1345 {
1346         struct pollfd pfd = { .events = POLLIN };
1347         int len, res;
1348
1349 #ifdef HAVE_OPENSSL
1350         if (aji_is_secure(client)) {
1351                 pfd.fd = SSL_get_fd(client->ssl_session);
1352                 if (pfd.fd < 0) {
1353                         return -1;
1354                 }
1355         } else
1356 #endif /* HAVE_OPENSSL */
1357                 pfd.fd = iks_fd(client->p);
1358
1359         res = ast_poll(&pfd, 1, timeout > 0 ? timeout * 1000 : -1);
1360         if (res > 0) {
1361 #ifdef HAVE_OPENSSL
1362                 if (aji_is_secure(client)) {
1363                         len = SSL_read(client->ssl_session, buffer, buf_len);
1364                 } else
1365 #endif /* HAVE_OPENSSL */
1366                         len = recv(pfd.fd, buffer, buf_len, 0);
1367
1368                 if (len > 0) {
1369                         return len;
1370                 } else if (len <= 0) {
1371                         return -1;
1372                 }
1373         }
1374         return res;
1375 }
1376
1377 /*!
1378  * \internal
1379  * \brief Tries to receive data from the Jabber server
1380  * \param client the configured XMPP client we use to connect to a XMPP server
1381  * \param timeout the timeout value
1382  * This function receives (encrypted or unencrypted) data from the XMPP server,
1383  * and passes it to the parser.
1384  * \retval IKS_OK success
1385  * \retval IKS_NET_RWERR IO error
1386  * \retval IKS_NET_NOCONN no connection available
1387  * \retval IKS_NET_EXPIRED timeout expiration
1388  */
1389 static int aji_recv (struct aji_client *client, int timeout)
1390 {
1391         int len, ret;
1392         char buf[NET_IO_BUF_SIZE - 1];
1393         char newbuf[NET_IO_BUF_SIZE - 1];
1394         int pos = 0;
1395         int newbufpos = 0;
1396         unsigned char c;
1397
1398         memset(buf, 0, sizeof(buf));
1399         memset(newbuf, 0, sizeof(newbuf));
1400
1401         while (1) {
1402                 len = aji_io_recv(client, buf, NET_IO_BUF_SIZE - 2, timeout);
1403                 if (len < 0) return IKS_NET_RWERR;
1404                 if (len == 0) return IKS_NET_EXPIRED;
1405                 buf[len] = '\0';
1406
1407                 /* our iksemel parser won't work as expected if we feed
1408                    it with XML packets that contain multiple whitespace
1409                    characters between tags */
1410                 while (pos < len) {
1411                         c = buf[pos];
1412                         /* if we stumble on the ending tag character,
1413                            we skip any whitespace that follows it*/
1414                         if (c == '>') {
1415                                 while (isspace(buf[pos+1])) {
1416                                         pos++;
1417                                 }
1418                         }
1419                         newbuf[newbufpos] = c;
1420                         newbufpos ++;
1421                         pos++;
1422                 }
1423                 pos = 0;
1424                 newbufpos = 0;
1425
1426                 /* Log the message here, because iksemel's logHook is
1427                    unaccessible */
1428                 aji_log_hook(client, buf, len, 1);
1429
1430                 /* let iksemel deal with the string length,
1431                    and reset our buffer */
1432                 ret = iks_parse(client->p, newbuf, 0, 0);
1433                 memset(newbuf, 0, sizeof(newbuf));
1434
1435                 switch (ret) {
1436                 case IKS_NOMEM:
1437                         ast_log(LOG_WARNING, "Parsing failure: Out of memory.\n");
1438                         break;
1439                 case IKS_BADXML:
1440                         ast_log(LOG_WARNING, "Parsing failure: Invalid XML.\n");
1441                         break;
1442                 case IKS_HOOK:
1443                         ast_log(LOG_WARNING, "Parsing failure: Hook returned an error.\n");
1444                         break;
1445                 }
1446                 if (ret != IKS_OK) {
1447                         return ret;
1448                 }
1449                 ast_debug(3, "XML parsing successful\n");
1450         }
1451         return IKS_OK;
1452 }
1453
1454 /*!
1455  * \internal
1456  * \brief Sends XMPP header to the server
1457  * \param client the configured XMPP client we use to connect to a XMPP server
1458  * \param to the target XMPP server
1459  * \return IKS_OK on success, any other value on failure
1460  */
1461 static int aji_send_header(struct aji_client *client, const char *to)
1462 {
1463         char *msg;
1464         int len, err;
1465
1466         len = 91 + strlen(client->name_space) + 6 + strlen(to) + 16 + 1;
1467         msg = iks_malloc(len);
1468         if (!msg)
1469                 return IKS_NOMEM;
1470         sprintf(msg, "<?xml version='1.0'?>"
1471                 "<stream:stream xmlns:stream='http://etherx.jabber.org/streams' xmlns='"
1472                 "%s' to='%s' version='1.0'>", client->name_space, to);
1473         err = aji_send_raw(client, msg);
1474         iks_free(msg);
1475         if (err != IKS_OK)
1476                 return err;
1477
1478         return IKS_OK;
1479 }
1480
1481 /*!
1482  * \brief Wraps raw sending
1483  * \param client the configured XMPP client we use to connect to a XMPP server
1484  * \param x the XMPP packet to send
1485  * \return IKS_OK on success, any other value on failure
1486  */
1487 int ast_aji_send(struct aji_client *client, iks *x)
1488 {
1489         return aji_send_raw(client, iks_string(iks_stack(x), x));
1490 }
1491
1492 /*!
1493  * \internal
1494  * \brief Sends an XML string over an XMPP connection
1495  * \param client the configured XMPP client we use to connect to a XMPP server
1496  * \param xmlstr the XML string to send
1497  * The XML data is sent whether the connection is secured or not. In the
1498  * latter case, we just call iks_send_raw().
1499  * \return IKS_OK on success, any other value on failure
1500  */
1501 static int aji_send_raw(struct aji_client *client, const char *xmlstr)
1502 {
1503         int ret;
1504 #ifdef HAVE_OPENSSL
1505         int len = strlen(xmlstr);
1506
1507         if (aji_is_secure(client)) {
1508                 ret = SSL_write(client->ssl_session, xmlstr, len);
1509                 if (ret) {
1510                         /* Log the message here, because iksemel's logHook is
1511                            unaccessible */
1512                         aji_log_hook(client, xmlstr, len, 0);
1513                         return IKS_OK;
1514                 }
1515         }
1516 #endif
1517         /* If needed, data will be sent unencrypted, and logHook will
1518            be called inside iks_send_raw */
1519         ret = iks_send_raw(client->p, xmlstr);
1520         if (ret != IKS_OK) {
1521                 return ret;
1522         }
1523
1524         return IKS_OK;
1525 }
1526
1527 /*!
1528  * \internal
1529  * \brief the debug loop.
1530  * \param data void
1531  * \param xmpp xml data as string
1532  * \param size size of string
1533  * \param is_incoming direction of packet 1 for inbound 0 for outbound.
1534  */
1535 static void aji_log_hook(void *data, const char *xmpp, size_t size, int is_incoming)
1536 {
1537         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1538
1539         if (client->debug) {
1540                 if (is_incoming) {
1541                         ast_verbose("\nJABBER: %s INCOMING: %s\n", client->name, xmpp);
1542                 } else {
1543                         if (strlen(xmpp) == 1) {
1544                                 if (option_debug > 2  && xmpp[0] == ' ') {
1545                                         ast_verbose("\nJABBER: Keep alive packet\n");
1546                                 }
1547                         } else {
1548                                 ast_verbose("\nJABBER: %s OUTGOING: %s\n", client->name, xmpp);
1549                         }
1550                 }
1551
1552         }
1553         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1554 }
1555
1556 /*!
1557  * \internal
1558  * \brief A wrapper function for iks_start_sasl
1559  * \param client the configured XMPP client we use to connect to a XMPP server
1560  * \param type the SASL authentication type. Supported types are PLAIN and MD5
1561  * \param username
1562  * \param pass password.
1563  *
1564  * \return IKS_OK on success, IKSNET_NOTSUPP on failure.
1565  */
1566 static int aji_start_sasl(struct aji_client *client, enum ikssasltype type, char *username, char *pass)
1567 {
1568         iks *x = NULL;
1569         int len;
1570         char *s;
1571         char *base64;
1572
1573         /* trigger SASL DIGEST-MD5 only over an unsecured connection.
1574            iks_start_sasl is an iksemel API function and relies on GnuTLS,
1575            whereas we use OpenSSL */
1576         if ((type & IKS_STREAM_SASL_MD5) && !aji_is_secure(client))
1577                 return iks_start_sasl(client->p, IKS_SASL_DIGEST_MD5, username, pass); 
1578         if (!(type & IKS_STREAM_SASL_PLAIN)) {
1579                 ast_log(LOG_ERROR, "Server does not support SASL PLAIN authentication\n");
1580                 return IKS_NET_NOTSUPP;
1581         }
1582
1583         x = iks_new("auth"); 
1584         if (!x) {
1585                 ast_log(LOG_ERROR, "Out of memory.\n");
1586                 return IKS_NET_NOTSUPP;
1587         }
1588
1589         iks_insert_attrib(x, "xmlns", IKS_NS_XMPP_SASL);
1590         len = strlen(username) + strlen(pass) + 3;
1591         s = ast_alloca(len);
1592         base64 = ast_alloca((len + 2) * 4 / 3);
1593         iks_insert_attrib(x, "mechanism", "PLAIN");
1594         snprintf(s, len, "%c%s%c%s", 0, username, 0, pass);
1595
1596         /* exclude the NULL training byte from the base64 encoding operation
1597            as some XMPP servers will refuse it.
1598            The format for authentication is [authzid]\0authcid\0password
1599            not [authzid]\0authcid\0password\0 */
1600         ast_base64encode(base64, (const unsigned char *) s, len - 1, (len + 2) * 4 / 3);
1601         iks_insert_cdata(x, base64, 0);
1602         ast_aji_send(client, x);
1603         iks_delete(x);
1604
1605         return IKS_OK;
1606 }
1607
1608 /*!
1609  * \internal
1610  * \brief The action hook parses the inbound packets, constantly running.
1611  * \param data aji client structure 
1612  * \param type type of packet 
1613  * \param node the actual packet.
1614  * \return IKS_OK or IKS_HOOK .
1615  */
1616 static int aji_act_hook(void *data, int type, iks *node)
1617 {
1618         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1619         ikspak *pak = NULL;
1620         iks *auth = NULL;
1621         int features = 0;
1622
1623         if (!node) {
1624                 ast_log(LOG_ERROR, "aji_act_hook was called with out a packet\n"); /* most likely cause type is IKS_NODE_ERROR lost connection */
1625                 ASTOBJ_UNREF(client, ast_aji_client_destroy);
1626                 return IKS_HOOK;
1627         }
1628
1629         if (client->state == AJI_DISCONNECTING) {
1630                 ASTOBJ_UNREF(client, ast_aji_client_destroy);
1631                 return IKS_HOOK;
1632         }
1633
1634         pak = iks_packet(node);
1635
1636         /* work around iksemel's impossibility to recognize node names
1637          * containing a semicolon. Set the namespace of the corresponding
1638          * node accordingly. */
1639         if (iks_has_children(node) && strchr(iks_name(iks_child(node)), ':')) {
1640                 char *node_ns = NULL;
1641                 char attr[AJI_MAX_ATTRLEN];
1642                 char *node_name = iks_name(iks_child(node));
1643                 char *aux = strchr(node_name, ':') + 1;
1644                 snprintf(attr, strlen("xmlns:") + (strlen(node_name) - strlen(aux)), "xmlns:%s", node_name);
1645                 node_ns = iks_find_attrib(iks_child(node), attr);
1646                 if (node_ns) {
1647                         pak->ns = node_ns;
1648                         pak->query = iks_child(node);
1649                 }
1650         }
1651
1652
1653         if (!client->component) { /*client */
1654                 switch (type) {
1655                 case IKS_NODE_START:
1656                         if (client->usetls && !aji_is_secure(client)) {
1657 #ifndef HAVE_OPENSSL
1658                                 ast_log(LOG_ERROR, "TLS connection cannot be established. Please install OpenSSL and its development libraries on this system, or disable the TLS option in your configuration file\n");
1659                                 ASTOBJ_UNREF(client, ast_aji_client_destroy);
1660                                 return IKS_HOOK;
1661 #else
1662                                 if (aji_start_tls(client) == IKS_NET_TLSFAIL) {
1663                                         ast_log(LOG_ERROR, "Could not start TLS\n");
1664                                         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1665                                         return IKS_HOOK;
1666                                 }
1667                                 break;
1668 #endif
1669                         }
1670                         if (!client->usesasl) {
1671                                 iks_filter_add_rule(client->f, aji_client_connect, client, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_SUBTYPE, IKS_TYPE_RESULT, IKS_RULE_ID, client->mid, IKS_RULE_DONE);
1672                                 auth = jabber_make_auth(client->jid, client->password, iks_find_attrib(node, "id"));
1673                                 if (auth) {
1674                                         iks_insert_attrib(auth, "id", client->mid);
1675                                         iks_insert_attrib(auth, "to", client->jid->server);
1676                                         ast_aji_increment_mid(client->mid);
1677                                         ast_aji_send(client, auth);
1678                                         iks_delete(auth);
1679                                 } else {
1680                                         ast_log(LOG_ERROR, "Out of memory.\n");
1681                                 }
1682                         }
1683                         break;
1684
1685                 case IKS_NODE_NORMAL:
1686 #ifdef HAVE_OPENSSL
1687                         if (client->stream_flags & TRY_SECURE) {
1688                                 if (!strcmp("proceed", iks_name(node))) {
1689                                         return aji_tls_handshake(client);
1690                                 }
1691                         }
1692 #endif
1693                         if (!strcmp("stream:features", iks_name(node))) {
1694                                 features = iks_stream_features(node);
1695                                 if (client->usesasl) {
1696                                         if (client->usetls && !aji_is_secure(client)) {
1697                                                 break;
1698                                         }
1699                                         if (client->authorized) {
1700                                                 if (features & IKS_STREAM_BIND) {
1701                                                         iks_filter_add_rule(client->f, aji_client_connect, client, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_SUBTYPE, IKS_TYPE_RESULT, IKS_RULE_DONE);
1702                                                         auth = iks_make_resource_bind(client->jid);
1703                                                         if (auth) {
1704                                                                 iks_insert_attrib(auth, "id", client->mid);
1705                                                                 ast_aji_increment_mid(client->mid);
1706                                                                 ast_aji_send(client, auth);
1707                                                                 iks_delete(auth);
1708                                                         } else {
1709                                                                 ast_log(LOG_ERROR, "Out of memory.\n");
1710                                                                 break;
1711                                                         }
1712                                                 }
1713                                                 if (features & IKS_STREAM_SESSION) {
1714                                                         iks_filter_add_rule (client->f, aji_client_connect, client, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_SUBTYPE, IKS_TYPE_RESULT, IKS_RULE_ID, "auth", IKS_RULE_DONE);
1715                                                         auth = iks_make_session();
1716                                                         if (auth) {
1717                                                                 iks_insert_attrib(auth, "id", "auth");
1718                                                                 ast_aji_increment_mid(client->mid);
1719                                                                 ast_aji_send(client, auth);
1720                                                                 iks_delete(auth);
1721                                                         } else {
1722                                                                 ast_log(LOG_ERROR, "Out of memory.\n");
1723                                                         }
1724                                                 }
1725                                         } else {
1726                                                 int ret;
1727                                                 if (!client->jid->user) {
1728                                                         ast_log(LOG_ERROR, "Malformed Jabber ID : %s (domain missing?)\n", client->jid->full);
1729                                                         break;
1730                                                 }
1731
1732                                                 ret = aji_start_sasl(client, features, client->jid->user, client->password);
1733                                                 if (ret != IKS_OK) {
1734                                                         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1735                                                         return IKS_HOOK;
1736                                                 }
1737                                                 break;
1738                                         }
1739                                 }
1740                         } else if (!strcmp("failure", iks_name(node))) {
1741                                 ast_log(LOG_ERROR, "JABBER: encryption failure. possible bad password.\n");
1742                         } else if (!strcmp("success", iks_name(node))) {
1743                                 client->authorized = 1;
1744                                 aji_send_header(client, client->jid->server);
1745                         }
1746                         break;
1747                 case IKS_NODE_ERROR:
1748                         ast_log(LOG_ERROR, "JABBER: Node Error\n");
1749                         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1750                         return IKS_HOOK;
1751                         break;
1752                 case IKS_NODE_STOP:
1753                         ast_log(LOG_WARNING, "JABBER: Disconnected\n");
1754                         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1755                         return IKS_HOOK;
1756                         break;
1757                 }
1758         } else if (client->state != AJI_CONNECTED && client->component) {
1759                 switch (type) {
1760                 case IKS_NODE_START:
1761                         if (client->state == AJI_DISCONNECTED) {
1762                                 char secret[160], shasum[320], *handshake;
1763
1764                                 sprintf(secret, "%s%s", pak->id, client->password);
1765                                 ast_sha1_hash(shasum, secret);
1766                                 if (ast_asprintf(&handshake, "<handshake>%s</handshake>", shasum) >= 0) {
1767                                         aji_send_raw(client, handshake);
1768                                         ast_free(handshake);
1769                                 }
1770                                 client->state = AJI_CONNECTING;
1771                                 if (aji_recv(client, 1) == 2) /*XXX proper result for iksemel library on iks_recv of <handshake/> XXX*/
1772                                         client->state = AJI_CONNECTED;
1773                                 else
1774                                         ast_log(LOG_WARNING, "Jabber didn't seem to handshake, failed to authenticate.\n");
1775                                 break;
1776                         }
1777                         break;
1778
1779                 case IKS_NODE_NORMAL:
1780                         break;
1781
1782                 case IKS_NODE_ERROR:
1783                         ast_log(LOG_ERROR, "JABBER: Node Error\n");
1784                         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1785                         return IKS_HOOK;
1786
1787                 case IKS_NODE_STOP:
1788                         ast_log(LOG_WARNING, "JABBER: Disconnected\n");
1789                         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1790                         return IKS_HOOK;
1791                 }
1792         }
1793
1794         switch (pak->type) {
1795         case IKS_PAK_NONE:
1796                 ast_debug(1, "JABBER: I don't know what to do with paktype NONE.\n");
1797                 break;
1798         case IKS_PAK_MESSAGE:
1799                 aji_handle_message(client, pak);
1800                 ast_debug(1, "JABBER: Handling paktype MESSAGE.\n");
1801                 break;
1802         case IKS_PAK_PRESENCE:
1803                 aji_handle_presence(client, pak);
1804                 ast_debug(1, "JABBER: Handling paktype PRESENCE\n");
1805                 break;
1806         case IKS_PAK_S10N:
1807                 aji_handle_subscribe(client, pak);
1808                 ast_debug(1, "JABBER: Handling paktype S10N\n");
1809                 break;
1810         case IKS_PAK_IQ:
1811                 ast_debug(1, "JABBER: Handling paktype IQ\n");
1812                 aji_handle_iq(client, node);
1813                 break;
1814         default:
1815                 ast_debug(1, "JABBER: I don't know anything about paktype '%d'\n", pak->type);
1816                 break;
1817         }
1818
1819         iks_filter_packet(client->f, pak);
1820
1821         if (node)
1822                 iks_delete(node);
1823
1824         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1825         return IKS_OK;
1826 }
1827 /*!
1828  * \internal
1829  * \brief Unknown
1830  * \param data void
1831  * \param pak ikspak
1832  * \return IKS_FILTER_EAT.
1833 */
1834 static int aji_register_approve_handler(void *data, ikspak *pak)
1835 {
1836         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1837         iks *iq = NULL, *presence = NULL, *x = NULL;
1838
1839         iq = iks_new("iq");
1840         presence = iks_new("presence");
1841         x = iks_new("x");
1842         if (client && iq && presence && x) {
1843                 if (!iks_find(pak->query, "remove")) {
1844                         iks_insert_attrib(iq, "from", client->jid->full);
1845                         iks_insert_attrib(iq, "to", pak->from->full);
1846                         iks_insert_attrib(iq, "id", pak->id);
1847                         iks_insert_attrib(iq, "type", "result");
1848                         ast_aji_send(client, iq);
1849
1850                         iks_insert_attrib(presence, "from", client->jid->full);
1851                         iks_insert_attrib(presence, "to", pak->from->partial);
1852                         iks_insert_attrib(presence, "id", client->mid);
1853                         ast_aji_increment_mid(client->mid);
1854                         iks_insert_attrib(presence, "type", "subscribe");
1855                         iks_insert_attrib(x, "xmlns", "vcard-temp:x:update");
1856                         iks_insert_node(presence, x);
1857                         ast_aji_send(client, presence);
1858                 }
1859         } else {
1860                 ast_log(LOG_ERROR, "Out of memory.\n");
1861         }
1862
1863         iks_delete(iq);
1864         iks_delete(presence);
1865         iks_delete(x);
1866
1867         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1868         return IKS_FILTER_EAT;
1869 }
1870 /*!
1871  * \internal
1872  * \brief register handler for incoming querys (IQ's)
1873  * \param data incoming aji_client request
1874  * \param pak ikspak
1875  * \return IKS_FILTER_EAT.
1876 */
1877 static int aji_register_query_handler(void *data, ikspak *pak)
1878 {
1879         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1880         struct aji_buddy *buddy = NULL;
1881         iks *iq = NULL, *query = NULL;
1882
1883         client = (struct aji_client *) data;
1884
1885         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
1886         if (!buddy) {
1887                 iks  *error = NULL, *notacceptable = NULL;
1888
1889                 ast_log(LOG_ERROR, "Someone.... %s tried to register but they aren't allowed\n", pak->from->partial);
1890                 iq = iks_new("iq");
1891                 query = iks_new("query");
1892                 error = iks_new("error");
1893                 notacceptable = iks_new("not-acceptable");
1894                 if (iq && query && error && notacceptable) {
1895                         iks_insert_attrib(iq, "type", "error");
1896                         iks_insert_attrib(iq, "from", client->user);
1897                         iks_insert_attrib(iq, "to", pak->from->full);
1898                         iks_insert_attrib(iq, "id", pak->id);
1899                         iks_insert_attrib(query, "xmlns", "jabber:iq:register");
1900                         iks_insert_attrib(error, "code" , "406");
1901                         iks_insert_attrib(error, "type", "modify");
1902                         iks_insert_attrib(notacceptable, "xmlns", "urn:ietf:params:xml:ns:xmpp-stanzas");
1903                         iks_insert_node(iq, query);
1904                         iks_insert_node(iq, error);
1905                         iks_insert_node(error, notacceptable);
1906                         ast_aji_send(client, iq);
1907                 } else {
1908                         ast_log(LOG_ERROR, "Out of memory.\n");
1909                 }
1910
1911                 iks_delete(error);
1912                 iks_delete(notacceptable);
1913         } else if (!iks_find_attrib(pak->query, "node")) {
1914                 iks *instructions = NULL;
1915                 char *explain = "Welcome to Asterisk - the Open Source PBX.\n";
1916                 iq = iks_new("iq");
1917                 query = iks_new("query");
1918                 instructions = iks_new("instructions");
1919                 if (iq && query && instructions && client) {
1920                         iks_insert_attrib(iq, "from", client->user);
1921                         iks_insert_attrib(iq, "to", pak->from->full);
1922                         iks_insert_attrib(iq, "id", pak->id);
1923                         iks_insert_attrib(iq, "type", "result");
1924                         iks_insert_attrib(query, "xmlns", "jabber:iq:register");
1925                         iks_insert_cdata(instructions, explain, 0);
1926                         iks_insert_node(iq, query);
1927                         iks_insert_node(query, instructions);
1928                         ast_aji_send(client, iq);
1929                 } else {
1930                         ast_log(LOG_ERROR, "Out of memory.\n");
1931                 }
1932
1933                 iks_delete(instructions);
1934         }
1935         iks_delete(iq);
1936         iks_delete(query);
1937         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
1938         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1939         return IKS_FILTER_EAT;
1940 }
1941
1942 /*!
1943  * \internal
1944  * \brief Handles stuff
1945  * \param data void
1946  * \param pak ikspak
1947  * \return IKS_FILTER_EAT.
1948 */
1949 static int aji_ditems_handler(void *data, ikspak *pak)
1950 {
1951         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1952         char *node = NULL;
1953
1954         if (!(node = iks_find_attrib(pak->query, "node"))) {
1955                 iks *iq = NULL, *query = NULL, *item = NULL;
1956                 iq = iks_new("iq");
1957                 query = iks_new("query");
1958                 item = iks_new("item");
1959
1960                 if (iq && query && item) {
1961                         iks_insert_attrib(iq, "from", client->user);
1962                         iks_insert_attrib(iq, "to", pak->from->full);
1963                         iks_insert_attrib(iq, "id", pak->id);
1964                         iks_insert_attrib(iq, "type", "result");
1965                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
1966                         iks_insert_attrib(item, "node", "http://jabber.org/protocol/commands");
1967                         iks_insert_attrib(item, "name", "Million Dollar Asterisk Commands");
1968                         iks_insert_attrib(item, "jid", client->user);
1969
1970                         iks_insert_node(iq, query);
1971                         iks_insert_node(query, item);
1972                         ast_aji_send(client, iq);
1973                 } else {
1974                         ast_log(LOG_ERROR, "Out of memory.\n");
1975                 }
1976
1977                 iks_delete(iq);
1978                 iks_delete(query);
1979                 iks_delete(item);
1980
1981         } else if (!strcasecmp(node, "http://jabber.org/protocol/commands")) {
1982                 iks *iq, *query, *confirm;
1983                 iq = iks_new("iq");
1984                 query = iks_new("query");
1985                 confirm = iks_new("item");
1986                 if (iq && query && confirm && client) {
1987                         iks_insert_attrib(iq, "from", client->user);
1988                         iks_insert_attrib(iq, "to", pak->from->full);
1989                         iks_insert_attrib(iq, "id", pak->id);
1990                         iks_insert_attrib(iq, "type", "result");
1991                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
1992                         iks_insert_attrib(query, "node", "http://jabber.org/protocol/commands");
1993                         iks_insert_attrib(confirm, "node", "confirmaccount");
1994                         iks_insert_attrib(confirm, "name", "Confirm AIM account");
1995                         iks_insert_attrib(confirm, "jid", "blog.astjab.org");
1996
1997                         iks_insert_node(iq, query);
1998                         iks_insert_node(query, confirm);
1999                         ast_aji_send(client, iq);
2000                 } else {
2001                         ast_log(LOG_ERROR, "Out of memory.\n");
2002                 }
2003
2004                 iks_delete(iq);
2005                 iks_delete(query);
2006                 iks_delete(confirm);
2007
2008         } else if (!strcasecmp(node, "confirmaccount")) {
2009                 iks *iq = NULL, *query = NULL, *feature = NULL;
2010
2011                 iq = iks_new("iq");
2012                 query = iks_new("query");
2013                 feature = iks_new("feature");
2014
2015                 if (iq && query && feature && client) {
2016                         iks_insert_attrib(iq, "from", client->user);
2017                         iks_insert_attrib(iq, "to", pak->from->full);
2018                         iks_insert_attrib(iq, "id", pak->id);
2019                         iks_insert_attrib(iq, "type", "result");
2020                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
2021                         iks_insert_attrib(feature, "var", "http://jabber.org/protocol/commands");
2022                         iks_insert_node(iq, query);
2023                         iks_insert_node(query, feature);
2024                         ast_aji_send(client, iq);
2025                 } else {
2026                         ast_log(LOG_ERROR, "Out of memory.\n");
2027                 }
2028
2029                 iks_delete(iq);
2030                 iks_delete(query);
2031                 iks_delete(feature);
2032         }
2033
2034         ASTOBJ_UNREF(client, ast_aji_client_destroy);
2035         return IKS_FILTER_EAT;
2036
2037 }
2038
2039 /*!
2040  * \internal
2041  * \brief Handle add extra info
2042  * \param data void
2043  * \param pak ikspak
2044  * \return IKS_FILTER_EAT
2045 */
2046 static int aji_client_info_handler(void *data, ikspak *pak)
2047 {
2048         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
2049         struct aji_resource *resource = NULL;
2050         struct aji_buddy *buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
2051
2052         if (!buddy) {
2053                 ast_log(LOG_NOTICE, "JABBER: Received client info from unknown buddy: %s.\n", pak->from->full);
2054                 ASTOBJ_UNREF(client, ast_aji_client_destroy);
2055                 return IKS_FILTER_EAT;
2056         }
2057
2058         resource = aji_find_resource(buddy, pak->from->resource);
2059         if (pak->subtype == IKS_TYPE_RESULT) {
2060                 if (!resource) {
2061                         ast_log(LOG_NOTICE, "JABBER: Received client info from %s when not requested.\n", pak->from->full);
2062                         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
2063                         ASTOBJ_UNREF(client, ast_aji_client_destroy);
2064                         return IKS_FILTER_EAT;
2065                 }
2066                 if (iks_find_with_attrib(pak->query, "feature", "var", "http://www.google.com/xmpp/protocol/voice/v1")) {
2067                         resource->cap->jingle = 1;
2068                 } else {
2069                         resource->cap->jingle = 0;
2070                 }
2071         } else if (pak->subtype == IKS_TYPE_GET) {
2072                 iks *iq, *disco, *ident, *google, *query;
2073                 iq = iks_new("iq");
2074                 query = iks_new("query");
2075                 ident = iks_new("identity");
2076                 disco = iks_new("feature");
2077                 google = iks_new("feature");
2078                 if (iq && ident && disco && google) {
2079                         iks_insert_attrib(iq, "from", client->jid->full);
2080                         iks_insert_attrib(iq, "to", pak->from->full);
2081                         iks_insert_attrib(iq, "type", "result");
2082                         iks_insert_attrib(iq, "id", pak->id);
2083                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
2084                         iks_insert_attrib(ident, "category", "client");
2085                         iks_insert_attrib(ident, "type", "pc");
2086                         iks_insert_attrib(ident, "name", "asterisk");
2087                         iks_insert_attrib(disco, "var", "http://jabber.org/protocol/disco#info");
2088                         iks_insert_attrib(google, "var", "http://www.google.com/xmpp/protocol/voice/v1");
2089                         iks_insert_node(iq, query);
2090                         iks_insert_node(query, ident);
2091                         iks_insert_node(query, google);
2092                         iks_insert_node(query, disco);
2093                         ast_aji_send(client, iq);
2094                 } else {
2095                         ast_log(LOG_ERROR, "Out of Memory.\n");
2096                 }
2097
2098                 iks_delete(iq);
2099                 iks_delete(query);
2100                 iks_delete(ident);
2101                 iks_delete(google);
2102                 iks_delete(disco);
2103         } else if (pak->subtype == IKS_TYPE_ERROR) {
2104                 ast_log(LOG_NOTICE, "User %s does not support discovery.\n", pak->from->full);
2105         }
2106         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
2107         ASTOBJ_UNREF(client, ast_aji_client_destroy);
2108         return IKS_FILTER_EAT;
2109 }
2110
2111 /*!
2112  * \internal
2113  * \brief Handler of the return info packet
2114  * \param data aji_client
2115  * \param pak ikspak
2116  * \return IKS_FILTER_EAT
2117 */
2118 static int aji_dinfo_handler(void *data, ikspak *pak)
2119 {
2120         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
2121         char *node = NULL;
2122         struct aji_resource *resource = NULL;
2123         struct aji_buddy *buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
2124
2125         if (!buddy) {
2126                 ast_log(LOG_NOTICE, "JABBER: Received client info from unknown buddy: %s.\n", pak->from->full);
2127                 ASTOBJ_UNREF(client, ast_aji_client_destroy);
2128                 return IKS_FILTER_EAT;
2129         }
2130
2131         if (pak->subtype == IKS_TYPE_ERROR) {
2132                 ast_log(LOG_WARNING, "Received error from a client, turn on jabber debug!\n");
2133                 ASTOBJ_UNREF(client, ast_aji_client_destroy);
2134                 return IKS_FILTER_EAT;
2135         }
2136         resource = aji_find_resource(buddy, pak->from->resource);
2137         if (pak->subtype == IKS_TYPE_RESULT) {
2138                 if (!resource) {
2139                         ast_log(LOG_NOTICE, "JABBER: Received client info from %s when not requested.\n", pak->from->full);
2140                         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
2141                         ASTOBJ_UNREF(client, ast_aji_client_destroy);
2142                         return IKS_FILTER_EAT;
2143                 }
2144                 if (iks_find_with_attrib(pak->query, "feature", "var", "http://www.google.com/xmpp/protocol/voice/v1")) {
2145                         resource->cap->jingle = 1;
2146                 } else {
2147                         resource->cap->jingle = 0;
2148                 }
2149         } else if (pak->subtype == IKS_TYPE_GET && !(node = iks_find_attrib(pak->query, "node"))) {
2150                 iks *iq, *query, *identity, *disco, *reg, *commands, *gateway, *version, *vcard, *search;
2151
2152                 iq = iks_new("iq");
2153                 query = iks_new("query");
2154                 identity = iks_new("identity");
2155                 disco = iks_new("feature");
2156                 reg = iks_new("feature");
2157                 commands = iks_new("feature");
2158                 gateway = iks_new("feature");
2159                 version = iks_new("feature");
2160                 vcard = iks_new("feature");
2161                 search = iks_new("feature");
2162                 if (iq && query && identity && disco && reg && commands && gateway && version && vcard && search && client) {
2163                         iks_insert_attrib(iq, "from", client->user);
2164                         iks_insert_attrib(iq, "to", pak->from->full);
2165                         iks_insert_attrib(iq, "id", pak->id);
2166                         iks_insert_attrib(iq, "type", "result");
2167                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
2168                         iks_insert_attrib(identity, "category", "gateway");
2169                         iks_insert_attrib(identity, "type", "pstn");
2170                         iks_insert_attrib(identity, "name", "Asterisk The Open Source PBX");
2171                         iks_insert_attrib(disco, "var", "http://jabber.org/protocol/disco");
2172                         iks_insert_attrib(reg, "var", "jabber:iq:register");
2173                         iks_insert_attrib(commands, "var", "http://jabber.org/protocol/commands");
2174                         iks_insert_attrib(gateway, "var", "jabber:iq:gateway");
2175                         iks_insert_attrib(version, "var", "jabber:iq:version");
2176                         iks_insert_attrib(vcard, "var", "vcard-temp");
2177                         iks_insert_attrib(search, "var", "jabber:iq:search");
2178
2179                         iks_insert_node(iq, query);
2180                         iks_insert_node(query, identity);
2181                         iks_insert_node(query, disco);
2182                         iks_insert_node(query, reg);
2183                         iks_insert_node(query, commands);
2184                         iks_insert_node(query, gateway);
2185                         iks_insert_node(query, version);
2186                         iks_insert_node(query, vcard);
2187                         iks_insert_node(query, search);
2188                         ast_aji_send(client, iq);
2189                 } else {
2190                         ast_log(LOG_ERROR, "Out of memory.\n");
2191                 }
2192
2193                 iks_delete(iq);
2194                 iks_delete(query);
2195                 iks_delete(identity);
2196                 iks_delete(disco);
2197                 iks_delete(reg);
2198                 iks_delete(commands);
2199                 iks_delete(gateway);
2200                 iks_delete(version);
2201                 iks_delete(vcard);
2202                 iks_delete(search);
2203         } else if (pak->subtype == IKS_TYPE_GET && !strcasecmp(node, "http://jabber.org/protocol/commands")) {
2204                 iks *iq, *query, *confirm;
2205                 iq = iks_new("iq");
2206                 query = iks_new("query");
2207                 confirm = iks_new("item");
2208
2209                 if (iq && query && confirm && client) {
2210                         iks_insert_attrib(iq, "from", client->user);
2211                         iks_insert_attrib(iq, "to", pak->from->full);
2212                         iks_insert_attrib(iq, "id", pak->id);
2213                         iks_insert_attrib(iq, "type", "result");
2214                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
2215                         iks_insert_attrib(query, "node", "http://jabber.org/protocol/commands");
2216                         iks_insert_attrib(confirm, "node", "confirmaccount");
2217                         iks_insert_attrib(confirm, "name", "Confirm AIM account");
2218                         iks_insert_attrib(confirm, "jid", client->user);
2219                         iks_insert_node(iq, query);
2220                         iks_insert_node(query, confirm);
2221                         ast_aji_send(client, iq);
2222                 } else {
2223                         ast_log(LOG_ERROR, "Out of memory.\n");
2224                 }
2225
2226                 iks_delete(iq);
2227                 iks_delete(query);
2228                 iks_delete(confirm);
2229
2230         } else if (pak->subtype == IKS_TYPE_GET && !strcasecmp(node, "confirmaccount")) {
2231                 iks *iq, *query, *feature;
2232
2233                 iq = iks_new("iq");
2234                 query = iks_new("query");
2235                 feature = iks_new("feature");
2236
2237                 if (iq && query && feature && client) {
2238                         iks_insert_attrib(iq, "from", client->user);
2239                         iks_insert_attrib(iq, "to", pak->from->full);
2240                         iks_insert_attrib(iq, "id", pak->id);
2241                         iks_insert_attrib(iq, "type", "result");
2242                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
2243                         iks_insert_attrib(feature, "var", "http://jabber.org/protocol/commands");
2244                         iks_insert_node(iq, query);
2245                         iks_insert_node(query, feature);
2246                         ast_aji_send(client, iq);
2247                 } else {
2248                         ast_log(LOG_ERROR, "Out of memory.\n");
2249                 }
2250
2251                 iks_delete(iq);
2252                 iks_delete(query);
2253                 iks_delete(feature);
2254         }
2255
2256         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
2257         ASTOBJ_UNREF(client, ast_aji_client_destroy);
2258         return IKS_FILTER_EAT;
2259 }
2260
2261 /*!
2262  * \internal
2263  * \brief Handles \verbatim <iq> \endverbatim stanzas.
2264  * \param client the configured XMPP client we use to connect to a XMPP server
2265  * \param node iks
2266  * \return void.
2267  */
2268 static void aji_handle_iq(struct aji_client *client, iks *node)
2269 {
2270         /*Nothing to see here */
2271 }
2272
2273 /*!
2274  * \internal
2275  * \brief Handles \verbatim <message>\endverbatim stanzas.
2276  * Adds the incoming message to the client's message list.
2277  * \param client the configured XMPP client we use to connect to a XMPP server
2278  * \param pak ikspak the node
2279  */
2280 static void aji_handle_message(struct aji_client *client, ikspak *pak)
2281 {
2282         struct aji_message *insert;
2283         int deleted = 0;
2284         struct ast_msg *msg;
2285
2286         ast_debug(3, "client %s received a message\n", client->name);
2287
2288         if (!(insert = ast_calloc(1, sizeof(*insert)))) {
2289                 return;
2290         }
2291
2292         insert->arrived = ast_tvnow();
2293
2294         /* wake up threads waiting for messages */
2295         ast_mutex_lock(&messagelock);
2296         ast_cond_broadcast(&message_received_condition);
2297         ast_mutex_unlock(&messagelock);
2298
2299         if (iks_find_cdata(pak->x, "body")) {
2300                 insert->message = ast_strdup(iks_find_cdata(pak->x, "body"));
2301         }
2302         if (pak->id) {
2303                 ast_copy_string(insert->id, pak->id, sizeof(insert->id));
2304         }
2305         if (pak->from){
2306                 /* insert will furtherly be added to message list */
2307                 insert->from = ast_strdup(pak->from->full);
2308                 if (!insert->from) {
2309                         ast_free(insert);
2310                         ast_log(LOG_ERROR, "Memory allocation failure\n");
2311                         return;
2312                 }
2313                 ast_debug(3, "message comes from %s\n", insert->from);
2314         }
2315
2316         if (client->send_to_dialplan) {
2317                 if ((msg = ast_msg_alloc())) {
2318                         int res;
2319
2320                         res = ast_msg_set_to(msg, "xmpp:%s", client->user);
2321                         res |= ast_msg_set_from(msg, "xmpp:%s", insert->from);
2322                         res |= ast_msg_set_body(msg, "%s", insert->message);
2323                         res |= ast_msg_set_context(msg, "%s", client->context);
2324
2325                         if (res) {
2326                                 ast_msg_destroy(msg);
2327                         } else {
2328                                 ast_msg_queue(msg);
2329                         }
2330
2331                         msg = NULL;
2332                 }
2333         }
2334
2335         /* remove old messages received from this JID
2336          * and insert received message */
2337         deleted = delete_old_messages(client, pak->from->partial);
2338         ast_debug(3, "Deleted %d messages for client %s from JID %s\n", deleted, client->name, pak->from->partial);
2339         AST_LIST_LOCK(&client->messages);
2340         AST_LIST_INSERT_HEAD(&client->messages, insert, list);
2341         AST_LIST_UNLOCK(&client->messages);
2342 }
2343
2344 /*!
2345  * \internal
2346  * \brief handles \verbatim <presence>\endverbatim stanzas.
2347  * \param client the configured XMPP client we use to connect to a XMPP server
2348  * \param pak ikspak
2349  */
2350 static void aji_handle_presence(struct aji_client *client, ikspak *pak)
2351 {
2352         int status, priority;
2353         struct aji_buddy *buddy;
2354         struct aji_resource *tmp = NULL, *last = NULL, *found = NULL;
2355         char *ver, *node, *descrip, *type;
2356
2357         if (client->state != AJI_CONNECTED)
2358                 aji_create_buddy(pak->from->partial, client);
2359
2360         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
2361         if (!buddy && pak->from->partial) {
2362                 /* allow our jid to be used to log in with another resource */
2363                 if (!strcmp((const char *)pak->from->partial, (const char *)client->jid->partial))
2364                         aji_create_buddy(pak->from->partial, client);
2365                 else
2366                         ast_log(LOG_NOTICE, "Got presence packet from %s, someone not in our roster!!!!\n", pak->from->partial);
2367                 return;
2368         }
2369         type = iks_find_attrib(pak->x, "type");
2370         if (client->component && type &&!strcasecmp("probe", type)) {
2371                 aji_set_presence(client, pak->from->full, iks_find_attrib(pak->x, "to"), client->status, client->statusmessage);
2372                 ast_verbose("what i was looking for \n");
2373         }
2374         ASTOBJ_WRLOCK(buddy);
2375         status = (pak->show) ? pak->show : 6;
2376         priority = atoi((iks_find_cdata(pak->x, "priority")) ? iks_find_cdata(pak->x, "priority") : "0");
2377         tmp = buddy->resources;
2378         descrip = ast_strdup(iks_find_cdata(pak->x, "status"));
2379
2380         while (tmp && pak->from->resource) {
2381                 if (!strcasecmp(tmp->resource, pak->from->resource)) {
2382                         tmp->status = status;
2383                         if (tmp->description) {
2384                                 ast_free(tmp->description);
2385                         }
2386                         tmp->description = descrip;
2387                         found = tmp;
2388                         if (status == 6) {      /* Sign off Destroy resource */
2389                                 if (last && found->next) {
2390                                         last->next = found->next;
2391                                 } else if (!last) {
2392                                         if (found->next) {
2393                                                 buddy->resources = found->next;
2394                                         } else {
2395                                                 buddy->resources = NULL;
2396                                         }
2397                                 } else if (!found->next) {
2398                                         if (last) {
2399                                                 last->next = NULL;
2400                                         } else {
2401                                                 buddy->resources = NULL;
2402                                         }
2403                                 }
2404                                 ast_free(found);
2405                                 found = NULL;
2406                                 break;
2407                         }
2408                         /* resource list is sorted by descending priority */
2409                         if (tmp->priority != priority) {
2410                                 found->priority = priority;
2411                                 if (!last && !found->next) {
2412                                         /* resource was found to be unique,
2413                                            leave loop */
2414                                         break;
2415                                 }
2416                                 /* search for resource in our list
2417                                    and take it out for the moment */
2418                                 if (last) {
2419                                         last->next = found->next;
2420                                 } else {
2421                                         buddy->resources = found->next;
2422                                 }
2423
2424                                 last = NULL;
2425                                 tmp = buddy->resources;
2426                                 if (!buddy->resources) {
2427                                         buddy->resources = found;
2428                                 }
2429                                 /* priority processing */
2430                                 while (tmp) {
2431                                         /* insert resource back according to
2432                                            its priority value */
2433                                         if (found->priority > tmp->priority) {
2434                                                 if (last) {
2435                                                         /* insert within list */
2436                                                         last->next = found;
2437                                                 }
2438                                                 found->next = tmp;
2439                                                 if (!last) {
2440                                                         /* insert on top */
2441                                                         buddy->resources = found;
2442                                                 }
2443                                                 break;
2444                                         }
2445                                         if (!tmp->next) {
2446                                                 /* insert at the end of the list */
2447                                                 tmp->next = found;
2448                                                 found->next = NULL;
2449                                                 break;
2450                                         }
2451                                         last = tmp;
2452                                         tmp = tmp->next;
2453                                 }
2454                         }
2455                         break;
2456                 }
2457                 last = tmp;
2458                 tmp = tmp->next;
2459         }
2460
2461         /* resource not found in our list, create it */
2462         if (!found && status != 6 && pak->from->resource) {
2463                 found = ast_calloc(1, sizeof(*found));
2464
2465                 if (!found) {
2466                         ast_log(LOG_ERROR, "Out of memory!\n");
2467                         ASTOBJ_UNLOCK(buddy);
2468                         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
2469                         return;
2470                 }
2471                 ast_copy_string(found->resource, pak->from->resource, sizeof(found->resource));
2472                 found->status = status;
2473                 found->description = descrip;
2474                 found->priority = priority;
2475                 found->next = NULL;
2476                 last = NULL;
2477                 tmp = buddy->resources;
2478                 while (tmp) {
2479                         if (found->priority > tmp->priority) {
2480                                 if (last) {
2481                                         last->next = found;
2482                                 }
2483                                 found->next = tmp;
2484                                 if (!last) {
2485                                         buddy->resources = found;
2486                                 }
2487                                 break;
2488                         }
2489                         if (!tmp->next) {
2490                                 tmp->next = found;
2491                                 break;
2492                         }
2493                         last = tmp;
2494                         tmp = tmp->next;
2495                 }
2496                 if (!tmp) {
2497                         buddy->resources = found;
2498                 }
2499         }
2500
2501         ASTOBJ_UNLOCK(buddy);
2502         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
2503
2504         node = iks_find_attrib(iks_find(pak->x, "c"), "node");
2505         ver = iks_find_attrib(iks_find(pak->x, "c"), "ver");
2506
2507         /* handle gmail client's special caps:c tag */
2508         if (!node && !ver) {
2509                 node = iks_find_attrib(iks_find(pak->x, "caps:c"), "node");
2510                 ver = iks_find_attrib(iks_find(pak->x, "caps:c"), "ver");
2511         }
2512
2513         /* retrieve capabilites of the new resource */
2514         if (status != 6 && found && !found->cap) {
2515                 found->cap = aji_find_version(node, ver, pak);
2516                 if (gtalk_yuck(pak->x)) { /* gtalk should do discover */
2517                         found->cap->jingle = 1;
2518                 }
2519                 if (found->cap->jingle) {
2520                         ast_debug(1, "Special case for google till they support discover.\n");
2521                 } else {
2522                         iks *iq, *query;
2523                         iq = iks_new("iq");
2524                         query = iks_new("query");
2525                         if (query && iq) {
2526                                 iks_insert_attrib(iq, "type", "get");
2527                                 iks_insert_attrib(iq, "to", pak->from->full);
2528                                 iks_insert_attrib(iq, "from", client->jid->full);
2529                                 iks_insert_attrib(iq, "id", client->mid);
2530                                 ast_aji_increment_mid(client->mid);
2531                                 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
2532                                 iks_insert_node(iq, query);
2533                                 ast_aji_send(client, iq);
2534                         } else {
2535                                 ast_log(LOG_ERROR, "Out of memory.\n");
2536                         }
2537                         iks_delete(query);
2538                         iks_delete(iq);
2539                 }
2540         }
2541         switch (pak->subtype) {
2542         case IKS_TYPE_AVAILABLE:
2543                 ast_debug(3, "JABBER: I am available ^_* %i\n", pak->subtype);
2544                 break;
2545         case IKS_TYPE_UNAVAILABLE:
2546                 ast_debug(3, "JABBER: I am unavailable ^_* %i\n", pak->subtype);
2547                 break;
2548         default:
2549                 ast_debug(3, "JABBER: Ohh sexy and the wrong type: %i\n", pak->subtype);
2550         }
2551         switch (pak->show) {
2552         case IKS_SHOW_UNAVAILABLE:
2553                 ast_debug(3, "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
2554                 break;
2555         case IKS_SHOW_AVAILABLE:
2556                 ast_debug(3, "JABBER: type is available\n");
2557                 break;
2558         case IKS_SHOW_CHAT:
2559                 ast_debug(3, "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
2560                 break;
2561         case IKS_SHOW_AWAY:
2562                 ast_debug(3, "JABBER: type is away\n");
2563                 break;
2564         case IKS_SHOW_XA:
2565                 ast_debug(3, "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
2566                 break;
2567         case IKS_SHOW_DND:
2568                 ast_debug(3, "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
2569                 break;
2570         default:
2571                 ast_debug(3, "JABBER: Kinky! how did that happen %i\n", pak->show);
2572         }
2573
2574         if (found) {
2575                 manager_event(EVENT_FLAG_USER, "JabberStatus",
2576                         "Account: %s\r\nJID: %s\r\nResource: %s\r\nStatus: %d\r\nPriority: %d"
2577                         "\r\nDescription: %s\r\n",
2578                         client->name, pak->from->partial, found->resource, found->status,
2579                         found->priority, S_OR(found->description, ""));
2580         } else {
2581                 manager_event(EVENT_FLAG_USER, "JabberStatus",
2582                         "Account: %s\r\nJID: %s\r\nStatus: %d\r\n",
2583                         client->name, pak->from->partial, pak->show ? pak->show : IKS_SHOW_UNAVAILABLE);
2584         }
2585 }
2586
2587 /*!
2588  * \internal
2589  * \brief handles subscription requests.
2590  * \param client the configured XMPP client we use to connect to a XMPP server
2591  * \param pak ikspak iksemel packet.
2592  * \return void.
2593  */
2594 static void aji_handle_subscribe(struct aji_client *client, ikspak *pak)
2595 {
2596         iks *presence = NULL, *status = NULL;
2597         struct aji_buddy* buddy = NULL;
2598
2599         switch (pak->subtype) {
2600         case IKS_TYPE_SUBSCRIBE:
2601                 if (ast_test_flag(&client->flags, AJI_AUTOACCEPT)) {
2602                         presence = iks_new("presence");
2603                         status = iks_new("status");
2604                         if (presence && status) {
2605                                 iks_insert_attrib(presence, "type", "subscribed");
2606                                 iks_insert_attrib(presence, "to", pak->from->full);
2607                                 iks_insert_attrib(presence, "from", client->jid->full);
2608                                 if (pak->id)
2609                                         iks_insert_attrib(presence, "id", pak->id);
2610                                 iks_insert_cdata(status, "Asterisk has approved subscription", 0);
2611                                 iks_insert_node(presence, status);
2612                                 ast_aji_send(client, presence);
2613                         } else {
2614                                 ast_log(LOG_ERROR, "Unable to allocate nodes\n");
2615                         }
2616
2617                         iks_delete(presence);
2618                         iks_delete(status);
2619                 }
2620
2621                 if (client->component)
2622                         aji_set_presence(client, pak->from->full, iks_find_attrib(pak->x, "to"), client->status, client->statusmessage);
2623         case IKS_TYPE_SUBSCRIBED:
2624                 buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
2625                 if (!buddy && pak->from->partial) {
2626                         aji_create_buddy(pak->from->partial, client);
2627                 } else if (buddy) {
2628                         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
2629                 }
2630         default:
2631                 ast_verb(5, "JABBER: This is a subcription of type %i\n", pak->subtype);
2632         }
2633 }
2634
2635 /*!
2636  * \brief sends messages.
2637  * \param client the configured XMPP client we use to connect to a XMPP server
2638  * \param address
2639  * \param message
2640  * \retval IKS_OK success
2641  * \retval -1 failure
2642  */
2643 int ast_aji_send_chat(struct aji_client *client, const char *address, const char *message)
2644 {
2645         return aji_send_raw_chat(client, 0, NULL, address, message);
2646 }
2647
2648 /*!
2649 * \brief sends message to a groupchat
2650 * Prior to sending messages to a groupchat, one must be connected to it.
2651 * \param client the configured XMPP client we use to connect to a XMPP server
2652 * \param nick the nickname we use in the chatroom
2653 * \param address the user the messages must be sent to
2654 * \param message the message to send
2655 * \return IKS_OK on success, any other value on failure
2656 */
2657 int ast_aji_send_groupchat(struct aji_client *client, const char *nick, const char *address, const char *message) {
2658         return aji_send_raw_chat(client, 1, nick, address, message);
2659 }
2660
2661 /*!
2662 * \brief sends messages.
2663 * \param client the configured XMPP client we use to connect to a XMPP server
2664 * \param groupchat 
2665 * \param nick the nickname we use in chatrooms
2666 * \param address
2667 * \param message
2668 * \return IKS_OK on success, any other value on failure
2669 */
2670 static int aji_send_raw_chat(struct aji_client *client, int groupchat, const char *nick, const char *address, const char *message)
2671 {
2672         int res = 0;
2673         iks *message_packet = NULL;
2674         char from[AJI_MAX_JIDLEN];
2675         /* the nickname is used only in component mode */
2676         if (nick && client->component) {
2677                 snprintf(from, AJI_MAX_JIDLEN, "%s@%s/%s", nick, client->jid->full, nick);
2678         } else {
2679                 snprintf(from, AJI_MAX_JIDLEN, "%s", client->jid->full);
2680         }
2681
2682         if (client->state != AJI_CONNECTED) {
2683                 ast_log(LOG_WARNING, "JABBER: Not connected can't send\n");
2684                 return -1;
2685         }
2686
2687         message_packet = iks_make_msg(groupchat ? IKS_TYPE_GROUPCHAT : IKS_TYPE_CHAT, address, message);
2688         if (!message_packet) {
2689                 ast_log(LOG_ERROR, "Out of memory.\n");
2690                 return -1;
2691         }
2692         iks_insert_attrib(message_packet, "from", from);
2693         res = ast_aji_send(client, message_packet);
2694         iks_delete(message_packet);
2695
2696         return res;
2697 }
2698
2699 /*!
2700  * \brief create a chatroom.
2701  * \param client the configured XMPP client we use to connect to a XMPP server
2702  * \param room name of room
2703  * \param server name of server
2704  * \param topic topic for the room.
2705  * \return 0.
2706  */
2707 int ast_aji_create_chat(struct aji_client *client, char *room, char *server, char *topic)
2708 {
2709         int res = 0;
2710         iks *iq = NULL;
2711         iq = iks_new("iq");
2712
2713         if (iq && client) {
2714                 iks_insert_attrib(iq, "type", "get");
2715                 iks_insert_attrib(iq, "to", server);
2716                 iks_insert_attrib(iq, "id", client->mid);
2717                 ast_aji_increment_mid(client->mid);
2718                 ast_aji_send(client, iq);
2719         } else {
2720                 ast_log(LOG_ERROR, "Out of memory.\n");
2721         }
2722
2723         iks_delete(iq);
2724
2725         return res;
2726 }
2727
2728 /*!
2729  * \brief join a chatroom.
2730  * \param client the configured XMPP client we use to connect to a XMPP server
2731  * \param room room to join
2732  * \param nick the nickname to use in this room
2733  * \return IKS_OK on success, any other value on failure.
2734  */
2735 int ast_aji_join_chat(struct aji_client *client, char *room, char *nick)
2736 {
2737         return aji_set_group_presence(client, room, IKS_SHOW_AVAILABLE, nick, NULL);
2738 }
2739
2740 /*!
2741  * \brief leave a chatroom.
2742  * \param client the configured XMPP client we use to connect to a XMPP server
2743  * \param room room to leave
2744  * \param nick the nickname used in this room
2745  * \return IKS_OK on success, any other value on failure.
2746  */
2747 int ast_aji_leave_chat(struct aji_client *client, char *room, char *nick)
2748 {
2749         return aji_set_group_presence(client, room, IKS_SHOW_UNAVAILABLE, nick, NULL);
2750 }
2751 /*!
2752  * \brief invite to a chatroom.
2753  * \param client the configured XMPP client we use to connect to a XMPP server
2754  * \param user
2755  * \param room
2756  * \param message
2757  * \return res.
2758  */
2759 int ast_aji_invite_chat(struct aji_client *client, char *user, char *room, char *message)
2760 {
2761         int res = 0;
2762         iks *invite, *body, *namespace;
2763
2764         invite = iks_new("message");
2765         body = iks_new("body");
2766         namespace = iks_new("x");
2767         if (client && invite && body && namespace) {
2768                 iks_insert_attrib(invite, "to", user);
2769                 iks_insert_attrib(invite, "id", client->mid);
2770                 ast_aji_increment_mid(client->mid);
2771                 iks_insert_cdata(body, message, 0);
2772                 iks_insert_attrib(namespace, "xmlns", "jabber:x:conference");
2773                 iks_insert_attrib(namespace, "jid", room);
2774                 iks_insert_node(invite, body);
2775                 iks_insert_node(invite, namespace);
2776                 res = ast_aji_send(client, invite);
2777         } else {
2778                 ast_log(LOG_ERROR, "Out of memory.\n");
2779         }
2780
2781         iks_delete(body);
2782         iks_delete(namespace);
2783         iks_delete(invite);
2784
2785         return res;
2786 }
2787
2788 /*!
2789  * \internal
2790  * \brief receive message loop.
2791  * \param data void
2792  * \return void.
2793  */
2794 static void *aji_recv_loop(void *data)
2795 {
2796         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
2797         int res = IKS_HOOK;
2798
2799         while (res != IKS_OK) {
2800                 ast_debug(3, "JABBER: Connecting.\n");
2801                 res = aji_reconnect(client);
2802                 sleep(4);
2803         }
2804
2805         do {
2806                 if (res == IKS_NET_RWERR || client->timeout == 0) {
2807                         while (res != IKS_OK) {
2808                                 ast_debug(3, "JABBER: reconnecting.\n");
2809                                 res = aji_reconnect(client);
2810                                 sleep(4);
2811                         }
2812                 }
2813
2814                 res = aji_recv(client, 1);
2815
2816                 if (client->state == AJI_DISCONNECTING) {
2817                         ast_debug(2, "Ending our Jabber client's thread due to a disconnect\n");
2818                         pthread_exit(NULL);
2819                 }
2820
2821                 /* Decrease timeout if no data received, and delete
2822                  * old messages globally */
2823                 if (res == IKS_NET_EXPIRED) {
2824                         client->timeout--;
2825                         delete_old_messages_all(client);
2826                 }
2827                 if (res == IKS_HOOK) {
2828                         ast_log(LOG_WARNING, "JABBER: Got hook event.\n");
2829                 } else if (res == IKS_NET_TLSFAIL) {
2830                         ast_log(LOG_ERROR, "JABBER:  Failure in TLS.\n");
2831                 } else if (client->timeout == 0 && client->state == AJI_CONNECTED) {
2832                         res = client->keepalive ? aji_send_raw(client, " ") : IKS_OK;
2833                         if (res == IKS_OK) {
2834                                 client->timeout = 50;
2835                         } else {
2836                                 ast_log(LOG_WARNING, "JABBER:  Network Timeout\n");
2837                         }
2838                 } else if (res == IKS_NET_RWERR) {
2839                         ast_log(LOG_WARNING, "JABBER: socket read error\n");
2840                 }
2841         } while (client);
2842         ASTOBJ_UNREF(client, ast_aji_client_destroy);
2843         return 0;
2844 }
2845
2846 /*!
2847  * \brief increments the mid field for messages and other events.
2848  * \param mid char.
2849  * \return void.
2850  */
2851 void ast_aji_increment_mid(char *mid)
2852 {
2853         int i = 0;
2854
2855         for (i = strlen(mid) - 1; i >= 0; i--) {
2856                 if (mid[i] != 'z') {
2857                         mid[i] = mid[i] + 1;
2858                         i = 0;
2859                 } else
2860                         mid[i] = 'a';
2861         }
2862 }
2863
2864 #if 0
2865 /*!
2866  * \brief attempts to register to a transport.
2867  * \param aji_client struct, and xml packet.
2868  * \return IKS_FILTER_EAT.
2869  */
2870 /*allows for registering to transport , was too sketch and is out for now. */
2871 static int aji_register_transport(void *data, ikspak *pak)
2872 {
2873         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
2874         int res = 0;
2875         struct aji_buddy *buddy = NULL;
2876         iks *send = iks_make_iq(IKS_TYPE_GET, "jabber:iq:register");
2877
2878         if (client && send) {
2879                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
2880                         ASTOBJ_RDLOCK(iterator); 
2881                         if (iterator->btype == AJI_TRANS) {
2882                                   buddy = iterator;
2883                         }
2884                         ASTOBJ_UNLOCK(iterator);
2885                 });
2886                 iks_filter_remove_hook(client->f, aji_register_transport);
2887                 iks_filter_add_rule(client->f, aji_register_transport2, client, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_SUBTYPE, IKS_TYPE_RESULT, IKS_RULE_NS, IKS_NS_REGISTER, IKS_RULE_DONE);
2888                 iks_insert_attrib(send, "to", buddy->host);
2889                 iks_insert_attrib(send, "id", client->mid);
2890                 ast_aji_increment_mid(client->mid);
2891                 iks_insert_attrib(send, "from", client->user);
2892                 res = ast_aji_send(client, send);
2893         } else 
2894                 ast_log(LOG_ERROR, "Out of memory.\n");
2895
2896         if (send)
2897                 iks_delete(send);
2898         ASTOBJ_UNREF(client, ast_aji_client_destroy);
2899         return IKS_FILTER_EAT;
2900
2901 }
2902 /*!
2903  * \brief attempts to register to a transport step 2.
2904  * \param aji_client struct, and xml packet.
2905  * \return IKS_FILTER_EAT.
2906  */
2907 /* more of the same blob of code, too wonky for now*/
2908 static int aji_register_transport2(void *data, ikspak *pak)
2909 {
2910         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
2911         int res = 0;
2912         struct aji_buddy *buddy = NULL;
2913
2914         iks *regiq = iks_new("iq");
2915         iks *regquery = iks_new("query");
2916         iks *reguser = iks_new("username");
2917         iks *regpass = iks_new("password");
2918
2919         if (client && regquery && reguser && regpass && regiq) {
2920                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
2921                         ASTOBJ_RDLOCK(iterator);
2922                         if (iterator->btype == AJI_TRANS)
2923                                 buddy = iterator; ASTOBJ_UNLOCK(iterator);
2924                 });
2925                 iks_filter_remove_hook(client->f, aji_register_transport2);
2926                 iks_insert_attrib(regiq, "to", buddy->host);
2927                 iks_insert_attrib(regiq, "type", "set");
2928                 iks_insert_attrib(regiq, "id", client->mid);
2929                 ast_aji_increment_mid(client->mid);
2930                 iks_insert_attrib(regiq, "from", client->user);
2931                 iks_insert_attrib(regquery, "xmlns", "jabber:iq:register");
2932                 iks_insert_cdata(reguser, buddy->user, 0);
2933                 iks_insert_cdata(regpass, buddy->pass, 0);
2934                 iks_insert_node(regiq, regquery);
2935                 iks_insert_node(regquery, reguser);
2936                 iks_insert_node(regquery, regpass);
2937                 res = ast_aji_send(client, regiq);
2938         } else
2939                 ast_log(LOG_ERROR, "Out of memory.\n");
2940         if (regiq)
2941                 iks_delete(regiq);
2942         if (regquery)
2943                 iks_delete(regquery);
2944         if (reguser)
2945                 iks_delete(reguser);
2946         if (regpass)
2947                 iks_delete(regpass);
2948         ASTOBJ_UNREF(client, ast_aji_client_destroy);
2949         return IKS_FILTER_EAT;
2950 }
2951 #endif
2952
2953 /*!
2954  * \internal
2955  * \brief goes through roster and prunes users not needed in list, or adds them accordingly.
2956  * \param client the configured XMPP client we use to connect to a XMPP server
2957  * \return void.
2958  * \note The messages here should be configurable.
2959  */
2960 static void aji_pruneregister(struct aji_client *client)
2961 {
2962         iks *removeiq = iks_new("iq");
2963         iks *removequery = iks_new("query");
2964         iks *removeitem = iks_new("item");
2965         iks *send = iks_make_iq(IKS_TYPE_GET, "http://jabber.org/protocol/disco#items");
2966         if (!client || !removeiq || !removequery || !removeitem || !send) {
2967                 ast_log(LOG_ERROR, "Out of memory.\n");
2968                 goto safeout;
2969         }
2970
2971         iks_insert_node(removeiq, removequery);
2972         iks_insert_node(removequery, removeitem);
2973         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
2974                 ASTOBJ_RDLOCK(iterator);
2975                 /* For an aji_buddy, both AUTOPRUNE and AUTOREGISTER will never
2976                  * be called at the same time */
2977                 if (ast_test_flag(&iterator->flags, AJI_AUTOPRUNE)) { /* If autoprune is set on jabber.conf */
2978                         ast_aji_send(client, iks_make_s10n(IKS_TYPE_UNSUBSCRIBE, iterator->name,
2979                                                                  "GoodBye. Your status is no longer needed by Asterisk the Open Source PBX"
2980                                                                  " so I am no longer subscribing to your presence.\n"));
2981                         ast_aji_send(client, iks_make_s10n(IKS_TYPE_UNSUBSCRIBED, iterator->name,
2982                                                                  "GoodBye.  You are no longer in the Asterisk config file so I am removing"
2983                                                                  " your access to my presence.\n"));
2984                         iks_insert_attrib(removeiq, "from", client->jid->full);
2985                         iks_insert_attrib(removeiq, "type", "set");
2986                         iks_insert_attrib(removequery, "xmlns", "jabber:iq:roster");
2987                         iks_insert_attrib(removeitem, "jid", iterator->name);
2988                         iks_insert_attrib(removeitem, "subscription", "remove");
2989                         ast_aji_send(client, removeiq);
2990                 } else if (ast_test_flag(&iterator->flags, AJI_AUTOREGISTER)) {
2991                         ast_aji_send(client, iks_make_s10n(IKS_TYPE_SUBSCRIBE, iterator->name,
2992                                                                  "Greetings! I am the Asterisk Open Source PBX and I want to subscribe to your presence\n"));
2993                         ast_clear_flag(&iterator->flags, AJI_AUTOREGISTER);
2994                 }
2995                 ASTOBJ_UNLOCK(iterator);
2996         });
2997
2998  safeout:
2999         iks_delete(removeiq);
3000         iks_delete(removequery);
3001         iks_delete(removeitem);
3002         iks_delete(send);
3003
3004         ASTOBJ_CONTAINER_PRUNE_MARKED(&client->buddies, ast_aji_buddy_destroy);
3005 }
3006
3007 /*!
3008  * \internal
3009  * \brief filters the roster packet we get back from server.
3010  * \param data void
3011  * \param pak ikspak iksemel packet.
3012  * \return IKS_FILTER_EAT.
3013  */
3014 static int aji_filter_roster(void *data, ikspak *pak)
3015 {
3016         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
3017         int flag = 0;
3018         iks *x = NULL;
3019         struct aji_buddy *buddy;
3020
3021         client->state = AJI_CONNECTED;
3022         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
3023                 ASTOBJ_RDLOCK(iterator);
3024                 x = iks_child(pak->query);
3025                 flag = 0;
3026                 while (x) {
3027                         if (!iks_strcmp(iks_name(x), "item")) {
3028                                 if (!strcasecmp(iterator->name, iks_find_attrib(x, "jid"))) {
3029                                         flag = 1;
3030                                         ast_clear_flag(&iterator->flags, AJI_AUTOPRUNE | AJI_AUTOREGISTER);
3031                                 }
3032                         }
3033                         x = iks_next(x);
3034                 }
3035                 if (!flag) {
3036                         ast_copy_flags(&iterator->flags, &client->flags, AJI_AUTOREGISTER);
3037                 }
3038                 iks_delete(x);
3039
3040                 ASTOBJ_UNLOCK(iterator);
3041         });
3042
3043         x = iks_child(pak->query);
3044         while (x) {
3045                 flag = 0;
3046                 if (iks_strcmp(iks_name(x), "item") == 0) {
3047                         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
3048                                 ASTOBJ_RDLOCK(iterator);
3049                                 if (!strcasecmp(iterator->name, iks_find_attrib(x, "jid")))
3050                                         flag = 1;
3051                                 ASTOBJ_UNLOCK(iterator);
3052                         });
3053
3054                         if (flag) {
3055                                 /* found buddy, don't create a new one */
3056                                 x = iks_next(x);
3057                                 continue;
3058                         }
3059
3060                         buddy = ast_calloc(1, sizeof(*buddy));
3061                         if (!buddy) {
3062                                 ast_log(LOG_WARNING, "Out of memory\n");
3063                                 ASTOBJ_UNREF(client, ast_aji_client_destroy);
3064                                 return 0;
3065                         }
3066                         ASTOBJ_INIT(buddy);
3067                         ASTOBJ_WRLOCK(buddy);
3068                         ast_copy_string(buddy->name, iks_find_attrib(x, "jid"), sizeof(buddy->name));
3069                         ast_clear_flag(&buddy->flags, AST_FLAGS_ALL);
3070                         if (ast_test_flag(&client->flags, AJI_AUTOPRUNE)) {
3071                                 ast_set_flag(&buddy->flags, AJI_AUTOPRUNE);
3072                                 ASTOBJ_MARK(buddy);
3073                         } else if (ast_test_flag(&client->flags, AJI_AUTOREGISTER)) {
3074                                 if (!iks_strcmp(iks_find_attrib(x,&nbs