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