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