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