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