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