Check for presence of buddy in info/dinfo handlers
[asterisk/asterisk.git] / res / res_jabber.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2010, Digium, Inc.
5  *
6  * Matt O'Gorman <mogorman@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  * \brief A resource for interfacing Asterisk directly as a client
21  * or a component to a XMPP/Jabber compliant server.
22  *
23  * References:
24  * - http://www.xmpp.org - The XMPP standards foundation
25  *
26  * Iksemel http://code.google.com/p/iksemel/
27  *
28  * \todo If you unload this module, chan_gtalk/jingle will be dead. How do we handle that?
29  * \todo Dialplan applications need RETURN variable, like JABBERSENDSTATUS
30  *
31  */
32
33 /*** MODULEINFO
34         <defaultenabled>no</defaultenabled>
35         <depend>iksemel</depend>
36         <use type="external">openssl</use>
37         <support_level>deprecated</support_level>
38         <replacement>res_xmpp</replacement>
39  ***/
40
41 #include "asterisk.h"
42
43 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
44
45 #include <ctype.h>
46 #include <iksemel.h>
47
48 #include "asterisk/channel.h"
49 #include "asterisk/jabber.h"
50 #include "asterisk/file.h"
51 #include "asterisk/config.h"
52 #include "asterisk/callerid.h"
53 #include "asterisk/lock.h"
54 #include "asterisk/cli.h"
55 #include "asterisk/app.h"
56 #include "asterisk/pbx.h"
57 #include "asterisk/md5.h"
58 #include "asterisk/acl.h"
59 #include "asterisk/utils.h"
60 #include "asterisk/module.h"
61 #include "asterisk/astobj.h"
62 #include "asterisk/astdb.h"
63 #include "asterisk/manager.h"
64 #include "asterisk/event.h"
65 #include "asterisk/devicestate.h"
66 #include "asterisk/message.h"
67
68 /*** DOCUMENTATION
69         <application name="JabberSend" language="en_US">
70                 <synopsis>
71                         Sends an XMPP message to a buddy.
72                 </synopsis>
73                 <syntax>
74                         <parameter name="account" required="true">
75                                 <para>The local named account to listen on (specified in
76                                 jabber.conf)</para>
77                         </parameter>
78                         <parameter name="jid" required="true">
79                                 <para>Jabber ID of the buddy to send the message to. It can be a
80                                 bare JID (username@domain) or a full JID (username@domain/resource).</para>
81                         </parameter>
82                         <parameter name="message" required="true">
83                                 <para>The message to send.</para>
84                         </parameter>
85                 </syntax>
86                 <description>
87                         <para>Sends the content of <replaceable>message</replaceable> as text message
88                         from the given <replaceable>account</replaceable> to the buddy identified by
89                         <replaceable>jid</replaceable></para>
90                         <para>Example: JabberSend(asterisk,bob@domain.com,Hello world) sends "Hello world"
91                         to <replaceable>bob@domain.com</replaceable> as an XMPP message from the account
92                         <replaceable>asterisk</replaceable>, configured in jabber.conf.</para>
93                 </description>
94                 <see-also>
95                         <ref type="function">JABBER_STATUS</ref>
96                         <ref type="function">JABBER_RECEIVE</ref>
97                 </see-also>
98         </application>
99         <function name="JABBER_RECEIVE" language="en_US">
100                 <synopsis>
101                         Reads XMPP messages.
102                 </synopsis>
103                 <syntax>
104                         <parameter name="account" required="true">
105                                 <para>The local named account to listen on (specified in
106                                 jabber.conf)</para>
107                         </parameter>
108                         <parameter name="jid" required="true">
109                                 <para>Jabber ID of the buddy to receive message from. It can be a
110                                 bare JID (username@domain) or a full JID (username@domain/resource).</para>
111                         </parameter>
112                         <parameter name="timeout">
113                                 <para>In seconds, defaults to <literal>20</literal>.</para>
114                         </parameter>
115                 </syntax>
116                 <description>
117                         <para>Receives a text message on the given <replaceable>account</replaceable>
118                         from the buddy identified by <replaceable>jid</replaceable> and returns the contents.</para>
119                         <para>Example: ${JABBER_RECEIVE(asterisk,bob@domain.com)} returns an XMPP message
120                         sent from <replaceable>bob@domain.com</replaceable> (or nothing in case of a time out), to
121                         the <replaceable>asterisk</replaceable> XMPP account configured in jabber.conf.</para>
122                 </description>
123                 <see-also>
124                         <ref type="function">JABBER_STATUS</ref>
125                         <ref type="application">JabberSend</ref>
126                 </see-also>
127         </function>
128         <function name="JABBER_STATUS" language="en_US">
129                 <synopsis>
130                         Retrieves a buddy's status.
131                 </synopsis>
132                 <syntax>
133                         <parameter name="account" required="true">
134                                 <para>The local named account to listen on (specified in
135                                 jabber.conf)</para>
136                         </parameter>
137                         <parameter name="jid" required="true">
138                                 <para>Jabber ID of the buddy to receive message from. It can be a
139                                 bare JID (username@domain) or a full JID (username@domain/resource).</para>
140                         </parameter>
141                 </syntax>
142                 <description>
143                         <para>Retrieves the numeric status associated with the buddy identified
144                         by <replaceable>jid</replaceable>.
145                         If the buddy does not exist in the buddylist, returns 7.</para>
146                         <para>Status will be 1-7.</para>
147                         <para>1=Online, 2=Chatty, 3=Away, 4=XAway, 5=DND, 6=Offline</para>
148                         <para>If not in roster variable will be set to 7.</para>
149                         <para>Example: ${JABBER_STATUS(asterisk,bob@domain.com)} returns 1 if
150                         <replaceable>bob@domain.com</replaceable> is online. <replaceable>asterisk</replaceable> is
151                         the associated XMPP account configured in jabber.conf.</para>
152                 </description>
153                 <see-also>
154                         <ref type="function">JABBER_RECEIVE</ref>
155                         <ref type="application">JabberSend</ref>
156                 </see-also>
157         </function>
158         <application name="JabberSendGroup" language="en_US">
159                 <synopsis>
160                         Send a Jabber Message to a specified chat room
161                 </synopsis>
162                 <syntax>
163                         <parameter name="Jabber" required="true">
164                                 <para>Client or transport Asterisk uses to connect to Jabber.</para>
165                         </parameter>
166                         <parameter name="RoomJID" required="true">
167                                 <para>XMPP/Jabber JID (Name) of chat room.</para>
168                         </parameter>
169                         <parameter name="Message" required="true">
170                                 <para>Message to be sent to the chat room.</para>
171                         </parameter>
172                         <parameter name="Nickname" required="false">
173                                 <para>The nickname Asterisk uses in the chat room.</para>
174                         </parameter>
175                 </syntax>
176                 <description>
177                         <para>Allows user to send a message to a chat room via XMPP.</para>
178                         <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>
179                 </description>
180         </application>
181         <application name="JabberJoin" language="en_US">
182                 <synopsis>
183                         Join a chat room
184                 </synopsis>
185                 <syntax>
186                         <parameter name="Jabber" required="true">
187                                 <para>Client or transport Asterisk uses to connect to Jabber.</para>
188                         </parameter>
189                         <parameter name="RoomJID" required="true">
190                                 <para>XMPP/Jabber JID (Name) of chat room.</para>
191                         </parameter>
192                         <parameter name="Nickname" required="false">
193                                 <para>The nickname Asterisk will use in the chat room.</para>
194                                 <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>
195                         </parameter>
196                 </syntax>
197                 <description>
198                         <para>Allows Asterisk to join a chat room.</para>
199                 </description>
200         </application>
201         <application name="JabberLeave" language="en_US">
202                 <synopsis>
203                         Leave a chat room
204                 </synopsis>
205                 <syntax>
206                         <parameter name="Jabber" required="true">
207                                 <para>Client or transport Asterisk uses to connect to Jabber.</para>
208                         </parameter>
209                         <parameter name="RoomJID" required="true">
210                                 <para>XMPP/Jabber JID (Name) of chat room.</para>
211                         </parameter>
212                         <parameter name="Nickname" required="false">
213                                 <para>The nickname Asterisk uses in the chat room.</para>
214                         </parameter>
215                 </syntax>
216                 <description>
217                         <para>Allows Asterisk to leave a chat room.</para>
218                 </description>
219         </application>
220         <application name="JabberStatus" language="en_US">
221                 <synopsis>
222                         Retrieve the status of a jabber list member
223                 </synopsis>
224                 <syntax>
225                         <parameter name="Jabber" required="true">
226                                 <para>Client or transport Asterisk users to connect to Jabber.</para>
227                         </parameter>
228                         <parameter name="JID" required="true">
229                                 <para>XMPP/Jabber JID (Name) of recipient.</para>
230                         </parameter>
231                         <parameter name="Variable" required="true">
232                                 <para>Variable to store the status of requested user.</para>
233                         </parameter>
234                 </syntax>
235                 <description>
236                         <para>This application is deprecated. Please use the JABBER_STATUS() function instead.</para>
237                         <para>Retrieves the numeric status associated with the specified buddy <replaceable>JID</replaceable>.
238                         The return value in the <replaceable>Variable</replaceable>will be one of the following.</para>
239                         <enumlist>
240                                 <enum name="1">
241                                         <para>Online.</para>
242                                 </enum>
243                                 <enum name="2">
244                                         <para>Chatty.</para>
245                                 </enum>
246                                 <enum name="3">
247                                         <para>Away.</para>
248                                 </enum>
249                                 <enum name="4">
250                                         <para>Extended Away.</para>
251                                 </enum>
252                                 <enum name="5">
253                                         <para>Do Not Disturb.</para>
254                                 </enum>
255                                 <enum name="6">
256                                         <para>Offline.</para>
257                                 </enum>
258                                 <enum name="7">
259                                         <para>Not In Roster.</para>
260                                 </enum>
261                         </enumlist>
262                 </description>
263         </application>
264         <manager name="JabberSend" language="en_US">
265                 <synopsis>
266                         Sends a message to a Jabber Client.
267                 </synopsis>
268                 <syntax>
269                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
270                         <parameter name="Jabber" required="true">
271                                 <para>Client or transport Asterisk uses to connect to JABBER.</para>
272                         </parameter>
273                         <parameter name="JID" required="true">
274                                 <para>XMPP/Jabber JID (Name) of recipient.</para>
275                         </parameter>
276                         <parameter name="Message" required="true">
277                                 <para>Message to be sent to the buddy.</para>
278                         </parameter>
279                 </syntax>
280                 <description>
281                         <para>Sends a message to a Jabber Client.</para>
282                 </description>
283         </manager>
284  ***/
285
286 /*!\todo This should really be renamed to xmpp.conf. For backwards compatibility, we
287  * need to read both files */
288 #define JABBER_CONFIG "jabber.conf"
289
290 /*-- Forward declarations */
291 static void aji_message_destroy(struct aji_message *obj);
292 static int aji_is_secure(struct aji_client *client);
293 #ifdef HAVE_OPENSSL
294 static int aji_start_tls(struct aji_client *client);
295 static int aji_tls_handshake(struct aji_client *client);
296 #endif
297 static int aji_io_recv(struct aji_client *client, char *buffer, size_t buf_len, int timeout);
298 static int aji_recv(struct aji_client *client, int timeout);
299 static int aji_send_header(struct aji_client *client, const char *to);
300 static int aji_send_raw(struct aji_client *client, const char *xmlstr);
301 static void aji_log_hook(void *data, const char *xmpp, size_t size, int is_incoming);
302 static int aji_start_sasl(struct aji_client *client, enum ikssasltype type, char *username, char *pass);
303 static int aji_act_hook(void *data, int type, iks *node);
304 static void aji_handle_iq(struct aji_client *client, iks *node);
305 static void aji_handle_message(struct aji_client *client, ikspak *pak);
306 static void aji_handle_presence(struct aji_client *client, ikspak *pak);
307 static void aji_handle_subscribe(struct aji_client *client, ikspak *pak);
308 static int aji_send_raw_chat(struct aji_client *client, int groupchat, const char *nick, const char *address, const char *message);
309 static void *aji_recv_loop(void *data);
310 static int aji_initialize(struct aji_client *client);
311 static int aji_client_connect(void *data, ikspak *pak);
312 static void aji_set_presence(struct aji_client *client, char *to, char *from, int level, char *desc);
313 static int aji_set_group_presence(struct aji_client *client, char *room, int level, char *nick, char *desc);
314 static char *aji_do_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
315 static char *aji_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
316 static char *aji_show_clients(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
317 static char *aji_show_buddies(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
318 static int aji_create_client(char *label, struct ast_variable *var, int debug);
319 static int aji_create_buddy(char *label, struct aji_client *client);
320 static int aji_reload(int reload);
321 static int aji_load_config(int reload);
322 static void aji_pruneregister(struct aji_client *client);
323 static int aji_filter_roster(void *data, ikspak *pak);
324 static int aji_get_roster(struct aji_client *client);
325 static int aji_client_info_handler(void *data, ikspak *pak);
326 static int aji_dinfo_handler(void *data, ikspak *pak);
327 static int aji_ditems_handler(void *data, ikspak *pak);
328 static int aji_register_query_handler(void *data, ikspak *pak);
329 static int aji_register_approve_handler(void *data, ikspak *pak);
330 static int aji_reconnect(struct aji_client *client);
331 static char *aji_cli_create_collection(struct ast_cli_entry *e, int cmd,
332         struct ast_cli_args *a);
333 static char *aji_cli_list_pubsub_nodes(struct ast_cli_entry *e, int cmd,
334         struct ast_cli_args *a);
335 static char *aji_cli_delete_pubsub_node(struct ast_cli_entry *e, int cmd, struct
336         ast_cli_args *a);
337 static char *aji_cli_purge_pubsub_nodes(struct ast_cli_entry *e, int cmd, struct
338                 ast_cli_args *a);
339 static iks *jabber_make_auth(iksid * id, const char *pass, const char *sid);
340 static int aji_receive_node_list(void *data, ikspak* pak);
341 static void aji_init_event_distribution(struct aji_client *client);
342 static iks* aji_create_pubsub_node(struct aji_client *client, const char *node_type,
343         const char *name, const char *collection_name);
344 static iks* aji_build_node_config(iks *pubsub, const char *node_type,
345         const char *collection_name);
346 static void aji_create_pubsub_collection(struct aji_client *client,
347         const char *collection_name);
348 static void aji_create_pubsub_leaf(struct aji_client *client, const char *collection_name,
349    const char *leaf_name);
350 static char *aji_cli_create_leafnode(struct ast_cli_entry *e, int cmd,
351         struct ast_cli_args *a);
352 static void aji_create_affiliations(struct aji_client *client, const char *node);
353 static iks* aji_pubsub_iq_create(struct aji_client *client, const char *type);
354 static void aji_publish_device_state(struct aji_client *client, const char * device,
355         const char *device_state);
356 static int aji_handle_pubsub_error(void *data, ikspak *pak);
357 static int aji_handle_pubsub_event(void *data, ikspak *pak);
358 static void aji_pubsub_subscribe(struct aji_client *client, const char *node);
359 static void aji_delete_pubsub_node(struct aji_client *client, const char *node_name);
360 static iks* aji_build_node_request(struct aji_client *client, const char *collection);
361 static int aji_delete_node_list(void *data, ikspak* pak);
362 static void aji_pubsub_purge_nodes(struct aji_client *client,
363         const char* collection_name);
364 static void aji_publish_mwi(struct aji_client *client, const char *mailbox,
365         const char *context, const char *oldmsgs, const char *newmsgs);
366 static void aji_devstate_cb(const struct ast_event *ast_event, void *data);
367 static void aji_mwi_cb(const struct ast_event *ast_event, void *data);
368 static iks* aji_build_publish_skeleton(struct aji_client *client, const char *node,
369         const char *event_type);
370 /* No transports in this version */
371 /*
372 static int aji_create_transport(char *label, struct aji_client *client);
373 static int aji_register_transport(void *data, ikspak *pak);
374 static int aji_register_transport2(void *data, ikspak *pak);
375 */
376
377 static int msg_send_cb(const struct ast_msg *msg, const char *to, const char *from);
378
379 static const struct ast_msg_tech msg_tech = {
380         .name = "xmpp",
381         .msg_send = msg_send_cb,
382 };
383
384 static struct ast_cli_entry aji_cli[] = {
385         AST_CLI_DEFINE(aji_do_set_debug, "Enable/Disable Jabber debug"),
386         AST_CLI_DEFINE(aji_do_reload, "Reload Jabber configuration"),
387         AST_CLI_DEFINE(aji_show_clients, "Show state of clients and components"),
388         AST_CLI_DEFINE(aji_show_buddies, "Show buddy lists of our clients"),
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 = ast_alloca(len);
1588         base64 = ast_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                                 if (ast_asprintf(&handshake, "<handshake>%s</handshake>", shasum) >= 0) {
1763                                         aji_send_raw(client, handshake);
1764                                         ast_free(handshake);
1765                                 }
1766                                 client->state = AJI_CONNECTING;
1767                                 if (aji_recv(client, 1) == 2) /*XXX proper result for iksemel library on iks_recv of <handshake/> XXX*/
1768                                         client->state = AJI_CONNECTED;
1769                                 else
1770                                         ast_log(LOG_WARNING, "Jabber didn't seem to handshake, failed to authenticate.\n");
1771                                 break;
1772                         }
1773                         break;
1774
1775                 case IKS_NODE_NORMAL:
1776                         break;
1777
1778                 case IKS_NODE_ERROR:
1779                         ast_log(LOG_ERROR, "JABBER: Node Error\n");
1780                         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1781                         return IKS_HOOK;
1782
1783                 case IKS_NODE_STOP:
1784                         ast_log(LOG_WARNING, "JABBER: Disconnected\n");
1785                         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1786                         return IKS_HOOK;
1787                 }
1788         }
1789
1790         switch (pak->type) {
1791         case IKS_PAK_NONE:
1792                 ast_debug(1, "JABBER: I don't know what to do with paktype NONE.\n");
1793                 break;
1794         case IKS_PAK_MESSAGE:
1795                 aji_handle_message(client, pak);
1796                 ast_debug(1, "JABBER: Handling paktype MESSAGE.\n");
1797                 break;
1798         case IKS_PAK_PRESENCE:
1799                 aji_handle_presence(client, pak);
1800                 ast_debug(1, "JABBER: Handling paktype PRESENCE\n");
1801                 break;
1802         case IKS_PAK_S10N:
1803                 aji_handle_subscribe(client, pak);
1804                 ast_debug(1, "JABBER: Handling paktype S10N\n");
1805                 break;
1806         case IKS_PAK_IQ:
1807                 ast_debug(1, "JABBER: Handling paktype IQ\n");
1808                 aji_handle_iq(client, node);
1809                 break;
1810         default:
1811                 ast_debug(1, "JABBER: I don't know anything about paktype '%d'\n", pak->type);
1812                 break;
1813         }
1814
1815         iks_filter_packet(client->f, pak);
1816
1817         if (node)
1818                 iks_delete(node);
1819
1820         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1821         return IKS_OK;
1822 }
1823 /*!
1824  * \internal
1825  * \brief Unknown
1826  * \param data void
1827  * \param pak ikspak
1828  * \return IKS_FILTER_EAT.
1829 */
1830 static int aji_register_approve_handler(void *data, ikspak *pak)
1831 {
1832         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1833         iks *iq = NULL, *presence = NULL, *x = NULL;
1834
1835         iq = iks_new("iq");
1836         presence = iks_new("presence");
1837         x = iks_new("x");
1838         if (client && iq && presence && x) {
1839                 if (!iks_find(pak->query, "remove")) {
1840                         iks_insert_attrib(iq, "from", client->jid->full);
1841                         iks_insert_attrib(iq, "to", pak->from->full);
1842                         iks_insert_attrib(iq, "id", pak->id);
1843                         iks_insert_attrib(iq, "type", "result");
1844                         ast_aji_send(client, iq);
1845
1846                         iks_insert_attrib(presence, "from", client->jid->full);
1847                         iks_insert_attrib(presence, "to", pak->from->partial);
1848                         iks_insert_attrib(presence, "id", client->mid);
1849                         ast_aji_increment_mid(client->mid);
1850                         iks_insert_attrib(presence, "type", "subscribe");
1851                         iks_insert_attrib(x, "xmlns", "vcard-temp:x:update");
1852                         iks_insert_node(presence, x);
1853                         ast_aji_send(client, presence);
1854                 }
1855         } else {
1856                 ast_log(LOG_ERROR, "Out of memory.\n");
1857         }
1858
1859         iks_delete(iq);
1860         iks_delete(presence);
1861         iks_delete(x);
1862
1863         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1864         return IKS_FILTER_EAT;
1865 }
1866 /*!
1867  * \internal
1868  * \brief register handler for incoming querys (IQ's)
1869  * \param data incoming aji_client request
1870  * \param pak ikspak
1871  * \return IKS_FILTER_EAT.
1872 */
1873 static int aji_register_query_handler(void *data, ikspak *pak)
1874 {
1875         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1876         struct aji_buddy *buddy = NULL;
1877         iks *iq = NULL, *query = NULL;
1878
1879         client = (struct aji_client *) data;
1880
1881         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
1882         if (!buddy) {
1883                 iks  *error = NULL, *notacceptable = NULL;
1884
1885                 ast_log(LOG_ERROR, "Someone.... %s tried to register but they aren't allowed\n", pak->from->partial);
1886                 iq = iks_new("iq");
1887                 query = iks_new("query");
1888                 error = iks_new("error");
1889                 notacceptable = iks_new("not-acceptable");
1890                 if (iq && query && error && notacceptable) {
1891                         iks_insert_attrib(iq, "type", "error");
1892                         iks_insert_attrib(iq, "from", client->user);
1893                         iks_insert_attrib(iq, "to", pak->from->full);
1894                         iks_insert_attrib(iq, "id", pak->id);
1895                         iks_insert_attrib(query, "xmlns", "jabber:iq:register");
1896                         iks_insert_attrib(error, "code" , "406");
1897                         iks_insert_attrib(error, "type", "modify");
1898                         iks_insert_attrib(notacceptable, "xmlns", "urn:ietf:params:xml:ns:xmpp-stanzas");
1899                         iks_insert_node(iq, query);
1900                         iks_insert_node(iq, error);
1901                         iks_insert_node(error, notacceptable);
1902                         ast_aji_send(client, iq);
1903                 } else {
1904                         ast_log(LOG_ERROR, "Out of memory.\n");
1905                 }
1906
1907                 iks_delete(error);
1908                 iks_delete(notacceptable);
1909         } else if (!iks_find_attrib(pak->query, "node")) {
1910                 iks *instructions = NULL;
1911                 char *explain = "Welcome to Asterisk - the Open Source PBX.\n";
1912                 iq = iks_new("iq");
1913                 query = iks_new("query");
1914                 instructions = iks_new("instructions");
1915                 if (iq && query && instructions && client) {
1916                         iks_insert_attrib(iq, "from", client->user);
1917                         iks_insert_attrib(iq, "to", pak->from->full);
1918                         iks_insert_attrib(iq, "id", pak->id);
1919                         iks_insert_attrib(iq, "type", "result");
1920                         iks_insert_attrib(query, "xmlns", "jabber:iq:register");
1921                         iks_insert_cdata(instructions, explain, 0);
1922                         iks_insert_node(iq, query);
1923                         iks_insert_node(query, instructions);
1924                         ast_aji_send(client, iq);
1925                 } else {
1926                         ast_log(LOG_ERROR, "Out of memory.\n");
1927                 }
1928
1929                 iks_delete(instructions);
1930         }
1931         iks_delete(iq);
1932         iks_delete(query);
1933         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
1934         ASTOBJ_UNREF(client, ast_aji_client_destroy);
1935         return IKS_FILTER_EAT;
1936 }
1937
1938 /*!
1939  * \internal
1940  * \brief Handles stuff
1941  * \param data void
1942  * \param pak ikspak
1943  * \return IKS_FILTER_EAT.
1944 */
1945 static int aji_ditems_handler(void *data, ikspak *pak)
1946 {
1947         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1948         char *node = NULL;
1949
1950         if (!(node = iks_find_attrib(pak->query, "node"))) {
1951                 iks *iq = NULL, *query = NULL, *item = NULL;
1952                 iq = iks_new("iq");
1953                 query = iks_new("query");
1954                 item = iks_new("item");
1955
1956                 if (iq && query && item) {
1957                         iks_insert_attrib(iq, "from", client->user);
1958                         iks_insert_attrib(iq, "to", pak->from->full);
1959                         iks_insert_attrib(iq, "id", pak->id);
1960                         iks_insert_attrib(iq, "type", "result");
1961                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
1962                         iks_insert_attrib(item, "node", "http://jabber.org/protocol/commands");
1963                         iks_insert_attrib(item, "name", "Million Dollar Asterisk Commands");
1964                         iks_insert_attrib(item, "jid", client->user);
1965
1966                         iks_insert_node(iq, query);
1967                         iks_insert_node(query, item);
1968                         ast_aji_send(client, iq);
1969                 } else {
1970                         ast_log(LOG_ERROR, "Out of memory.\n");
1971                 }
1972
1973                 iks_delete(iq);
1974                 iks_delete(query);
1975                 iks_delete(item);
1976
1977         } else if (!strcasecmp(node, "http://jabber.org/protocol/commands")) {
1978                 iks *iq, *query, *confirm;
1979                 iq = iks_new("iq");
1980                 query = iks_new("query");
1981                 confirm = iks_new("item");
1982                 if (iq && query && confirm && client) {
1983                         iks_insert_attrib(iq, "from", client->user);
1984                         iks_insert_attrib(iq, "to", pak->from->full);
1985                         iks_insert_attrib(iq, "id", pak->id);
1986                         iks_insert_attrib(iq, "type", "result");
1987                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
1988                         iks_insert_attrib(query, "node", "http://jabber.org/protocol/commands");
1989                         iks_insert_attrib(confirm, "node", "confirmaccount");
1990                         iks_insert_attrib(confirm, "name", "Confirm AIM account");
1991                         iks_insert_attrib(confirm, "jid", "blog.astjab.org");
1992
1993                         iks_insert_node(iq, query);
1994                         iks_insert_node(query, confirm);
1995                         ast_aji_send(client, iq);
1996                 } else {
1997                         ast_log(LOG_ERROR, "Out of memory.\n");
1998                 }
1999
2000                 iks_delete(iq);
2001                 iks_delete(query);
2002                 iks_delete(confirm);
2003
2004         } else if (!strcasecmp(node, "confirmaccount")) {
2005                 iks *iq = NULL, *query = NULL, *feature = NULL;
2006
2007                 iq = iks_new("iq");
2008                 query = iks_new("query");
2009                 feature = iks_new("feature");
2010
2011                 if (iq && query && feature && client) {
2012                         iks_insert_attrib(iq, "from", client->user);
2013                         iks_insert_attrib(iq, "to", pak->from->full);
2014                         iks_insert_attrib(iq, "id", pak->id);
2015                         iks_insert_attrib(iq, "type", "result");
2016                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
2017                         iks_insert_attrib(feature, "var", "http://jabber.org/protocol/commands");
2018                         iks_insert_node(iq, query);
2019                         iks_insert_node(query, feature);
2020                         ast_aji_send(client, iq);
2021                 } else {
2022                         ast_log(LOG_ERROR, "Out of memory.\n");
2023                 }
2024
2025                 iks_delete(iq);
2026                 iks_delete(query);
2027                 iks_delete(feature);
2028         }
2029
2030         ASTOBJ_UNREF(client, ast_aji_client_destroy);
2031         return IKS_FILTER_EAT;
2032
2033 }
2034
2035 /*!
2036  * \internal
2037  * \brief Handle add extra info
2038  * \param data void
2039  * \param pak ikspak
2040  * \return IKS_FILTER_EAT
2041 */
2042 static int aji_client_info_handler(void *data, ikspak *pak)
2043 {
2044         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
2045         struct aji_resource *resource = NULL;
2046         struct aji_buddy *buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
2047
2048         if (!buddy) {
2049                 ast_log(LOG_NOTICE, "JABBER: Received client info from unknown buddy: %s.\n", pak->from->full);
2050                 ASTOBJ_UNREF(client, ast_aji_client_destroy);
2051                 return IKS_FILTER_EAT;
2052         }
2053
2054         resource = aji_find_resource(buddy, pak->from->resource);
2055         if (pak->subtype == IKS_TYPE_RESULT) {
2056                 if (!resource) {
2057                         ast_log(LOG_NOTICE, "JABBER: Received client info from %s when not requested.\n", pak->from->full);
2058                         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
2059                         ASTOBJ_UNREF(client, ast_aji_client_destroy);
2060                         return IKS_FILTER_EAT;
2061                 }
2062                 if (iks_find_with_attrib(pak->query, "feature", "var", "http://www.google.com/xmpp/protocol/voice/v1")) {
2063                         resource->cap->jingle = 1;
2064                 } else {
2065                         resource->cap->jingle = 0;
2066                 }
2067         } else if (pak->subtype == IKS_TYPE_GET) {
2068                 iks *iq, *disco, *ident, *google, *query;
2069                 iq = iks_new("iq");
2070                 query = iks_new("query");
2071                 ident = iks_new("identity");
2072                 disco = iks_new("feature");
2073                 google = iks_new("feature");
2074                 if (iq && ident && disco && google) {
2075                         iks_insert_attrib(iq, "from", client->jid->full);
2076                         iks_insert_attrib(iq, "to", pak->from->full);
2077                         iks_insert_attrib(iq, "type", "result");
2078                         iks_insert_attrib(iq, "id", pak->id);
2079                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
2080                         iks_insert_attrib(ident, "category", "client");
2081                         iks_insert_attrib(ident, "type", "pc");
2082                         iks_insert_attrib(ident, "name", "asterisk");
2083                         iks_insert_attrib(disco, "var", "http://jabber.org/protocol/disco#info");
2084                         iks_insert_attrib(google, "var", "http://www.google.com/xmpp/protocol/voice/v1");
2085                         iks_insert_node(iq, query);
2086                         iks_insert_node(query, ident);
2087                         iks_insert_node(query, google);
2088                         iks_insert_node(query, disco);
2089                         ast_aji_send(client, iq);
2090                 } else {
2091                         ast_log(LOG_ERROR, "Out of Memory.\n");
2092                 }
2093
2094                 iks_delete(iq);
2095                 iks_delete(query);
2096                 iks_delete(ident);
2097                 iks_delete(google);
2098                 iks_delete(disco);
2099         } else if (pak->subtype == IKS_TYPE_ERROR) {
2100                 ast_log(LOG_NOTICE, "User %s does not support discovery.\n", pak->from->full);
2101         }
2102         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
2103         ASTOBJ_UNREF(client, ast_aji_client_destroy);
2104         return IKS_FILTER_EAT;
2105 }
2106
2107 /*!
2108  * \internal
2109  * \brief Handler of the return info packet
2110  * \param data aji_client
2111  * \param pak ikspak
2112  * \return IKS_FILTER_EAT
2113 */
2114 static int aji_dinfo_handler(void *data, ikspak *pak)
2115 {
2116         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
2117         char *node = NULL;
2118         struct aji_resource *resource = NULL;
2119         struct aji_buddy *buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
2120
2121         if (!buddy) {
2122                 ast_log(LOG_NOTICE, "JABBER: Received client info from unknown buddy: %s.\n", pak->from->full);
2123                 ASTOBJ_UNREF(client, ast_aji_client_destroy);
2124                 return IKS_FILTER_EAT;
2125         }
2126
2127         if (pak->subtype == IKS_TYPE_ERROR) {
2128                 ast_log(LOG_WARNING, "Received error from a client, turn on jabber debug!\n");
2129                 ASTOBJ_UNREF(client, ast_aji_client_destroy);
2130                 return IKS_FILTER_EAT;
2131         }
2132         resource = aji_find_resource(buddy, pak->from->resource);
2133         if (pak->subtype == IKS_TYPE_RESULT) {
2134                 if (!resource) {
2135                         ast_log(LOG_NOTICE, "JABBER: Received client info from %s when not requested.\n", pak->from->full);
2136                         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
2137                         ASTOBJ_UNREF(client, ast_aji_client_destroy);
2138                         return IKS_FILTER_EAT;
2139                 }
2140                 if (iks_find_with_attrib(pak->query, "feature", "var", "http://www.google.com/xmpp/protocol/voice/v1")) {
2141                         resource->cap->jingle = 1;
2142                 } else {
2143                         resource->cap->jingle = 0;
2144                 }
2145         } else if (pak->subtype == IKS_TYPE_GET && !(node = iks_find_attrib(pak->query, "node"))) {
2146                 iks *iq, *query, *identity, *disco, *reg, *commands, *gateway, *version, *vcard, *search;
2147
2148                 iq = iks_new("iq");
2149                 query = iks_new("query");
2150                 identity = iks_new("identity");
2151                 disco = iks_new("feature");
2152                 reg = iks_new("feature");
2153                 commands = iks_new("feature");
2154                 gateway = iks_new("feature");
2155                 version = iks_new("feature");
2156                 vcard = iks_new("feature");
2157                 search = iks_new("feature");
2158                 if (iq && query && identity && disco && reg && commands && gateway && version && vcard && search && client) {
2159                         iks_insert_attrib(iq, "from", client->user);
2160                         iks_insert_attrib(iq, "to", pak->from->full);
2161                         iks_insert_attrib(iq, "id", pak->id);
2162                         iks_insert_attrib(iq, "type", "result");
2163                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
2164                         iks_insert_attrib(identity, "category", "gateway");
2165                         iks_insert_attrib(identity, "type", "pstn");
2166                         iks_insert_attrib(identity, "name", "Asterisk The Open Source PBX");
2167                         iks_insert_attrib(disco, "var", "http://jabber.org/protocol/disco");
2168                         iks_insert_attrib(reg, "var", "jabber:iq:register");
2169                         iks_insert_attrib(commands, "var", "http://jabber.org/protocol/commands");
2170                         iks_insert_attrib(gateway, "var", "jabber:iq:gateway");
2171                         iks_insert_attrib(version, "var", "jabber:iq:version");
2172                         iks_insert_attrib(vcard, "var", "vcard-temp");
2173                         iks_insert_attrib(search, "var", "jabber:iq:search");
2174
2175                         iks_insert_node(iq, query);
2176                         iks_insert_node(query, identity);
2177                         iks_insert_node(query, disco);
2178                         iks_insert_node(query, reg);
2179                         iks_insert_node(query, commands);
2180                         iks_insert_node(query, gateway);
2181                         iks_insert_node(query, version);
2182                         iks_insert_node(query, vcard);
2183                         iks_insert_node(query, search);
2184                         ast_aji_send(client, iq);
2185                 } else {
2186                         ast_log(LOG_ERROR, "Out of memory.\n");
2187                 }
2188
2189                 iks_delete(iq);
2190                 iks_delete(query);
2191                 iks_delete(identity);
2192                 iks_delete(disco);
2193                 iks_delete(reg);
2194                 iks_delete(commands);
2195                 iks_delete(gateway);
2196                 iks_delete(version);
2197                 iks_delete(vcard);
2198                 iks_delete(search);
2199         } else if (pak->subtype == IKS_TYPE_GET && !strcasecmp(node, "http://jabber.org/protocol/commands")) {
2200                 iks *iq, *query, *confirm;
2201                 iq = iks_new("iq");
2202                 query = iks_new("query");
2203                 confirm = iks_new("item");
2204
2205                 if (iq && query && confirm && client) {
2206                         iks_insert_attrib(iq, "from", client->user);
2207                         iks_insert_attrib(iq, "to", pak->from->full);
2208                         iks_insert_attrib(iq, "id", pak->id);
2209                         iks_insert_attrib(iq, "type", "result");
2210                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
2211                         iks_insert_attrib(query, "node", "http://jabber.org/protocol/commands");
2212                         iks_insert_attrib(confirm, "node", "confirmaccount");
2213                         iks_insert_attrib(confirm, "name", "Confirm AIM account");
2214                         iks_insert_attrib(confirm, "jid", client->user);
2215                         iks_insert_node(iq, query);
2216                         iks_insert_node(query, confirm);
2217                         ast_aji_send(client, iq);
2218                 } else {
2219                         ast_log(LOG_ERROR, "Out of memory.\n");
2220                 }
2221
2222                 iks_delete(iq);
2223                 iks_delete(query);
2224                 iks_delete(confirm);
2225
2226         } else if (pak->subtype == IKS_TYPE_GET && !strcasecmp(node, "confirmaccount")) {
2227                 iks *iq, *query, *feature;
2228
2229                 iq = iks_new("iq");
2230                 query = iks_new("query");
2231                 feature = iks_new("feature");
2232
2233                 if (iq && query && feature && client) {
2234                         iks_insert_attrib(iq, "from", client->user);
2235                         iks_insert_attrib(iq, "to", pak->from->full);
2236                         iks_insert_attrib(iq, "id", pak->id);
2237                         iks_insert_attrib(iq, "type", "result");
2238                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
2239                         iks_insert_attrib(feature, "var", "http://jabber.org/protocol/commands");
2240                         iks_insert_node(iq, query);
2241                         iks_insert_node(query, feature);
2242                         ast_aji_send(client, iq);
2243                 } else {
2244                         ast_log(LOG_ERROR, "Out of memory.\n");
2245                 }
2246
2247                 iks_delete(iq);
2248                 iks_delete(query);
2249                 iks_delete(feature);
2250         }
2251
2252         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
2253         ASTOBJ_UNREF(client, ast_aji_client_destroy);
2254         return IKS_FILTER_EAT;
2255 }
2256
2257 /*!
2258  * \internal
2259  * \brief Handles \verbatim <iq> \endverbatim stanzas.
2260  * \param client the configured XMPP client we use to connect to a XMPP server
2261  * \param node iks
2262  * \return void.
2263  */
2264 static void aji_handle_iq(struct aji_client *client, iks *node)
2265 {
2266         /*Nothing to see here */
2267 }
2268
2269 /*!
2270  * \internal
2271  * \brief Handles \verbatim <message>\endverbatim stanzas.
2272  * Adds the incoming message to the client's message list.
2273  * \param client the configured XMPP client we use to connect to a XMPP server
2274  * \param pak ikspak the node
2275  */
2276 static void aji_handle_message(struct aji_client *client, ikspak *pak)
2277 {
2278         struct aji_message *insert;
2279         int deleted = 0;
2280         struct ast_msg *msg;
2281
2282         ast_debug(3, "client %s received a message\n", client->name);
2283
2284         if (!(insert = ast_calloc(1, sizeof(*insert)))) {
2285                 return;
2286         }
2287
2288         insert->arrived = ast_tvnow();
2289
2290         /* wake up threads waiting for messages */
2291         ast_mutex_lock(&messagelock);
2292         ast_cond_broadcast(&message_received_condition);
2293         ast_mutex_unlock(&messagelock);
2294
2295         if (iks_find_cdata(pak->x, "body")) {
2296                 insert->message = ast_strdup(iks_find_cdata(pak->x, "body"));
2297         }
2298         if (pak->id) {
2299                 ast_copy_string(insert->id, pak->id, sizeof(insert->id));
2300         }
2301         if (pak->from){
2302                 /* insert will furtherly be added to message list */
2303                 insert->from = ast_strdup(pak->from->full);
2304                 if (!insert->from) {
2305                         ast_free(insert);
2306                         ast_log(LOG_ERROR, "Memory allocation failure\n");
2307                         return;
2308                 }
2309                 ast_debug(3, "message comes from %s\n", insert->from);
2310         }
2311
2312         if (client->send_to_dialplan) {
2313                 if ((msg = ast_msg_alloc())) {
2314                         int res;
2315
2316                         res = ast_msg_set_to(msg, "xmpp:%s", client->user);
2317                         res |= ast_msg_set_from(msg, "xmpp:%s", insert->from);
2318                         res |= ast_msg_set_body(msg, "%s", insert->message);
2319                         res |= ast_msg_set_context(msg, "%s", client->context);
2320
2321                         if (res) {
2322                                 ast_msg_destroy(msg);
2323                         } else {
2324                                 ast_msg_queue(msg);
2325                         }
2326
2327                         msg = NULL;
2328                 }
2329         }
2330
2331         /* remove old messages received from this JID
2332          * and insert received message */
2333         deleted = delete_old_messages(client, pak->from->partial);
2334         ast_debug(3, "Deleted %d messages for client %s from JID %s\n", deleted, client->name, pak->from->partial);
2335         AST_LIST_LOCK(&client->messages);
2336         AST_LIST_INSERT_HEAD(&client->messages, insert, list);
2337         AST_LIST_UNLOCK(&client->messages);
2338 }
2339
2340 /*!
2341  * \internal
2342  * \brief handles \verbatim <presence>\endverbatim stanzas.
2343  * \param client the configured XMPP client we use to connect to a XMPP server
2344  * \param pak ikspak
2345  */
2346 static void aji_handle_presence(struct aji_client *client, ikspak *pak)
2347 {
2348         int status, priority;
2349         struct aji_buddy *buddy;
2350         struct aji_resource *tmp = NULL, *last = NULL, *found = NULL;
2351         char *ver, *node, *descrip, *type;
2352
2353         if (client->state != AJI_CONNECTED)
2354                 aji_create_buddy(pak->from->partial, client);
2355
2356         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
2357         if (!buddy && pak->from->partial) {
2358                 /* allow our jid to be used to log in with another resource */
2359                 if (!strcmp((const char *)pak->from->partial, (const char *)client->jid->partial))
2360                         aji_create_buddy(pak->from->partial, client);
2361                 else
2362                         ast_log(LOG_NOTICE, "Got presence packet from %s, someone not in our roster!!!!\n", pak->from->partial);
2363                 return;
2364         }
2365         type = iks_find_attrib(pak->x, "type");
2366         if (client->component && type &&!strcasecmp("probe", type)) {
2367                 aji_set_presence(client, pak->from->full, iks_find_attrib(pak->x, "to"), client->status, client->statusmessage);
2368                 ast_verbose("what i was looking for \n");
2369         }
2370         ASTOBJ_WRLOCK(buddy);
2371         status = (pak->show) ? pak->show : 6;
2372         priority = atoi((iks_find_cdata(pak->x, "priority")) ? iks_find_cdata(pak->x, "priority") : "0");
2373         tmp = buddy->resources;
2374         descrip = ast_strdup(iks_find_cdata(pak->x, "status"));
2375
2376         while (tmp && pak->from->resource) {
2377                 if (!strcasecmp(tmp->resource, pak->from->resource)) {
2378                         tmp->status = status;
2379                         if (tmp->description) {
2380                                 ast_free(tmp->description);
2381                         }
2382                         tmp->description = descrip;
2383                         found = tmp;
2384                         if (status == 6) {      /* Sign off Destroy resource */
2385                                 if (last && found->next) {
2386                                         last->next = found->next;
2387                                 } else if (!last) {
2388                                         if (found->next) {
2389                                                 buddy->resources = found->next;
2390                                         } else {
2391                                                 buddy->resources = NULL;
2392                                         }
2393                                 } else if (!found->next) {
2394                                         if (last) {
2395                                                 last->next = NULL;
2396                                         } else {
2397                                                 buddy->resources = NULL;
2398                                         }
2399                                 }
2400                                 ast_free(found);
2401                                 found = NULL;
2402                                 break;
2403                         }
2404                         /* resource list is sorted by descending priority */
2405                         if (tmp->priority != priority) {
2406                                 found->priority = priority;
2407                                 if (!last && !found->next) {
2408                                         /* resource was found to be unique,
2409                                            leave loop */
2410                                         break;
2411                                 }
2412                                 /* search for resource in our list
2413                                    and take it out for the moment */
2414                                 if (last) {
2415                                         last->next = found->next;
2416                                 } else {
2417                                         buddy->resources = found->next;
2418                                 }
2419
2420                                 last = NULL;
2421                                 tmp = buddy->resources;
2422                                 if (!buddy->resources) {
2423                                         buddy->resources = found;
2424                                 }
2425                                 /* priority processing */
2426                                 while (tmp) {
2427                                         /* insert resource back according to
2428                                            its priority value */
2429                                         if (found->priority > tmp->priority) {
2430                                                 if (last) {
2431                                                         /* insert within list */
2432                                                         last->next = found;
2433                                                 }
2434                                                 found->next = tmp;
2435                                                 if (!last) {
2436                                                         /* insert on top */
2437                                                         buddy->resources = found;
2438                                                 }
2439                                                 break;
2440                                         }
2441                                         if (!tmp->next) {
2442                                                 /* insert at the end of the list */
2443                                                 tmp->next = found;
2444                                                 found->next = NULL;
2445                                                 break;
2446                                         }
2447                                         last = tmp;
2448                                         tmp = tmp->next;
2449                                 }
2450                         }
2451                         break;
2452                 }
2453                 last = tmp;
2454                 tmp = tmp->next;
2455         }
2456
2457         /* resource not found in our list, create it */
2458         if (!found && status != 6 && pak->from->resource) {
2459                 found = ast_calloc(1, sizeof(*found));
2460
2461                 if (!found) {
2462                         ast_log(LOG_ERROR, "Out of memory!\n");
2463                         ASTOBJ_UNLOCK(buddy);
2464                         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
2465                         return;
2466                 }
2467                 ast_copy_string(found->resource, pak->from->resource, sizeof(found->resource));
2468                 found->status = status;
2469                 found->description = descrip;
2470                 found->priority = priority;
2471                 found->next = NULL;
2472                 last = NULL;
2473                 tmp = buddy->resources;
2474                 while (tmp) {
2475                         if (found->priority > tmp->priority) {
2476                                 if (last) {
2477                                         last->next = found;
2478                                 }
2479                                 found->next = tmp;
2480                                 if (!last) {
2481                                         buddy->resources = found;
2482                                 }
2483                                 break;
2484                         }
2485                         if (!tmp->next) {
2486                                 tmp->next = found;
2487                                 break;
2488                         }
2489                         last = tmp;
2490                         tmp = tmp->next;
2491                 }
2492                 if (!tmp) {
2493                         buddy->resources = found;
2494                 }
2495         }
2496
2497         ASTOBJ_UNLOCK(buddy);
2498         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
2499
2500         node = iks_find_attrib(iks_find(pak->x, "c"), "node");
2501         ver = iks_find_attrib(iks_find(pak->x, "c"), "ver");
2502
2503         /* handle gmail client's special caps:c tag */
2504         if (!node && !ver) {
2505                 node = iks_find_attrib(iks_find(pak->x, "caps:c"), "node");
2506                 ver = iks_find_attrib(iks_find(pak->x, "caps:c"), "ver");
2507         }
2508
2509         /* retrieve capabilites of the new resource */
2510         if (status != 6 && found && !found->cap) {
2511                 found->cap = aji_find_version(node, ver, pak);
2512                 if (gtalk_yuck(pak->x)) { /* gtalk should do discover */
2513                         found->cap->jingle = 1;
2514                 }
2515                 if (found->cap->jingle) {
2516                         ast_debug(1, "Special case for google till they support discover.\n");
2517                 } else {
2518                         iks *iq, *query;
2519                         iq = iks_new("iq");
2520                         query = iks_new("query");
2521                         if (query && iq) {
2522                                 iks_insert_attrib(iq, "type", "get");
2523                                 iks_insert_attrib(iq, "to", pak->from->full);
2524                                 iks_insert_attrib(iq, "from", client->jid->full);
2525                                 iks_insert_attrib(iq, "id", client->mid);
2526                                 ast_aji_increment_mid(client->mid);
2527                                 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
2528                                 iks_insert_node(iq, query);
2529                                 ast_aji_send(client, iq);
2530                         } else {
2531                                 ast_log(LOG_ERROR, "Out of memory.\n");
2532                         }
2533                         iks_delete(query);
2534                         iks_delete(iq);
2535                 }
2536         }
2537         switch (pak->subtype) {
2538         case IKS_TYPE_AVAILABLE:
2539                 ast_debug(3, "JABBER: I am available ^_* %i\n", pak->subtype);
2540                 break;
2541         case IKS_TYPE_UNAVAILABLE:
2542                 ast_debug(3, "JABBER: I am unavailable ^_* %i\n", pak->subtype);
2543                 break;
2544         default:
2545                 ast_debug(3, "JABBER: Ohh sexy and the wrong type: %i\n", pak->subtype);
2546         }
2547         switch (pak->show) {
2548         case IKS_SHOW_UNAVAILABLE:
2549                 ast_debug(3, "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
2550                 break;
2551         case IKS_SHOW_AVAILABLE:
2552                 ast_debug(3, "JABBER: type is available\n");
2553                 break;
2554         case IKS_SHOW_CHAT:
2555                 ast_debug(3, "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
2556                 break;
2557         case IKS_SHOW_AWAY:
2558                 ast_debug(3, "JABBER: type is away\n");
2559                 break;
2560         case IKS_SHOW_XA:
2561                 ast_debug(3, "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
2562                 break;
2563         case IKS_SHOW_DND:
2564                 ast_debug(3, "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
2565                 break;
2566         default:
2567                 ast_debug(3, "JABBER: Kinky! how did that happen %i\n", pak->show);
2568         }
2569
2570         if (found) {
2571                 manager_event(EVENT_FLAG_USER, "JabberStatus",
2572                         "Account: %s\r\nJID: %s\r\nResource: %s\r\nStatus: %d\r\nPriority: %d"
2573                         "\r\nDescription: %s\r\n",
2574                         client->name, pak->from->partial, found->resource, found->status,
2575                         found->priority, S_OR(found->description, ""));
2576         } else {
2577                 manager_event(EVENT_FLAG_USER, "JabberStatus",
2578                         "Account: %s\r\nJID: %s\r\nStatus: %d\r\n",
2579                         client->name, pak->from->partial, pak->show ? pak->show : IKS_SHOW_UNAVAILABLE);
2580         }
2581 }
2582
2583 /*!
2584  * \internal
2585  * \brief handles subscription requests.
2586  * \param client the configured XMPP client we use to connect to a XMPP server
2587  * \param pak ikspak iksemel packet.
2588  * \return void.
2589  */
2590 static void aji_handle_subscribe(struct aji_client *client, ikspak *pak)
2591 {
2592         iks *presence = NULL, *status = NULL;
2593         struct aji_buddy* buddy = NULL;
2594
2595         switch (pak->subtype) {
2596         case IKS_TYPE_SUBSCRIBE:
2597                 if (ast_test_flag(&client->flags, AJI_AUTOACCEPT)) {
2598                         presence = iks_new("presence");
2599                         status = iks_new("status");
2600                         if (presence && status) {
2601                                 iks_insert_attrib(presence, "type", "subscribed");
2602                                 iks_insert_attrib(presence, "to", pak->from->full);
2603                                 iks_insert_attrib(presence, "from", client->jid->full);
2604                                 if (pak->id)
2605                                         iks_insert_attrib(presence, "id", pak->id);
2606                                 iks_insert_cdata(status, "Asterisk has approved subscription", 0);
2607                                 iks_insert_node(presence, status);
2608                                 ast_aji_send(client, presence);
2609                         } else {
2610                                 ast_log(LOG_ERROR, "Unable to allocate nodes\n");
2611                         }
2612
2613                         iks_delete(presence);
2614                         iks_delete(status);
2615                 }
2616
2617                 if (client->component)
2618                         aji_set_presence(client, pak->from->full, iks_find_attrib(pak->x, "to"), client->status, client->statusmessage);
2619         case IKS_TYPE_SUBSCRIBED:
2620                 buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
2621                 if (!buddy && pak->from->partial) {
2622                         aji_create_buddy(pak->from->partial, client);
2623                 } else if (buddy) {
2624                         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
2625                 }
2626         default:
2627                 ast_verb(5, "JABBER: This is a subcription of type %i\n", pak->subtype);
2628         }
2629 }
2630
2631 /*!
2632  * \brief sends messages.
2633  * \param client the configured XMPP client we use to connect to a XMPP server
2634  * \param address
2635  * \param message
2636  * \retval IKS_OK success
2637  * \retval -1 failure
2638  */
2639 int ast_aji_send_chat(struct aji_client *client, const char *address, const char *message)
2640 {
2641         return aji_send_raw_chat(client, 0, NULL, address, message);
2642 }
2643
2644 /*!
2645 * \brief sends message to a groupchat
2646 * Prior to sending messages to a groupchat, one must be connected to it.
2647 * \param client the configured XMPP client we use to connect to a XMPP server
2648 * \param nick the nickname we use in the chatroom
2649 * \param address the user the messages must be sent to
2650 * \param message the message to send
2651 * \return IKS_OK on success, any other value on failure
2652 */
2653 int ast_aji_send_groupchat(struct aji_client *client, const char *nick, const char *address, const char *message) {
2654         return aji_send_raw_chat(client, 1, nick, address, message);
2655 }
2656
2657 /*!
2658 * \brief sends messages.
2659 * \param client the configured XMPP client we use to connect to a XMPP server
2660 * \param groupchat 
2661 * \param nick the nickname we use in chatrooms
2662 * \param address
2663 * \param message
2664 * \return IKS_OK on success, any other value on failure
2665 */
2666 static int aji_send_raw_chat(struct aji_client *client, int groupchat, const char *nick, const char *address, const char *message)
2667 {
2668         int res = 0;
2669         iks *message_packet = NULL;
2670         char from[AJI_MAX_JIDLEN];
2671         /* the nickname is used only in component mode */
2672         if (nick && client->component) {
2673                 snprintf(from, AJI_MAX_JIDLEN, "%s@%s/%s", nick, client->jid->full, nick);
2674         } else {
2675                 snprintf(from, AJI_MAX_JIDLEN, "%s", client->jid->full);
2676         }
2677
2678         if (client->state != AJI_CONNECTED) {
2679                 ast_log(LOG_WARNING, "JABBER: Not connected can't send\n");
2680                 return -1;
2681         }
2682
2683         message_packet = iks_make_msg(groupchat ? IKS_TYPE_GROUPCHAT : IKS_TYPE_CHAT, address, message);
2684         if (!message_packet) {
2685                 ast_log(LOG_ERROR, "Out of memory.\n");
2686                 return -1;
2687         }
2688         iks_insert_attrib(message_packet, "from", from);
2689         res = ast_aji_send(client, message_packet);
2690         iks_delete(message_packet);
2691
2692         return res;
2693 }
2694
2695 /*!
2696  * \brief create a chatroom.
2697  * \param client the configured XMPP client we use to connect to a XMPP server
2698  * \param room name of room
2699  * \param server name of server
2700  * \param topic topic for the room.
2701  * \return 0.
2702  */
2703 int ast_aji_create_chat(struct aji_client *client, char *room, char *server, char *topic)
2704 {
2705         int res = 0;
2706         iks *iq = NULL;
2707         iq = iks_new("iq");
2708
2709         if (iq && client) {
2710                 iks_insert_attrib(iq, "type", "get");
2711                 iks_insert_attrib(iq, "to", server);
2712                 iks_insert_attrib(iq, "id", client->mid);
2713                 ast_aji_increment_mid(client->mid);
2714                 ast_aji_send(client, iq);
2715         } else {
2716                 ast_log(LOG_ERROR, "Out of memory.\n");
2717         }
2718
2719         iks_delete(iq);
2720
2721         return res;
2722 }
2723
2724 /*!
2725  * \brief join a chatroom.
2726  * \param client the configured XMPP client we use to connect to a XMPP server
2727  * \param room room to join
2728  * \param nick the nickname to use in this room
2729  * \return IKS_OK on success, any other value on failure.
2730  */
2731 int ast_aji_join_chat(struct aji_client *client, char *room, char *nick)
2732 {
2733         return aji_set_group_presence(client, room, IKS_SHOW_AVAILABLE, nick, NULL);
2734 }
2735
2736 /*!
2737  * \brief leave a chatroom.
2738  * \param client the configured XMPP client we use to connect to a XMPP server
2739  * \param room room to leave
2740  * \param nick the nickname used in this room
2741  * \return IKS_OK on success, any other value on failure.
2742  */
2743 int ast_aji_leave_chat(struct aji_client *client, char *room, char *nick)
2744 {
2745         return aji_set_group_presence(client, room, IKS_SHOW_UNAVAILABLE, nick, NULL);
2746 }
2747 /*!
2748  * \brief invite to a chatroom.
2749  * \param client the configured XMPP client we use to connect to a XMPP server
2750  * \param user
2751  * \param room
2752  * \param message
2753  * \return res.
2754  */
2755 int ast_aji_invite_chat(struct aji_client *client, char *user, char *room, char *message)
2756 {
2757         int res = 0;
2758         iks *invite, *body, *namespace;
2759
2760         invite = iks_new("message");
2761         body = iks_new("body");
2762         namespace = iks_new("x");
2763         if (client && invite && body && namespace) {
2764                 iks_insert_attrib(invite, "to", user);
2765                 iks_insert_attrib(invite, "id", client->mid);
2766                 ast_aji_increment_mid(client->mid);
2767                 iks_insert_cdata(body, message, 0);
2768                 iks_insert_attrib(namespace, "xmlns", "jabber:x:conference");
2769                 iks_insert_attrib(namespace, "jid", room);
2770                 iks_insert_node(invite, body);
2771                 iks_insert_node(invite, namespace);
2772                 res = ast_aji_send(client, invite);
2773         } else {
2774                 ast_log(LOG_ERROR, "Out of memory.\n");
2775         }
2776
2777         iks_delete(body);
2778         iks_delete(namespace);
2779         iks_delete(invite);
2780
2781         return res;
2782 }
2783
2784 /*!
2785  * \internal
2786  * \brief receive message loop.
2787  * \param data void
2788  * \return void.
2789  */
2790 static void *aji_recv_loop(void *data)
2791 {
2792         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
2793         int res = IKS_HOOK;
2794
2795         while (res != IKS_OK) {
2796                 ast_debug(3, "JABBER: Connecting.\n");
2797                 res = aji_reconnect(client);
2798                 sleep(4);
2799         }
2800
2801         do {
2802                 if (res == IKS_NET_RWERR || client->timeout == 0) {
2803                         while (res != IKS_OK) {
2804                                 ast_debug(3, "JABBER: reconnecting.\n");
2805                                 res = aji_reconnect(client);
2806                                 sleep(4);
2807                         }
2808                 }
2809
2810                 res = aji_recv(client, 1);
2811
2812                 if (client->state == AJI_DISCONNECTING) {
2813                         ast_debug(2, "Ending our Jabber client's thread due to a disconnect\n");
2814                         pthread_exit(NULL);
2815                 }
2816
2817                 /* Decrease timeout if no data received, and delete
2818                  * old messages globally */
2819                 if (res == IKS_NET_EXPIRED) {
2820                         client->timeout--;
2821                         delete_old_messages_all(client);
2822                 }
2823                 if (res == IKS_HOOK) {
2824                         ast_log(LOG_WARNING, "JABBER: Got hook event.\n");
2825                 } else if (res == IKS_NET_TLSFAIL) {
2826                         ast_log(LOG_ERROR, "JABBER:  Failure in TLS.\n");
2827                 } else if (client->timeout == 0 && client->state == AJI_CONNECTED) {
2828                         res = client->keepalive ? aji_send_raw(client, " ") : IKS_OK;
2829                         if (res == IKS_OK) {
2830                                 client->timeout = 50;
2831                         } else {
2832                                 ast_log(LOG_WARNING, "JABBER:  Network Timeout\n");
2833                         }
2834                 } else if (res == IKS_NET_RWERR) {
2835                         ast_log(LOG_WARNING, "JABBER: socket read error\n");
2836                 }
2837         } while (client);
2838         ASTOBJ_UNREF(client, ast_aji_client_destroy);
2839         return 0;
2840 }
2841
2842 /*!
2843  * \brief increments the mid field for messages and other events.
2844  * \param mid char.
2845  * \return void.
2846  */
2847 void ast_aji_increment_mid(char *mid)
2848 {
2849         int i = 0;
2850
2851         for (i = strlen(mid) - 1; i >= 0; i--) {
2852                 if (mid[i] != 'z') {
2853                         mid[i] = mid[i] + 1;
2854                         i = 0;
2855                 } else
2856                         mid[i] = 'a';
2857         }
2858 }
2859
2860 #if 0
2861 /*!
2862  * \brief attempts to register to a transport.
2863  * \param aji_client struct, and xml packet.
2864  * \return IKS_FILTER_EAT.
2865  */
2866 /*allows for registering to transport , was too sketch and is out for now. */
2867 static int aji_register_transport(void *data, ikspak *pak)
2868 {
2869         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
2870         int res = 0;
2871         struct aji_buddy *buddy = NULL;
2872         iks *send = iks_make_iq(IKS_TYPE_GET, "jabber:iq:register");
2873
2874         if (client && send) {
2875                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
2876                         ASTOBJ_RDLOCK(iterator); 
2877                         if (iterator->btype == AJI_TRANS) {
2878                                   buddy = iterator;
2879                         }
2880                         ASTOBJ_UNLOCK(iterator);
2881                 });
2882                 iks_filter_remove_hook(client->f, aji_register_transport);
2883                 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);
2884                 iks_insert_attrib(send, "to", buddy->host);
2885                 iks_insert_attrib(send, "id", client->mid);
2886                 ast_aji_increment_mid(client->mid);
2887                 iks_insert_attrib(send, "from", client->user);
2888                 res = ast_aji_send(client, send);
2889         } else 
2890                 ast_log(LOG_ERROR, "Out of memory.\n");
2891
2892         if (send)
2893                 iks_delete(send);
2894         ASTOBJ_UNREF(client, ast_aji_client_destroy);
2895         return IKS_FILTER_EAT;
2896
2897 }
2898 /*!
2899  * \brief attempts to register to a transport step 2.
2900  * \param aji_client struct, and xml packet.
2901  * \return IKS_FILTER_EAT.
2902  */
2903 /* more of the same blob of code, too wonky for now*/
2904 static int aji_register_transport2(void *data, ikspak *pak)
2905 {
2906         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
2907         int res = 0;
2908         struct aji_buddy *buddy = NULL;
2909
2910         iks *regiq = iks_new("iq");
2911         iks *regquery = iks_new("query");
2912         iks *reguser = iks_new("username");
2913         iks *regpass = iks_new("password");
2914
2915         if (client && regquery && reguser && regpass && regiq) {
2916                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
2917                         ASTOBJ_RDLOCK(iterator);
2918                         if (iterator->btype == AJI_TRANS)
2919                                 buddy = iterator; ASTOBJ_UNLOCK(iterator);
2920                 });
2921                 iks_filter_remove_hook(client->f, aji_register_transport2);
2922                 iks_insert_attrib(regiq, "to", buddy->host);
2923                 iks_insert_attrib(regiq, "type", "set");
2924                 iks_insert_attrib(regiq, "id", client->mid);
2925                 ast_aji_increment_mid(client->mid);
2926                 iks_insert_attrib(regiq, "from", client->user);
2927                 iks_insert_attrib(regquery, "xmlns", "jabber:iq:register");
2928                 iks_insert_cdata(reguser, buddy->user, 0);
2929                 iks_insert_cdata(regpass, buddy->pass, 0);
2930                 iks_insert_node(regiq, regquery);
2931                 iks_insert_node(regquery, reguser);
2932                 iks_insert_node(regquery, regpass);
2933                 res = ast_aji_send(client, regiq);
2934         } else
2935                 ast_log(LOG_ERROR, "Out of memory.\n");
2936         if (regiq)
2937                 iks_delete(regiq);
2938         if (regquery)
2939                 iks_delete(regquery);
2940         if (reguser)
2941                 iks_delete(reguser);
2942         if (regpass)
2943                 iks_delete(regpass);
2944         ASTOBJ_UNREF(client, ast_aji_client_destroy);
2945         return IKS_FILTER_EAT;
2946 }
2947 #endif
2948
2949 /*!
2950  * \internal
2951  * \brief goes through roster and prunes users not needed in list, or adds them accordingly.
2952  * \param client the configured XMPP client we use to connect to a XMPP server
2953  * \return void.
2954  * \note The messages here should be configurable.
2955  */
2956 static void aji_pruneregister(struct aji_client *client)
2957 {
2958         iks *removeiq = iks_new("iq");
2959         iks *removequery = iks_new("query");
2960         iks *removeitem = iks_new("item");
2961         iks *send = iks_make_iq(IKS_TYPE_GET, "http://jabber.org/protocol/disco#items");
2962         if (!client || !removeiq || !removequery || !removeitem || !send) {
2963                 ast_log(LOG_ERROR, "Out of memory.\n");
2964                 goto safeout;
2965         }
2966
2967         iks_insert_node(removeiq, removequery);
2968         iks_insert_node(removequery, removeitem);
2969         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
2970                 ASTOBJ_RDLOCK(iterator);
2971                 /* For an aji_buddy, both AUTOPRUNE and AUTOREGISTER will never
2972                  * be called at the same time */
2973                 if (ast_test_flag(&iterator->flags, AJI_AUTOPRUNE)) { /* If autoprune is set on jabber.conf */
2974                         ast_aji_send(client, iks_make_s10n(IKS_TYPE_UNSUBSCRIBE, iterator->name,
2975                                                                  "GoodBye. Your status is no longer needed by Asterisk the Open Source PBX"
2976                                                                  " so I am no longer subscribing to your presence.\n"));
2977                         ast_aji_send(client, iks_make_s10n(IKS_TYPE_UNSUBSCRIBED, iterator->name,
2978                                                                  "GoodBye.  You are no longer in the Asterisk config file so I am removing"
2979                                                                  " your access to my presence.\n"));
2980                         iks_insert_attrib(removeiq, "from", client->jid->full);
2981                         iks_insert_attrib(removeiq, "type", "set");
2982                         iks_insert_attrib(removequery, "xmlns", "jabber:iq:roster");
2983                         iks_insert_attrib(removeitem, "jid", iterator->name);
2984                         iks_insert_attrib(removeitem, "subscription", "remove");
2985                         ast_aji_send(client, removeiq);
2986                 } else if (ast_test_flag(&iterator->flags, AJI_AUTOREGISTER)) {
2987                         ast_aji_send(client, iks_make_s10n(IKS_TYPE_SUBSCRIBE, iterator->name,
2988                                                                  "Greetings! I am the Asterisk Open Source PBX and I want to subscribe to your presence\n"));
2989                         ast_clear_flag(&iterator->flags, AJI_AUTOREGISTER);
2990                 }
2991                 ASTOBJ_UNLOCK(iterator);
2992         });
2993
2994  safeout:
2995         iks_delete(removeiq);
2996         iks_delete(removequery);
2997         iks_delete(removeitem);
2998         iks_delete(send);
2999
3000         ASTOBJ_CONTAINER_PRUNE_MARKED(&client->buddies, ast_aji_buddy_destroy);
3001 }
3002
3003 /*!
3004  * \internal
3005  * \brief filters the roster packet we get back from server.
3006  * \param data void
3007  * \param pak ikspak iksemel packet.
3008  * \return IKS_FILTER_EAT.
3009  */
3010 static int aji_filter_roster(void *data, ikspak *pak)
3011 {
3012         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
3013         int flag = 0;
3014         iks *x = NULL;
3015         struct aji_buddy *buddy;
3016
3017         client->state = AJI_CONNECTED;
3018         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
3019                 ASTOBJ_RDLOCK(iterator);
3020                 x = iks_child(pak->query);
3021                 flag = 0;
3022                 while (x) {
3023                         if (!iks_strcmp(iks_name(x), "item")) {
3024                                 if (!strcasecmp(iterator->name, iks_find_attrib(x, "jid"))) {
3025                                         flag = 1;
3026                                         ast_clear_flag(&iterator->flags, AJI_AUTOPRUNE | AJI_AUTOREGISTER);
3027                                 }
3028                         }
3029                         x = iks_next(x);
3030                 }
3031                 if (!flag) {
3032                         ast_copy_flags(&iterator->flags, &client->flags, AJI_AUTOREGISTER);
3033                 }
3034                 iks_delete(x);
3035
3036                 ASTOBJ_UNLOCK(iterator);
3037         });
3038
3039         x = iks_child(pak->query);
3040         while (x) {
3041                 flag = 0;
3042                 if (iks_strcmp(iks_name(x), "item") == 0) {
3043                         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
3044                                 ASTOBJ_RDLOCK(iterator);
3045                                 if (!strcasecmp(iterator->name, iks_find_attrib(x, "jid")))
3046                                         flag = 1;
3047                                 ASTOBJ_UNLOCK(iterator);
3048                         });
3049
3050                         if (flag) {
3051                                 /* found buddy, don't create a new one */
3052                                 x = iks_next(x);
3053                                 continue;
3054                         }
3055
3056                         buddy = ast_calloc(1, sizeof(*buddy));
3057                         if (!buddy) {
3058                                 ast_log(LOG_WARNING, "Out of memory\n");
3059                                 ASTOBJ_UNREF(client, ast_aji_client_destroy);
3060                                 return 0;
3061                         }
3062                         ASTOBJ_INIT(buddy);
3063                         ASTOBJ_WRLOCK(buddy);
3064                         ast_copy_string(buddy->name, iks_find_attrib(x, "jid"), sizeof(buddy->name));
3065                         ast_clear_flag(&buddy->flags, AST_FLAGS_ALL);
3066                         if (ast_test_flag(&client->flags, AJI_AUTOPRUNE)) {
3067                                 ast_set_flag(&buddy->flags, AJI_AUTOPRUNE);
3068                                 ASTOBJ_MARK(buddy);
3069                         } else if (ast_test_flag(&client->flags, AJI_AUTOREGISTER)) {
3070                                 if (!iks_strcmp(iks_find_attrib(x, "subscription"), "none") || !iks_strcmp(iks_find_attrib(x, "subscription"), "from")) {
3071                                         /* subscribe to buddy's presence only