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