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