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