83114a5e590f21999ef5a3f6171c5d5432e78ad4
[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 && pak->from->resource) {
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 && pak->from->resource) {
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         ASTOBJ_UNLOCK(buddy);
1395         ASTOBJ_UNREF(buddy, aji_buddy_destroy);
1396
1397         node = iks_find_attrib(iks_find(pak->x, "c"), "node");
1398         ver = iks_find_attrib(iks_find(pak->x, "c"), "ver");
1399
1400         /* handle gmail client's special caps:c tag */
1401         if (!node && !ver) {
1402                 node = iks_find_attrib(iks_find(pak->x, "caps:c"), "node");
1403                 ver = iks_find_attrib(iks_find(pak->x, "caps:c"), "ver");
1404         }
1405
1406         /* retrieve capabilites of the new resource */
1407         if(status !=6 && found && !found->cap) {
1408                 found->cap = aji_find_version(node, ver, pak);
1409                 if(gtalk_yuck(pak->x)) /* gtalk should do discover */
1410                         found->cap->jingle = 1;
1411                 if(found->cap->jingle && option_debug > 4) {
1412                         ast_debug(1,"Special case for google till they support discover.\n");
1413                 }
1414                 else {
1415                         iks *iq, *query;
1416                         iq = iks_new("iq");
1417                         query = iks_new("query");
1418                         if(query && iq)  {
1419                                 iks_insert_attrib(iq, "type", "get");
1420                                 iks_insert_attrib(iq, "to", pak->from->full);
1421                                 iks_insert_attrib(iq,"from", client->jid->full);
1422                                 iks_insert_attrib(iq, "id", client->mid);
1423                                 ast_aji_increment_mid(client->mid);
1424                                 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
1425                                 iks_insert_node(iq, query);
1426                                 iks_send(client->p, iq);
1427                                 
1428                         } else
1429                                 ast_log(LOG_ERROR, "Out of memory.\n");
1430                         if(query)
1431                                 iks_delete(query);
1432                         if(iq)
1433                                 iks_delete(iq);
1434                 }
1435         }
1436                 switch (pak->subtype) {
1437                 case IKS_TYPE_AVAILABLE:
1438                         ast_verb(5, "JABBER: I am available ^_* %i\n", pak->subtype);
1439                         break;
1440                 case IKS_TYPE_UNAVAILABLE:
1441                         ast_verb(5, "JABBER: I am unavailable ^_* %i\n", pak->subtype);
1442                         break;
1443                 default:
1444                         ast_verb(5, "JABBER: Ohh sexy and the wrong type: %i\n", pak->subtype);
1445                 }
1446                 switch (pak->show) {
1447                 case IKS_SHOW_UNAVAILABLE:
1448                         ast_verb(5, "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1449                         break;
1450                 case IKS_SHOW_AVAILABLE:
1451                         ast_verb(5, "JABBER: type is available\n");
1452                         break;
1453                 case IKS_SHOW_CHAT:
1454                         ast_verb(5, "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1455                         break;
1456                 case IKS_SHOW_AWAY:
1457                         ast_verb(5, "JABBER: type is away\n");
1458                         break;
1459                 case IKS_SHOW_XA:
1460                         ast_verb(5, "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1461                         break;
1462                 case IKS_SHOW_DND:
1463                         ast_verb(5, "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1464                         break;
1465                 default:
1466                         ast_verb(5, "JABBER: Kinky! how did that happen %i\n", pak->show);
1467                 }
1468         }
1469
1470 /*!
1471  * \brief handles subscription requests.
1472  * \param client aji_client
1473  * \param pak ikspak iksemel packet.
1474  * \return void.
1475  */
1476 static void aji_handle_subscribe(struct aji_client *client, ikspak *pak)
1477 {
1478         if (pak->subtype == IKS_TYPE_SUBSCRIBE) { 
1479                 iks *presence = NULL, *status = NULL;
1480                 presence = iks_new("presence");
1481                 status = iks_new("status");
1482                 if (presence && status) {
1483                         iks_insert_attrib(presence, "type", "subscribed");
1484                         iks_insert_attrib(presence, "to", pak->from->full);
1485                         iks_insert_attrib(presence, "from", client->jid->full);
1486                         if (pak->id)
1487                                 iks_insert_attrib(presence, "id", pak->id);
1488                         iks_insert_cdata(status, "Asterisk has approved subscription", 0);
1489                         iks_insert_node(presence, status);
1490                         iks_send(client->p, presence);
1491                 } else
1492                         ast_log(LOG_ERROR, "Unable to allocate nodes\n");
1493                 if (presence)
1494                         iks_delete(presence);
1495                 if (status)
1496                         iks_delete(status);
1497                 if (client->component)
1498                         aji_set_presence(client, pak->from->full, iks_find_attrib(pak->x, "to"), 1, client->statusmessage);
1499         }
1500
1501         switch (pak->subtype) {
1502         case IKS_TYPE_SUBSCRIBE:
1503                 ast_verb(5, "JABBER: Subscribe handled.\n");
1504                 break;
1505         case IKS_TYPE_SUBSCRIBED:
1506                 ast_verb(5, "JABBER: Subscribed (%d) not handled.\n", pak->subtype);
1507                 break;
1508         case IKS_TYPE_UNSUBSCRIBE:
1509                 ast_verb(5, "JABBER: Unsubscribe (%d) not handled.\n", pak->subtype);
1510                 break;
1511         case IKS_TYPE_UNSUBSCRIBED:
1512                 ast_verb(5, "JABBER: Unsubscribed (%d) not handled.\n", pak->subtype);
1513                 break;
1514         default:                                /*IKS_TYPE_ERROR: */
1515                 ast_verb(5, "JABBER: Unknown pak subtype %d.\n", pak->subtype);
1516                 break;
1517         }
1518 }
1519
1520 /*!
1521  * \brief sends messages.
1522  * \param client aji_client 
1523  * \param address
1524  * \param message
1525  * \return 1.
1526  */
1527 int ast_aji_send(struct aji_client *client, const char *address, const char *message)
1528 {
1529         int res = 0;
1530         iks *message_packet = NULL;
1531         if (client->state == AJI_CONNECTED) {
1532                 message_packet = iks_make_msg(IKS_TYPE_CHAT, address, message);
1533                 if (message_packet) {
1534                         iks_insert_attrib(message_packet, "from", client->jid->full);
1535                         res = iks_send(client->p, message_packet);
1536                 } else {
1537                         ast_log(LOG_ERROR, "Out of memory.\n");
1538                 }
1539                 if (message_packet)
1540                         iks_delete(message_packet);
1541         } else
1542                 ast_log(LOG_WARNING, "JABBER: Not connected can't send\n");
1543         return 1;
1544 }
1545
1546 /*!
1547  * \brief create a chatroom.
1548  * \param client aji_client
1549  * \param room name of room
1550  * \param server name of server
1551  * \param topic topic for the room.
1552  * \return 0.
1553  */
1554 int ast_aji_create_chat(struct aji_client *client, char *room, char *server, char *topic)
1555 {
1556         int res = 0;
1557         iks *iq = NULL;
1558         iq = iks_new("iq");
1559         if (iq && client) {
1560                 iks_insert_attrib(iq, "type", "get");
1561                 iks_insert_attrib(iq, "to", server);
1562                 iks_insert_attrib(iq, "id", client->mid);
1563                 ast_aji_increment_mid(client->mid);
1564                 iks_send(client->p, iq);
1565         } else 
1566                 ast_log(LOG_ERROR, "Out of memory.\n");
1567         return res;
1568 }
1569
1570 /*!
1571  * \brief join a chatroom.
1572  * \param client aji_client 
1573  * \param room room to join
1574  * \return res.
1575  */
1576 int ast_aji_join_chat(struct aji_client *client, char *room)
1577 {
1578         int res = 0;
1579         iks *presence = NULL, *priority = NULL;
1580         presence = iks_new("presence");
1581         priority = iks_new("priority");
1582         if (presence && priority && client) {
1583                 iks_insert_cdata(priority, "0", 1);
1584                 iks_insert_attrib(presence, "to", room);
1585                 iks_insert_node(presence, priority);
1586                 res = iks_send(client->p, presence);
1587                 iks_insert_cdata(priority, "5", 1);
1588                 iks_insert_attrib(presence, "to", room);
1589                 res = iks_send(client->p, presence);
1590         } else 
1591                 ast_log(LOG_ERROR, "Out of memory.\n");
1592         if (presence)
1593                 iks_delete(presence);
1594         if (priority)
1595                 iks_delete(priority);
1596         return res;
1597 }
1598
1599 /*!
1600  * \brief invite to a chatroom.
1601  * \param client aji_client
1602  * \param user 
1603  * \param room
1604  * \param message
1605  * \return res.
1606  */
1607 int ast_aji_invite_chat(struct aji_client *client, char *user, char *room, char *message)
1608 {
1609         int res = 0;
1610         iks *invite, *body, *namespace;
1611
1612         invite = iks_new("message");
1613         body = iks_new("body");
1614         namespace = iks_new("x");
1615         if (client && invite && body && namespace) {
1616                 iks_insert_attrib(invite, "to", user);
1617                 iks_insert_attrib(invite, "id", client->mid);
1618                 ast_aji_increment_mid(client->mid);
1619                 iks_insert_cdata(body, message, 0);
1620                 iks_insert_attrib(namespace, "xmlns", "jabber:x:conference");
1621                 iks_insert_attrib(namespace, "jid", room);
1622                 iks_insert_node(invite, body);
1623                 iks_insert_node(invite, namespace);
1624                 res = iks_send(client->p, invite);
1625         } else 
1626                 ast_log(LOG_ERROR, "Out of memory.\n");
1627         if (body)
1628                 iks_delete(body);
1629         if (namespace)
1630                 iks_delete(namespace);
1631         if (invite)
1632                 iks_delete(invite);
1633         return res;
1634 }
1635
1636
1637 /*!
1638  * \brief receive message loop.
1639  * \param data void
1640  * \return void.
1641  */
1642 static void *aji_recv_loop(void *data)
1643 {
1644         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1645         int res = IKS_HOOK;
1646         do {
1647                 if (res != IKS_OK) {
1648                         while(res != IKS_OK) {
1649                                 ast_verb(4, "JABBER: reconnecting.\n");
1650                                 res = aji_reconnect(client);
1651                                 sleep(4);
1652                         }
1653                 }
1654
1655                 res = iks_recv(client->p, 1);
1656
1657                 if (client->state == AJI_DISCONNECTING) {
1658                         ast_debug(2, "Ending our Jabber client's thread due to a disconnect\n");
1659                         pthread_exit(NULL);
1660                 }
1661                 client->timeout--;
1662                 if (res == IKS_HOOK) 
1663                         ast_log(LOG_WARNING, "JABBER: Got hook event.\n");
1664                 else if (res == IKS_NET_TLSFAIL)
1665                         ast_log(LOG_WARNING, "JABBER:  Failure in TLS.\n");
1666                 else if (client->timeout == 0 && client->state == AJI_CONNECTED) {
1667                         res = iks_send_raw(client->p, " ");
1668                         if(res == IKS_OK)
1669                                 client->timeout = 50;
1670                         else
1671                                 ast_log(LOG_WARNING, "JABBER:  Network Timeout\n");
1672                 } else if (res == IKS_NET_RWERR)
1673                         ast_log(LOG_WARNING, "JABBER: socket read error\n");
1674         } while (client);
1675         ASTOBJ_UNREF(client, aji_client_destroy);
1676         return 0;
1677 }
1678
1679 /*!
1680  * \brief increments the mid field for messages and other events.
1681  * \param mid char.
1682  * \return void.
1683  */
1684 void ast_aji_increment_mid(char *mid)
1685 {
1686         int i = 0;
1687
1688         for (i = strlen(mid) - 1; i >= 0; i--) {
1689                 if (mid[i] != 'z') {
1690                         mid[i] = mid[i] + 1;
1691                         i = 0;
1692                 } else
1693                         mid[i] = 'a';
1694         }
1695 }
1696
1697 #if 0
1698 /*!
1699  * \brief attempts to register to a transport.
1700  * \param aji_client struct, and xml packet.
1701  * \return IKS_FILTER_EAT.
1702  */
1703 /*allows for registering to transport , was too sketch and is out for now. */
1704 static int aji_register_transport(void *data, ikspak *pak)
1705 {
1706         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1707         int res = 0;
1708         struct aji_buddy *buddy = NULL;
1709         iks *send = iks_make_iq(IKS_TYPE_GET, "jabber:iq:register");
1710
1711         if (client && send) {
1712                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1713                         ASTOBJ_RDLOCK(iterator); 
1714                         if (iterator->btype == AJI_TRANS) {
1715                                   buddy = iterator;
1716                         }
1717                         ASTOBJ_UNLOCK(iterator);
1718                 });
1719                 iks_filter_remove_hook(client->f, aji_register_transport);
1720                 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);
1721                 iks_insert_attrib(send, "to", buddy->host);
1722                 iks_insert_attrib(send, "id", client->mid);
1723                 ast_aji_increment_mid(client->mid);
1724                 iks_insert_attrib(send, "from", client->user);
1725                 res = iks_send(client->p, send);
1726         } else 
1727                 ast_log(LOG_ERROR, "Out of memory.\n");
1728
1729         if (send)
1730                 iks_delete(send);
1731         ASTOBJ_UNREF(client, aji_client_destroy);
1732         return IKS_FILTER_EAT;
1733
1734 }
1735 /*!
1736  * \brief attempts to register to a transport step 2.
1737  * \param aji_client struct, and xml packet.
1738  * \return IKS_FILTER_EAT.
1739  */
1740 /* more of the same blob of code, too wonky for now*/
1741 static int aji_register_transport2(void *data, ikspak *pak)
1742 {
1743         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1744         int res = 0;
1745         struct aji_buddy *buddy = NULL;
1746
1747         iks *regiq = iks_new("iq");
1748         iks *regquery = iks_new("query");
1749         iks *reguser = iks_new("username");
1750         iks *regpass = iks_new("password");
1751
1752         if (client && regquery && reguser && regpass && regiq) {
1753                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1754                         ASTOBJ_RDLOCK(iterator);
1755                         if (iterator->btype == AJI_TRANS)
1756                                 buddy = iterator; ASTOBJ_UNLOCK(iterator);
1757                 });
1758                 iks_filter_remove_hook(client->f, aji_register_transport2);
1759                 iks_insert_attrib(regiq, "to", buddy->host);
1760                 iks_insert_attrib(regiq, "type", "set");
1761                 iks_insert_attrib(regiq, "id", client->mid);
1762                 ast_aji_increment_mid(client->mid);
1763                 iks_insert_attrib(regiq, "from", client->user);
1764                 iks_insert_attrib(regquery, "xmlns", "jabber:iq:register");
1765                 iks_insert_cdata(reguser, buddy->user, 0);
1766                 iks_insert_cdata(regpass, buddy->pass, 0);
1767                 iks_insert_node(regiq, regquery);
1768                 iks_insert_node(regquery, reguser);
1769                 iks_insert_node(regquery, regpass);
1770                 res = iks_send(client->p, regiq);
1771         } else
1772                 ast_log(LOG_ERROR, "Out of memory.\n");
1773         if (regiq)
1774                 iks_delete(regiq);
1775         if (regquery)
1776                 iks_delete(regquery);
1777         if (reguser)
1778                 iks_delete(reguser);
1779         if (regpass)
1780                 iks_delete(regpass);
1781         ASTOBJ_UNREF(client, aji_client_destroy);
1782         return IKS_FILTER_EAT;
1783 }
1784 #endif
1785
1786 /*!
1787  * \brief goes through roster and prunes users not needed in list, or adds them accordingly.
1788  * \param client aji_client
1789  * \return void.
1790  */
1791 static void aji_pruneregister(struct aji_client *client)
1792 {
1793         int res = 0;
1794         iks *removeiq = iks_new("iq");
1795         iks *removequery = iks_new("query");
1796         iks *removeitem = iks_new("item");
1797         iks *send = iks_make_iq(IKS_TYPE_GET, "http://jabber.org/protocol/disco#items");
1798
1799         if (client && removeiq && removequery && removeitem && send) {
1800                 iks_insert_node(removeiq, removequery);
1801                 iks_insert_node(removequery, removeitem);
1802                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1803                         ASTOBJ_RDLOCK(iterator);
1804                         /* For an aji_buddy, both AUTOPRUNE and AUTOREGISTER will never
1805                          * be called at the same time */
1806                         if (ast_test_flag(iterator, AJI_AUTOPRUNE)) {
1807                                 res = iks_send(client->p, iks_make_s10n(IKS_TYPE_UNSUBSCRIBE, iterator->name,
1808                                                 "GoodBye your status is no longer needed by Asterisk the Open Source PBX"
1809                                                 " so I am no longer subscribing to your presence.\n"));
1810                                 res = iks_send(client->p, iks_make_s10n(IKS_TYPE_UNSUBSCRIBED, iterator->name,
1811                                                 "GoodBye you are no longer in the asterisk config file so I am removing"
1812                                                 " your access to my presence.\n"));
1813                                 iks_insert_attrib(removeiq, "from", client->jid->full); 
1814                                 iks_insert_attrib(removeiq, "type", "set"); 
1815                                 iks_insert_attrib(removequery, "xmlns", "jabber:iq:roster");
1816                                 iks_insert_attrib(removeitem, "jid", iterator->name);
1817                                 iks_insert_attrib(removeitem, "subscription", "remove");
1818                                 res = iks_send(client->p, removeiq);
1819                         } else if (ast_test_flag(iterator, AJI_AUTOREGISTER)) {
1820                                 res = iks_send(client->p, iks_make_s10n(IKS_TYPE_SUBSCRIBE, iterator->name, 
1821                                                 "Greetings I am the Asterisk Open Source PBX and I want to subscribe to your presence\n"));
1822                                 ast_clear_flag(iterator, AJI_AUTOREGISTER);
1823                         }
1824                         ASTOBJ_UNLOCK(iterator);
1825                 });
1826         } else
1827                 ast_log(LOG_ERROR, "Out of memory.\n");
1828         if (removeiq)
1829                 iks_delete(removeiq);
1830         if (removequery)
1831                 iks_delete(removequery);
1832         if (removeitem)
1833                 iks_delete(removeitem);
1834         if (send)
1835                 iks_delete(send);
1836         ASTOBJ_CONTAINER_PRUNE_MARKED(&client->buddies, aji_buddy_destroy);
1837 }
1838
1839 /*!
1840  * \brief filters the roster packet we get back from server.
1841  * \param data void
1842  * \param pak ikspak iksemel packet.
1843  * \return IKS_FILTER_EAT.
1844  */
1845 static int aji_filter_roster(void *data, ikspak *pak)
1846 {
1847         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1848         int flag = 0;
1849         iks *x = NULL;
1850         struct aji_buddy *buddy;
1851         
1852         client->state = AJI_CONNECTED;
1853         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1854                 ASTOBJ_RDLOCK(iterator);
1855                 x = iks_child(pak->query);
1856                 flag = 0;
1857                 while (x) {
1858                         if (!iks_strcmp(iks_name(x), "item")) {
1859                                 if (!strcasecmp(iterator->name, iks_find_attrib(x, "jid"))) {
1860                                         flag = 1;
1861                                         ast_clear_flag(iterator, AJI_AUTOPRUNE | AJI_AUTOREGISTER);
1862                                 }
1863                         }
1864                         x = iks_next(x);
1865                 }
1866                 if (!flag)
1867                         ast_copy_flags(iterator, client, AJI_AUTOREGISTER);
1868                 if (x)
1869                         iks_delete(x);
1870                 ASTOBJ_UNLOCK(iterator);
1871         });
1872
1873         x = iks_child(pak->query);
1874         while (x) {
1875                 flag = 0;
1876                 if (iks_strcmp(iks_name(x), "item") == 0) {
1877                         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1878                                 ASTOBJ_RDLOCK(iterator);
1879                                 if (!strcasecmp(iterator->name, iks_find_attrib(x, "jid")))
1880                                         flag = 1;
1881                                 ASTOBJ_UNLOCK(iterator);
1882                         });
1883
1884                         if (!flag) {
1885                                 buddy = ast_calloc(1, sizeof(*buddy));
1886                                 if (!buddy) {
1887                                         ast_log(LOG_WARNING, "Out of memory\n");
1888                                         return 0;
1889                                 }
1890                                 ASTOBJ_INIT(buddy);
1891                                 ASTOBJ_WRLOCK(buddy);
1892                                 ast_copy_string(buddy->name, iks_find_attrib(x, "jid"), sizeof(buddy->name));
1893                                 ast_clear_flag(buddy, AST_FLAGS_ALL);
1894                                 if(ast_test_flag(client, AJI_AUTOPRUNE)) {
1895                                         ast_set_flag(buddy, AJI_AUTOPRUNE);
1896                                         buddy->objflags |= ASTOBJ_FLAG_MARKED;
1897                                 } else
1898                                         ast_set_flag(buddy, AJI_AUTOREGISTER);
1899                                 ASTOBJ_UNLOCK(buddy);
1900                                 if (buddy) {
1901                                         ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
1902                                         ASTOBJ_UNREF(buddy, aji_buddy_destroy);
1903                                 }
1904                         }
1905                 }
1906                 x = iks_next(x);
1907         }
1908         if (x)
1909                 iks_delete(x);
1910         aji_pruneregister(client);
1911
1912         ASTOBJ_UNREF(client, aji_client_destroy);
1913         return IKS_FILTER_EAT;
1914 }
1915 /*!
1916  * \brief reconnect to jabber server
1917  * \param client aji_client
1918  * \return res.
1919 */
1920 static int aji_reconnect(struct aji_client *client)
1921 {
1922         int res = 0;
1923
1924         if (client->state)
1925                 client->state = AJI_DISCONNECTED;
1926         client->timeout=50;
1927         if (client->p)
1928                 iks_parser_reset(client->p);
1929         if (client->authorized)
1930                 client->authorized = 0;
1931
1932         res = aji_initialize(client);
1933
1934         return res;
1935 }
1936 /*!
1937  * \brief Get the roster of jabber users
1938  * \param client aji_client
1939  * \return 1.
1940 */
1941 static int aji_get_roster(struct aji_client *client)
1942 {
1943         iks *roster = NULL;
1944         roster = iks_make_iq(IKS_TYPE_GET, IKS_NS_ROSTER);
1945         if(roster) {
1946                 iks_insert_attrib(roster, "id", "roster");
1947                 aji_set_presence(client, NULL, client->jid->full, 1, client->statusmessage);
1948                 iks_send(client->p, roster);
1949         }
1950         if (roster)
1951                 iks_delete(roster);
1952         return 1;
1953 }
1954
1955 /*!
1956  * \brief connects as a client to jabber server.
1957  * \param data void
1958  * \param pak ikspak iksemel packet
1959  * \return res.
1960  */
1961 static int aji_client_connect(void *data, ikspak *pak)
1962 {
1963         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1964         int res = 0;
1965
1966         if (client) {
1967                 if (client->state == AJI_DISCONNECTED) {
1968                         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);
1969                         client->state = AJI_CONNECTING;
1970                         client->jid = (iks_find_cdata(pak->query, "jid")) ? iks_id_new(client->stack, iks_find_cdata(pak->query, "jid")) : client->jid;
1971                         iks_filter_remove_hook(client->f, aji_client_connect);
1972                         if(!client->component) /*client*/
1973                                 aji_get_roster(client);
1974                 }
1975         } else
1976                 ast_log(LOG_ERROR, "Out of memory.\n");
1977
1978         ASTOBJ_UNREF(client, aji_client_destroy);
1979         return res;
1980 }
1981
1982 /*!
1983  * \brief prepares client for connect.
1984  * \param client aji_client
1985  * \return 1.
1986  */
1987 static int aji_initialize(struct aji_client *client)
1988 {
1989         /* If it's a component, connect to user, otherwise, connect to server */
1990         int connected = iks_connect_via(client->p, S_OR(client->serverhost, client->jid->server), client->port, client->component ? client->user : client->jid->server);
1991
1992         if (connected == IKS_NET_NOCONN) {
1993                 ast_log(LOG_ERROR, "JABBER ERROR: No Connection\n");
1994                 return IKS_HOOK;
1995         } else  if (connected == IKS_NET_NODNS) {
1996                 ast_log(LOG_ERROR, "JABBER ERROR: No DNS %s for client to  %s\n", client->name, S_OR(client->serverhost, client->jid->server));
1997                 return IKS_HOOK;
1998         } else /* if (!connected) phsultan: check if this is needed! */
1999                 iks_recv(client->p, 30);
2000         return IKS_OK;
2001 }
2002
2003 /*!
2004  * \brief disconnect from jabber server.
2005  * \param client aji_client
2006  * \return 1.
2007  */
2008 int ast_aji_disconnect(struct aji_client *client)
2009 {
2010         if (client) {
2011                 ast_verb(4, "JABBER: Disconnecting\n");
2012                 iks_disconnect(client->p);
2013                 iks_parser_delete(client->p);
2014                 ASTOBJ_UNREF(client, aji_client_destroy);
2015         }
2016
2017         return 1;
2018 }
2019
2020 /*!
2021  * \brief set presence of client.
2022  * \param client aji_client
2023  * \param to user send it to
2024  * \param from user it came from
2025  * \param level
2026  * \param desc
2027  * \return void.
2028  */
2029 static void aji_set_presence(struct aji_client *client, char *to, char *from, int level, char *desc)
2030 {
2031         int res = 0;
2032         iks *presence = iks_make_pres(level, desc);
2033         iks *cnode = iks_new("c");
2034         iks *priority = iks_new("priority");
2035
2036         iks_insert_cdata(priority, "0", 1);
2037         if (presence && cnode && client) {
2038                 if(to)
2039                         iks_insert_attrib(presence, "to", to);
2040                 if(from)
2041                         iks_insert_attrib(presence, "from", from);
2042                 iks_insert_attrib(cnode, "node", "http://www.asterisk.org/xmpp/client/caps");
2043                 iks_insert_attrib(cnode, "ver", "asterisk-xmpp");
2044                 iks_insert_attrib(cnode, "ext", "voice-v1");
2045                 iks_insert_attrib(cnode, "xmlns", "http://jabber.org/protocol/caps");
2046                 iks_insert_node(presence, cnode);
2047                 res = iks_send(client->p, presence);
2048         } else
2049                 ast_log(LOG_ERROR, "Out of memory.\n");
2050         if (cnode)
2051                 iks_delete(cnode);
2052         if (presence)
2053                 iks_delete(presence);
2054 }
2055
2056 /*!
2057  * \brief Turn on console debugging.
2058  * \return CLI_SUCCESS.
2059  */
2060 static char *aji_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2061 {
2062
2063         switch (cmd) {
2064         case CLI_INIT:
2065                 e->command = "jabber debug";
2066                 e->usage =
2067                         "Usage: jabber debug\n"
2068                         "       Enables dumping of Jabber packets for debugging purposes.\n";
2069                 return NULL;
2070         case CLI_GENERATE:
2071                 return NULL;
2072         }
2073
2074         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2075                 ASTOBJ_RDLOCK(iterator); 
2076                 iterator->debug = 1;
2077                 ASTOBJ_UNLOCK(iterator);
2078         });
2079         ast_cli(a->fd, "Jabber Debugging Enabled.\n");
2080         return CLI_SUCCESS;
2081 }
2082
2083 /*!
2084  * \brief Reload jabber module.
2085  * \return CLI_SUCCESS.
2086  */
2087 static char *aji_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2088 {
2089         switch (cmd) {
2090         case CLI_INIT:
2091                 e->command = "jabber reload";
2092                 e->usage =
2093                         "Usage: jabber reload\n"
2094                         "       Reloads the Jabber module.\n";
2095                 return NULL;
2096         case CLI_GENERATE:
2097                 return NULL;
2098         }
2099
2100         aji_reload(1);
2101         ast_cli(a->fd, "Jabber Reloaded.\n");
2102         return CLI_SUCCESS;
2103 }
2104
2105 /*!
2106  * \brief Turn off console debugging.
2107  * \return CLI_SUCCESS.
2108  */
2109 static char *aji_no_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2110 {
2111         switch (cmd) {
2112         case CLI_INIT:
2113                 e->command = "jabber debug off";
2114                 e->usage =
2115                         "Usage: jabber debug off\n"
2116                         "       Disables dumping of Jabber packets for debugging purposes.\n";
2117                 return NULL;
2118         case CLI_GENERATE:
2119                 return NULL;
2120         }
2121
2122         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2123                 ASTOBJ_RDLOCK(iterator);
2124                 iterator->debug = 0;
2125                 ASTOBJ_UNLOCK(iterator);
2126         });
2127         ast_cli(a->fd, "Jabber Debugging Disabled.\n");
2128         return CLI_SUCCESS;
2129 }
2130
2131 /*!
2132  * \brief Show client status.
2133  * \return CLI_SUCCESS.
2134  */
2135 static char *aji_show_clients(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2136 {
2137         char *status;
2138         int count = 0;
2139         
2140         switch (cmd) {
2141         case CLI_INIT:
2142                 e->command = "jabber show connected";
2143                 e->usage =
2144                         "Usage: jabber show connected\n"
2145                         "       Shows state of clients and components\n";
2146                 return NULL;
2147         case CLI_GENERATE:
2148                 return NULL;
2149         }
2150
2151         ast_cli(a->fd, "Jabber Users and their status:\n");
2152         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2153                 ASTOBJ_RDLOCK(iterator);
2154                 count++;
2155                 switch (iterator->state) {
2156                 case AJI_DISCONNECTED:
2157                         status = "Disconnected";
2158                         break;
2159                 case AJI_CONNECTING:
2160                         status = "Connecting";
2161                         break;
2162                 case AJI_CONNECTED:
2163                         status = "Connected";
2164                         break;
2165                 default:
2166                         status = "Unknown";
2167                 }
2168                 ast_cli(a->fd, "       User: %s     - %s\n", iterator->user, status);
2169                 ASTOBJ_UNLOCK(iterator);
2170         });
2171         ast_cli(a->fd, "----\n");
2172         ast_cli(a->fd, "   Number of users: %d\n", count);
2173         return CLI_SUCCESS;
2174 }
2175
2176 /*!
2177  * \brief Show buddy lists
2178  * \return CLI_SUCCESS.
2179  */
2180 static char *aji_show_buddies(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2181 {
2182         struct aji_resource *resource;
2183         struct aji_client *client;
2184
2185         switch (cmd) {
2186         case CLI_INIT:
2187                 e->command = "jabber show buddies";
2188                 e->usage =
2189                         "Usage: jabber show buddies\n"
2190                         "       Shows buddy lists of our clients\n";
2191                 return NULL;
2192         case CLI_GENERATE:
2193                 return NULL;
2194         }
2195
2196         ast_cli(a->fd, "Jabber buddy lists\n");
2197         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2198                 ast_cli(a->fd,"Client: %s\n", iterator->user);
2199                 client = iterator;
2200                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
2201                         ASTOBJ_RDLOCK(iterator);
2202                         ast_cli(a->fd,"\tBuddy:\t%s\n", iterator->name);
2203                         if (!iterator->resources)
2204                                 ast_cli(a->fd,"\t\tResource: None\n");  
2205                         for (resource = iterator->resources; resource; resource = resource->next) {
2206                                 ast_cli(a->fd,"\t\tResource: %s\n", resource->resource);
2207                                 if(resource->cap) {
2208                                         ast_cli(a->fd,"\t\t\tnode: %s\n", resource->cap->parent->node);
2209                                         ast_cli(a->fd,"\t\t\tversion: %s\n", resource->cap->version);
2210                                         ast_cli(a->fd,"\t\t\tJingle capable: %s\n", resource->cap->jingle ? "yes" : "no");
2211                                 }
2212                                 ast_cli(a->fd,"\t\tStatus: %d\n", resource->status);
2213                                 ast_cli(a->fd,"\t\tPriority: %d\n", resource->priority);
2214                         }
2215                         ASTOBJ_UNLOCK(iterator);
2216                 });
2217                 iterator = client;
2218         });
2219         return CLI_SUCCESS;
2220 }
2221
2222 /*!
2223  * \brief Send test message for debugging.
2224  * \return CLI_SUCCESS,CLI_FAILURE.
2225  */
2226 static char *aji_test(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2227 {
2228         struct aji_client *client;
2229         struct aji_resource *resource;
2230         const char *name = "asterisk";
2231         struct aji_message *tmp;
2232
2233         switch (cmd) {
2234         case CLI_INIT:
2235                 e->command = "jabber test";
2236                 e->usage =
2237                         "Usage: jabber test [client]\n"
2238                         "       Sends test message for debugging purposes.  A specific client\n"
2239                         "       as configured in jabber.conf can be optionally specified.\n";
2240                 return NULL;
2241         case CLI_GENERATE:
2242                 return NULL;
2243         }
2244
2245         if (a->argc > 3)
2246                 return CLI_SHOWUSAGE;
2247         else if (a->argc == 3)
2248                 name = a->argv[2];
2249
2250         if (!(client = ASTOBJ_CONTAINER_FIND(&clients, name))) {
2251                 ast_cli(a->fd, "Unable to find client '%s'!\n", name);
2252                 return CLI_FAILURE;
2253         }
2254
2255         /* XXX Does Matt really want everyone to use his personal address for tests? */ /* XXX yes he does */
2256         ast_aji_send(client, "mogorman@astjab.org", "blahblah");
2257         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
2258                 ASTOBJ_RDLOCK(iterator);
2259                 ast_verbose("User: %s\n", iterator->name);
2260                 for (resource = iterator->resources; resource; resource = resource->next) {
2261                         ast_verbose("Resource: %s\n", resource->resource);
2262                         if(resource->cap) {
2263                                 ast_verbose("   client: %s\n", resource->cap->parent->node);
2264                                 ast_verbose("   version: %s\n", resource->cap->version);
2265                                 ast_verbose("   Jingle Capable: %d\n", resource->cap->jingle);
2266                         }
2267                         ast_verbose("   Priority: %d\n", resource->priority);
2268                         ast_verbose("   Status: %d\n", resource->status); 
2269                         ast_verbose("   Message: %s\n", S_OR(resource->description,"")); 
2270                 }
2271                 ASTOBJ_UNLOCK(iterator);
2272         });
2273         ast_verbose("\nOooh a working message stack!\n");
2274         AST_LIST_LOCK(&client->messages);
2275         AST_LIST_TRAVERSE(&client->messages, tmp, list) {
2276                 ast_verbose("   Message from: %s with id %s @ %s        %s\n",tmp->from, S_OR(tmp->id,""), ctime(&tmp->arrived), S_OR(tmp->message, ""));
2277         }
2278         AST_LIST_UNLOCK(&client->messages);
2279         ASTOBJ_UNREF(client, aji_client_destroy);
2280
2281         return CLI_SUCCESS;
2282 }
2283
2284 /*!
2285  * \brief creates aji_client structure.
2286  * \param label
2287  * \param var ast_variable
2288  * \param debug 
2289  * \return 0.
2290  */
2291 static int aji_create_client(char *label, struct ast_variable *var, int debug)
2292 {
2293         char *resource;
2294         struct aji_client *client = NULL;
2295         int flag = 0;
2296
2297         client = ASTOBJ_CONTAINER_FIND(&clients,label);
2298         if (!client) {
2299                 flag = 1;
2300                 client = ast_calloc(1, sizeof(*client));
2301                 if (!client) {
2302                         ast_log(LOG_ERROR, "Out of memory!\n");
2303                         return 0;
2304                 }
2305                 ASTOBJ_INIT(client);
2306                 ASTOBJ_WRLOCK(client);
2307                 ASTOBJ_CONTAINER_INIT(&client->buddies);
2308         } else {
2309                 ASTOBJ_WRLOCK(client);
2310                 ASTOBJ_UNMARK(client);
2311         }
2312         ASTOBJ_CONTAINER_MARKALL(&client->buddies);
2313         ast_copy_string(client->name, label, sizeof(client->name));
2314         ast_copy_string(client->mid, "aaaaa", sizeof(client->mid));
2315
2316         /* Set default values for the client object */
2317         client->debug = debug;
2318         ast_copy_flags(client, &globalflags, AST_FLAGS_ALL);
2319         client->port = 5222;
2320         client->usetls = 1;
2321         client->usesasl = 1;
2322         client->forcessl = 0;
2323         client->keepalive = 1;
2324         client->timeout = 50;
2325         client->message_timeout = 100;
2326         AST_LIST_HEAD_INIT(&client->messages);
2327         client->component = 0;
2328         ast_copy_string(client->statusmessage, "Online and Available", sizeof(client->statusmessage));
2329
2330         if (flag) {
2331                 client->authorized = 0;
2332                 client->state = AJI_DISCONNECTED;
2333         }
2334         while (var) {
2335                 if (!strcasecmp(var->name, "username"))
2336                         ast_copy_string(client->user, var->value, sizeof(client->user));
2337                 else if (!strcasecmp(var->name, "serverhost"))
2338                         ast_copy_string(client->serverhost, var->value, sizeof(client->serverhost));
2339                 else if (!strcasecmp(var->name, "secret"))
2340                         ast_copy_string(client->password, var->value, sizeof(client->password));
2341                 else if (!strcasecmp(var->name, "statusmessage"))
2342                         ast_copy_string(client->statusmessage, var->value, sizeof(client->statusmessage));
2343                 else if (!strcasecmp(var->name, "port"))
2344                         client->port = atoi(var->value);
2345                 else if (!strcasecmp(var->name, "timeout"))
2346                         client->message_timeout = atoi(var->value);
2347                 else if (!strcasecmp(var->name, "debug"))
2348                         client->debug = (ast_false(var->value)) ? 0 : 1;
2349                 else if (!strcasecmp(var->name, "type")) {
2350                         if (!strcasecmp(var->value, "component"))
2351                                 client->component = 1;
2352                 } else if (!strcasecmp(var->name, "usetls")) {
2353                         client->usetls = (ast_false(var->value)) ? 0 : 1;
2354                 } else if (!strcasecmp(var->name, "usesasl")) {
2355                         client->usesasl = (ast_false(var->value)) ? 0 : 1;
2356                 } else if (!strcasecmp(var->name, "forceoldssl"))
2357                         client->forcessl = (ast_false(var->value)) ? 0 : 1;
2358                 else if (!strcasecmp(var->name, "keepalive"))
2359                         client->keepalive = (ast_false(var->value)) ? 0 : 1;
2360                 else if (!strcasecmp(var->name, "autoprune"))
2361                         ast_set2_flag(client, ast_true(var->value), AJI_AUTOPRUNE);
2362                 else if (!strcasecmp(var->name, "autoregister"))
2363                         ast_set2_flag(client, ast_true(var->value), AJI_AUTOREGISTER);
2364                 else if (!strcasecmp(var->name, "buddy"))
2365                                 aji_create_buddy(var->value, client);
2366         /* no transport support in this version */
2367         /*      else if (!strcasecmp(var->name, "transport"))
2368                                 aji_create_transport(var->value, client);
2369         */
2370                 var = var->next;
2371         }
2372         if (!flag) {
2373                 ASTOBJ_UNLOCK(client);
2374                 ASTOBJ_UNREF(client, aji_client_destroy);
2375                 return 1;
2376         }
2377         client->p = iks_stream_new(((client->component) ? "jabber:component:accept" : "jabber:client"), client, aji_act_hook);
2378         if (!client->p) {
2379                 ast_log(LOG_ERROR, "Failed to create stream for client '%s'!\n", client->name);
2380                 return 0;
2381         }
2382         client->stack = iks_stack_new(8192, 8192);
2383         if (!client->stack) {
2384                 ast_log(LOG_ERROR, "Failed to allocate stack for client '%s'\n", client->name);
2385                 return 0;
2386         }
2387         client->f = iks_filter_new();
2388         if (!client->f) {
2389                 ast_log(LOG_ERROR, "Failed to create filter for client '%s'\n", client->name);
2390                 return 0;
2391         }
2392         if (!strchr(client->user, '/') && !client->component) { /*client */
2393                 resource = NULL;
2394                 asprintf(&resource, "%s/asterisk", client->user);
2395                 if (resource) {
2396                         client->jid = iks_id_new(client->stack, resource);
2397                         ast_free(resource);
2398                 }
2399         } else
2400                 client->jid = iks_id_new(client->stack, client->user);
2401         if (client->component) {
2402                 iks_filter_add_rule(client->f, aji_dinfo_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
2403                 iks_filter_add_rule(client->f, aji_ditems_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#items", IKS_RULE_DONE);
2404                 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);
2405                 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);
2406         } else {
2407                 iks_filter_add_rule(client->f, aji_client_info_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
2408         }
2409         if (!strchr(client->user, '/') && !client->component) { /*client */
2410                 resource = NULL;
2411                 asprintf(&resource, "%s/asterisk", client->user);
2412                 if (resource) {
2413                         client->jid = iks_id_new(client->stack, resource);
2414                         ast_free(resource);
2415                 }
2416         } else
2417                 client->jid = iks_id_new(client->stack, client->user);
2418         iks_set_log_hook(client->p, aji_log_hook);
2419         ASTOBJ_UNLOCK(client);
2420         ASTOBJ_CONTAINER_LINK(&clients,client);
2421         return 1;
2422 }
2423
2424 #if 0
2425 /*!
2426  * \brief creates transport.
2427  * \param label, buddy to dump it into. 
2428  * \return 0.
2429  */
2430 /* no connecting to transports today */
2431 static int aji_create_transport(char *label, struct aji_client *client)
2432 {
2433         char *server = NULL, *buddyname = NULL, *user = NULL, *pass = NULL;
2434         struct aji_buddy *buddy = NULL;
2435
2436         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies,label);
2437         if (!buddy) {
2438                 buddy = ast_calloc(1, sizeof(*buddy));
2439                 if(!buddy) {
2440                         ast_log(LOG_WARNING, "Out of memory\n");
2441                         return 0;
2442                 }
2443                 ASTOBJ_INIT(buddy);
2444         }
2445         ASTOBJ_WRLOCK(buddy);
2446         server = label;
2447         if ((buddyname = strchr(label, ','))) {
2448                 *buddyname = '\0';
2449                 buddyname++;
2450                 if (buddyname && buddyname[0] != '\0') {
2451                         if ((user = strchr(buddyname, ','))) {
2452                                 *user = '\0';
2453                                 user++;
2454                                 if (user && user[0] != '\0') {
2455                                         if ((pass = strchr(user, ','))) {
2456                                                 *pass = '\0';
2457                                                 pass++;
2458                                                 ast_copy_string(buddy->pass, pass, sizeof(buddy->pass));
2459                                                 ast_copy_string(buddy->user, user, sizeof(buddy->user));
2460                                                 ast_copy_string(buddy->name, buddyname, sizeof(buddy->name));
2461                                                 ast_copy_string(buddy->server, server, sizeof(buddy->server));
2462                                                 return 1;
2463                                         }
2464                                 }
2465                         }
2466                 }
2467         }
2468         ASTOBJ_UNLOCK(buddy);
2469         ASTOBJ_UNMARK(buddy);
2470         ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
2471         return 0;
2472 }
2473 #endif
2474
2475 /*!
2476  * \brief creates buddy.
2477  * \param label char.
2478  * \param client aji_client buddy to dump it into. 
2479  * \return 1 on success, 0 on failure.
2480  */
2481 static int aji_create_buddy(char *label, struct aji_client *client)
2482 {
2483         struct aji_buddy *buddy = NULL;
2484         int flag = 0;
2485         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies,label);
2486         if (!buddy) {
2487                 flag = 1;
2488                 buddy = ast_calloc(1, sizeof(*buddy));
2489                 if(!buddy) {
2490                         ast_log(LOG_WARNING, "Out of memory\n");
2491                         return 0;
2492                 }
2493                 ASTOBJ_INIT(buddy);
2494         }
2495         ASTOBJ_WRLOCK(buddy);
2496         ast_copy_string(buddy->name, label, sizeof(buddy->name));
2497         ASTOBJ_UNLOCK(buddy);
2498         if(flag)
2499                 ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
2500         else {
2501                 ASTOBJ_UNMARK(buddy);
2502                 ASTOBJ_UNREF(buddy, aji_buddy_destroy);
2503         }
2504         return 1;
2505 }
2506
2507 /*!< load config file. \return 1. */
2508 static int aji_load_config(int reload)
2509 {
2510         char *cat = NULL;
2511         int debug = 1;
2512         struct ast_config *cfg = NULL;
2513         struct ast_variable *var = NULL;
2514         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
2515
2516         if ((cfg = ast_config_load(JABBER_CONFIG, config_flags)) == CONFIG_STATUS_FILEUNCHANGED)
2517                 return -1;
2518
2519         /* Reset flags to default value */
2520         ast_set_flag(&globalflags, AJI_AUTOPRUNE | AJI_AUTOREGISTER);
2521
2522         if (!cfg) {
2523                 ast_log(LOG_WARNING, "No such configuration file %s\n", JABBER_CONFIG);
2524                 return 0;
2525         }
2526
2527         cat = ast_category_browse(cfg, NULL);
2528         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
2529                 if (!strcasecmp(var->name, "debug"))
2530                         debug = (ast_false(ast_variable_retrieve(cfg, "general", "debug"))) ? 0 : 1;
2531                 else if (!strcasecmp(var->name, "autoprune"))
2532                         ast_set2_flag(&globalflags, ast_true(var->value), AJI_AUTOPRUNE);
2533                 else if (!strcasecmp(var->name, "autoregister"))
2534                         ast_set2_flag(&globalflags, ast_true(var->value), AJI_AUTOREGISTER);
2535         }
2536
2537         while (cat) {
2538                 if (strcasecmp(cat, "general")) {
2539                                 var = ast_variable_browse(cfg, cat);
2540                                 aji_create_client(cat, var, debug);
2541                 }
2542                 cat = ast_category_browse(cfg, cat);
2543         }
2544         return 1;
2545 }
2546
2547 /*!
2548  * \brief grab a aji_client structure by label name.
2549  * \param name label name 
2550  * \return aji_client.
2551  */
2552 struct aji_client *ast_aji_get_client(const char *name)
2553 {
2554         struct aji_client *client = NULL;
2555
2556         client = ASTOBJ_CONTAINER_FIND(&clients, name);
2557         if (!client && !strchr(name, '@'))
2558                 client = ASTOBJ_CONTAINER_FIND_FULL(&clients, name, user,,, strcasecmp);
2559         return client;
2560 }
2561
2562 struct aji_client_container *ast_aji_get_clients(void)
2563 {
2564         return &clients;
2565 }
2566
2567 static char mandescr_jabber_send[] =
2568 "Description: Sends a message to a Jabber Client.\n"
2569 "Variables: \n"
2570 "  Jabber:      Client or transport Asterisk uses to connect to JABBER.\n"
2571 "  ScreenName:  User Name to message.\n"
2572 "  Message:     Message to be sent to the buddy\n";
2573
2574 /*! 
2575  * \brief  Send a Jabber Message via call from the Manager 
2576  * \param s mansession Manager session
2577  * \param m message Message to send
2578  * \return  0
2579 */
2580 static int manager_jabber_send(struct mansession *s, const struct message *m)
2581 {
2582         struct aji_client *client = NULL;
2583         const char *id = astman_get_header(m,"ActionID");
2584         const char *jabber = astman_get_header(m,"Jabber");
2585         const char *screenname = astman_get_header(m,"ScreenName");
2586         const char *message = astman_get_header(m,"Message");
2587
2588         if (ast_strlen_zero(jabber)) {
2589                 astman_send_error(s, m, "No transport specified");
2590                 return 0;
2591         }
2592         if (ast_strlen_zero(screenname)) {
2593                 astman_send_error(s, m, "No ScreenName specified");
2594                 return 0;
2595         }
2596         if (ast_strlen_zero(message)) {
2597                 astman_send_error(s, m, "No Message specified");
2598                 return 0;
2599         }
2600
2601         astman_send_ack(s, m, "Attempting to send Jabber Message");
2602         client = ast_aji_get_client(jabber);
2603         if (!client) {
2604                 astman_send_error(s, m, "Could not find Sender");
2605                 return 0;
2606         }       
2607         if (strchr(screenname, '@') && message){
2608                 ast_aji_send(client, screenname, message);      
2609                 if (!ast_strlen_zero(id))
2610                         astman_append(s, "ActionID: %s\r\n",id);
2611                 astman_append(s, "Response: Success\r\n");
2612                 return 0;
2613         }
2614         if (!ast_strlen_zero(id))
2615                 astman_append(s, "ActionID: %s\r\n",id);
2616         astman_append(s, "Response: Failure\r\n");
2617         return 0;
2618 }
2619
2620 /*! \brief Reload the jabber module */
2621 static int aji_reload(int reload)
2622 {
2623         int res;
2624
2625         ASTOBJ_CONTAINER_MARKALL(&clients);
2626         if (!(res = aji_load_config(reload))) {
2627                 ast_log(LOG_ERROR, "JABBER: Failed to load config.\n");
2628                 return 0;
2629         } else if (res == -1)
2630                 return 1;
2631
2632         ASTOBJ_CONTAINER_PRUNE_MARKED(&clients, aji_client_destroy);
2633         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2634                 ASTOBJ_RDLOCK(iterator);
2635                 if(iterator->state == AJI_DISCONNECTED) {
2636                         if (!iterator->thread)
2637                                 ast_pthread_create_background(&iterator->thread, NULL, aji_recv_loop, iterator);
2638                 } else if (iterator->state == AJI_CONNECTING)
2639                         aji_get_roster(iterator);
2640                 ASTOBJ_UNLOCK(iterator);
2641         });
2642         
2643         return 1;
2644 }
2645
2646 /*! \brief Unload the jabber module */
2647 static int unload_module(void)
2648 {
2649
2650         /* Check if TLS is initialized. If that's the case, we can't unload this
2651            module due to a bug in the iksemel library that will cause a crash or
2652            a deadlock. We're trying to find a way to handle this, but in the meantime
2653            we will simply refuse to die... 
2654          */
2655         if (tls_initialized) {
2656                 ast_log(LOG_ERROR, "Module can't be unloaded due to a bug in the Iksemel library when using TLS.\n");
2657                 return 1;       /* You need a forced unload to get rid of this module */
2658         }
2659
2660         ast_cli_unregister_multiple(aji_cli, sizeof(aji_cli) / sizeof(struct ast_cli_entry));
2661         ast_unregister_application(app_ajisend);
2662         ast_unregister_application(app_ajistatus);
2663         ast_manager_unregister("JabberSend");
2664         ast_custom_function_unregister(&jabberstatus_function);
2665         
2666         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2667                 ASTOBJ_RDLOCK(iterator);
2668                 ast_debug(3, "JABBER: Releasing and disconneing client: %s\n", iterator->name);
2669                 iterator->state = AJI_DISCONNECTING;
2670                 ast_aji_disconnect(iterator);
2671                 pthread_join(iterator->thread, NULL);
2672                 ASTOBJ_UNLOCK(iterator);
2673         });
2674
2675         ASTOBJ_CONTAINER_DESTROYALL(&clients, aji_client_destroy);
2676         ASTOBJ_CONTAINER_DESTROY(&clients);
2677         return 0;
2678 }
2679
2680 /*! \brief Unload the jabber module */
2681 static int load_module(void)
2682 {
2683         ASTOBJ_CONTAINER_INIT(&clients);
2684         if(!aji_reload(0))
2685                 return AST_MODULE_LOAD_DECLINE;
2686         ast_manager_register2("JabberSend", EVENT_FLAG_SYSTEM, manager_jabber_send,
2687                         "Sends a message to a Jabber Client", mandescr_jabber_send);
2688         ast_register_application(app_ajisend, aji_send_exec, ajisend_synopsis, ajisend_descrip);
2689         ast_register_application(app_ajistatus, aji_status_exec, ajistatus_synopsis, ajistatus_descrip);
2690         ast_cli_register_multiple(aji_cli, sizeof(aji_cli) / sizeof(struct ast_cli_entry));
2691         ast_custom_function_register(&jabberstatus_function);
2692
2693         return 0;
2694 }
2695
2696 /*! \brief Wrapper for aji_reload */
2697 static int reload(void)
2698 {
2699         aji_reload(1);
2700         return 0;
2701 }
2702
2703 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "AJI - Asterisk Jabber Interface",
2704                 .load = load_module,
2705                 .unload = unload_module,
2706                 .reload = reload,
2707                );