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