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