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