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