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