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