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