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