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