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