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