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