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