Issue #9842 - Doxygen updates by snuffy. Thanks!
[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                         free(tmp->from);
188                 if (tmp->message)
189                         free(tmp->message);
190         }
191         AST_LIST_HEAD_DESTROY(&obj->messages);
192         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                 free(tmp->description);
207                 free(tmp);
208         }
209
210         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 = (struct aji_version *)malloc(sizeof(struct aji_version));
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 = (struct aji_capabilities *)malloc(sizeof(struct aji_capabilities));
262                 if(!list) {
263                         ast_log(LOG_ERROR, "Out of memory!\n");
264                         return NULL;
265                 }
266                 res = (struct aji_version *)malloc(sizeof(struct aji_version));
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                                                         features = aji_highest_bit(features);
550                                                         if (features == IKS_STREAM_SASL_MD5)
551                                                                 iks_start_sasl(client->p, IKS_SASL_DIGEST_MD5, client->jid->user, client->password);
552                                                         else {
553                                                                 if (features == IKS_STREAM_SASL_PLAIN) {
554                                                                         iks *x = NULL;
555                                                                         x = iks_new("auth");
556                                                                         if (x) {
557                                                                                 int len = strlen(client->jid->user) + strlen(client->password) + 3;
558                                                                                 /* XXX Check return values XXX */
559                                                                                 char *s = ast_malloc(80 + len);
560                                                                                 char *base64 = ast_malloc(80 + len * 2);
561
562                                                                                 iks_insert_attrib(x, "xmlns", IKS_NS_XMPP_SASL);
563                                                                                 iks_insert_attrib(x, "mechanism", "PLAIN");
564                                                                                 sprintf(s, "%c%s%c%s", 0, client->jid->user, 0, client->password);
565                                                                                 ast_base64encode(base64, (const unsigned char *) s, len, len * 2);
566                                                                                 iks_insert_cdata(x, base64, 0);
567                                                                                 iks_send(client->p, x);
568                                                                                 iks_delete(x);
569                                                                                 if (base64)
570                                                                                         free(base64);
571                                                                                 if (s)
572                                                                                         free(s);
573                                                                         } else {
574                                                                                 ast_log(LOG_ERROR, "Out of memory.\n");
575                                                                         }
576                                                                 }
577                                                         }
578                                                 }
579                                         }
580                                 } else if (!strcmp("failure", iks_name(node))) {
581                                         ast_log(LOG_ERROR, "JABBER: encryption failure. possible bad password.\n");
582                                 } else if (!strcmp("success", iks_name(node))) {
583                                         client->authorized = 1;
584                                         iks_send_header(client->p, client->jid->server);
585                                 }
586                                 break;
587                         }
588                 case IKS_NODE_ERROR: 
589                                 ast_log(LOG_ERROR, "JABBER: Node Error\n");
590                                 ASTOBJ_UNREF(client, aji_client_destroy);
591                                 return IKS_HOOK;
592                                 break;
593                 case IKS_NODE_STOP: 
594                                 ast_log(LOG_WARNING, "JABBER: Disconnected\n");
595                                 ASTOBJ_UNREF(client, aji_client_destroy);
596                                 return IKS_HOOK;
597                                 break;
598                 }
599         } else if (client->state != AJI_CONNECTED && client->component) {
600                 switch (type) {
601                 case IKS_NODE_START:
602                         if (client->state == AJI_DISCONNECTED) {
603                                 char secret[160], shasum[320], *handshake;
604
605                                 sprintf(secret, "%s%s", pak->id, client->password);
606                                 ast_sha1_hash(shasum, secret);
607                                 handshake = NULL;
608                                 asprintf(&handshake, "<handshake>%s</handshake>", shasum);
609                                 if (handshake) {
610                                         iks_send_raw(client->p, handshake);
611                                         free(handshake);
612                                         handshake = NULL;
613                                 }
614                                 client->state = AJI_CONNECTING;
615                                 if(iks_recv(client->p,1) == 2) /*XXX proper result for iksemel library on iks_recv of <handshake/> XXX*/
616                                         client->state = AJI_CONNECTED;
617                                 else
618                                         ast_log(LOG_WARNING,"Jabber didn't seem to handshake, failed to authenicate.\n");
619                                 break;
620                         }
621                         break;
622
623                 case IKS_NODE_NORMAL:
624                         break;
625
626                 case IKS_NODE_ERROR:
627                         ast_log(LOG_ERROR, "JABBER: Node Error\n");
628                         ASTOBJ_UNREF(client, aji_client_destroy);
629                         return IKS_HOOK;
630
631                 case IKS_NODE_STOP:
632                         ast_log(LOG_WARNING, "JABBER: Disconnected\n");
633                         ASTOBJ_UNREF(client, aji_client_destroy);
634                         return IKS_HOOK;
635                 }
636         }
637
638         switch (pak->type) {
639         case IKS_PAK_NONE:
640                 if (option_debug)
641                         ast_log(LOG_DEBUG, "JABBER: I Don't know what to do with you NONE\n");
642                 break;
643         case IKS_PAK_MESSAGE:
644                 aji_handle_message(client, pak);
645                 if (option_debug)
646                         ast_log(LOG_DEBUG, "JABBER: I Don't know what to do with you MESSAGE\n");
647                 break;
648         case IKS_PAK_PRESENCE:
649                 aji_handle_presence(client, pak);
650                 if (option_debug)
651                         ast_log(LOG_DEBUG, "JABBER: I Do know how to handle presence!!\n");
652                 break;
653         case IKS_PAK_S10N:
654                 aji_handle_subscribe(client, pak);
655                 if (option_debug)
656                         ast_log(LOG_DEBUG, "JABBER: I Dont know S10N subscribe!!\n");
657                 break;
658         case IKS_PAK_IQ:
659                 if (option_debug)
660                         ast_log(LOG_DEBUG, "JABBER: I Dont have an IQ!!!\n");
661                 aji_handle_iq(client, node);
662                 break;
663         default:
664                 if (option_debug)
665                         ast_log(LOG_DEBUG, "JABBER: I Dont know %i\n", pak->type);
666                 break;
667         }
668         
669         iks_filter_packet(client->f, pak);
670
671         if (node)
672                 iks_delete(node);
673
674         ASTOBJ_UNREF(client, aji_client_destroy);
675         return IKS_OK;
676 }
677
678 static int aji_register_approve_handler(void *data, ikspak *pak)
679 {
680         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
681         iks *iq = NULL, *presence = NULL, *x = NULL;
682
683         iq = iks_new("iq");
684         presence = iks_new("presence");
685         x = iks_new("x");
686         if (client && iq && presence && x) {
687                 if (!iks_find(pak->query, "remove")) {
688                         iks_insert_attrib(iq, "from", client->jid->full);
689                         iks_insert_attrib(iq, "to", pak->from->full);
690                         iks_insert_attrib(iq, "id", pak->id);
691                         iks_insert_attrib(iq, "type", "result");
692                         iks_send(client->p, iq);
693
694                         iks_insert_attrib(presence, "from", client->jid->full);
695                         iks_insert_attrib(presence, "to", pak->from->partial);
696                         iks_insert_attrib(presence, "id", client->mid);
697                         ast_aji_increment_mid(client->mid);
698                         iks_insert_attrib(presence, "type", "subscribe");
699                         iks_insert_attrib(x, "xmlns", "vcard-temp:x:update");
700                         iks_insert_node(presence, x);
701                         iks_send(client->p, presence); 
702                 }
703         } else {
704                 ast_log(LOG_ERROR, "Out of memory.\n");
705         }
706
707         if (iq)
708                 iks_delete(iq);
709         if(presence)
710                 iks_delete(presence);
711         if (x)
712                 iks_delete(x);
713         ASTOBJ_UNREF(client, aji_client_destroy);
714         return IKS_FILTER_EAT;
715 }
716
717 static int aji_register_query_handler(void *data, ikspak *pak)
718 {
719         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
720         struct aji_buddy *buddy = NULL; 
721         char *node = NULL;
722
723         client = (struct aji_client *) data;
724
725         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
726         if (!buddy) {
727                 iks *iq = NULL, *query = NULL, *error = NULL, *notacceptable = NULL;
728
729                 ast_verbose("Someone.... %s tried to register but they aren't allowed\n", pak->from->partial);
730                 iq = iks_new("iq");
731                 query = iks_new("query");
732                 error = iks_new("error");
733                 notacceptable = iks_new("not-acceptable");
734                 if(iq && query && error && notacceptable) {
735                         iks_insert_attrib(iq, "type", "error");
736                         iks_insert_attrib(iq, "from", client->user);
737                         iks_insert_attrib(iq, "to", pak->from->full);
738                         iks_insert_attrib(iq, "id", pak->id);
739                         iks_insert_attrib(query, "xmlns", "jabber:iq:register");
740                         iks_insert_attrib(error, "code" , "406");
741                         iks_insert_attrib(error, "type", "modify");
742                         iks_insert_attrib(notacceptable, "xmlns", "urn:ietf:params:xml:ns:xmpp-stanzas");
743                         iks_insert_node(iq, query);
744                         iks_insert_node(iq, error);
745                         iks_insert_node(error, notacceptable);
746                         iks_send(client->p, iq);
747                 } else {
748                         ast_log(LOG_ERROR, "Out of memory.\n");
749                 }
750                 if (iq)
751                         iks_delete(iq);
752                 if (query)
753                         iks_delete(query);
754                 if (error)
755                         iks_delete(error);
756                 if (notacceptable)
757                         iks_delete(notacceptable);
758         } else  if (!(node = iks_find_attrib(pak->query, "node"))) {
759                 iks *iq = NULL, *query = NULL, *instructions = NULL;
760                 char *explain = "Welcome to Asterisk - the Open Source PBX.\n";
761                 iq = iks_new("iq");
762                 query = iks_new("query");
763                 instructions = iks_new("instructions");
764                 if (iq && query && instructions && client) {
765                         iks_insert_attrib(iq, "from", client->user);
766                         iks_insert_attrib(iq, "to", pak->from->full);
767                         iks_insert_attrib(iq, "id", pak->id);
768                         iks_insert_attrib(iq, "type", "result");
769                         iks_insert_attrib(query, "xmlns", "jabber:iq:register");
770                         iks_insert_cdata(instructions, explain, 0);
771                         iks_insert_node(iq, query);
772                         iks_insert_node(query, instructions);
773                         iks_send(client->p, iq);
774                 } else {
775                         ast_log(LOG_ERROR, "Out of memory.\n");
776                 }
777                 if (iq)
778                         iks_delete(iq);
779                 if (query)
780                         iks_delete(query);
781                 if (instructions)
782                         iks_delete(instructions);
783         }
784         ASTOBJ_UNREF(client, aji_client_destroy);
785         return IKS_FILTER_EAT;
786 }
787
788 static int aji_ditems_handler(void *data, ikspak *pak)
789 {
790         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
791         char *node = NULL;
792
793         if (!(node = iks_find_attrib(pak->query, "node"))) {
794                 iks *iq = NULL, *query = NULL, *item = NULL;
795                 iq = iks_new("iq");
796                 query = iks_new("query");
797                 item = iks_new("item");
798
799                 if (iq && query && item) {
800                         iks_insert_attrib(iq, "from", client->user);
801                         iks_insert_attrib(iq, "to", pak->from->full);
802                         iks_insert_attrib(iq, "id", pak->id);
803                         iks_insert_attrib(iq, "type", "result");
804                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
805                         iks_insert_attrib(item, "node", "http://jabber.org/protocol/commands");
806                         iks_insert_attrib(item, "name", "Million Dollar Asterisk Commands");
807                         iks_insert_attrib(item, "jid", client->user);
808
809                         iks_insert_node(iq, query);
810                         iks_insert_node(query, item);
811                         iks_send(client->p, iq);
812                 } else {
813                         ast_log(LOG_ERROR, "Out of memory.\n");
814                 }
815                 if (iq)
816                         iks_delete(iq);
817                 if (query)
818                         iks_delete(query);
819                 if (item)
820                         iks_delete(item);
821
822         } else if (!strcasecmp(node, "http://jabber.org/protocol/commands")) {
823                 iks *iq, *query, *confirm;
824                 iq = iks_new("iq");
825                 query = iks_new("query");
826                 confirm = iks_new("item");
827                 if (iq && query && confirm && client) {
828                         iks_insert_attrib(iq, "from", client->user);
829                         iks_insert_attrib(iq, "to", pak->from->full);
830                         iks_insert_attrib(iq, "id", pak->id);
831                         iks_insert_attrib(iq, "type", "result");
832                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
833                         iks_insert_attrib(query, "node", "http://jabber.org/protocol/commands");
834                         iks_insert_attrib(confirm, "node", "confirmaccount");
835                         iks_insert_attrib(confirm, "name", "Confirm AIM account");
836                         iks_insert_attrib(confirm, "jid", "blog.astjab.org");
837
838                         iks_insert_node(iq, query);
839                         iks_insert_node(query, confirm);
840                         iks_send(client->p, iq);
841                 } else {
842                         ast_log(LOG_ERROR, "Out of memory.\n");
843                 }
844                 if (iq)
845                         iks_delete(iq);
846                 if (query)
847                         iks_delete(query);
848                 if (confirm)
849                         iks_delete(confirm);
850
851         } else if (!strcasecmp(node, "confirmaccount")) {
852                 iks *iq = NULL, *query = NULL, *feature = NULL;
853
854                 iq = iks_new("iq");
855                 query = iks_new("query");
856                 feature = iks_new("feature");
857
858                 if (iq && query && feature && client) {
859                         iks_insert_attrib(iq, "from", client->user);
860                         iks_insert_attrib(iq, "to", pak->from->full);
861                         iks_insert_attrib(iq, "id", pak->id);
862                         iks_insert_attrib(iq, "type", "result");
863                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
864                         iks_insert_attrib(feature, "var", "http://jabber.org/protocol/commands");
865                         iks_insert_node(iq, query);
866                         iks_insert_node(query, feature);
867                         iks_send(client->p, iq);
868                 } else {
869                         ast_log(LOG_ERROR, "Out of memory.\n");
870                 }
871                 if (iq)
872                         iks_delete(iq);
873                 if (query)
874                         iks_delete(query);
875                 if (feature)
876                         iks_delete(feature);
877         }
878
879         ASTOBJ_UNREF(client, aji_client_destroy);
880         return IKS_FILTER_EAT;
881
882 }
883
884 static int aji_client_info_handler(void *data, ikspak *pak)
885 {
886         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
887         struct aji_resource *resource = NULL;
888         struct aji_buddy *buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
889
890         resource = aji_find_resource(buddy, pak->from->resource);
891         if (pak->subtype == IKS_TYPE_RESULT) {
892                 if (!resource) {
893                         ast_log(LOG_NOTICE,"JABBER: Received client info from %s when not requested.\n", pak->from->full);
894                         ASTOBJ_UNREF(client, aji_client_destroy);
895                         return IKS_FILTER_EAT;
896                 }
897                 if (iks_find_with_attrib(pak->query, "feature", "var", "http://www.google.com/xmpp/protocol/voice/v1")) {
898                         resource->cap->jingle = 1;
899                 } else
900                         resource->cap->jingle = 0;
901         } else if (pak->subtype == IKS_TYPE_GET) {
902                 iks *iq, *disco, *ident, *google, *query;
903                 iq = iks_new("iq");
904                 query = iks_new("query");
905                 ident = iks_new("identity");
906                 disco = iks_new("feature");
907                 google = iks_new("feature");
908                 if (iq && ident && disco && google) {
909                         iks_insert_attrib(iq, "from", client->jid->full);
910                         iks_insert_attrib(iq, "to", pak->from->full);
911                         iks_insert_attrib(iq, "type", "result");
912                         iks_insert_attrib(iq, "id", pak->id);
913                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
914                         iks_insert_attrib(ident, "category", "client");
915                         iks_insert_attrib(ident, "type", "pc");
916                         iks_insert_attrib(ident, "name", "asterisk");
917                         iks_insert_attrib(disco, "var", "http://jabber.org/protocol/disco#info");
918                         iks_insert_attrib(google, "var", "http://www.google.com/xmpp/protocol/voice/v1");
919                         iks_insert_node(iq, query);
920                         iks_insert_node(query, ident);
921                         iks_insert_node(query, google);
922                         iks_insert_node(query, disco);
923                         iks_send(client->p, iq);
924                 } else
925                         ast_log(LOG_ERROR, "Out of Memory.\n");
926                 if (iq)
927                         iks_delete(iq);
928                 if (query)
929                         iks_delete(query);
930                 if (ident)
931                         iks_delete(ident);
932                 if (google)
933                         iks_delete(google);
934                 if (disco)
935                         iks_delete(disco);
936         } else if (pak->subtype == IKS_TYPE_ERROR) {
937                 ast_log(LOG_NOTICE, "User %s does not support discovery.\n", pak->from->full);
938         }
939         ASTOBJ_UNREF(client, aji_client_destroy);
940         return IKS_FILTER_EAT;
941 }
942
943 static int aji_dinfo_handler(void *data, ikspak *pak)
944 {
945         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
946         char *node = NULL;
947         struct aji_resource *resource = NULL;
948         struct aji_buddy *buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
949
950         resource = aji_find_resource(buddy, pak->from->resource);
951         if (pak->subtype == IKS_TYPE_ERROR) {
952                 ast_log(LOG_WARNING, "Recieved error from a client, turn on jabber debug!\n");
953                 return IKS_FILTER_EAT;
954         }
955         if (pak->subtype == IKS_TYPE_RESULT) {
956                 if (!resource) {
957                         ast_log(LOG_NOTICE,"JABBER: Received client info from %s when not requested.\n", pak->from->full);
958                         ASTOBJ_UNREF(client, aji_client_destroy);
959                         return IKS_FILTER_EAT;
960                 }
961                 if (iks_find_with_attrib(pak->query, "feature", "var", "http://www.google.com/xmpp/protocol/voice/v1")) {
962                         resource->cap->jingle = 1;
963                 } else
964                         resource->cap->jingle = 0;
965         } else if (pak->subtype == IKS_TYPE_GET && !(node = iks_find_attrib(pak->query, "node"))) {
966                 iks *iq, *query, *identity, *disco, *reg, *commands, *gateway, *version, *vcard, *search;
967
968                 iq = iks_new("iq");
969                 query = iks_new("query");
970                 identity = iks_new("identity");
971                 disco = iks_new("feature");
972                 reg = iks_new("feature");
973                 commands = iks_new("feature");
974                 gateway = iks_new("feature");
975                 version = iks_new("feature");
976                 vcard = iks_new("feature");
977                 search = iks_new("feature");
978
979                 if (iq && query && identity && disco && reg && commands && gateway && version && vcard && search && client) {
980                         iks_insert_attrib(iq, "from", client->user);
981                         iks_insert_attrib(iq, "to", pak->from->full);
982                         iks_insert_attrib(iq, "id", pak->id);
983                         iks_insert_attrib(iq, "type", "result");
984                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
985                         iks_insert_attrib(identity, "category", "gateway");
986                         iks_insert_attrib(identity, "type", "pstn");
987                         iks_insert_attrib(identity, "name", "Asterisk The Open Source PBX");
988                         iks_insert_attrib(disco, "var", "http://jabber.org/protocol/disco");
989                         iks_insert_attrib(reg, "var", "jabber:iq:register");
990                         iks_insert_attrib(commands, "var", "http://jabber.org/protocol/commands");
991                         iks_insert_attrib(gateway, "var", "jabber:iq:gateway");
992                         iks_insert_attrib(version, "var", "jabber:iq:version");
993                         iks_insert_attrib(vcard, "var", "vcard-temp");
994                         iks_insert_attrib(search, "var", "jabber:iq:search");
995
996                         iks_insert_node(iq, query);
997                         iks_insert_node(query, identity);
998                         iks_insert_node(query, disco);
999                         iks_insert_node(query, reg);
1000                         iks_insert_node(query, commands);
1001                         iks_insert_node(query, gateway);
1002                         iks_insert_node(query, version);
1003                         iks_insert_node(query, vcard);
1004                         iks_insert_node(query, search);
1005                         iks_send(client->p, iq);
1006                 } else {
1007                         ast_log(LOG_ERROR, "Out of memory.\n");
1008                 }
1009
1010                 if (iq)
1011                         iks_delete(iq);
1012                 if (query)
1013                         iks_delete(query);
1014                 if (identity)
1015                         iks_delete(identity);
1016                 if (disco)
1017                         iks_delete(disco);
1018                 if (reg)
1019                         iks_delete(reg);
1020                 if (commands)
1021                         iks_delete(commands);
1022                 if (gateway)
1023                         iks_delete(gateway);
1024                 if (version)
1025                         iks_delete(version);
1026                 if (vcard)
1027                         iks_delete(vcard);
1028                 if (search)
1029                         iks_delete(search);
1030
1031         } else if (pak->subtype == IKS_TYPE_GET && !strcasecmp(node, "http://jabber.org/protocol/commands")) {
1032                 iks *iq, *query, *confirm;
1033                 iq = iks_new("iq");
1034                 query = iks_new("query");
1035                 confirm = iks_new("item");
1036
1037                 if (iq && query && confirm && client) {
1038                         iks_insert_attrib(iq, "from", client->user);
1039                         iks_insert_attrib(iq, "to", pak->from->full);
1040                         iks_insert_attrib(iq, "id", pak->id);
1041                         iks_insert_attrib(iq, "type", "result");
1042                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
1043                         iks_insert_attrib(query, "node", "http://jabber.org/protocol/commands");
1044                         iks_insert_attrib(confirm, "node", "confirmaccount");
1045                         iks_insert_attrib(confirm, "name", "Confirm AIM account");
1046                         iks_insert_attrib(confirm, "jid", client->user);
1047                         iks_insert_node(iq, query);
1048                         iks_insert_node(query, confirm);
1049                         iks_send(client->p, iq);
1050                 } else {
1051                         ast_log(LOG_ERROR, "Out of memory.\n");
1052                 }
1053                 if (iq)
1054                         iks_delete(iq);
1055                 if (query)
1056                         iks_delete(query);
1057                 if (confirm)
1058                         iks_delete(confirm);
1059
1060         } else if (pak->subtype == IKS_TYPE_GET && !strcasecmp(node, "confirmaccount")) {
1061                 iks *iq, *query, *feature;
1062
1063                 iq = iks_new("iq");
1064                 query = iks_new("query");
1065                 feature = iks_new("feature");
1066
1067                 if (iq && query && feature && client) {
1068                         iks_insert_attrib(iq, "from", client->user);
1069                         iks_insert_attrib(iq, "to", pak->from->full);
1070                         iks_insert_attrib(iq, "id", pak->id);
1071                         iks_insert_attrib(iq, "type", "result");
1072                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
1073                         iks_insert_attrib(feature, "var", "http://jabber.org/protocol/commands");
1074                         iks_insert_node(iq, query);
1075                         iks_insert_node(query, feature);
1076                         iks_send(client->p, iq);
1077                 } else {
1078                         ast_log(LOG_ERROR, "Out of memory.\n");
1079                 }
1080                 if (iq)
1081                         iks_delete(iq);
1082                 if (query)
1083                         iks_delete(query);
1084                 if (feature)
1085                         iks_delete(feature);
1086         }
1087
1088         ASTOBJ_UNREF(client, aji_client_destroy);
1089         return IKS_FILTER_EAT;
1090 }
1091
1092 /*!
1093  * \brief Handles \verbatim <iq> \endverbatim tags.
1094  * \param client structure and the iq node.
1095  * \return void.
1096  */
1097 static void aji_handle_iq(struct aji_client *client, iks *node)
1098 {
1099         /*Nothing to see here */
1100 }
1101
1102 /*!
1103  * \brief Handles presence packets.
1104  * \param client structure and the node.
1105  * \return void.
1106  */
1107 static void aji_handle_message(struct aji_client *client, ikspak *pak)
1108 {
1109         struct aji_message *insert, *tmp;
1110         int flag = 0;
1111         
1112         if (!(insert = ast_calloc(1, sizeof(struct aji_message))))
1113                 return;
1114         time(&insert->arrived);
1115         if (iks_find_cdata(pak->x, "body"))
1116                 insert->message = ast_strdup(iks_find_cdata(pak->x, "body"));
1117         if(pak->id)
1118                 ast_copy_string(insert->id, pak->id, sizeof(insert->message));
1119         if (pak->from)
1120                 insert->from = ast_strdup(pak->from->full);
1121         AST_LIST_LOCK(&client->messages);
1122         AST_LIST_TRAVERSE_SAFE_BEGIN(&client->messages, tmp, list) {
1123                 if (flag) {
1124                         AST_LIST_REMOVE_CURRENT(&client->messages, list);
1125                         if (tmp->from)
1126                                 free(tmp->from);
1127                         if (tmp->message)
1128                                 free(tmp->message);
1129                 } else if (difftime(time(NULL), tmp->arrived) >= client->message_timeout) {
1130                         flag = 1;
1131                         AST_LIST_REMOVE_CURRENT(&client->messages, list);
1132                         if (tmp->from)
1133                                 free(tmp->from);
1134                         if (tmp->message)
1135                                 free(tmp->message);
1136                 }
1137         }
1138         AST_LIST_TRAVERSE_SAFE_END;
1139         AST_LIST_INSERT_HEAD(&client->messages, insert, list);
1140         AST_LIST_UNLOCK(&client->messages);
1141 }
1142
1143 static void aji_handle_presence(struct aji_client *client, ikspak *pak)
1144 {
1145         int status, priority;
1146         struct aji_buddy *buddy;
1147         struct aji_resource *tmp = NULL, *last = NULL, *found = NULL;
1148         char *ver, *node, *descrip, *type;
1149         
1150         if(client->state != AJI_CONNECTED)
1151                 aji_create_buddy(pak->from->partial, client);
1152
1153         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
1154         if (!buddy) {
1155                 ast_log(LOG_NOTICE, "Got presence packet from %s, someone not in our roster!!!!\n", pak->from->partial);
1156                 return;
1157         }
1158         type = iks_find_attrib(pak->x, "type");
1159         if(client->component && type &&!strcasecmp("probe", type)) {
1160                 aji_set_presence(client, pak->from->full, iks_find_attrib(pak->x, "to"), 1, client->statusmessage);
1161                 ast_verbose("what i was looking for \n");
1162         }
1163         ASTOBJ_WRLOCK(buddy);
1164         status = (pak->show) ? pak->show : 6;
1165         priority = atoi((iks_find_cdata(pak->x, "priority")) ? iks_find_cdata(pak->x, "priority") : "0");
1166         tmp = buddy->resources;
1167         descrip = ast_strdup(iks_find_cdata(pak->x,"status"));
1168
1169         while (tmp) {
1170                 if (!strcasecmp(tmp->resource, pak->from->resource)) {
1171                         tmp->status = status;
1172                         if (tmp->description) free(tmp->description);
1173                         tmp->description = descrip;
1174                         found = tmp;
1175                         if (status == 6) {      /* Sign off Destroy resource */
1176                                 if (last && found->next) {
1177                                         last->next = found->next;
1178                                 } else if (!last) {
1179                                         if (found->next)
1180                                                 buddy->resources = found->next;
1181                                         else
1182                                                 buddy->resources = NULL;
1183                                 } else if (!found->next) {
1184                                         if (last)
1185                                                 last->next = NULL;
1186                                         else
1187                                                 buddy->resources = NULL;
1188                                 }
1189                                 free(found);
1190                                 found = NULL;
1191                                 break;
1192                         }
1193                         if (tmp->priority != priority) {
1194                                 found->priority = priority;
1195                                 if (!last && !found->next)
1196                                         break;
1197                                 if (last)
1198                                         last->next = found->next;
1199                                 else
1200                                         buddy->resources = found->next;
1201                                 last = NULL;
1202                                 tmp = buddy->resources;
1203                                 if (!buddy->resources)
1204                                         buddy->resources = found;
1205                                 while (tmp) {
1206                                         if (found->priority > tmp->priority) {
1207                                                 if (last)
1208                                                         last->next = found;
1209                                                 found->next = tmp;
1210                                                 if (!last)
1211                                                         buddy->resources = found;
1212                                                 break;
1213                                         }
1214                                         if (!tmp->next) {
1215                                                 tmp->next = found;
1216                                                 break;
1217                                         }
1218                                         last = tmp;
1219                                         tmp = tmp->next;
1220                                 }
1221                         }
1222                         break;
1223                 }
1224                 last = tmp;
1225                 tmp = tmp->next;
1226         }
1227
1228         if (!found && status != 6) {
1229                 found = (struct aji_resource *) malloc(sizeof(struct aji_resource));
1230                 memset(found, 0, sizeof(struct aji_resource));
1231
1232                 if (!found) {
1233                         ast_log(LOG_ERROR, "Out of memory!\n");
1234                         return;
1235                 }
1236                 ast_copy_string(found->resource, pak->from->resource, sizeof(found->resource));
1237                 found->status = status;
1238                 found->description = descrip;
1239                 found->priority = priority;
1240                 found->next = NULL;
1241                 last = NULL;
1242                 tmp = buddy->resources;
1243                 while (tmp) {
1244                         if (found->priority > tmp->priority) {
1245                                 if (last)
1246                                         last->next = found;
1247                                 found->next = tmp;
1248                                 if (!last)
1249                                         buddy->resources = found;
1250                                 break;
1251                         }
1252                         if (!tmp->next) {
1253                                 tmp->next = found;
1254                                 break;
1255                         }
1256                         last = tmp;
1257                         tmp = tmp->next;
1258                 }
1259                 if (!tmp)
1260                         buddy->resources = found;
1261         }
1262         ASTOBJ_UNLOCK(buddy);
1263         ASTOBJ_UNREF(buddy, aji_buddy_destroy);
1264
1265         node = iks_find_attrib(iks_find(pak->x, "c"), "node");
1266         ver = iks_find_attrib(iks_find(pak->x, "c"), "ver");
1267
1268         if(status !=6 && !found->cap) {
1269                 found->cap = aji_find_version(node, ver, pak);
1270                 if(gtalk_yuck(pak->x)) /* gtalk should do discover */
1271                         found->cap->jingle = 1;
1272                 if(found->cap->jingle && option_debug > 4) {
1273                         if (option_debug)
1274                                 ast_log(LOG_DEBUG,"Special case for google till they support discover.\n");
1275                 }
1276                 else {
1277                         iks *iq, *query;
1278                         iq = iks_new("iq");
1279                         query = iks_new("query");
1280                         if(query && iq)  {
1281                                 iks_insert_attrib(iq, "type", "get");
1282                                 iks_insert_attrib(iq, "to", pak->from->full);
1283                                 iks_insert_attrib(iq,"from",iks_find_attrib(pak->x,"to"));
1284                                 iks_insert_attrib(iq, "id", client->mid);
1285                                 ast_aji_increment_mid(client->mid);
1286                                 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
1287                                 iks_insert_node(iq, query);
1288                                 iks_send(client->p, iq);
1289                                 
1290                         } else
1291                                 ast_log(LOG_ERROR, "Out of memory.\n");
1292                         if(query)
1293                                 iks_delete(query);
1294                         if(iq)
1295                                 iks_delete(iq);
1296                 }
1297         }
1298         if (option_verbose > 4) {
1299                 switch (pak->subtype) {
1300                 case IKS_TYPE_AVAILABLE:
1301                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I am available ^_* %i\n", pak->subtype);
1302                         break;
1303                 case IKS_TYPE_UNAVAILABLE:
1304                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I am unavailable ^_* %i\n", pak->subtype);
1305                         break;
1306                 default:
1307                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: Ohh sexy and the wrong type: %i\n", pak->subtype);
1308                 }
1309                 switch (pak->show) {
1310                 case IKS_SHOW_UNAVAILABLE:
1311                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1312                         break;
1313                 case IKS_SHOW_AVAILABLE:
1314                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type is available\n");
1315                         break;
1316                 case IKS_SHOW_CHAT:
1317                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1318                         break;
1319                 case IKS_SHOW_AWAY:
1320                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type is away\n");
1321                         break;
1322                 case IKS_SHOW_XA:
1323                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1324                         break;
1325                 case IKS_SHOW_DND:
1326                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1327                         break;
1328                 default:
1329                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: Kinky! how did that happen %i\n", pak->show);
1330                 }
1331         }
1332 }
1333
1334 /*!
1335  * \brief handles subscription requests.
1336  * \param aji_client struct and xml packet.
1337  * \return void.
1338  */
1339 static void aji_handle_subscribe(struct aji_client *client, ikspak *pak)
1340 {
1341         if(pak->subtype == IKS_TYPE_SUBSCRIBE) { 
1342                 iks *presence = NULL, *status = NULL;
1343                 presence = iks_new("presence");
1344                 status = iks_new("status");
1345                 if(presence && status) {
1346                         iks_insert_attrib(presence, "type", "subscribed");
1347                         iks_insert_attrib(presence, "to", pak->from->full);
1348                         iks_insert_attrib(presence, "from", client->jid->full);
1349                         if(pak->id)
1350                                 iks_insert_attrib(presence, "id", pak->id);
1351                         iks_insert_cdata(status, "Asterisk has approved subscription", 0);
1352                         iks_insert_node(presence, status);
1353                         iks_send(client->p, presence);
1354                 } else
1355                         ast_log(LOG_ERROR, "Unable to allocate nodes\n");
1356                 if(presence)
1357                         iks_delete(presence);
1358                 if(status)
1359                         iks_delete(status);
1360                 if(client->component)
1361                         aji_set_presence(client, pak->from->full, iks_find_attrib(pak->x, "to"), 1, client->statusmessage);
1362         }
1363         if (option_verbose > 4) {
1364                 switch (pak->subtype) {
1365                 case IKS_TYPE_SUBSCRIBE:
1366                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1367                         break;
1368                 case IKS_TYPE_SUBSCRIBED:
1369                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1370                         break;
1371                 case IKS_TYPE_UNSUBSCRIBE:
1372                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1373                         break;
1374                 case IKS_TYPE_UNSUBSCRIBED:
1375                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1376                         break;
1377                 default:                                /*IKS_TYPE_ERROR: */
1378                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1379                         break;
1380                 }
1381         }
1382 }
1383
1384 /*!
1385  * \brief sends messages.
1386  * \param aji_client struct , reciever, message.
1387  * \return 1.
1388  */
1389 int ast_aji_send(struct aji_client *client, const char *address, const char *message)
1390 {
1391         int res = 0;
1392         iks *message_packet = NULL;
1393         if (client->state == AJI_CONNECTED) {
1394                 message_packet = iks_make_msg(IKS_TYPE_CHAT, address, message);
1395                 if (message_packet) {
1396                         iks_insert_attrib(message_packet, "from", client->jid->full);
1397                         res = iks_send(client->p, message_packet);
1398                 } else {
1399                         ast_log(LOG_ERROR, "Out of memory.\n");
1400                 }
1401                 if (message_packet)
1402                         iks_delete(message_packet);
1403         } else
1404                 ast_log(LOG_WARNING, "JABBER: Not connected can't send\n");
1405         return 1;
1406 }
1407
1408 /*!
1409  * \brief create a chatroom.
1410  * \param aji_client struct , room, server, topic for the room.
1411  * \return 0.
1412  */
1413 int ast_aji_create_chat(struct aji_client *client, char *room, char *server, char *topic)
1414 {
1415         int res = 0;
1416         iks *iq = NULL;
1417         iq = iks_new("iq");
1418         if (iq && client) {
1419                 iks_insert_attrib(iq, "type", "get");
1420                 iks_insert_attrib(iq, "to", server);
1421                 iks_insert_attrib(iq, "id", client->mid);
1422                 ast_aji_increment_mid(client->mid);
1423                 iks_send(client->p, iq);
1424         } else 
1425                 ast_log(LOG_ERROR, "Out of memory.\n");
1426         return res;
1427 }
1428
1429 /*!
1430  * \brief join a chatroom.
1431  * \param aji_client struct , room.
1432  * \return res.
1433  */
1434 int ast_aji_join_chat(struct aji_client *client, char *room)
1435 {
1436         int res = 0;
1437         iks *presence = NULL, *priority = NULL;
1438         presence = iks_new("presence");
1439         priority = iks_new("priority");
1440         if (presence && priority && client) {
1441                 iks_insert_cdata(priority, "0", 1);
1442                 iks_insert_attrib(presence, "to", room);
1443                 iks_insert_node(presence, priority);
1444                 res = iks_send(client->p, presence);
1445                 iks_insert_cdata(priority, "5", 1);
1446                 iks_insert_attrib(presence, "to", room);
1447                 res = iks_send(client->p, presence);
1448         } else 
1449                 ast_log(LOG_ERROR, "Out of memory.\n");
1450         if (presence)
1451                 iks_delete(presence);
1452         if (priority)
1453                 iks_delete(priority);
1454         return res;
1455 }
1456
1457 /*!
1458  * \brief invite to a chatroom.
1459  * \param aji_client struct ,user, room, message.
1460  * \return res.
1461  */
1462 int ast_aji_invite_chat(struct aji_client *client, char *user, char *room, char *message)
1463 {
1464         int res = 0;
1465         iks *invite, *body, *namespace;
1466
1467         invite = iks_new("message");
1468         body = iks_new("body");
1469         namespace = iks_new("x");
1470         if (client && invite && body && namespace) {
1471                 iks_insert_attrib(invite, "to", user);
1472                 iks_insert_attrib(invite, "id", client->mid);
1473                 ast_aji_increment_mid(client->mid);
1474                 iks_insert_cdata(body, message, 0);
1475                 iks_insert_attrib(namespace, "xmlns", "jabber:x:conference");
1476                 iks_insert_attrib(namespace, "jid", room);
1477                 iks_insert_node(invite, body);
1478                 iks_insert_node(invite, namespace);
1479                 res = iks_send(client->p, invite);
1480         } else 
1481                 ast_log(LOG_ERROR, "Out of memory.\n");
1482         if (body)
1483                 iks_delete(body);
1484         if (namespace)
1485                 iks_delete(namespace);
1486         if (invite)
1487                 iks_delete(invite);
1488         return res;
1489 }
1490
1491
1492 /*!
1493  * \brief receive message loop.
1494  * \param aji_client struct.
1495  * \return void.
1496  */
1497 static void *aji_recv_loop(void *data)
1498 {
1499         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1500         int res = IKS_HOOK;
1501         do {
1502                 if (res != IKS_OK) {
1503                         while(res != IKS_OK) {
1504                                 if(option_verbose > 3)
1505                                         ast_verbose("JABBER: reconnecting.\n");
1506                                 res = aji_reconnect(client);
1507                                 sleep(4);
1508                         }
1509                 }
1510
1511                 res = iks_recv(client->p, 1);
1512                 client->timeout--;
1513                 if (res == IKS_HOOK) 
1514                         ast_log(LOG_WARNING, "JABBER: Got hook event.\n");
1515                 else if (res == IKS_NET_TLSFAIL)
1516                         ast_log(LOG_WARNING, "JABBER:  Failure in TLS.\n");
1517                 else if (client->timeout == 0 && client->state == AJI_CONNECTED) {
1518                         res = iks_send_raw(client->p, " ");
1519                         if(res == IKS_OK)
1520                                 client->timeout = 50;
1521                         else
1522                                 ast_log(LOG_WARNING, "JABBER:  Network Timeout\n");
1523                 } else if (res == IKS_NET_RWERR)
1524                         ast_log(LOG_WARNING, "JABBER: socket read error\n");
1525         } while (client);
1526         ASTOBJ_UNREF(client, aji_client_destroy);
1527         return 0;
1528 }
1529
1530 /*!
1531  * \brief increments the mid field for messages and other events.
1532  * \param message id.
1533  * \return void.
1534  */
1535 void ast_aji_increment_mid(char *mid)
1536 {
1537         int i = 0;
1538
1539         for (i = strlen(mid) - 1; i >= 0; i--) {
1540                 if (mid[i] != 'z') {
1541                         mid[i] = mid[i] + 1;
1542                         i = 0;
1543                 } else
1544                         mid[i] = 'a';
1545         }
1546 }
1547
1548
1549 /*!
1550  * \brief attempts to register to a transport.
1551  * \param aji_client struct, and xml packet.
1552  * \return IKS_FILTER_EAT.
1553  */
1554 /*allows for registering to transport , was too sketch and is out for now. */
1555 /*static int aji_register_transport(void *data, ikspak *pak)
1556 {
1557         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1558         int res = 0;
1559         struct aji_buddy *buddy = NULL;
1560         iks *send = iks_make_iq(IKS_TYPE_GET, "jabber:iq:register");
1561
1562         if (client && send) {
1563                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1564                         ASTOBJ_RDLOCK(iterator); 
1565                         if (iterator->btype == AJI_TRANS) {
1566                                   buddy = iterator;
1567                         }
1568                         ASTOBJ_UNLOCK(iterator);
1569                 });
1570                 iks_filter_remove_hook(client->f, aji_register_transport);
1571                 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);
1572                 iks_insert_attrib(send, "to", buddy->host);
1573                 iks_insert_attrib(send, "id", client->mid);
1574                 ast_aji_increment_mid(client->mid);
1575                 iks_insert_attrib(send, "from", client->user);
1576                 res = iks_send(client->p, send);
1577         } else 
1578                 ast_log(LOG_ERROR, "Out of memory.\n");
1579
1580         if (send)
1581                 iks_delete(send);
1582         ASTOBJ_UNREF(client, aji_client_destroy);
1583         return IKS_FILTER_EAT;
1584
1585 }
1586 */
1587 /*!
1588  * \brief attempts to register to a transport step 2.
1589  * \param aji_client struct, and xml packet.
1590  * \return IKS_FILTER_EAT.
1591  */
1592 /* more of the same blob of code, too wonky for now*/
1593 /* static int aji_register_transport2(void *data, ikspak *pak)
1594 {
1595         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1596         int res = 0;
1597         struct aji_buddy *buddy = NULL;
1598
1599         iks *regiq = iks_new("iq");
1600         iks *regquery = iks_new("query");
1601         iks *reguser = iks_new("username");
1602         iks *regpass = iks_new("password");
1603
1604         if (client && regquery && reguser && regpass && regiq) {
1605                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1606                         ASTOBJ_RDLOCK(iterator);
1607                         if (iterator->btype == AJI_TRANS)
1608                                 buddy = iterator; ASTOBJ_UNLOCK(iterator);
1609                 });
1610                 iks_filter_remove_hook(client->f, aji_register_transport2);
1611                 iks_insert_attrib(regiq, "to", buddy->host);
1612                 iks_insert_attrib(regiq, "type", "set");
1613                 iks_insert_attrib(regiq, "id", client->mid);
1614                 ast_aji_increment_mid(client->mid);
1615                 iks_insert_attrib(regiq, "from", client->user);
1616                 iks_insert_attrib(regquery, "xmlns", "jabber:iq:register");
1617                 iks_insert_cdata(reguser, buddy->user, 0);
1618                 iks_insert_cdata(regpass, buddy->pass, 0);
1619                 iks_insert_node(regiq, regquery);
1620                 iks_insert_node(regquery, reguser);
1621                 iks_insert_node(regquery, regpass);
1622                 res = iks_send(client->p, regiq);
1623         } else
1624                 ast_log(LOG_ERROR, "Out of memory.\n");
1625         if (regiq)
1626                 iks_delete(regiq);
1627         if (regquery)
1628                 iks_delete(regquery);
1629         if (reguser)
1630                 iks_delete(reguser);
1631         if (regpass)
1632                 iks_delete(regpass);
1633         ASTOBJ_UNREF(client, aji_client_destroy);
1634         return IKS_FILTER_EAT;
1635 }
1636 */
1637 /*!
1638  * \brief goes through roster and prunes users not needed in list, or adds them accordingly.
1639  * \param aji_client struct.
1640  * \return void.
1641  */
1642 static void aji_pruneregister(struct aji_client *client)
1643 {
1644         int res = 0;
1645         iks *removeiq = iks_new("iq");
1646         iks *removequery = iks_new("query");
1647         iks *removeitem = iks_new("item");
1648         iks *send = iks_make_iq(IKS_TYPE_GET, "http://jabber.org/protocol/disco#items");
1649
1650         if (client && removeiq && removequery && removeitem && send) {
1651                 iks_insert_node(removeiq, removequery);
1652                 iks_insert_node(removequery, removeitem);
1653                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1654                         ASTOBJ_RDLOCK(iterator);
1655                         /* For an aji_buddy, both AUTOPRUNE and AUTOREGISTER will never
1656                          * be called at the same time */
1657                         if (ast_test_flag(iterator, AJI_AUTOPRUNE)) {
1658                                 res = iks_send(client->p, iks_make_s10n(IKS_TYPE_UNSUBSCRIBE, iterator->name,
1659                                                 "GoodBye your status is no longer needed by Asterisk the Open Source PBX"
1660                                                 " so I am no longer subscribing to your presence.\n"));
1661                                 res = iks_send(client->p, iks_make_s10n(IKS_TYPE_UNSUBSCRIBED, iterator->name,
1662                                                 "GoodBye you are no longer in the asterisk config file so I am removing"
1663                                                 " your access to my presence.\n"));
1664                                 iks_insert_attrib(removeiq, "from", client->jid->full); 
1665                                 iks_insert_attrib(removeiq, "type", "set"); 
1666                                 iks_insert_attrib(removequery, "xmlns", "jabber:iq:roster");
1667                                 iks_insert_attrib(removeitem, "jid", iterator->name);
1668                                 iks_insert_attrib(removeitem, "subscription", "remove");
1669                                 res = iks_send(client->p, removeiq);
1670                         } else if (ast_test_flag(iterator, AJI_AUTOREGISTER)) {
1671                                 res = iks_send(client->p, iks_make_s10n(IKS_TYPE_SUBSCRIBE, iterator->name, 
1672                                                 "Greetings I am the Asterisk Open Source PBX and I want to subscribe to your presence\n"));
1673                                 ast_clear_flag(iterator, AJI_AUTOREGISTER);
1674                         }
1675                         ASTOBJ_UNLOCK(iterator);
1676                 });
1677         } else
1678                 ast_log(LOG_ERROR, "Out of memory.\n");
1679         if (removeiq)
1680                 iks_delete(removeiq);
1681         if (removequery)
1682                 iks_delete(removequery);
1683         if (removeitem)
1684                 iks_delete(removeitem);
1685         if (send)
1686                 iks_delete(send);
1687         ASTOBJ_CONTAINER_PRUNE_MARKED(&client->buddies, aji_buddy_destroy);
1688 }
1689
1690 /*!
1691  * \brief filters the roster packet we get back from server.
1692  * \param aji_client struct, and xml packet.
1693  * \return IKS_FILTER_EAT.
1694  */
1695 static int aji_filter_roster(void *data, ikspak *pak)
1696 {
1697         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1698         int flag = 0;
1699         iks *x = NULL;
1700         struct aji_buddy *buddy;
1701         
1702         client->state = AJI_CONNECTED;
1703         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1704                 ASTOBJ_RDLOCK(iterator);
1705                 x = iks_child(pak->query);
1706                 flag = 0;
1707                 while (x) {
1708                         if (!iks_strcmp(iks_name(x), "item")) {
1709                                 if (!strcasecmp(iterator->name, iks_find_attrib(x, "jid"))) {
1710                                         flag = 1;
1711                                         ast_clear_flag(iterator, AJI_AUTOPRUNE | AJI_AUTOREGISTER);
1712                                 }
1713                         }
1714                         x = iks_next(x);
1715                 }
1716                 if (!flag)
1717                         ast_copy_flags(iterator, client, AJI_AUTOREGISTER);
1718                 if (x)
1719                         iks_delete(x);
1720                 ASTOBJ_UNLOCK(iterator);
1721         });
1722
1723         x = iks_child(pak->query);
1724         while (x) {
1725                 flag = 0;
1726                 if (iks_strcmp(iks_name(x), "item") == 0) {
1727                         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1728                                 ASTOBJ_RDLOCK(iterator);
1729                                 if (!strcasecmp(iterator->name, iks_find_attrib(x, "jid")))
1730                                         flag = 1;
1731                                 ASTOBJ_UNLOCK(iterator);
1732                         });
1733
1734                         if (!flag) {
1735                                 buddy = (struct aji_buddy *) malloc(sizeof(struct aji_buddy));
1736                                 if (!buddy) {
1737                                         ast_log(LOG_WARNING, "Out of memory\n");
1738                                         return 0;
1739                                 }
1740                                 memset(buddy, 0, sizeof(struct aji_buddy));
1741                                 ASTOBJ_INIT(buddy);
1742                                 ASTOBJ_WRLOCK(buddy);
1743                                 ast_copy_string(buddy->name, iks_find_attrib(x, "jid"), sizeof(buddy->name));
1744                                 ast_clear_flag(buddy, AST_FLAGS_ALL);
1745                                 if(ast_test_flag(client, AJI_AUTOPRUNE)) {
1746                                         ast_set_flag(buddy, AJI_AUTOPRUNE);
1747                                         buddy->objflags |= ASTOBJ_FLAG_MARKED;
1748                                 } else
1749                                         ast_set_flag(buddy, AJI_AUTOREGISTER);
1750                                 ASTOBJ_UNLOCK(buddy);
1751                                 if (buddy) {
1752                                         ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
1753                                         ASTOBJ_UNREF(buddy, aji_buddy_destroy);
1754                                 }
1755                         }
1756                 }
1757                 x = iks_next(x);
1758         }
1759         if (x)
1760                 iks_delete(x);
1761         aji_pruneregister(client);
1762
1763         ASTOBJ_UNREF(client, aji_client_destroy);
1764         return IKS_FILTER_EAT;
1765 }
1766
1767 static int aji_reconnect(struct aji_client *client)
1768 {
1769         int res = 0;
1770
1771         if (client->state)
1772                 client->state = AJI_DISCONNECTED;
1773         client->timeout=50;
1774         if (client->p)
1775                 iks_parser_reset(client->p);
1776         if (client->authorized)
1777                 client->authorized = 0;
1778
1779         if(client->component)
1780                 res = aji_component_initialize(client);
1781         else
1782                 res = aji_client_initialize(client);
1783
1784         return res;
1785 }
1786
1787 static int aji_get_roster(struct aji_client *client)
1788 {
1789         iks *roster = NULL;
1790         roster = iks_make_iq(IKS_TYPE_GET, IKS_NS_ROSTER);
1791         if(roster) {
1792                 iks_insert_attrib(roster, "id", "roster");
1793                 aji_set_presence(client, NULL, client->jid->full, 1, client->statusmessage);
1794                 iks_send(client->p, roster);
1795         }
1796         if (roster)
1797                 iks_delete(roster);
1798         return 1;
1799 }
1800
1801 /*!
1802  * \brief connects as a client to jabber server.
1803  * \param aji_client struct, and xml packet.
1804  * \return res.
1805  */
1806 static int aji_client_connect(void *data, ikspak *pak)
1807 {
1808         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1809         int res = 0;
1810
1811         if (client) {
1812                 if (client->state == AJI_DISCONNECTED) {
1813                         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);
1814                         client->state = AJI_CONNECTING;
1815                         client->jid = (iks_find_cdata(pak->query, "jid")) ? iks_id_new(client->stack, iks_find_cdata(pak->query, "jid")) : client->jid;
1816                         iks_filter_remove_hook(client->f, aji_client_connect);
1817                         if(!client->component) /*client*/
1818                                 aji_get_roster(client);
1819                 }
1820         } else
1821                 ast_log(LOG_ERROR, "Out of memory.\n");
1822
1823         ASTOBJ_UNREF(client, aji_client_destroy);
1824         return res;
1825 }
1826
1827 /*!
1828  * \brief prepares client for connect.
1829  * \param aji_client struct.
1830  * \return 1.
1831  */
1832 static int aji_client_initialize(struct aji_client *client)
1833 {
1834         int connected = 0;
1835
1836         connected = iks_connect_via(client->p, S_OR(client->serverhost, client->jid->server), client->port, client->jid->server);
1837
1838         if (connected == IKS_NET_NOCONN) {
1839                 ast_log(LOG_ERROR, "JABBER ERROR: No Connection\n");
1840                 return IKS_HOOK;
1841         } else  if (connected == IKS_NET_NODNS) {
1842                 ast_log(LOG_ERROR, "JABBER ERROR: No DNS %s for client to  %s\n", client->name, S_OR(client->serverhost, client->jid->server));
1843                 return IKS_HOOK;
1844         } else
1845                 iks_recv(client->p, 30);
1846         return IKS_OK;
1847 }
1848
1849 /*!
1850  * \brief prepares component for connect.
1851  * \param aji_client struct.
1852  * \return 1.
1853  */
1854 static int aji_component_initialize(struct aji_client *client)
1855 {
1856         int connected = 1;
1857
1858         connected = iks_connect_via(client->p, S_OR(client->serverhost, client->jid->server), client->port, client->user);
1859         if (connected == IKS_NET_NOCONN) {
1860                 ast_log(LOG_ERROR, "JABBER ERROR: No Connection\n");
1861                 return IKS_HOOK;
1862         } else if (connected == IKS_NET_NODNS) {
1863                 ast_log(LOG_ERROR, "JABBER ERROR: No DNS %s for client to  %s\n", client->name, S_OR(client->serverhost, client->jid->server));
1864                 return IKS_HOOK;
1865         } else if (!connected) 
1866                 iks_recv(client->p, 30);
1867         return IKS_OK;
1868 }
1869
1870 /*!
1871  * \brief disconnect from jabber server.
1872  * \param aji_client struct.
1873  * \return 1.
1874  */
1875 int ast_aji_disconnect(struct aji_client *client)
1876 {
1877         if (client) {
1878                 if (option_verbose > 3)
1879                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: Disconnecting\n");
1880                 iks_disconnect(client->p);
1881                 iks_parser_delete(client->p);
1882                 ASTOBJ_UNREF(client, aji_client_destroy);
1883         }
1884
1885         return 1;
1886 }
1887
1888 /*!
1889  * \brief set presence of client.
1890  * \param aji_client struct, user to send it to, and from, level, description.
1891  * \return void.
1892  */
1893 static void aji_set_presence(struct aji_client *client, char *to, char *from, int level, char *desc)
1894 {
1895         int res = 0;
1896         iks *presence = iks_make_pres(level, desc);
1897         iks *cnode = iks_new("c");
1898         iks *priority = iks_new("priority");
1899
1900         iks_insert_cdata(priority, "0", 1);
1901         if (presence && cnode && client) {
1902                 if(to)
1903                         iks_insert_attrib(presence, "to", to);
1904                 if(from)
1905                         iks_insert_attrib(presence, "from", from);
1906                 iks_insert_attrib(cnode, "node", "http://www.asterisk.org/xmpp/client/caps");
1907                 iks_insert_attrib(cnode, "ver", "asterisk-xmpp");
1908                 iks_insert_attrib(cnode, "ext", "voice-v1");
1909                 iks_insert_attrib(cnode, "xmlns", "http://jabber.org/protocol/caps");
1910                 iks_insert_node(presence, cnode);
1911                 res = iks_send(client->p, presence);
1912         } else
1913                 ast_log(LOG_ERROR, "Out of memory.\n");
1914         if (cnode)
1915                 iks_delete(cnode);
1916         if (presence)
1917                 iks_delete(presence);
1918 }
1919
1920 /*!
1921  * \brief turnon console debugging.
1922  * \param fd, number of args, args.
1923  * \return RESULT_SUCCESS.
1924  */
1925 static int aji_do_debug(int fd, int argc, char *argv[])
1926 {
1927         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
1928                 ASTOBJ_RDLOCK(iterator); 
1929                 iterator->debug = 1;
1930                 ASTOBJ_UNLOCK(iterator);
1931         });
1932         ast_cli(fd, "Jabber Debugging Enabled.\n");
1933         return RESULT_SUCCESS;
1934 }
1935
1936 /*!
1937  * \brief reload jabber module.
1938  * \param fd, number of args, args.
1939  * \return RESULT_SUCCESS.
1940  */
1941 static int aji_do_reload(int fd, int argc, char *argv[])
1942 {
1943         aji_reload();
1944         ast_cli(fd, "Jabber Reloaded.\n");
1945         return RESULT_SUCCESS;
1946 }
1947
1948 /*!
1949  * \brief turnoff console debugging.
1950  * \param fd, number of args, args.
1951  * \return RESULT_SUCCESS.
1952  */
1953 static int aji_no_debug(int fd, int argc, char *argv[])
1954 {
1955         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
1956                 ASTOBJ_RDLOCK(iterator);
1957                 iterator->debug = 0;
1958                 ASTOBJ_UNLOCK(iterator);
1959         });
1960         ast_cli(fd, "Jabber Debugging Disabled.\n");
1961         return RESULT_SUCCESS;
1962 }
1963
1964 /*!
1965  * \brief show client status.
1966  * \param fd, number of args, args.
1967  * \return RESULT_SUCCESS.
1968  */
1969 static int aji_show_clients(int fd, int argc, char *argv[])
1970 {
1971         char *status;
1972         int count = 0;
1973         ast_cli(fd, "Jabber Users and their status:\n");
1974         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
1975                 ASTOBJ_RDLOCK(iterator);
1976                 count++;
1977                 switch (iterator->state) {
1978                 case AJI_DISCONNECTED:
1979                         status = "Disconnected";
1980                         break;
1981                 case AJI_CONNECTING:
1982                         status = "Connecting";
1983                         break;
1984                 case AJI_CONNECTED:
1985                         status = "Connected";
1986                         break;
1987                 default:
1988                         status = "Unknown";
1989                 }
1990                 ast_cli(fd, "       User: %s     - %s\n", iterator->user, status);
1991                 ASTOBJ_UNLOCK(iterator);
1992         });
1993         ast_cli(fd, "----\n");
1994         ast_cli(fd, "   Number of users: %d\n", count);
1995         return RESULT_SUCCESS;
1996 }
1997
1998 /*!
1999  * \brief send test message for debugging.
2000  * \param fd, number of args, args.
2001  * \return RESULT_SUCCESS.
2002  */
2003 static int aji_test(int fd, int argc, char *argv[])
2004 {
2005         struct aji_client *client;
2006         struct aji_resource *resource;
2007         const char *name = "asterisk";
2008         struct aji_message *tmp;
2009
2010         if (argc > 3)
2011                 return RESULT_SHOWUSAGE;
2012         else if (argc == 3)
2013                 name = argv[2];
2014
2015         if (!(client = ASTOBJ_CONTAINER_FIND(&clients, name))) {
2016                 ast_cli(fd, "Unable to find client '%s'!\n", name);
2017                 return RESULT_FAILURE;
2018         }
2019
2020         /* XXX Does Matt really want everyone to use his personal address for tests? */ /* XXX yes he does */
2021         ast_aji_send(client, "mogorman@astjab.org", "blahblah");
2022         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
2023                 ASTOBJ_RDLOCK(iterator);
2024                 ast_verbose("User: %s\n", iterator->name);
2025                 for (resource = iterator->resources; resource; resource = resource->next) {
2026                         ast_verbose("Resource: %s\n", resource->resource);
2027                         if(resource->cap) {
2028                                 ast_verbose("   client: %s\n", resource->cap->parent->node);
2029                                 ast_verbose("   version: %s\n", resource->cap->version);
2030                                 ast_verbose("   Jingle Capable: %d\n", resource->cap->jingle);
2031                         }
2032                         ast_verbose("   Priority: %d\n", resource->priority);
2033                         ast_verbose("   Status: %d\n", resource->status); 
2034                         ast_verbose("   Message: %s\n", S_OR(resource->description,"")); 
2035                 }
2036                 ASTOBJ_UNLOCK(iterator);
2037         });
2038         ast_verbose("\nOooh a working message stack!\n");
2039         AST_LIST_LOCK(&client->messages);
2040         AST_LIST_TRAVERSE(&client->messages, tmp, list) {
2041                 ast_verbose("   Message from: %s with id %s @ %s        %s\n",tmp->from, S_OR(tmp->id,""), ctime(&tmp->arrived), S_OR(tmp->message, ""));
2042         }
2043         AST_LIST_UNLOCK(&client->messages);
2044         ASTOBJ_UNREF(client, aji_client_destroy);
2045
2046         return RESULT_SUCCESS;
2047 }
2048
2049 /*!
2050  * \brief creates aji_client structure.
2051  * \param label, ast_variable, debug, pruneregister, component/client, aji_client to dump into. 
2052  * \return 0.
2053  */
2054 static int aji_create_client(char *label, struct ast_variable *var, int debug)
2055 {
2056         char *resource;
2057         struct aji_client *client = NULL;
2058         int flag = 0;
2059
2060         client = ASTOBJ_CONTAINER_FIND(&clients,label);
2061         if (!client) {
2062                 flag = 1;
2063                 client = (struct aji_client *) malloc(sizeof(struct aji_client));
2064                 if (!client) {
2065                         ast_log(LOG_ERROR, "Out of memory!\n");
2066                         return 0;
2067                 }
2068                 memset(client, 0, sizeof(struct aji_client));
2069                 ASTOBJ_INIT(client);
2070                 ASTOBJ_WRLOCK(client);
2071                 ASTOBJ_CONTAINER_INIT(&client->buddies);
2072         } else {
2073                 ASTOBJ_WRLOCK(client);
2074                 ASTOBJ_UNMARK(client);
2075         }
2076         ASTOBJ_CONTAINER_MARKALL(&client->buddies);
2077         ast_copy_string(client->name, label, sizeof(client->name));
2078         ast_copy_string(client->mid, "aaaaa", sizeof(client->mid));
2079
2080         client->debug = debug;
2081         ast_copy_flags(client, &globalflags, AST_FLAGS_ALL);
2082         client->port = 5222;
2083         client->usetls = 1;
2084         client->usesasl = 1;
2085         client->forcessl = 0;
2086         client->keepalive = 1;
2087         client->timeout = 50;
2088         client->message_timeout = 100;
2089         AST_LIST_HEAD_INIT(&client->messages);
2090         client->component = 0;
2091         ast_copy_string(client->statusmessage, "Online and Available", sizeof(client->statusmessage));
2092
2093         if (flag) {
2094                 client->authorized = 0;
2095                 client->state = AJI_DISCONNECTED;
2096         }
2097         while (var) {
2098                 if (!strcasecmp(var->name, "username"))
2099                         ast_copy_string(client->user, var->value, sizeof(client->user));
2100                 else if (!strcasecmp(var->name, "serverhost"))
2101                         ast_copy_string(client->serverhost, var->value, sizeof(client->serverhost));
2102                 else if (!strcasecmp(var->name, "secret"))
2103                         ast_copy_string(client->password, var->value, sizeof(client->password));
2104                 else if (!strcasecmp(var->name, "statusmessage"))
2105                         ast_copy_string(client->statusmessage, var->value, sizeof(client->statusmessage));
2106                 else if (!strcasecmp(var->name, "port"))
2107                         client->port = atoi(var->value);
2108                 else if (!strcasecmp(var->name, "timeout"))
2109                         client->message_timeout = atoi(var->value);
2110                 else if (!strcasecmp(var->name, "debug"))
2111                         client->debug = (ast_false(var->value)) ? 0 : 1;
2112                 else if (!strcasecmp(var->name, "type")) {
2113                         if (!strcasecmp(var->value, "component"))
2114                                 client->component = 1;
2115                 } else if (!strcasecmp(var->name, "usetls")) {
2116                         client->usetls = (ast_false(var->value)) ? 0 : 1;
2117                 } else if (!strcasecmp(var->name, "usesasl")) {
2118                         client->usesasl = (ast_false(var->value)) ? 0 : 1;
2119                 } else if (!strcasecmp(var->name, "forceoldssl"))
2120                         client->forcessl = (ast_false(var->value)) ? 0 : 1;
2121                 else if (!strcasecmp(var->name, "keepalive"))
2122                         client->keepalive = (ast_false(var->value)) ? 0 : 1;
2123                 else if (!strcasecmp(var->name, "autoprune"))
2124                         ast_set2_flag(client, ast_true(var->value), AJI_AUTOPRUNE);
2125                 else if (!strcasecmp(var->name, "autoregister"))
2126                         ast_set2_flag(client, ast_true(var->value), AJI_AUTOREGISTER);
2127                 else if (!strcasecmp(var->name, "buddy"))
2128                                 aji_create_buddy(var->value, client);
2129         /* no transport support in this version */
2130         /*      else if (!strcasecmp(var->name, "transport"))
2131                                 aji_create_transport(var->value, client);
2132         */
2133                 var = var->next;
2134         }
2135         if (!flag) {
2136                 ASTOBJ_UNLOCK(client);
2137                 ASTOBJ_UNREF(client, aji_client_destroy);
2138                 return 1;
2139         }
2140         client->p = iks_stream_new(((client->component) ? "jabber:component:accept" : "jabber:client"), client, aji_act_hook);
2141         if (!client->p) {
2142                 ast_log(LOG_ERROR, "Failed to create stream for client '%s'!\n", client->name);
2143                 return 0;
2144         }
2145         client->stack = iks_stack_new(8192, 8192);
2146         if (!client->stack) {
2147                 ast_log(LOG_ERROR, "Failed to allocate stack for client '%s'\n", client->name);
2148                 return 0;
2149         }
2150         client->f = iks_filter_new();
2151         if (!client->f) {
2152                 ast_log(LOG_ERROR, "Failed to create filter for client '%s'\n", client->name);
2153                 return 0;
2154         }
2155         if (!strchr(client->user, '/') && !client->component) { /*client */
2156                 resource = NULL;
2157                 asprintf(&resource, "%s/asterisk", client->user);
2158                 if (resource) {
2159                         client->jid = iks_id_new(client->stack, resource);
2160                         free(resource);
2161                 }
2162         } else
2163                 client->jid = iks_id_new(client->stack, client->user);
2164         if (client->component) {
2165                 iks_filter_add_rule(client->f, aji_dinfo_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
2166                 iks_filter_add_rule(client->f, aji_ditems_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#items", IKS_RULE_DONE);
2167                 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);
2168                 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);
2169         } else {
2170                 iks_filter_add_rule(client->f, aji_client_info_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
2171         }
2172         if (!strchr(client->user, '/') && !client->component) { /*client */
2173                 resource = NULL;
2174                 asprintf(&resource, "%s/asterisk", client->user);
2175                 if (resource) {
2176                         client->jid = iks_id_new(client->stack, resource);
2177                         free(resource);
2178                 }
2179         } else
2180                 client->jid = iks_id_new(client->stack, client->user);
2181         iks_set_log_hook(client->p, aji_log_hook);
2182         ASTOBJ_UNLOCK(client);
2183         ASTOBJ_CONTAINER_LINK(&clients,client);
2184         return 1;
2185 }
2186
2187 /*!
2188  * \brief creates transport.
2189  * \param label, buddy to dump it into. 
2190  * \return 0.
2191  */
2192 /* no connecting to transports today */
2193 /*
2194 static int aji_create_transport(char *label, struct aji_client *client)
2195 {
2196         char *server = NULL, *buddyname = NULL, *user = NULL, *pass = NULL;
2197         struct aji_buddy *buddy = NULL;
2198
2199         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies,label);
2200         if (!buddy) {
2201                 buddy = malloc(sizeof(struct aji_buddy));
2202                 if(!buddy) {
2203                         ast_log(LOG_WARNING, "Out of memory\n");
2204                         return 0;
2205                 }
2206                 memset(buddy, 0, sizeof(struct aji_buddy));
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 = malloc(sizeof(struct aji_buddy));
2252                 if(!buddy) {
2253                         ast_log(LOG_WARNING, "Out of memory\n");
2254                         return 0;
2255                 }
2256                 memset(buddy, 0, sizeof(struct aji_buddy));
2257                 ASTOBJ_INIT(buddy);
2258         }
2259         ASTOBJ_WRLOCK(buddy);
2260         ast_copy_string(buddy->name, label, sizeof(buddy->name));
2261         ASTOBJ_UNLOCK(buddy);
2262         if(flag)
2263                 ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
2264         else {
2265                 ASTOBJ_UNMARK(buddy);
2266                 ASTOBJ_UNREF(buddy, aji_buddy_destroy);
2267         }
2268         return 1;
2269 }
2270
2271 /*!
2272  * \brief load config file.
2273  * \param void. 
2274  * \return 1.
2275  */
2276 static int aji_load_config(void)
2277 {
2278         char *cat = NULL;
2279         int debug = 1;
2280         struct ast_config *cfg = NULL;
2281         struct ast_variable *var = NULL;
2282
2283         /* Reset flags to default value */
2284         ast_set_flag(&globalflags, AJI_AUTOPRUNE | AJI_AUTOREGISTER);
2285
2286         cfg = ast_config_load(JABBER_CONFIG);
2287         if (!cfg) {
2288                 ast_log(LOG_WARNING, "No such configuration file %s\n", JABBER_CONFIG);
2289                 return 0;
2290         }
2291
2292         cat = ast_category_browse(cfg, NULL);
2293         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
2294                 if (!strcasecmp(var->name, "debug"))
2295                         debug = (ast_false(ast_variable_retrieve(cfg, "general", "debug"))) ? 0 : 1;
2296                 else if (!strcasecmp(var->name, "autoprune"))
2297                         ast_set2_flag(&globalflags, ast_true(var->value), AJI_AUTOPRUNE);
2298                 else if (!strcasecmp(var->name, "autoregister"))
2299                         ast_set2_flag(&globalflags, ast_true(var->value), AJI_AUTOREGISTER);
2300         }
2301
2302         while (cat) {
2303                 if (strcasecmp(cat, "general")) {
2304                                 var = ast_variable_browse(cfg, cat);
2305                                 aji_create_client(cat, var, debug);
2306                 }
2307                 cat = ast_category_browse(cfg, cat);
2308         }
2309         return 1;
2310 }
2311
2312 /*!
2313  * \brief grab a aji_client structure by label name.
2314  * \param void. 
2315  * \return 1.
2316  */
2317 struct aji_client *ast_aji_get_client(const char *name)
2318 {
2319         struct aji_client *client = NULL;
2320
2321         client = ASTOBJ_CONTAINER_FIND(&clients, name);
2322         if (!client && !strchr(name, '@'))
2323                 client = ASTOBJ_CONTAINER_FIND_FULL(&clients, name, user,,, strcasecmp);
2324         return client;
2325 }
2326
2327 struct aji_client_container *ast_aji_get_clients(void)
2328 {
2329         return &clients;
2330 }
2331
2332 static char mandescr_jabber_send[] =
2333 "Description: Sends a message to a Jabber Client.\n"
2334 "Variables: \n"
2335 "  Jabber:      Client or transport Asterisk uses to connect to JABBER.\n"
2336 "  ScreenName:  User Name to message.\n"
2337 "  Message:     Message to be sent to the buddy\n";
2338
2339 /*! \brief  Send a Jabber Message via call from the Manager */
2340 static int manager_jabber_send(struct mansession *s, const struct message *m)
2341 {
2342         struct aji_client *client = NULL;
2343         const char *id = astman_get_header(m,"ActionID");
2344         const char *jabber = astman_get_header(m,"Jabber");
2345         const char *screenname = astman_get_header(m,"ScreenName");
2346         const char *message = astman_get_header(m,"Message");
2347
2348         if (ast_strlen_zero(jabber)) {
2349                 astman_send_error(s, m, "No transport specified");
2350                 return 0;
2351         }
2352         if (ast_strlen_zero(screenname)) {
2353                 astman_send_error(s, m, "No ScreenName specified");
2354                 return 0;
2355         }
2356         if (ast_strlen_zero(message)) {
2357                 astman_send_error(s, m, "No Message specified");
2358                 return 0;
2359         }
2360
2361         astman_send_ack(s, m, "Attempting to send Jabber Message");
2362         client = ast_aji_get_client(jabber);
2363         if (!client) {
2364                 astman_send_error(s, m, "Could not find Sender");
2365                 return 0;
2366         }       
2367         if (strchr(screenname, '@') && message){
2368                 ast_aji_send(client, screenname, message);      
2369                 if (!ast_strlen_zero(id))
2370                         astman_append(s, "ActionID: %s\r\n",id);
2371                 astman_append(s, "Response: Success\r\n");
2372                 return 0;
2373         }
2374         if (!ast_strlen_zero(id))
2375                 astman_append(s, "ActionID: %s\r\n",id);
2376         astman_append(s, "Response: Failure\r\n");
2377         return 0;
2378 }
2379
2380
2381 static int aji_reload()
2382 {
2383         ASTOBJ_CONTAINER_MARKALL(&clients);
2384         if (!aji_load_config()) {
2385                 ast_log(LOG_ERROR, "JABBER: Failed to load config.\n");
2386                 return 0;
2387         }
2388         ASTOBJ_CONTAINER_PRUNE_MARKED(&clients, aji_client_destroy);
2389         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2390                 ASTOBJ_RDLOCK(iterator);
2391                 if(iterator->state == AJI_DISCONNECTED) {
2392                         if (!iterator->thread)
2393                                 ast_pthread_create_background(&iterator->thread, NULL, aji_recv_loop, iterator);
2394                 } else if (iterator->state == AJI_CONNECTING)
2395                         aji_get_roster(iterator);
2396                 ASTOBJ_UNLOCK(iterator);
2397         });
2398         
2399         return 1;
2400 }
2401
2402 static int unload_module(void)
2403 {
2404         ast_cli_unregister_multiple(aji_cli, sizeof(aji_cli) / sizeof(struct ast_cli_entry));
2405         ast_unregister_application(app_ajisend);
2406         ast_unregister_application(app_ajistatus);
2407         ast_manager_unregister("JabberSend");
2408         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2409                 ASTOBJ_RDLOCK(iterator);
2410                 if (option_verbose > 2)
2411                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: %s\n", iterator->name);
2412                 iterator->state = AJI_DISCONNECTED;
2413                 ast_aji_disconnect(iterator);
2414                 pthread_join(iterator->thread, NULL);
2415                 ASTOBJ_UNLOCK(iterator);
2416         });
2417
2418         ASTOBJ_CONTAINER_DESTROYALL(&clients, aji_client_destroy);
2419         ASTOBJ_CONTAINER_DESTROY(&clients);
2420
2421         ast_log(LOG_NOTICE, "res_jabber unloaded.\n");
2422         return 0;
2423 }
2424
2425 static int load_module(void)
2426 {
2427         ASTOBJ_CONTAINER_INIT(&clients);
2428         if(!aji_reload())
2429                 return AST_MODULE_LOAD_DECLINE;
2430         ast_manager_register2("JabberSend", EVENT_FLAG_SYSTEM, manager_jabber_send,
2431                         "Sends a message to a Jabber Client", mandescr_jabber_send);
2432         ast_register_application(app_ajisend, aji_send_exec, ajisend_synopsis, ajisend_descrip);
2433         ast_register_application(app_ajistatus, aji_status_exec, ajistatus_synopsis, ajistatus_descrip);
2434         ast_cli_register_multiple(aji_cli, sizeof(aji_cli) / sizeof(struct ast_cli_entry));
2435
2436         ast_log(LOG_NOTICE, "res_jabber.so loaded.\n");
2437         return 0;
2438 }
2439
2440 static int reload(void)
2441 {
2442         aji_reload();
2443         return 0;
2444 }
2445
2446 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "AJI - Asterisk Jabber Interface",
2447                 .load = load_module,
2448                 .unload = unload_module,
2449                 .reload = reload,
2450                );