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