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