Continuation of issue 9968 (revision 69081). This should be the last one.
[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                 if (option_debug)
687                         ast_log(LOG_DEBUG, "JABBER: I Don't know what to do with you NONE\n");
688                 break;
689         case IKS_PAK_MESSAGE:
690                 aji_handle_message(client, pak);
691                 if (option_debug)
692                         ast_log(LOG_DEBUG, "JABBER: I Don't know what to do with you MESSAGE\n");
693                 break;
694         case IKS_PAK_PRESENCE:
695                 aji_handle_presence(client, pak);
696                 if (option_debug)
697                         ast_log(LOG_DEBUG, "JABBER: I Do know how to handle presence!!\n");
698                 break;
699         case IKS_PAK_S10N:
700                 aji_handle_subscribe(client, pak);
701                 if (option_debug)
702                         ast_log(LOG_DEBUG, "JABBER: I Dont know S10N subscribe!!\n");
703                 break;
704         case IKS_PAK_IQ:
705                 if (option_debug)
706                         ast_log(LOG_DEBUG, "JABBER: I Dont have an IQ!!!\n");
707                 aji_handle_iq(client, node);
708                 break;
709         default:
710                 if (option_debug)
711                         ast_log(LOG_DEBUG, "JABBER: I Dont know %i\n", pak->type);
712                 break;
713         }
714         
715         iks_filter_packet(client->f, pak);
716
717         if (node)
718                 iks_delete(node);
719
720         ASTOBJ_UNREF(client, aji_client_destroy);
721         return IKS_OK;
722 }
723 /*!
724  * \brief Uknown
725  * \param data void
726  * \param pak ikspak
727  * \return IKS_FILTER_EAT.
728 */
729 static int aji_register_approve_handler(void *data, ikspak *pak)
730 {
731         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
732         iks *iq = NULL, *presence = NULL, *x = NULL;
733
734         iq = iks_new("iq");
735         presence = iks_new("presence");
736         x = iks_new("x");
737         if (client && iq && presence && x) {
738                 if (!iks_find(pak->query, "remove")) {
739                         iks_insert_attrib(iq, "from", client->jid->full);
740                         iks_insert_attrib(iq, "to", pak->from->full);
741                         iks_insert_attrib(iq, "id", pak->id);
742                         iks_insert_attrib(iq, "type", "result");
743                         iks_send(client->p, iq);
744
745                         iks_insert_attrib(presence, "from", client->jid->full);
746                         iks_insert_attrib(presence, "to", pak->from->partial);
747                         iks_insert_attrib(presence, "id", client->mid);
748                         ast_aji_increment_mid(client->mid);
749                         iks_insert_attrib(presence, "type", "subscribe");
750                         iks_insert_attrib(x, "xmlns", "vcard-temp:x:update");
751                         iks_insert_node(presence, x);
752                         iks_send(client->p, presence); 
753                 }
754         } else {
755                 ast_log(LOG_ERROR, "Out of memory.\n");
756         }
757
758         if (iq)
759                 iks_delete(iq);
760         if(presence)
761                 iks_delete(presence);
762         if (x)
763                 iks_delete(x);
764         ASTOBJ_UNREF(client, aji_client_destroy);
765         return IKS_FILTER_EAT;
766 }
767 /*!
768  * \brief register query
769  * \param data incoming aji_client request
770  * \param pak ikspak
771  * \return IKS_FILTER_EAT.
772 */
773 static int aji_register_query_handler(void *data, ikspak *pak)
774 {
775         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
776         struct aji_buddy *buddy = NULL; 
777         char *node = NULL;
778
779         client = (struct aji_client *) data;
780
781         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
782         if (!buddy) {
783                 iks *iq = NULL, *query = NULL, *error = NULL, *notacceptable = NULL;
784
785                 ast_verbose("Someone.... %s tried to register but they aren't allowed\n", pak->from->partial);
786                 iq = iks_new("iq");
787                 query = iks_new("query");
788                 error = iks_new("error");
789                 notacceptable = iks_new("not-acceptable");
790                 if(iq && query && error && notacceptable) {
791                         iks_insert_attrib(iq, "type", "error");
792                         iks_insert_attrib(iq, "from", client->user);
793                         iks_insert_attrib(iq, "to", pak->from->full);
794                         iks_insert_attrib(iq, "id", pak->id);
795                         iks_insert_attrib(query, "xmlns", "jabber:iq:register");
796                         iks_insert_attrib(error, "code" , "406");
797                         iks_insert_attrib(error, "type", "modify");
798                         iks_insert_attrib(notacceptable, "xmlns", "urn:ietf:params:xml:ns:xmpp-stanzas");
799                         iks_insert_node(iq, query);
800                         iks_insert_node(iq, error);
801                         iks_insert_node(error, notacceptable);
802                         iks_send(client->p, iq);
803                 } else {
804                         ast_log(LOG_ERROR, "Out of memory.\n");
805                 }
806                 if (iq)
807                         iks_delete(iq);
808                 if (query)
809                         iks_delete(query);
810                 if (error)
811                         iks_delete(error);
812                 if (notacceptable)
813                         iks_delete(notacceptable);
814         } else  if (!(node = iks_find_attrib(pak->query, "node"))) {
815                 iks *iq = NULL, *query = NULL, *instructions = NULL;
816                 char *explain = "Welcome to Asterisk - the Open Source PBX.\n";
817                 iq = iks_new("iq");
818                 query = iks_new("query");
819                 instructions = iks_new("instructions");
820                 if (iq && query && instructions && client) {
821                         iks_insert_attrib(iq, "from", client->user);
822                         iks_insert_attrib(iq, "to", pak->from->full);
823                         iks_insert_attrib(iq, "id", pak->id);
824                         iks_insert_attrib(iq, "type", "result");
825                         iks_insert_attrib(query, "xmlns", "jabber:iq:register");
826                         iks_insert_cdata(instructions, explain, 0);
827                         iks_insert_node(iq, query);
828                         iks_insert_node(query, instructions);
829                         iks_send(client->p, iq);
830                 } else {
831                         ast_log(LOG_ERROR, "Out of memory.\n");
832                 }
833                 if (iq)
834                         iks_delete(iq);
835                 if (query)
836                         iks_delete(query);
837                 if (instructions)
838                         iks_delete(instructions);
839         }
840         ASTOBJ_UNREF(client, aji_client_destroy);
841         return IKS_FILTER_EAT;
842 }
843
844 /*!
845  * \brief Handles stuff
846  * \param data void
847  * \param pak ikspak 
848  * \return IKS_FILTER_EAT.
849 */
850 static int aji_ditems_handler(void *data, ikspak *pak)
851 {
852         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
853         char *node = NULL;
854
855         if (!(node = iks_find_attrib(pak->query, "node"))) {
856                 iks *iq = NULL, *query = NULL, *item = NULL;
857                 iq = iks_new("iq");
858                 query = iks_new("query");
859                 item = iks_new("item");
860
861                 if (iq && query && item) {
862                         iks_insert_attrib(iq, "from", client->user);
863                         iks_insert_attrib(iq, "to", pak->from->full);
864                         iks_insert_attrib(iq, "id", pak->id);
865                         iks_insert_attrib(iq, "type", "result");
866                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
867                         iks_insert_attrib(item, "node", "http://jabber.org/protocol/commands");
868                         iks_insert_attrib(item, "name", "Million Dollar Asterisk Commands");
869                         iks_insert_attrib(item, "jid", client->user);
870
871                         iks_insert_node(iq, query);
872                         iks_insert_node(query, item);
873                         iks_send(client->p, iq);
874                 } else {
875                         ast_log(LOG_ERROR, "Out of memory.\n");
876                 }
877                 if (iq)
878                         iks_delete(iq);
879                 if (query)
880                         iks_delete(query);
881                 if (item)
882                         iks_delete(item);
883
884         } else if (!strcasecmp(node, "http://jabber.org/protocol/commands")) {
885                 iks *iq, *query, *confirm;
886                 iq = iks_new("iq");
887                 query = iks_new("query");
888                 confirm = iks_new("item");
889                 if (iq && query && confirm && client) {
890                         iks_insert_attrib(iq, "from", client->user);
891                         iks_insert_attrib(iq, "to", pak->from->full);
892                         iks_insert_attrib(iq, "id", pak->id);
893                         iks_insert_attrib(iq, "type", "result");
894                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
895                         iks_insert_attrib(query, "node", "http://jabber.org/protocol/commands");
896                         iks_insert_attrib(confirm, "node", "confirmaccount");
897                         iks_insert_attrib(confirm, "name", "Confirm AIM account");
898                         iks_insert_attrib(confirm, "jid", "blog.astjab.org");
899
900                         iks_insert_node(iq, query);
901                         iks_insert_node(query, confirm);
902                         iks_send(client->p, iq);
903                 } else {
904                         ast_log(LOG_ERROR, "Out of memory.\n");
905                 }
906                 if (iq)
907                         iks_delete(iq);
908                 if (query)
909                         iks_delete(query);
910                 if (confirm)
911                         iks_delete(confirm);
912
913         } else if (!strcasecmp(node, "confirmaccount")) {
914                 iks *iq = NULL, *query = NULL, *feature = NULL;
915
916                 iq = iks_new("iq");
917                 query = iks_new("query");
918                 feature = iks_new("feature");
919
920                 if (iq && query && feature && client) {
921                         iks_insert_attrib(iq, "from", client->user);
922                         iks_insert_attrib(iq, "to", pak->from->full);
923                         iks_insert_attrib(iq, "id", pak->id);
924                         iks_insert_attrib(iq, "type", "result");
925                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
926                         iks_insert_attrib(feature, "var", "http://jabber.org/protocol/commands");
927                         iks_insert_node(iq, query);
928                         iks_insert_node(query, feature);
929                         iks_send(client->p, iq);
930                 } else {
931                         ast_log(LOG_ERROR, "Out of memory.\n");
932                 }
933                 if (iq)
934                         iks_delete(iq);
935                 if (query)
936                         iks_delete(query);
937                 if (feature)
938                         iks_delete(feature);
939         }
940
941         ASTOBJ_UNREF(client, aji_client_destroy);
942         return IKS_FILTER_EAT;
943
944 }
945 /*!
946  * \brief Handle add extra info
947  * \param data void
948  * \param pak ikspak
949  * \return IKS_FILTER_EAT
950 */
951 static int aji_client_info_handler(void *data, ikspak *pak)
952 {
953         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
954         struct aji_resource *resource = NULL;
955         struct aji_buddy *buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
956
957         resource = aji_find_resource(buddy, pak->from->resource);
958         if (pak->subtype == IKS_TYPE_RESULT) {
959                 if (!resource) {
960                         ast_log(LOG_NOTICE,"JABBER: Received client info from %s when not requested.\n", pak->from->full);
961                         ASTOBJ_UNREF(client, aji_client_destroy);
962                         return IKS_FILTER_EAT;
963                 }
964                 if (iks_find_with_attrib(pak->query, "feature", "var", "http://www.google.com/xmpp/protocol/voice/v1")) {
965                         resource->cap->jingle = 1;
966                 } else
967                         resource->cap->jingle = 0;
968         } else if (pak->subtype == IKS_TYPE_GET) {
969                 iks *iq, *disco, *ident, *google, *query;
970                 iq = iks_new("iq");
971                 query = iks_new("query");
972                 ident = iks_new("identity");
973                 disco = iks_new("feature");
974                 google = iks_new("feature");
975                 if (iq && ident && disco && google) {
976                         iks_insert_attrib(iq, "from", client->jid->full);
977                         iks_insert_attrib(iq, "to", pak->from->full);
978                         iks_insert_attrib(iq, "type", "result");
979                         iks_insert_attrib(iq, "id", pak->id);
980                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
981                         iks_insert_attrib(ident, "category", "client");
982                         iks_insert_attrib(ident, "type", "pc");
983                         iks_insert_attrib(ident, "name", "asterisk");
984                         iks_insert_attrib(disco, "var", "http://jabber.org/protocol/disco#info");
985                         iks_insert_attrib(google, "var", "http://www.google.com/xmpp/protocol/voice/v1");
986                         iks_insert_node(iq, query);
987                         iks_insert_node(query, ident);
988                         iks_insert_node(query, google);
989                         iks_insert_node(query, disco);
990                         iks_send(client->p, iq);
991                 } else
992                         ast_log(LOG_ERROR, "Out of Memory.\n");
993                 if (iq)
994                         iks_delete(iq);
995                 if (query)
996                         iks_delete(query);
997                 if (ident)
998                         iks_delete(ident);
999                 if (google)
1000                         iks_delete(google);
1001                 if (disco)
1002                         iks_delete(disco);
1003         } else if (pak->subtype == IKS_TYPE_ERROR) {
1004                 ast_log(LOG_NOTICE, "User %s does not support discovery.\n", pak->from->full);
1005         }
1006         ASTOBJ_UNREF(client, aji_client_destroy);
1007         return IKS_FILTER_EAT;
1008 }
1009 /*!
1010  * \brief Handler of the return info packet
1011  * \param data aji_client
1012  * \param pak ikspak
1013  * \return IKS_FILTER_EAT
1014 */
1015 static int aji_dinfo_handler(void *data, ikspak *pak)
1016 {
1017         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1018         char *node = NULL;
1019         struct aji_resource *resource = NULL;
1020         struct aji_buddy *buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
1021
1022         resource = aji_find_resource(buddy, pak->from->resource);
1023         if (pak->subtype == IKS_TYPE_ERROR) {
1024                 ast_log(LOG_WARNING, "Recieved error from a client, turn on jabber debug!\n");
1025                 return IKS_FILTER_EAT;
1026         }
1027         if (pak->subtype == IKS_TYPE_RESULT) {
1028                 if (!resource) {
1029                         ast_log(LOG_NOTICE,"JABBER: Received client info from %s when not requested.\n", pak->from->full);
1030                         ASTOBJ_UNREF(client, aji_client_destroy);
1031                         return IKS_FILTER_EAT;
1032                 }
1033                 if (iks_find_with_attrib(pak->query, "feature", "var", "http://www.google.com/xmpp/protocol/voice/v1")) {
1034                         resource->cap->jingle = 1;
1035                 } else
1036                         resource->cap->jingle = 0;
1037         } else if (pak->subtype == IKS_TYPE_GET && !(node = iks_find_attrib(pak->query, "node"))) {
1038                 iks *iq, *query, *identity, *disco, *reg, *commands, *gateway, *version, *vcard, *search;
1039
1040                 iq = iks_new("iq");
1041                 query = iks_new("query");
1042                 identity = iks_new("identity");
1043                 disco = iks_new("feature");
1044                 reg = iks_new("feature");
1045                 commands = iks_new("feature");
1046                 gateway = iks_new("feature");
1047                 version = iks_new("feature");
1048                 vcard = iks_new("feature");
1049                 search = iks_new("feature");
1050
1051                 if (iq && query && identity && disco && reg && commands && gateway && version && vcard && search && client) {
1052                         iks_insert_attrib(iq, "from", client->user);
1053                         iks_insert_attrib(iq, "to", pak->from->full);
1054                         iks_insert_attrib(iq, "id", pak->id);
1055                         iks_insert_attrib(iq, "type", "result");
1056                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
1057                         iks_insert_attrib(identity, "category", "gateway");
1058                         iks_insert_attrib(identity, "type", "pstn");
1059                         iks_insert_attrib(identity, "name", "Asterisk The Open Source PBX");
1060                         iks_insert_attrib(disco, "var", "http://jabber.org/protocol/disco");
1061                         iks_insert_attrib(reg, "var", "jabber:iq:register");
1062                         iks_insert_attrib(commands, "var", "http://jabber.org/protocol/commands");
1063                         iks_insert_attrib(gateway, "var", "jabber:iq:gateway");
1064                         iks_insert_attrib(version, "var", "jabber:iq:version");
1065                         iks_insert_attrib(vcard, "var", "vcard-temp");
1066                         iks_insert_attrib(search, "var", "jabber:iq:search");
1067
1068                         iks_insert_node(iq, query);
1069                         iks_insert_node(query, identity);
1070                         iks_insert_node(query, disco);
1071                         iks_insert_node(query, reg);
1072                         iks_insert_node(query, commands);
1073                         iks_insert_node(query, gateway);
1074                         iks_insert_node(query, version);
1075                         iks_insert_node(query, vcard);
1076                         iks_insert_node(query, search);
1077                         iks_send(client->p, iq);
1078                 } else {
1079                         ast_log(LOG_ERROR, "Out of memory.\n");
1080                 }
1081
1082                 if (iq)
1083                         iks_delete(iq);
1084                 if (query)
1085                         iks_delete(query);
1086                 if (identity)
1087                         iks_delete(identity);
1088                 if (disco)
1089                         iks_delete(disco);
1090                 if (reg)
1091                         iks_delete(reg);
1092                 if (commands)
1093                         iks_delete(commands);
1094                 if (gateway)
1095                         iks_delete(gateway);
1096                 if (version)
1097                         iks_delete(version);
1098                 if (vcard)
1099                         iks_delete(vcard);
1100                 if (search)
1101                         iks_delete(search);
1102
1103         } else if (pak->subtype == IKS_TYPE_GET && !strcasecmp(node, "http://jabber.org/protocol/commands")) {
1104                 iks *iq, *query, *confirm;
1105                 iq = iks_new("iq");
1106                 query = iks_new("query");
1107                 confirm = iks_new("item");
1108
1109                 if (iq && query && confirm && client) {
1110                         iks_insert_attrib(iq, "from", client->user);
1111                         iks_insert_attrib(iq, "to", pak->from->full);
1112                         iks_insert_attrib(iq, "id", pak->id);
1113                         iks_insert_attrib(iq, "type", "result");
1114                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
1115                         iks_insert_attrib(query, "node", "http://jabber.org/protocol/commands");
1116                         iks_insert_attrib(confirm, "node", "confirmaccount");
1117                         iks_insert_attrib(confirm, "name", "Confirm AIM account");
1118                         iks_insert_attrib(confirm, "jid", client->user);
1119                         iks_insert_node(iq, query);
1120                         iks_insert_node(query, confirm);
1121                         iks_send(client->p, iq);
1122                 } else {
1123                         ast_log(LOG_ERROR, "Out of memory.\n");
1124                 }
1125                 if (iq)
1126                         iks_delete(iq);
1127                 if (query)
1128                         iks_delete(query);
1129                 if (confirm)
1130                         iks_delete(confirm);
1131
1132         } else if (pak->subtype == IKS_TYPE_GET && !strcasecmp(node, "confirmaccount")) {
1133                 iks *iq, *query, *feature;
1134
1135                 iq = iks_new("iq");
1136                 query = iks_new("query");
1137                 feature = iks_new("feature");
1138
1139                 if (iq && query && feature && client) {
1140                         iks_insert_attrib(iq, "from", client->user);
1141                         iks_insert_attrib(iq, "to", pak->from->full);
1142                         iks_insert_attrib(iq, "id", pak->id);
1143                         iks_insert_attrib(iq, "type", "result");
1144                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
1145                         iks_insert_attrib(feature, "var", "http://jabber.org/protocol/commands");
1146                         iks_insert_node(iq, query);
1147                         iks_insert_node(query, feature);
1148                         iks_send(client->p, iq);
1149                 } else {
1150                         ast_log(LOG_ERROR, "Out of memory.\n");
1151                 }
1152                 if (iq)
1153                         iks_delete(iq);
1154                 if (query)
1155                         iks_delete(query);
1156                 if (feature)
1157                         iks_delete(feature);
1158         }
1159
1160         ASTOBJ_UNREF(client, aji_client_destroy);
1161         return IKS_FILTER_EAT;
1162 }
1163
1164 /*!
1165  * \brief Handles \verbatim <iq> \endverbatim tags.
1166  * \param client aji_client
1167  * \param node iks 
1168  * \return void.
1169  */
1170 static void aji_handle_iq(struct aji_client *client, iks *node)
1171 {
1172         /*Nothing to see here */
1173 }
1174
1175 /*!
1176  * \brief Handles presence packets.
1177  * \param client aji_client
1178  * \param pak ikspak the node
1179  */
1180 static void aji_handle_message(struct aji_client *client, ikspak *pak)
1181 {
1182         struct aji_message *insert, *tmp;
1183         int flag = 0;
1184         
1185         if (!(insert = ast_calloc(1, sizeof(*insert))))
1186                 return;
1187         time(&insert->arrived);
1188         if (iks_find_cdata(pak->x, "body"))
1189                 insert->message = ast_strdup(iks_find_cdata(pak->x, "body"));
1190         if (pak->id)
1191                 ast_copy_string(insert->id, pak->id, sizeof(insert->message));
1192         if (pak->from)
1193                 insert->from = ast_strdup(pak->from->full);
1194         AST_LIST_LOCK(&client->messages);
1195         AST_LIST_TRAVERSE_SAFE_BEGIN(&client->messages, tmp, list) {
1196                 if (flag) {
1197                         AST_LIST_REMOVE_CURRENT(&client->messages, list);
1198                         if (tmp->from)
1199                                 ast_free(tmp->from);
1200                         if (tmp->message)
1201                                 ast_free(tmp->message);
1202                 } else if (difftime(time(NULL), tmp->arrived) >= client->message_timeout) {
1203                         flag = 1;
1204                         AST_LIST_REMOVE_CURRENT(&client->messages, list);
1205                         if (tmp->from)
1206                                 ast_free(tmp->from);
1207                         if (tmp->message)
1208                                 ast_free(tmp->message);
1209                 }
1210         }
1211         AST_LIST_TRAVERSE_SAFE_END;
1212         AST_LIST_INSERT_HEAD(&client->messages, insert, list);
1213         AST_LIST_UNLOCK(&client->messages);
1214 }
1215 /*!
1216  * \brief Check the presence info
1217  * \param client aji_client
1218  * \param pak ikspak
1219 */
1220 static void aji_handle_presence(struct aji_client *client, ikspak *pak)
1221 {
1222         int status, priority;
1223         struct aji_buddy *buddy;
1224         struct aji_resource *tmp = NULL, *last = NULL, *found = NULL;
1225         char *ver, *node, *descrip, *type;
1226         
1227         if(client->state != AJI_CONNECTED)
1228                 aji_create_buddy(pak->from->partial, client);
1229
1230         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
1231         if (!buddy) {
1232                 ast_log(LOG_NOTICE, "Got presence packet from %s, someone not in our roster!!!!\n", pak->from->partial);
1233                 return;
1234         }
1235         type = iks_find_attrib(pak->x, "type");
1236         if(client->component && type &&!strcasecmp("probe", type)) {
1237                 aji_set_presence(client, pak->from->full, iks_find_attrib(pak->x, "to"), 1, client->statusmessage);
1238                 ast_verbose("what i was looking for \n");
1239         }
1240         ASTOBJ_WRLOCK(buddy);
1241         status = (pak->show) ? pak->show : 6;
1242         priority = atoi((iks_find_cdata(pak->x, "priority")) ? iks_find_cdata(pak->x, "priority") : "0");
1243         tmp = buddy->resources;
1244         descrip = ast_strdup(iks_find_cdata(pak->x,"status"));
1245
1246         while (tmp) {
1247                 if (!strcasecmp(tmp->resource, pak->from->resource)) {
1248                         tmp->status = status;
1249                         if (tmp->description) ast_free(tmp->description);
1250                         tmp->description = descrip;
1251                         found = tmp;
1252                         if (status == 6) {      /* Sign off Destroy resource */
1253                                 if (last && found->next) {
1254                                         last->next = found->next;
1255                                 } else if (!last) {
1256                                         if (found->next)
1257                                                 buddy->resources = found->next;
1258                                         else
1259                                                 buddy->resources = NULL;
1260                                 } else if (!found->next) {
1261                                         if (last)
1262                                                 last->next = NULL;
1263                                         else
1264                                                 buddy->resources = NULL;
1265                                 }
1266                                 ast_free(found);
1267                                 found = NULL;
1268                                 break;
1269                         }
1270                         if (tmp->priority != priority) {
1271                                 found->priority = priority;
1272                                 if (!last && !found->next)
1273                                         break;
1274                                 if (last)
1275                                         last->next = found->next;
1276                                 else
1277                                         buddy->resources = found->next;
1278                                 last = NULL;
1279                                 tmp = buddy->resources;
1280                                 if (!buddy->resources)
1281                                         buddy->resources = found;
1282                                 while (tmp) {
1283                                         if (found->priority > tmp->priority) {
1284                                                 if (last)
1285                                                         last->next = found;
1286                                                 found->next = tmp;
1287                                                 if (!last)
1288                                                         buddy->resources = found;
1289                                                 break;
1290                                         }
1291                                         if (!tmp->next) {
1292                                                 tmp->next = found;
1293                                                 break;
1294                                         }
1295                                         last = tmp;
1296                                         tmp = tmp->next;
1297                                 }
1298                         }
1299                         break;
1300                 }
1301                 last = tmp;
1302                 tmp = tmp->next;
1303         }
1304
1305         if (!found && status != 6) {
1306                 found = ast_calloc(1, sizeof(*found));
1307
1308                 if (!found) {
1309                         ast_log(LOG_ERROR, "Out of memory!\n");
1310                         return;
1311                 }
1312                 ast_copy_string(found->resource, pak->from->resource, sizeof(found->resource));
1313                 found->status = status;
1314                 found->description = descrip;
1315                 found->priority = priority;
1316                 found->next = NULL;
1317                 last = NULL;
1318                 tmp = buddy->resources;
1319                 while (tmp) {
1320                         if (found->priority > tmp->priority) {
1321                                 if (last)
1322                                         last->next = found;
1323                                 found->next = tmp;
1324                                 if (!last)
1325                                         buddy->resources = found;
1326                                 break;
1327                         }
1328                         if (!tmp->next) {
1329                                 tmp->next = found;
1330                                 break;
1331                         }
1332                         last = tmp;
1333                         tmp = tmp->next;
1334                 }
1335                 if (!tmp)
1336                         buddy->resources = found;
1337         }
1338         ASTOBJ_UNLOCK(buddy);
1339         ASTOBJ_UNREF(buddy, aji_buddy_destroy);
1340
1341         node = iks_find_attrib(iks_find(pak->x, "c"), "node");
1342         ver = iks_find_attrib(iks_find(pak->x, "c"), "ver");
1343
1344         if(status !=6 && !found->cap) {
1345                 found->cap = aji_find_version(node, ver, pak);
1346                 if(gtalk_yuck(pak->x)) /* gtalk should do discover */
1347                         found->cap->jingle = 1;
1348                 if(found->cap->jingle && option_debug > 4) {
1349                         if (option_debug)
1350                                 ast_log(LOG_DEBUG,"Special case for google till they support discover.\n");
1351                 }
1352                 else {
1353                         iks *iq, *query;
1354                         iq = iks_new("iq");
1355                         query = iks_new("query");
1356                         if(query && iq)  {
1357                                 iks_insert_attrib(iq, "type", "get");
1358                                 iks_insert_attrib(iq, "to", pak->from->full);
1359                                 iks_insert_attrib(iq,"from",iks_find_attrib(pak->x,"to"));
1360                                 iks_insert_attrib(iq, "id", client->mid);
1361                                 ast_aji_increment_mid(client->mid);
1362                                 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
1363                                 iks_insert_node(iq, query);
1364                                 iks_send(client->p, iq);
1365                                 
1366                         } else
1367                                 ast_log(LOG_ERROR, "Out of memory.\n");
1368                         if(query)
1369                                 iks_delete(query);
1370                         if(iq)
1371                                 iks_delete(iq);
1372                 }
1373         }
1374         if (option_verbose > 4) {
1375                 switch (pak->subtype) {
1376                 case IKS_TYPE_AVAILABLE:
1377                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I am available ^_* %i\n", pak->subtype);
1378                         break;
1379                 case IKS_TYPE_UNAVAILABLE:
1380                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I am unavailable ^_* %i\n", pak->subtype);
1381                         break;
1382                 default:
1383                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: Ohh sexy and the wrong type: %i\n", pak->subtype);
1384                 }
1385                 switch (pak->show) {
1386                 case IKS_SHOW_UNAVAILABLE:
1387                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1388                         break;
1389                 case IKS_SHOW_AVAILABLE:
1390                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type is available\n");
1391                         break;
1392                 case IKS_SHOW_CHAT:
1393                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1394                         break;
1395                 case IKS_SHOW_AWAY:
1396                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type is away\n");
1397                         break;
1398                 case IKS_SHOW_XA:
1399                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1400                         break;
1401                 case IKS_SHOW_DND:
1402                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1403                         break;
1404                 default:
1405                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: Kinky! how did that happen %i\n", pak->show);
1406                 }
1407         }
1408 }
1409
1410 /*!
1411  * \brief handles subscription requests.
1412  * \param client aji_client
1413  * \param pak ikspak iksemel packet.
1414  * \return void.
1415  */
1416 static void aji_handle_subscribe(struct aji_client *client, ikspak *pak)
1417 {
1418         if(pak->subtype == IKS_TYPE_SUBSCRIBE) { 
1419                 iks *presence = NULL, *status = NULL;
1420                 presence = iks_new("presence");
1421                 status = iks_new("status");
1422                 if(presence && status) {
1423                         iks_insert_attrib(presence, "type", "subscribed");
1424                         iks_insert_attrib(presence, "to", pak->from->full);
1425                         iks_insert_attrib(presence, "from", client->jid->full);
1426                         if(pak->id)
1427                                 iks_insert_attrib(presence, "id", pak->id);
1428                         iks_insert_cdata(status, "Asterisk has approved subscription", 0);
1429                         iks_insert_node(presence, status);
1430                         iks_send(client->p, presence);
1431                 } else
1432                         ast_log(LOG_ERROR, "Unable to allocate nodes\n");
1433                 if(presence)
1434                         iks_delete(presence);
1435                 if(status)
1436                         iks_delete(status);
1437                 if(client->component)
1438                         aji_set_presence(client, pak->from->full, iks_find_attrib(pak->x, "to"), 1, client->statusmessage);
1439         }
1440         if (option_verbose > 4) {
1441                 switch (pak->subtype) {
1442                 case IKS_TYPE_SUBSCRIBE:
1443                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1444                         break;
1445                 case IKS_TYPE_SUBSCRIBED:
1446                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1447                         break;
1448                 case IKS_TYPE_UNSUBSCRIBE:
1449                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1450                         break;
1451                 case IKS_TYPE_UNSUBSCRIBED:
1452                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1453                         break;
1454                 default:                                /*IKS_TYPE_ERROR: */
1455                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1456                         break;
1457                 }
1458         }
1459 }
1460
1461 /*!
1462  * \brief sends messages.
1463  * \param client aji_client 
1464  * \param address
1465  * \param message
1466  * \return 1.
1467  */
1468 int ast_aji_send(struct aji_client *client, const char *address, const char *message)
1469 {
1470         int res = 0;
1471         iks *message_packet = NULL;
1472         if (client->state == AJI_CONNECTED) {
1473                 message_packet = iks_make_msg(IKS_TYPE_CHAT, address, message);
1474                 if (message_packet) {
1475                         iks_insert_attrib(message_packet, "from", client->jid->full);
1476                         res = iks_send(client->p, message_packet);
1477                 } else {
1478                         ast_log(LOG_ERROR, "Out of memory.\n");
1479                 }
1480                 if (message_packet)
1481                         iks_delete(message_packet);
1482         } else
1483                 ast_log(LOG_WARNING, "JABBER: Not connected can't send\n");
1484         return 1;
1485 }
1486
1487 /*!
1488  * \brief create a chatroom.
1489  * \param client aji_client
1490  * \param room name of room
1491  * \param server name of server
1492  * \param topic topic for the room.
1493  * \return 0.
1494  */
1495 int ast_aji_create_chat(struct aji_client *client, char *room, char *server, char *topic)
1496 {
1497         int res = 0;
1498         iks *iq = NULL;
1499         iq = iks_new("iq");
1500         if (iq && client) {
1501                 iks_insert_attrib(iq, "type", "get");
1502                 iks_insert_attrib(iq, "to", server);
1503                 iks_insert_attrib(iq, "id", client->mid);
1504                 ast_aji_increment_mid(client->mid);
1505                 iks_send(client->p, iq);
1506         } else 
1507                 ast_log(LOG_ERROR, "Out of memory.\n");
1508         return res;
1509 }
1510
1511 /*!
1512  * \brief join a chatroom.
1513  * \param client aji_client 
1514  * \param room room to join
1515  * \return res.
1516  */
1517 int ast_aji_join_chat(struct aji_client *client, char *room)
1518 {
1519         int res = 0;
1520         iks *presence = NULL, *priority = NULL;
1521         presence = iks_new("presence");
1522         priority = iks_new("priority");
1523         if (presence && priority && client) {
1524                 iks_insert_cdata(priority, "0", 1);
1525                 iks_insert_attrib(presence, "to", room);
1526                 iks_insert_node(presence, priority);
1527                 res = iks_send(client->p, presence);
1528                 iks_insert_cdata(priority, "5", 1);
1529                 iks_insert_attrib(presence, "to", room);
1530                 res = iks_send(client->p, presence);
1531         } else 
1532                 ast_log(LOG_ERROR, "Out of memory.\n");
1533         if (presence)
1534                 iks_delete(presence);
1535         if (priority)
1536                 iks_delete(priority);
1537         return res;
1538 }
1539
1540 /*!
1541  * \brief invite to a chatroom.
1542  * \param client aji_client
1543  * \param user 
1544  * \param room
1545  * \param message
1546  * \return res.
1547  */
1548 int ast_aji_invite_chat(struct aji_client *client, char *user, char *room, char *message)
1549 {
1550         int res = 0;
1551         iks *invite, *body, *namespace;
1552
1553         invite = iks_new("message");
1554         body = iks_new("body");
1555         namespace = iks_new("x");
1556         if (client && invite && body && namespace) {
1557                 iks_insert_attrib(invite, "to", user);
1558                 iks_insert_attrib(invite, "id", client->mid);
1559                 ast_aji_increment_mid(client->mid);
1560                 iks_insert_cdata(body, message, 0);
1561                 iks_insert_attrib(namespace, "xmlns", "jabber:x:conference");
1562                 iks_insert_attrib(namespace, "jid", room);
1563                 iks_insert_node(invite, body);
1564                 iks_insert_node(invite, namespace);
1565                 res = iks_send(client->p, invite);
1566         } else 
1567                 ast_log(LOG_ERROR, "Out of memory.\n");
1568         if (body)
1569                 iks_delete(body);
1570         if (namespace)
1571                 iks_delete(namespace);
1572         if (invite)
1573                 iks_delete(invite);
1574         return res;
1575 }
1576
1577
1578 /*!
1579  * \brief receive message loop.
1580  * \param data void
1581  * \return void.
1582  */
1583 static void *aji_recv_loop(void *data)
1584 {
1585         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1586         int res = IKS_HOOK;
1587         do {
1588                 if (res != IKS_OK) {
1589                         while(res != IKS_OK) {
1590                                 if(option_verbose > 3)
1591                                         ast_verbose("JABBER: reconnecting.\n");
1592                                 res = aji_reconnect(client);
1593                                 sleep(4);
1594                         }
1595                 }
1596
1597                 res = iks_recv(client->p, 1);
1598
1599                 if (client->state == AJI_DISCONNECTING) {
1600                         if (option_debug > 1)
1601                                 ast_log(LOG_DEBUG, "Ending our Jabber client's thread due to a disconnect\n");
1602                         pthread_exit(NULL);
1603                 }
1604                 client->timeout--;
1605                 if (res == IKS_HOOK) 
1606                         ast_log(LOG_WARNING, "JABBER: Got hook event.\n");
1607                 else if (res == IKS_NET_TLSFAIL)
1608                         ast_log(LOG_WARNING, "JABBER:  Failure in TLS.\n");
1609                 else if (client->timeout == 0 && client->state == AJI_CONNECTED) {
1610                         res = iks_send_raw(client->p, " ");
1611                         if(res == IKS_OK)
1612                                 client->timeout = 50;
1613                         else
1614                                 ast_log(LOG_WARNING, "JABBER:  Network Timeout\n");
1615                 } else if (res == IKS_NET_RWERR)
1616                         ast_log(LOG_WARNING, "JABBER: socket read error\n");
1617         } while (client);
1618         ASTOBJ_UNREF(client, aji_client_destroy);
1619         return 0;
1620 }
1621
1622 /*!
1623  * \brief increments the mid field for messages and other events.
1624  * \param mid char.
1625  * \return void.
1626  */
1627 void ast_aji_increment_mid(char *mid)
1628 {
1629         int i = 0;
1630
1631         for (i = strlen(mid) - 1; i >= 0; i--) {
1632                 if (mid[i] != 'z') {
1633                         mid[i] = mid[i] + 1;
1634                         i = 0;
1635                 } else
1636                         mid[i] = 'a';
1637         }
1638 }
1639
1640
1641 /*!
1642  * \brief attempts to register to a transport.
1643  * \param aji_client struct, and xml packet.
1644  * \return IKS_FILTER_EAT.
1645  */
1646 /*allows for registering to transport , was too sketch and is out for now. */
1647 /*static int aji_register_transport(void *data, ikspak *pak)
1648 {
1649         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1650         int res = 0;
1651         struct aji_buddy *buddy = NULL;
1652         iks *send = iks_make_iq(IKS_TYPE_GET, "jabber:iq:register");
1653
1654         if (client && send) {
1655                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1656                         ASTOBJ_RDLOCK(iterator); 
1657                         if (iterator->btype == AJI_TRANS) {
1658                                   buddy = iterator;
1659                         }
1660                         ASTOBJ_UNLOCK(iterator);
1661                 });
1662                 iks_filter_remove_hook(client->f, aji_register_transport);
1663                 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);
1664                 iks_insert_attrib(send, "to", buddy->host);
1665                 iks_insert_attrib(send, "id", client->mid);
1666                 ast_aji_increment_mid(client->mid);
1667                 iks_insert_attrib(send, "from", client->user);
1668                 res = iks_send(client->p, send);
1669         } else 
1670                 ast_log(LOG_ERROR, "Out of memory.\n");
1671
1672         if (send)
1673                 iks_delete(send);
1674         ASTOBJ_UNREF(client, aji_client_destroy);
1675         return IKS_FILTER_EAT;
1676
1677 }
1678 */
1679 /*!
1680  * \brief attempts to register to a transport step 2.
1681  * \param aji_client struct, and xml packet.
1682  * \return IKS_FILTER_EAT.
1683  */
1684 /* more of the same blob of code, too wonky for now*/
1685 /* static int aji_register_transport2(void *data, ikspak *pak)
1686 {
1687         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1688         int res = 0;
1689         struct aji_buddy *buddy = NULL;
1690
1691         iks *regiq = iks_new("iq");
1692         iks *regquery = iks_new("query");
1693         iks *reguser = iks_new("username");
1694         iks *regpass = iks_new("password");
1695
1696         if (client && regquery && reguser && regpass && regiq) {
1697                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1698                         ASTOBJ_RDLOCK(iterator);
1699                         if (iterator->btype == AJI_TRANS)
1700                                 buddy = iterator; ASTOBJ_UNLOCK(iterator);
1701                 });
1702                 iks_filter_remove_hook(client->f, aji_register_transport2);
1703                 iks_insert_attrib(regiq, "to", buddy->host);
1704                 iks_insert_attrib(regiq, "type", "set");
1705                 iks_insert_attrib(regiq, "id", client->mid);
1706                 ast_aji_increment_mid(client->mid);
1707                 iks_insert_attrib(regiq, "from", client->user);
1708                 iks_insert_attrib(regquery, "xmlns", "jabber:iq:register");
1709                 iks_insert_cdata(reguser, buddy->user, 0);
1710                 iks_insert_cdata(regpass, buddy->pass, 0);
1711                 iks_insert_node(regiq, regquery);
1712                 iks_insert_node(regquery, reguser);
1713                 iks_insert_node(regquery, regpass);
1714                 res = iks_send(client->p, regiq);
1715         } else
1716                 ast_log(LOG_ERROR, "Out of memory.\n");
1717         if (regiq)
1718                 iks_delete(regiq);
1719         if (regquery)
1720                 iks_delete(regquery);
1721         if (reguser)
1722                 iks_delete(reguser);
1723         if (regpass)
1724                 iks_delete(regpass);
1725         ASTOBJ_UNREF(client, aji_client_destroy);
1726         return IKS_FILTER_EAT;
1727 }
1728 */
1729 /*!
1730  * \brief goes through roster and prunes users not needed in list, or adds them accordingly.
1731  * \param client aji_client
1732  * \return void.
1733  */
1734 static void aji_pruneregister(struct aji_client *client)
1735 {
1736         int res = 0;
1737         iks *removeiq = iks_new("iq");
1738         iks *removequery = iks_new("query");
1739         iks *removeitem = iks_new("item");
1740         iks *send = iks_make_iq(IKS_TYPE_GET, "http://jabber.org/protocol/disco#items");
1741
1742         if (client && removeiq && removequery && removeitem && send) {
1743                 iks_insert_node(removeiq, removequery);
1744                 iks_insert_node(removequery, removeitem);
1745                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1746                         ASTOBJ_RDLOCK(iterator);
1747                         /* For an aji_buddy, both AUTOPRUNE and AUTOREGISTER will never
1748                          * be called at the same time */
1749                         if (ast_test_flag(iterator, AJI_AUTOPRUNE)) {
1750                                 res = iks_send(client->p, iks_make_s10n(IKS_TYPE_UNSUBSCRIBE, iterator->name,
1751                                                 "GoodBye your status is no longer needed by Asterisk the Open Source PBX"
1752                                                 " so I am no longer subscribing to your presence.\n"));
1753                                 res = iks_send(client->p, iks_make_s10n(IKS_TYPE_UNSUBSCRIBED, iterator->name,
1754                                                 "GoodBye you are no longer in the asterisk config file so I am removing"
1755                                                 " your access to my presence.\n"));
1756                                 iks_insert_attrib(removeiq, "from", client->jid->full); 
1757                                 iks_insert_attrib(removeiq, "type", "set"); 
1758                                 iks_insert_attrib(removequery, "xmlns", "jabber:iq:roster");
1759                                 iks_insert_attrib(removeitem, "jid", iterator->name);
1760                                 iks_insert_attrib(removeitem, "subscription", "remove");
1761                                 res = iks_send(client->p, removeiq);
1762                         } else if (ast_test_flag(iterator, AJI_AUTOREGISTER)) {
1763                                 res = iks_send(client->p, iks_make_s10n(IKS_TYPE_SUBSCRIBE, iterator->name, 
1764                                                 "Greetings I am the Asterisk Open Source PBX and I want to subscribe to your presence\n"));
1765                                 ast_clear_flag(iterator, AJI_AUTOREGISTER);
1766                         }
1767                         ASTOBJ_UNLOCK(iterator);
1768                 });
1769         } else
1770                 ast_log(LOG_ERROR, "Out of memory.\n");
1771         if (removeiq)
1772                 iks_delete(removeiq);
1773         if (removequery)
1774                 iks_delete(removequery);
1775         if (removeitem)
1776                 iks_delete(removeitem);
1777         if (send)
1778                 iks_delete(send);
1779         ASTOBJ_CONTAINER_PRUNE_MARKED(&client->buddies, aji_buddy_destroy);
1780 }
1781
1782 /*!
1783  * \brief filters the roster packet we get back from server.
1784  * \param data void
1785  * \param pak ikspak iksemel packet.
1786  * \return IKS_FILTER_EAT.
1787  */
1788 static int aji_filter_roster(void *data, ikspak *pak)
1789 {
1790         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1791         int flag = 0;
1792         iks *x = NULL;
1793         struct aji_buddy *buddy;
1794         
1795         client->state = AJI_CONNECTED;
1796         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1797                 ASTOBJ_RDLOCK(iterator);
1798                 x = iks_child(pak->query);
1799                 flag = 0;
1800                 while (x) {
1801                         if (!iks_strcmp(iks_name(x), "item")) {
1802                                 if (!strcasecmp(iterator->name, iks_find_attrib(x, "jid"))) {
1803                                         flag = 1;
1804                                         ast_clear_flag(iterator, AJI_AUTOPRUNE | AJI_AUTOREGISTER);
1805                                 }
1806                         }
1807                         x = iks_next(x);
1808                 }
1809                 if (!flag)
1810                         ast_copy_flags(iterator, client, AJI_AUTOREGISTER);
1811                 if (x)
1812                         iks_delete(x);
1813                 ASTOBJ_UNLOCK(iterator);
1814         });
1815
1816         x = iks_child(pak->query);
1817         while (x) {
1818                 flag = 0;
1819                 if (iks_strcmp(iks_name(x), "item") == 0) {
1820                         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1821                                 ASTOBJ_RDLOCK(iterator);
1822                                 if (!strcasecmp(iterator->name, iks_find_attrib(x, "jid")))
1823                                         flag = 1;
1824                                 ASTOBJ_UNLOCK(iterator);
1825                         });
1826
1827                         if (!flag) {
1828                                 buddy = ast_calloc(1, sizeof(*buddy));
1829                                 if (!buddy) {
1830                                         ast_log(LOG_WARNING, "Out of memory\n");
1831                                         return 0;
1832                                 }
1833                                 ASTOBJ_INIT(buddy);
1834                                 ASTOBJ_WRLOCK(buddy);
1835                                 ast_copy_string(buddy->name, iks_find_attrib(x, "jid"), sizeof(buddy->name));
1836                                 ast_clear_flag(buddy, AST_FLAGS_ALL);
1837                                 if(ast_test_flag(client, AJI_AUTOPRUNE)) {
1838                                         ast_set_flag(buddy, AJI_AUTOPRUNE);
1839                                         buddy->objflags |= ASTOBJ_FLAG_MARKED;
1840                                 } else
1841                                         ast_set_flag(buddy, AJI_AUTOREGISTER);
1842                                 ASTOBJ_UNLOCK(buddy);
1843                                 if (buddy) {
1844                                         ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
1845                                         ASTOBJ_UNREF(buddy, aji_buddy_destroy);
1846                                 }
1847                         }
1848                 }
1849                 x = iks_next(x);
1850         }
1851         if (x)
1852                 iks_delete(x);
1853         aji_pruneregister(client);
1854
1855         ASTOBJ_UNREF(client, aji_client_destroy);
1856         return IKS_FILTER_EAT;
1857 }
1858 /*!
1859  * \brief reconnect to jabber server
1860  * \param client aji_client
1861  * \return res.
1862 */
1863 static int aji_reconnect(struct aji_client *client)
1864 {
1865         int res = 0;
1866
1867         if (client->state)
1868                 client->state = AJI_DISCONNECTED;
1869         client->timeout=50;
1870         if (client->p)
1871                 iks_parser_reset(client->p);
1872         if (client->authorized)
1873                 client->authorized = 0;
1874
1875         res = aji_initialize(client);
1876
1877         return res;
1878 }
1879 /*!
1880  * \brief Get the roster of jabber users
1881  * \param client aji_client
1882  * \return 1.
1883 */
1884 static int aji_get_roster(struct aji_client *client)
1885 {
1886         iks *roster = NULL;
1887         roster = iks_make_iq(IKS_TYPE_GET, IKS_NS_ROSTER);
1888         if(roster) {
1889                 iks_insert_attrib(roster, "id", "roster");
1890                 aji_set_presence(client, NULL, client->jid->full, 1, client->statusmessage);
1891                 iks_send(client->p, roster);
1892         }
1893         if (roster)
1894                 iks_delete(roster);
1895         return 1;
1896 }
1897
1898 /*!
1899  * \brief connects as a client to jabber server.
1900  * \param data void
1901  * \param pak ikspak iksemel packet
1902  * \return res.
1903  */
1904 static int aji_client_connect(void *data, ikspak *pak)
1905 {
1906         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1907         int res = 0;
1908
1909         if (client) {
1910                 if (client->state == AJI_DISCONNECTED) {
1911                         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);
1912                         client->state = AJI_CONNECTING;
1913                         client->jid = (iks_find_cdata(pak->query, "jid")) ? iks_id_new(client->stack, iks_find_cdata(pak->query, "jid")) : client->jid;
1914                         iks_filter_remove_hook(client->f, aji_client_connect);
1915                         if(!client->component) /*client*/
1916                                 aji_get_roster(client);
1917                 }
1918         } else
1919                 ast_log(LOG_ERROR, "Out of memory.\n");
1920
1921         ASTOBJ_UNREF(client, aji_client_destroy);
1922         return res;
1923 }
1924
1925 /*!
1926  * \brief prepares client for connect.
1927  * \param client aji_client
1928  * \return 1.
1929  */
1930 static int aji_initialize(struct aji_client *client)
1931 {
1932         /* If it's a component, connect to user, otherwise, connect to server */
1933         int connected = iks_connect_via(client->p, S_OR(client->serverhost, client->jid->server), client->port, client->component ? client->user : client->jid->server);
1934
1935         if (connected == IKS_NET_NOCONN) {
1936                 ast_log(LOG_ERROR, "JABBER ERROR: No Connection\n");
1937                 return IKS_HOOK;
1938         } else  if (connected == IKS_NET_NODNS) {
1939                 ast_log(LOG_ERROR, "JABBER ERROR: No DNS %s for client to  %s\n", client->name, S_OR(client->serverhost, client->jid->server));
1940                 return IKS_HOOK;
1941         } else /* if (!connected) phsultan: check if this is needed! */
1942                 iks_recv(client->p, 30);
1943         return IKS_OK;
1944 }
1945
1946 /*!
1947  * \brief disconnect from jabber server.
1948  * \param client aji_client
1949  * \return 1.
1950  */
1951 int ast_aji_disconnect(struct aji_client *client)
1952 {
1953         if (client) {
1954                 if (option_verbose > 3)
1955                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: Disconnecting\n");
1956                 iks_disconnect(client->p);
1957                 iks_parser_delete(client->p);
1958                 ASTOBJ_UNREF(client, aji_client_destroy);
1959         }
1960
1961         return 1;
1962 }
1963
1964 /*!
1965  * \brief set presence of client.
1966  * \param client aji_client
1967  * \param to user send it to
1968  * \param from user it came from
1969  * \param level
1970  * \param desc
1971  * \return void.
1972  */
1973 static void aji_set_presence(struct aji_client *client, char *to, char *from, int level, char *desc)
1974 {
1975         int res = 0;
1976         iks *presence = iks_make_pres(level, desc);
1977         iks *cnode = iks_new("c");
1978         iks *priority = iks_new("priority");
1979
1980         iks_insert_cdata(priority, "0", 1);
1981         if (presence && cnode && client) {
1982                 if(to)
1983                         iks_insert_attrib(presence, "to", to);
1984                 if(from)
1985                         iks_insert_attrib(presence, "from", from);
1986                 iks_insert_attrib(cnode, "node", "http://www.asterisk.org/xmpp/client/caps");
1987                 iks_insert_attrib(cnode, "ver", "asterisk-xmpp");
1988                 iks_insert_attrib(cnode, "ext", "voice-v1");
1989                 iks_insert_attrib(cnode, "xmlns", "http://jabber.org/protocol/caps");
1990                 iks_insert_node(presence, cnode);
1991                 res = iks_send(client->p, presence);
1992         } else
1993                 ast_log(LOG_ERROR, "Out of memory.\n");
1994         if (cnode)
1995                 iks_delete(cnode);
1996         if (presence)
1997                 iks_delete(presence);
1998 }
1999
2000 /*!
2001  * \brief turnon console debugging.
2002  * \param fd
2003  * \param argc Integer. Number of args
2004  * \param argv List of arguements
2005  * \return RESULT_SUCCESS.
2006  */
2007 static int aji_do_debug(int fd, int argc, char *argv[])
2008 {
2009         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2010                 ASTOBJ_RDLOCK(iterator); 
2011                 iterator->debug = 1;
2012                 ASTOBJ_UNLOCK(iterator);
2013         });
2014         ast_cli(fd, "Jabber Debugging Enabled.\n");
2015         return RESULT_SUCCESS;
2016 }
2017
2018 /*!
2019  * \brief reload jabber module.
2020  * \param fd
2021  * \param argc no of args
2022  * \param argv list of arguements
2023  * \return RESULT_SUCCESS.
2024  */
2025 static int aji_do_reload(int fd, int argc, char *argv[])
2026 {
2027         aji_reload();
2028         ast_cli(fd, "Jabber Reloaded.\n");
2029         return RESULT_SUCCESS;
2030 }
2031
2032 /*!
2033  * \brief turnoff console debugging.
2034  * \param fd
2035  * \param argc Integer. number of args
2036  * \param argv list of arguements
2037  * \return RESULT_SUCCESS.
2038  */
2039 static int aji_no_debug(int fd, int argc, char *argv[])
2040 {
2041         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2042                 ASTOBJ_RDLOCK(iterator);
2043                 iterator->debug = 0;
2044                 ASTOBJ_UNLOCK(iterator);
2045         });
2046         ast_cli(fd, "Jabber Debugging Disabled.\n");
2047         return RESULT_SUCCESS;
2048 }
2049
2050 /*!
2051  * \brief show client status.
2052  * \param fd
2053  * \param argc Integer. number of args
2054  * \param argv list of arguements
2055  * \return RESULT_SUCCESS.
2056  */
2057 static int aji_show_clients(int fd, int argc, char *argv[])
2058 {
2059         char *status;
2060         int count = 0;
2061         ast_cli(fd, "Jabber Users and their status:\n");
2062         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2063                 ASTOBJ_RDLOCK(iterator);
2064                 count++;
2065                 switch (iterator->state) {
2066                 case AJI_DISCONNECTED:
2067                         status = "Disconnected";
2068                         break;
2069                 case AJI_CONNECTING:
2070                         status = "Connecting";
2071                         break;
2072                 case AJI_CONNECTED:
2073                         status = "Connected";
2074                         break;
2075                 default:
2076                         status = "Unknown";
2077                 }
2078                 ast_cli(fd, "       User: %s     - %s\n", iterator->user, status);
2079                 ASTOBJ_UNLOCK(iterator);
2080         });
2081         ast_cli(fd, "----\n");
2082         ast_cli(fd, "   Number of users: %d\n", count);
2083         return RESULT_SUCCESS;
2084 }
2085
2086 /*!
2087  * \brief send test message for debugging.
2088  * \param fd
2089  * \param argc Integer. number of args
2090  * \param argv list of arguements
2091  * \return RESULT_SUCCESS,RESULT_FAILURE.
2092  */
2093 static int aji_test(int fd, int argc, char *argv[])
2094 {
2095         struct aji_client *client;
2096         struct aji_resource *resource;
2097         const char *name = "asterisk";
2098         struct aji_message *tmp;
2099
2100         if (argc > 3)
2101                 return RESULT_SHOWUSAGE;
2102         else if (argc == 3)
2103                 name = argv[2];
2104
2105         if (!(client = ASTOBJ_CONTAINER_FIND(&clients, name))) {
2106                 ast_cli(fd, "Unable to find client '%s'!\n", name);
2107                 return RESULT_FAILURE;
2108         }
2109
2110         /* XXX Does Matt really want everyone to use his personal address for tests? */ /* XXX yes he does */
2111         ast_aji_send(client, "mogorman@astjab.org", "blahblah");
2112         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
2113                 ASTOBJ_RDLOCK(iterator);
2114                 ast_verbose("User: %s\n", iterator->name);
2115                 for (resource = iterator->resources; resource; resource = resource->next) {
2116                         ast_verbose("Resource: %s\n", resource->resource);
2117                         if(resource->cap) {
2118                                 ast_verbose("   client: %s\n", resource->cap->parent->node);
2119                                 ast_verbose("   version: %s\n", resource->cap->version);
2120                                 ast_verbose("   Jingle Capable: %d\n", resource->cap->jingle);
2121                         }
2122                         ast_verbose("   Priority: %d\n", resource->priority);
2123                         ast_verbose("   Status: %d\n", resource->status); 
2124                         ast_verbose("   Message: %s\n", S_OR(resource->description,"")); 
2125                 }
2126                 ASTOBJ_UNLOCK(iterator);
2127         });
2128         ast_verbose("\nOooh a working message stack!\n");
2129         AST_LIST_LOCK(&client->messages);
2130         AST_LIST_TRAVERSE(&client->messages, tmp, list) {
2131                 ast_verbose("   Message from: %s with id %s @ %s        %s\n",tmp->from, S_OR(tmp->id,""), ctime(&tmp->arrived), S_OR(tmp->message, ""));
2132         }
2133         AST_LIST_UNLOCK(&client->messages);
2134         ASTOBJ_UNREF(client, aji_client_destroy);
2135
2136         return RESULT_SUCCESS;
2137 }
2138
2139 /*!
2140  * \brief creates aji_client structure.
2141  * \param label
2142  * \param var ast_variable
2143  * \param debug 
2144  * \return 0.
2145  */
2146 static int aji_create_client(char *label, struct ast_variable *var, int debug)
2147 {
2148         char *resource;
2149         struct aji_client *client = NULL;
2150         int flag = 0;
2151
2152         client = ASTOBJ_CONTAINER_FIND(&clients,label);
2153         if (!client) {
2154                 flag = 1;
2155                 client = ast_calloc(1, sizeof(*client));
2156                 if (!client) {
2157                         ast_log(LOG_ERROR, "Out of memory!\n");
2158                         return 0;
2159                 }
2160                 ASTOBJ_INIT(client);
2161                 ASTOBJ_WRLOCK(client);
2162                 ASTOBJ_CONTAINER_INIT(&client->buddies);
2163         } else {
2164                 ASTOBJ_WRLOCK(client);
2165                 ASTOBJ_UNMARK(client);
2166         }
2167         ASTOBJ_CONTAINER_MARKALL(&client->buddies);
2168         ast_copy_string(client->name, label, sizeof(client->name));
2169         ast_copy_string(client->mid, "aaaaa", sizeof(client->mid));
2170
2171         /* Set default values for the client object */
2172         client->debug = debug;
2173         ast_copy_flags(client, &globalflags, AST_FLAGS_ALL);
2174         client->port = 5222;
2175         client->usetls = 1;
2176         client->usesasl = 1;
2177         client->forcessl = 0;
2178         client->keepalive = 1;
2179         client->timeout = 50;
2180         client->message_timeout = 100;
2181         AST_LIST_HEAD_INIT(&client->messages);
2182         client->component = 0;
2183         ast_copy_string(client->statusmessage, "Online and Available", sizeof(client->statusmessage));
2184
2185         if (flag) {
2186                 client->authorized = 0;
2187                 client->state = AJI_DISCONNECTED;
2188         }
2189         while (var) {
2190                 if (!strcasecmp(var->name, "username"))
2191                         ast_copy_string(client->user, var->value, sizeof(client->user));
2192                 else if (!strcasecmp(var->name, "serverhost"))
2193                         ast_copy_string(client->serverhost, var->value, sizeof(client->serverhost));
2194                 else if (!strcasecmp(var->name, "secret"))
2195                         ast_copy_string(client->password, var->value, sizeof(client->password));
2196                 else if (!strcasecmp(var->name, "statusmessage"))
2197                         ast_copy_string(client->statusmessage, var->value, sizeof(client->statusmessage));
2198                 else if (!strcasecmp(var->name, "port"))
2199                         client->port = atoi(var->value);
2200                 else if (!strcasecmp(var->name, "timeout"))
2201                         client->message_timeout = atoi(var->value);
2202                 else if (!strcasecmp(var->name, "debug"))
2203                         client->debug = (ast_false(var->value)) ? 0 : 1;
2204                 else if (!strcasecmp(var->name, "type")) {
2205                         if (!strcasecmp(var->value, "component"))
2206                                 client->component = 1;
2207                 } else if (!strcasecmp(var->name, "usetls")) {
2208                         client->usetls = (ast_false(var->value)) ? 0 : 1;
2209                 } else if (!strcasecmp(var->name, "usesasl")) {
2210                         client->usesasl = (ast_false(var->value)) ? 0 : 1;
2211                 } else if (!strcasecmp(var->name, "forceoldssl"))
2212                         client->forcessl = (ast_false(var->value)) ? 0 : 1;
2213                 else if (!strcasecmp(var->name, "keepalive"))
2214                         client->keepalive = (ast_false(var->value)) ? 0 : 1;
2215                 else if (!strcasecmp(var->name, "autoprune"))
2216                         ast_set2_flag(client, ast_true(var->value), AJI_AUTOPRUNE);
2217                 else if (!strcasecmp(var->name, "autoregister"))
2218                         ast_set2_flag(client, ast_true(var->value), AJI_AUTOREGISTER);
2219                 else if (!strcasecmp(var->name, "buddy"))
2220                                 aji_create_buddy(var->value, client);
2221         /* no transport support in this version */
2222         /*      else if (!strcasecmp(var->name, "transport"))
2223                                 aji_create_transport(var->value, client);
2224         */
2225                 var = var->next;
2226         }
2227         if (!flag) {
2228                 ASTOBJ_UNLOCK(client);
2229                 ASTOBJ_UNREF(client, aji_client_destroy);
2230                 return 1;
2231         }
2232         client->p = iks_stream_new(((client->component) ? "jabber:component:accept" : "jabber:client"), client, aji_act_hook);
2233         if (!client->p) {
2234                 ast_log(LOG_ERROR, "Failed to create stream for client '%s'!\n", client->name);
2235                 return 0;
2236         }
2237         client->stack = iks_stack_new(8192, 8192);
2238         if (!client->stack) {
2239                 ast_log(LOG_ERROR, "Failed to allocate stack for client '%s'\n", client->name);
2240                 return 0;
2241         }
2242         client->f = iks_filter_new();
2243         if (!client->f) {
2244                 ast_log(LOG_ERROR, "Failed to create filter for client '%s'\n", client->name);
2245                 return 0;
2246         }
2247         if (!strchr(client->user, '/') && !client->component) { /*client */
2248                 resource = NULL;
2249                 asprintf(&resource, "%s/asterisk", client->user);
2250                 if (resource) {
2251                         client->jid = iks_id_new(client->stack, resource);
2252                         ast_free(resource);
2253                 }
2254         } else
2255                 client->jid = iks_id_new(client->stack, client->user);
2256         if (client->component) {
2257                 iks_filter_add_rule(client->f, aji_dinfo_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
2258                 iks_filter_add_rule(client->f, aji_ditems_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#items", IKS_RULE_DONE);
2259                 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);
2260                 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);
2261         } else {
2262                 iks_filter_add_rule(client->f, aji_client_info_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
2263         }
2264         if (!strchr(client->user, '/') && !client->component) { /*client */
2265                 resource = NULL;
2266                 asprintf(&resource, "%s/asterisk", client->user);
2267                 if (resource) {
2268                         client->jid = iks_id_new(client->stack, resource);
2269                         ast_free(resource);
2270                 }
2271         } else
2272                 client->jid = iks_id_new(client->stack, client->user);
2273         iks_set_log_hook(client->p, aji_log_hook);
2274         ASTOBJ_UNLOCK(client);
2275         ASTOBJ_CONTAINER_LINK(&clients,client);
2276         return 1;
2277 }
2278
2279 /*!
2280  * \brief creates transport.
2281  * \param label, buddy to dump it into. 
2282  * \return 0.
2283  */
2284 /* no connecting to transports today */
2285 /*
2286 static int aji_create_transport(char *label, struct aji_client *client)
2287 {
2288         char *server = NULL, *buddyname = NULL, *user = NULL, *pass = NULL;
2289         struct aji_buddy *buddy = NULL;
2290
2291         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies,label);
2292         if (!buddy) {
2293                 buddy = ast_calloc(1, sizeof(*buddy));
2294                 if(!buddy) {
2295                         ast_log(LOG_WARNING, "Out of memory\n");
2296                         return 0;
2297                 }
2298                 ASTOBJ_INIT(buddy);
2299         }
2300         ASTOBJ_WRLOCK(buddy);
2301         server = label;
2302         if ((buddyname = strchr(label, ','))) {
2303                 *buddyname = '\0';
2304                 buddyname++;
2305                 if (buddyname && buddyname[0] != '\0') {
2306                         if ((user = strchr(buddyname, ','))) {
2307                                 *user = '\0';
2308                                 user++;
2309                                 if (user && user[0] != '\0') {
2310                                         if ((pass = strchr(user, ','))) {
2311                                                 *pass = '\0';
2312                                                 pass++;
2313                                                 ast_copy_string(buddy->pass, pass, sizeof(buddy->pass));
2314                                                 ast_copy_string(buddy->user, user, sizeof(buddy->user));
2315                                                 ast_copy_string(buddy->name, buddyname, sizeof(buddy->name));
2316                                                 ast_copy_string(buddy->server, server, sizeof(buddy->server));
2317                                                 return 1;
2318                                         }
2319                                 }
2320                         }
2321                 }
2322         }
2323         ASTOBJ_UNLOCK(buddy);
2324         ASTOBJ_UNMARK(buddy);
2325         ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
2326         return 0;
2327 }
2328 */
2329
2330 /*!
2331  * \brief creates buddy.
2332  * \param label char.
2333  * \param client aji_client buddy to dump it into. 
2334  * \return 1 on success, 0 on failure.
2335  */
2336 static int aji_create_buddy(char *label, struct aji_client *client)
2337 {
2338         struct aji_buddy *buddy = NULL;
2339         int flag = 0;
2340         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies,label);
2341         if (!buddy) {
2342                 flag = 1;
2343                 buddy = ast_calloc(1, sizeof(*buddy));
2344                 if(!buddy) {
2345                         ast_log(LOG_WARNING, "Out of memory\n");
2346                         return 0;
2347                 }
2348                 ASTOBJ_INIT(buddy);
2349         }
2350         ASTOBJ_WRLOCK(buddy);
2351         ast_copy_string(buddy->name, label, sizeof(buddy->name));
2352         ASTOBJ_UNLOCK(buddy);
2353         if(flag)
2354                 ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
2355         else {
2356                 ASTOBJ_UNMARK(buddy);
2357                 ASTOBJ_UNREF(buddy, aji_buddy_destroy);
2358         }
2359         return 1;
2360 }
2361
2362 /*!< load config file. \return 1. */
2363 static int aji_load_config(void)
2364 {
2365         char *cat = NULL;
2366         int debug = 1;
2367         struct ast_config *cfg = NULL;
2368         struct ast_variable *var = NULL;
2369
2370         /* Reset flags to default value */
2371         ast_set_flag(&globalflags, AJI_AUTOPRUNE | AJI_AUTOREGISTER);
2372
2373         cfg = ast_config_load(JABBER_CONFIG);
2374         if (!cfg) {
2375                 ast_log(LOG_WARNING, "No such configuration file %s\n", JABBER_CONFIG);
2376                 return 0;
2377         }
2378
2379         cat = ast_category_browse(cfg, NULL);
2380         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
2381                 if (!strcasecmp(var->name, "debug"))
2382                         debug = (ast_false(ast_variable_retrieve(cfg, "general", "debug"))) ? 0 : 1;
2383                 else if (!strcasecmp(var->name, "autoprune"))
2384                         ast_set2_flag(&globalflags, ast_true(var->value), AJI_AUTOPRUNE);
2385                 else if (!strcasecmp(var->name, "autoregister"))
2386                         ast_set2_flag(&globalflags, ast_true(var->value), AJI_AUTOREGISTER);
2387         }
2388
2389         while (cat) {
2390                 if (strcasecmp(cat, "general")) {
2391                                 var = ast_variable_browse(cfg, cat);
2392                                 aji_create_client(cat, var, debug);
2393                 }
2394                 cat = ast_category_browse(cfg, cat);
2395         }
2396         return 1;
2397 }
2398
2399 /*!
2400  * \brief grab a aji_client structure by label name.
2401  * \param name label name 
2402  * \return aji_client.
2403  */
2404 struct aji_client *ast_aji_get_client(const char *name)
2405 {
2406         struct aji_client *client = NULL;
2407
2408         client = ASTOBJ_CONTAINER_FIND(&clients, name);
2409         if (!client && !strchr(name, '@'))
2410                 client = ASTOBJ_CONTAINER_FIND_FULL(&clients, name, user,,, strcasecmp);
2411         return client;
2412 }
2413
2414 struct aji_client_container *ast_aji_get_clients(void)
2415 {
2416         return &clients;
2417 }
2418
2419 static char mandescr_jabber_send[] =
2420 "Description: Sends a message to a Jabber Client.\n"
2421 "Variables: \n"
2422 "  Jabber:      Client or transport Asterisk uses to connect to JABBER.\n"
2423 "  ScreenName:  User Name to message.\n"
2424 "  Message:     Message to be sent to the buddy\n";
2425
2426 /*! 
2427  * \brief  Send a Jabber Message via call from the Manager 
2428  * \param s mansession Manager session
2429  * \param m message Message to send
2430  * \return  0
2431 */
2432 static int manager_jabber_send(struct mansession *s, const struct message *m)
2433 {
2434         struct aji_client *client = NULL;
2435         const char *id = astman_get_header(m,"ActionID");
2436         const char *jabber = astman_get_header(m,"Jabber");
2437         const char *screenname = astman_get_header(m,"ScreenName");
2438         const char *message = astman_get_header(m,"Message");
2439
2440         if (ast_strlen_zero(jabber)) {
2441                 astman_send_error(s, m, "No transport specified");
2442                 return 0;
2443         }
2444         if (ast_strlen_zero(screenname)) {
2445                 astman_send_error(s, m, "No ScreenName specified");
2446                 return 0;
2447         }
2448         if (ast_strlen_zero(message)) {
2449                 astman_send_error(s, m, "No Message specified");
2450                 return 0;
2451         }
2452
2453         astman_send_ack(s, m, "Attempting to send Jabber Message");
2454         client = ast_aji_get_client(jabber);
2455         if (!client) {
2456                 astman_send_error(s, m, "Could not find Sender");
2457                 return 0;
2458         }       
2459         if (strchr(screenname, '@') && message){
2460                 ast_aji_send(client, screenname, message);      
2461                 if (!ast_strlen_zero(id))
2462                         astman_append(s, "ActionID: %s\r\n",id);
2463                 astman_append(s, "Response: Success\r\n");
2464                 return 0;
2465         }
2466         if (!ast_strlen_zero(id))
2467                 astman_append(s, "ActionID: %s\r\n",id);
2468         astman_append(s, "Response: Failure\r\n");
2469         return 0;
2470 }
2471
2472 /*! \brief Reload the jabber module */
2473 static int aji_reload()
2474 {
2475         ASTOBJ_CONTAINER_MARKALL(&clients);
2476         if (!aji_load_config()) {
2477                 ast_log(LOG_ERROR, "JABBER: Failed to load config.\n");
2478                 return 0;
2479         }
2480         ASTOBJ_CONTAINER_PRUNE_MARKED(&clients, aji_client_destroy);
2481         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2482                 ASTOBJ_RDLOCK(iterator);
2483                 if(iterator->state == AJI_DISCONNECTED) {
2484                         if (!iterator->thread)
2485                                 ast_pthread_create_background(&iterator->thread, NULL, aji_recv_loop, iterator);
2486                 } else if (iterator->state == AJI_CONNECTING)
2487                         aji_get_roster(iterator);
2488                 ASTOBJ_UNLOCK(iterator);
2489         });
2490         
2491         return 1;
2492 }
2493
2494 /*! \brief Unload the jabber module */
2495 static int unload_module(void)
2496 {
2497
2498         /* Check if TLS is initialized. If that's the case, we can't unload this
2499            module due to a bug in the iksemel library that will cause a crash or
2500            a deadlock. We're trying to find a way to handle this, but in the meantime
2501            we will simply refuse to die... 
2502          */
2503         if (tls_initialized) {
2504                 ast_log(LOG_ERROR, "Module can't be unloaded due to a bug in the Iksemel library when using TLS.\n");
2505                 return 1;       /* You need a forced unload to get rid of this module */
2506         }
2507
2508         ast_cli_unregister_multiple(aji_cli, sizeof(aji_cli) / sizeof(struct ast_cli_entry));
2509         ast_unregister_application(app_ajisend);
2510         ast_unregister_application(app_ajistatus);
2511         ast_manager_unregister("JabberSend");
2512         
2513         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2514                 ASTOBJ_RDLOCK(iterator);
2515                 if (option_debug > 2)
2516                         ast_log(LOG_DEBUG, "JABBER: Releasing and disconneing client: %s\n", iterator->name);
2517                 iterator->state = AJI_DISCONNECTING;
2518                 ast_aji_disconnect(iterator);
2519                 pthread_join(iterator->thread, NULL);
2520                 ASTOBJ_UNLOCK(iterator);
2521         });
2522
2523         ASTOBJ_CONTAINER_DESTROYALL(&clients, aji_client_destroy);
2524         ASTOBJ_CONTAINER_DESTROY(&clients);
2525         return 0;
2526 }
2527
2528 /*! \brief Unload the jabber module */
2529 static int load_module(void)
2530 {
2531         ASTOBJ_CONTAINER_INIT(&clients);
2532         if(!aji_reload())
2533                 return AST_MODULE_LOAD_DECLINE;
2534         ast_manager_register2("JabberSend", EVENT_FLAG_SYSTEM, manager_jabber_send,
2535                         "Sends a message to a Jabber Client", mandescr_jabber_send);
2536         ast_register_application(app_ajisend, aji_send_exec, ajisend_synopsis, ajisend_descrip);
2537         ast_register_application(app_ajistatus, aji_status_exec, ajistatus_synopsis, ajistatus_descrip);
2538         ast_cli_register_multiple(aji_cli, sizeof(aji_cli) / sizeof(struct ast_cli_entry));
2539
2540         return 0;
2541 }
2542
2543 /*! \brief Wrapper for aji_reload */
2544 static int reload(void)
2545 {
2546         aji_reload();
2547         return 0;
2548 }
2549
2550 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "AJI - Asterisk Jabber Interface",
2551                 .load = load_module,
2552                 .unload = unload_module,
2553                 .reload = reload,
2554                );