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