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