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