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