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