remove leading space in Packet manager event header
[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 #include "asterisk/manager.h"
54
55 #define JABBER_CONFIG "jabber.conf"
56
57 /*-- Forward declarations */
58 static int manager_jabber_send( struct mansession *s, struct message *m );
59 static int aji_highest_bit(int number);
60 static void aji_buddy_destroy(struct aji_buddy *obj);
61 static void aji_client_destroy(struct aji_client *obj);
62 static int aji_send_exec(struct ast_channel *chan, void *data);
63 static int aji_status_exec(struct ast_channel *chan, void *data);
64 static void aji_log_hook(void *data, const char *xmpp, size_t size, int is_incoming);
65 static int aji_act_hook(void *data, int type, iks *node);
66 static void aji_handle_iq(struct aji_client *client, iks *node);
67 static void aji_handle_message(struct aji_client *client, ikspak *pak);
68 static void aji_handle_presence(struct aji_client *client, ikspak *pak);
69 static void aji_handle_subscribe(struct aji_client *client, ikspak *pak);
70 static void *aji_recv_loop(void *data);
71 static int aji_component_initialize(struct aji_client *client);
72 static int aji_client_initialize(struct aji_client *client);
73 static int aji_client_connect(void *data, ikspak *pak);
74 static void aji_set_presence(struct aji_client *client, char *user, int level, char *desc);
75 static int aji_do_debug(int fd, int argc, char *argv[]);
76 static int aji_do_reload(int fd, int argc, char *argv[]);
77 static int aji_no_debug(int fd, int argc, char *argv[]);
78 static int aji_test(int fd, int argc, char *argv[]);
79 static int aji_show_clients(int fd, int argc, char *argv[]);
80 static int aji_create_client(char *label, struct ast_variable *var, int debug);
81 static int aji_create_buddy(char *label, struct aji_client *client);
82 static int aji_create_transport(char *label, struct aji_client *client);
83 static int aji_reload(void);
84 static int aji_load_config(void);
85 static void aji_pruneregister(struct aji_client *client);
86 static int aji_register_transport(void *data, ikspak *pak);
87 static int aji_register_transport2(void *data, ikspak *pak);
88 static int aji_filter_roster(void *data, ikspak *pak);
89 static int aji_get_roster(struct aji_client *client);
90 static int aji_client_info_handler(void *data, ikspak *pak);
91 static int aji_dinfo_handler(void *data, ikspak *pak);
92 static int aji_ditems_handler(void *data, ikspak *pak);
93 static int aji_register_query_handler(void *data, ikspak *pak);
94 static int aji_register_approve_handler(void *data, ikspak *pak);
95 static int aji_reconnect(struct aji_client *client);
96 static iks *jabber_make_auth(iksid * id, const char *pass, const char *sid);
97
98 static char debug_usage[] = 
99 "Usage: jabber debug\n" 
100 "       Enables dumping of Jabber packets for debugging purposes.\n";
101
102 static char no_debug_usage[] = 
103 "Usage: jabber no debug\n" 
104 "       Disables dumping of Jabber packets for debugging purposes.\n";
105
106 static char reload_usage[] = 
107 "Usage: jabber reload\n" 
108 "       Enables reloading of Jabber module.\n";
109
110 static char test_usage[] = 
111 "Usage: jabber test [client]\n" 
112 "       Sends test message for debugging purposes.  A specific client\n"
113 "       as configured in jabber.conf can be optionally specified.\n";
114
115 static struct ast_cli_entry aji_cli[] = {
116         {{ "jabber", "debug", NULL}, aji_do_debug, "Enable Jabber debugging", debug_usage },
117         {{ "jabber", "reload", NULL}, aji_do_reload, "Enable Jabber debugging", reload_usage },
118         {{ "jabber", "show", "connected", NULL}, aji_show_clients, "Show state of clients and components", debug_usage },
119         {{ "jabber", "no", "debug", NULL}, aji_no_debug, "Disable Jabber debug", no_debug_usage },
120         {{ "jabber", "test", NULL}, aji_test, "Shows roster, but is genearlly used for mog's debugging.", test_usage },
121  };
122
123 static char *app_ajisend = "JabberSend";
124
125 static char *ajisend_synopsis = "JabberSend(jabber,screenname,message)";
126
127 static char *ajisend_descrip =
128 "JabberSend(Jabber,ScreenName,Message)\n"
129 "  Jabber - Client or transport Asterisk uses to connect to Jabber\n" 
130 "  ScreenName - User Name to message.\n" 
131 "  Message - Message to be sent to the buddy\n";
132
133 static char *app_ajistatus = "JabberStatus";
134
135 static char *ajistatus_synopsis = "JabberStatus(Jabber,ScreenName,Variable)";
136
137 static char *ajistatus_descrip =
138 "JabberStatus(Jabber,ScreenName,Variable)\n"
139 "  Jabber - Client or transport Asterisk uses to connect to Jabber\n"
140 "  ScreenName - User Name to retrieve status from.\n"
141 "  Variable - Variable to store presence in will be 1-6.\n" 
142 "             In order, Online, Chatty, Away, XAway, DND, Offline\n" 
143 "             If not in roster variable will = 7\n";
144
145 struct aji_client_container clients;
146
147 struct aji_capabilities *capabilities;
148
149 /*! \brief Global flags, initialized to default values */
150 static struct ast_flags globalflags = { AJI_AUTOPRUNE | AJI_AUTOREGISTER };
151
152 /*!
153  * \brief Deletes the aji_client data structure.
154  * \param obj is the structure we will delete.
155  * \return void.
156  */
157 static void aji_client_destroy(struct aji_client *obj)
158 {
159         struct aji_message *tmp;
160         ASTOBJ_CONTAINER_DESTROYALL(&obj->buddies, aji_buddy_destroy);
161         ASTOBJ_CONTAINER_DESTROY(&obj->buddies);
162         iks_filter_delete(obj->f);
163         iks_parser_delete(obj->p);
164         iks_stack_delete(obj->stack);
165         AST_LIST_LOCK(&obj->messages);
166         while ((tmp = AST_LIST_REMOVE_HEAD(&obj->messages, list))) {
167                 if (tmp->from)
168                         free(tmp->from);
169                 if (tmp->message)
170                         free(tmp->message);
171         }
172         AST_LIST_HEAD_DESTROY(&obj->messages);
173         free(obj);
174 }
175
176 /*!
177  * \brief Deletes the aji_buddy data structure.
178  * \param obj is the structure we will delete.
179  * \return void.
180  */
181 static void aji_buddy_destroy(struct aji_buddy *obj)
182 {
183         struct aji_resource *tmp;
184
185         while ((tmp = obj->resources)) {
186                 obj->resources = obj->resources->next;
187                 free(tmp->description);
188                 free(tmp);
189         }
190
191         free(obj);
192 }
193
194 static struct aji_version *aji_find_version(char *node, char *version, ikspak *pak)
195 {
196         struct aji_capabilities *list = NULL;
197         struct aji_version *res = NULL;
198
199         list = capabilities;
200
201         if(!node)
202                 node = pak->from->full;
203         if(!version)
204                 version = "none supplied.";
205         while(list) {
206                 if(!strcasecmp(list->node, node)) {
207                         res = list->versions;
208                         while(res) {
209                                  if(!strcasecmp(res->version, version))
210                                          return res;
211                                  res = res->next;
212                         }
213                         if(!res) {
214                                 res = (struct aji_version *)malloc(sizeof(struct aji_version));
215                                 if(!res) {
216                                         ast_log(LOG_ERROR, "Out of memory!\n");
217                                         return NULL;
218                                 }
219                                 res->jingle = 0;
220                                 res->parent = list;
221                                 ast_copy_string(res->version, version, sizeof(res->version));
222                                 res->next = list->versions;
223                                 list->versions = res;
224                                 return res;
225                         }
226                 }
227                 list = list->next;
228         }
229         if(!list) {
230                 list = (struct aji_capabilities *)malloc(sizeof(struct aji_capabilities));
231                 if(!list) {
232                         ast_log(LOG_ERROR, "Out of memory!\n");
233                         return NULL;
234                 }
235                 res = (struct aji_version *)malloc(sizeof(struct aji_version));
236                 if(!res) {
237                         ast_log(LOG_ERROR, "Out of memory!\n");
238                         return NULL;
239                 }
240                 ast_copy_string(list->node, node, sizeof(list->node));
241                 ast_copy_string(res->version, version, sizeof(res->version));
242                 res->jingle = 0;
243                 res->parent = list;
244                 res->next = list->versions;
245                 list->versions = res;
246                 list->next = capabilities;
247                 capabilities = list;
248         }
249         return res;
250 }
251
252 static struct aji_resource *aji_find_resource(struct aji_buddy *buddy, char *rname)
253 {
254         struct aji_resource *res = NULL;
255         if (!buddy || !rname)
256                 return res;
257         res = buddy->resources;
258         while (res) {
259                 if (!strcasecmp(res->resource, rname)) {
260                         break;
261                 }
262                 res = res->next;
263         }
264         return res;
265 }
266
267 static int gtalk_yuck(iks *node)
268 {
269         if (iks_find_with_attrib(node, "c", "node", "http://www.google.com/xmpp/client/caps"))
270                 return 1;
271         return 0;
272 }
273
274 /*!
275  * \brief Detects the highest bit in a number.
276  * \param Number you want to have evaluated.
277  * \return the highest power of 2 that can go into the number.
278  */
279 static int aji_highest_bit(int number)
280 {
281         int x = sizeof(number) * 8 - 1;
282         if (!number)
283                 return 0;
284         for (; x > 0; x--) {
285                 if (number & (1 << x))
286                         break;
287         }
288         return (1 << x);
289 }
290
291 static iks *jabber_make_auth(iksid * id, const char *pass, const char *sid)
292 {
293         iks *x, *y;
294         x = iks_new("iq");
295         iks_insert_attrib(x, "type", "set");
296         y = iks_insert(x, "query");
297         iks_insert_attrib(y, "xmlns", IKS_NS_AUTH);
298         iks_insert_cdata(iks_insert(y, "username"), id->user, 0);
299         iks_insert_cdata(iks_insert(y, "resource"), id->resource, 0);
300         if (sid) {
301                 char buf[41];
302                 char sidpass[100];
303                 snprintf(sidpass, sizeof(sidpass), "%s%s", sid, pass);
304                 ast_sha1_hash(buf, sidpass);
305                 iks_insert_cdata(iks_insert(y, "digest"), buf, 0);
306         } else {
307                 iks_insert_cdata(iks_insert(y, "password"), pass, 0);
308         }
309         return x;
310 }
311
312 /*!
313  * \brief Dial plan function status(). puts the status of watched user 
314    into a channel variable.
315  * \param channel, and username,watched user, status var
316  * \return 0.
317  */
318 static int aji_status_exec(struct ast_channel *chan, void *data)
319 {
320         struct aji_client *client = NULL;
321         struct aji_buddy *buddy = NULL;
322         struct aji_resource *r = NULL;
323         char *s = NULL, *sender = NULL, *jid = NULL, *screenname = NULL, *resource = NULL, *variable = NULL;
324         int stat = 7;
325         char status[2];
326         if (data) {
327                 s = ast_strdupa((char *) data);
328                 if (s) {
329                         sender = strsep(&s, "|");
330                         if (sender && (sender[0] != '\0')) {
331                                 jid = strsep(&s, "|");
332                                 if (jid && (jid[0] != '\0')) {
333                                         variable = s;
334                                 } else {
335                                         ast_log(LOG_ERROR, "Bad arguments\n");
336                                         return -1;
337                                 }
338                         }
339                 }
340         } else {
341                 ast_log(LOG_ERROR, "Out of memory\n");
342                 return -1;
343         }
344
345         if(!strchr(jid, '/')) {
346                 resource = NULL;
347         } else {
348                 screenname = strsep(&jid, "/");
349                 resource = jid;
350         }
351         client = ast_aji_get_client(sender);
352         if (!client) {
353                 ast_log(LOG_WARNING, "Could not find Connection.\n");
354                 return -1;
355         }
356         if(!&client->buddies) {
357                 ast_log(LOG_WARNING, "No buddies for connection.\n");
358                 return -1;
359         }
360         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, (resource)?screenname:jid);
361         if (!buddy) {
362                 ast_log(LOG_WARNING, "Could not find Buddy in list.\n");
363                 return -1;
364         }
365         r = aji_find_resource(buddy, resource);
366         if(!r && buddy->resources) {
367                 r = buddy->resources;
368         }
369         if(!r){
370                 ast_log(LOG_NOTICE, "Resource %s of buddy %s not found \n", resource, screenname);
371         }
372         stat = r->status;
373         sprintf(status, "%d", stat);
374         pbx_builtin_setvar_helper(chan, variable, status);
375         return 0;
376 }
377
378 /*!
379  * \brief Dial plan function to send a message.
380  * \param channel, and data, data is sender, reciever, message.
381  * \return 0.
382  */
383 static int aji_send_exec(struct ast_channel *chan, void *data)
384 {
385         struct aji_client *client = NULL;
386
387         char *s = NULL, *sender = NULL, *recipient = NULL, *message = NULL;
388
389         if (!data) {
390                 ast_log(LOG_ERROR, "Out of memory\n");
391                 return -1;
392         }
393         s = ast_strdupa((char *) data);
394         if (s) {
395                 sender = strsep(&s, "|");
396                 if (sender && (sender[0] != '\0')) {
397                         recipient = strsep(&s, "|");
398                         if (recipient && (recipient[0] != '\0')) {
399                                 message = s;
400                         } else {
401                                 ast_log(LOG_ERROR, "Bad arguments \n");
402                                 return -1;
403                         }
404                 }
405         }
406         if (!(client = ast_aji_get_client(sender))) {
407                 ast_log(LOG_WARNING, "Could not find Sender.\n");
408                 return -1;
409         }
410         if (strchr(recipient, '@') && message)
411                 ast_aji_send(client, recipient, message);
412         return 0;
413 }
414
415 /*!
416  * \brief the debug loop.
417  * \param aji_client structure, xml data as string, size of string, direction of packet, 1 for inbound 0 for outbound.
418  */
419 static void aji_log_hook(void *data, const char *xmpp, size_t size, int is_incoming)
420 {
421         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
422         manager_event(EVENT_FLAG_USER, "JabberEvent", "Account: %s\r\nPacket: %s", client->name, xmpp);
423
424         if (client->debug == 1) {
425                 if (is_incoming)
426                         ast_verbose("\nJABBER: %s INCOMING: %s\n", client->name, xmpp);
427                 else
428                         ast_verbose("\nJABBER: %s OUTGOING: %s\n", client->name, xmpp);
429
430         }
431         ASTOBJ_UNREF(client, aji_client_destroy);
432 }
433
434 /*!
435  * \brief The action hook parses the inbound packets, constantly running.
436  * \param aji client structure, type of packet, the actual packet.
437  * \return IKS_OK or IKS_HOOK .
438  */
439 static int aji_act_hook(void *data, int type, iks *node)
440 {
441         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
442         ikspak *pak = NULL;
443         iks *auth = NULL;
444
445         if(!node) {
446                 ast_log(LOG_ERROR, "aji_act_hook was called with out a packet\n"); /* most likely cause type is IKS_NODE_ERROR lost connection */
447                 return IKS_HOOK;
448         }
449
450         pak = iks_packet(node);
451
452         if (client->component == AJI_CLIENT) {
453                 switch (type) {
454                 case IKS_NODE_START:
455                         if (client->usetls && !iks_is_secure(client->p)) {
456                                 if (iks_has_tls())
457                                         iks_start_tls(client->p);
458                                 else
459                                         ast_log(LOG_ERROR, "gnuTLS not installed.\n");
460                                 break;
461                         }
462                         if (!client->usesasl) {
463                                 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);
464                                 auth = jabber_make_auth(client->jid, client->password, iks_find_attrib(node, "id"));
465                                 if (auth) {
466                                         iks_insert_attrib(auth, "id", client->mid);
467                                         iks_insert_attrib(auth, "to", client->jid->server);
468                                         ast_aji_increment_mid(client->mid);
469                                         iks_send(client->p, auth);
470                                         iks_delete(auth);
471                                 } else
472                                         ast_log(LOG_ERROR, "Out of memory.\n");
473                         }
474                         break;
475
476                 case IKS_NODE_NORMAL:
477                         {
478                                 int features = 0;
479                                 if (!strcmp("stream:features", iks_name(node))) {
480                                         features = iks_stream_features(node);
481                                         if (client->usesasl) {
482                                                 if (client->usetls && !iks_is_secure(client->p))
483                                                         break;
484                                                 if (client->authorized) {
485                                                         if (features & IKS_STREAM_BIND) {
486                                                                 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);
487                                                                 auth = iks_make_resource_bind(client->jid);
488                                                                 if (auth) {
489                                                                         iks_insert_attrib(auth, "id", client->mid);
490                                                                         ast_aji_increment_mid(client->mid);
491                                                                         iks_send(client->p, auth);
492                                                                         iks_delete(auth);
493                                                                 } else {
494                                                                         ast_log(LOG_ERROR, "Out of memory.\n");
495                                                                         break;
496                                                                 }
497                                                         }
498                                                         if (features & IKS_STREAM_SESSION) {
499                                                                 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);
500                                                                 auth = iks_make_session();
501                                                                 if (auth) {
502                                                                         iks_insert_attrib(auth, "id", "auth");
503                                                                         ast_aji_increment_mid(client->mid);
504                                                                         iks_send(client->p, auth);
505                                                                         iks_delete(auth);
506                                                                 } else {
507                                                                         ast_log(LOG_ERROR, "Out of memory.\n");
508                                                                 }
509                                                         }
510                                                 } else {
511                                                         features = aji_highest_bit(features);
512                                                         if (features == IKS_STREAM_SASL_MD5)
513                                                                 iks_start_sasl(client->p, IKS_SASL_DIGEST_MD5, client->jid->user, client->password);
514                                                         else {
515                                                                 if (features == IKS_STREAM_SASL_PLAIN) {
516                                                                         iks *x = NULL;
517                                                                         x = iks_new("auth");
518                                                                         if (x) {
519                                                                                 iks_insert_attrib(x, "xmlns", IKS_NS_XMPP_SASL);
520                                                                                 int len = strlen(client->jid->user) + strlen(client->password) + 3;
521                                                                                 /* XXX Check return values XXX */
522                                                                                 char *s = ast_malloc(80 + len);
523                                                                                 char *base64 = ast_malloc(80 + len * 2);
524                                                                                 iks_insert_attrib(x, "mechanism", "PLAIN");
525                                                                                 sprintf(s, "%c%s%c%s", 0, client->jid->user, 0, client->password);
526                                                                                 ast_base64encode(base64, (const unsigned char *) s, len, len * 2);
527                                                                                 iks_insert_cdata(x, base64, 0);
528                                                                                 iks_send(client->p, x);
529                                                                                 iks_delete(x);
530                                                                                 if (base64)
531                                                                                         free(base64);
532                                                                                 if (s)
533                                                                                         free(s);
534                                                                         } else {
535                                                                                 ast_log(LOG_ERROR, "Out of memory.\n");
536                                                                         }
537                                                                 }
538                                                         }
539                                                 }
540                                         }
541                                 } else if (!strcmp("failure", iks_name(node))) {
542                                         ast_log(LOG_ERROR, "JABBER: encryption failure. possible bad password.\n");
543                                 } else if (!strcmp("success", iks_name(node))) {
544                                         client->authorized = 1;
545                                         iks_send_header(client->p, client->jid->server);
546                                 }
547                                 break;
548                         }
549                 case IKS_NODE_ERROR: 
550                                 ast_log(LOG_ERROR, "JABBER: Node Error\n");
551                                 ASTOBJ_UNREF(client, aji_client_destroy);
552                                 return IKS_HOOK;
553                                 break;
554                 case IKS_NODE_STOP: 
555                                 ast_log(LOG_WARNING, "JABBER: Disconnected\n");
556                                 ASTOBJ_UNREF(client, aji_client_destroy);
557                                 return IKS_HOOK;
558                                 break;
559                 }
560         } else if (client->state != AJI_CONNECTED && client->component == AJI_COMPONENT) {
561                 switch (type) {
562                 case IKS_NODE_START:
563                         if (client->state == AJI_DISCONNECTED) {
564                                 char secret[160], shasum[320], *handshake;
565
566                                 sprintf(secret, "%s%s", pak->id, client->password);
567                                 ast_sha1_hash(shasum, secret);
568                                 handshake = NULL;
569                                 asprintf(&handshake, "<handshake>%s</handshake>", shasum);
570                                 if (handshake) {
571                                         iks_send_raw(client->p, handshake);
572                                         free(handshake);
573                                         handshake = NULL;
574                                 }
575                                 client->state = AJI_CONNECTED;
576                         }
577                         break;
578
579                 case IKS_NODE_NORMAL:
580                         break;
581
582                 case IKS_NODE_ERROR:
583                         ast_log(LOG_ERROR, "JABBER: Node Error\n");
584                         ASTOBJ_UNREF(client, aji_client_destroy);
585                         return IKS_HOOK;
586
587                 case IKS_NODE_STOP:
588                         ast_log(LOG_WARNING, "JABBER: Disconnected\n");
589                         ASTOBJ_UNREF(client, aji_client_destroy);
590                         return IKS_HOOK;
591                 }
592         }
593
594         switch (pak->type) {
595         case IKS_PAK_NONE:
596                 if (option_verbose > 4)
597                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I Don't know what to do with you NONE\n");
598                 break;
599         case IKS_PAK_MESSAGE:
600                 aji_handle_message(client, pak);
601                 if (option_verbose > 4)
602                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I Don't know what to do with you MESSAGE\n");
603                 break;
604         case IKS_PAK_PRESENCE:
605                 aji_handle_presence(client, pak);
606                 if (option_verbose > 4)
607                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I Do know how to handle presence!!\n");
608                 break;
609         case IKS_PAK_S10N:
610                 aji_handle_subscribe(client, pak);
611                 if (option_verbose > 4)
612                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I Dont know S10N subscribe!!\n");
613                 break;
614         case IKS_PAK_IQ:
615                 if (option_verbose > 4)
616                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I Dont have an IQ!!!\n");
617                 aji_handle_iq(client, node);
618                 break;
619         default:
620                 if (option_verbose > 4)
621                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I Dont know %i\n", pak->type);
622                 break;
623         }
624         
625         iks_filter_packet(client->f, pak);
626
627         if (node)
628                 iks_delete(node);
629
630         ASTOBJ_UNREF(client, aji_client_destroy);
631         return IKS_OK;
632 }
633
634 static int aji_register_approve_handler(void *data, ikspak *pak)
635 {
636         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
637         iks *iq = NULL, *query = NULL, *item = NULL;
638
639         iq = iks_new("iq");
640         query = iks_new("query");
641         item = iks_new("item");
642
643         if (client && iq && query && item) {
644                 if (!iks_find(pak->query, "remove")) {
645                         iks_insert_attrib(iq, "from", client->jid->full);
646                         iks_insert_attrib(iq, "to", pak->from->full);
647                         iks_insert_attrib(iq, "id", pak->id);
648                         iks_insert_attrib(iq, "type", "result");
649                         iks_insert_attrib(query, "xmlns", "jabber:iq:register");
650
651                         iks_insert_node(iq, query);
652                         iks_send(client->p, iq);
653                         iks_insert_attrib(iq, "from", pak->from->full);
654                         iks_insert_attrib(iq, "to", pak->from->full);
655                         iks_insert_attrib(iq, "id", client->mid);
656                         ast_aji_increment_mid(client->mid);
657                         iks_insert_attrib(iq, "type", "set");
658                         iks_insert_attrib(query, "xmlns", "jabber:iq:roster");
659                         iks_insert_attrib(item, "subscription", "none");
660                         iks_insert_attrib(item, "jid", client->jid->full);
661                         iks_insert_node(query, item);
662                         iks_send(client->p, iq);
663                 }
664         } else {
665                 ast_log(LOG_ERROR, "Out of memory.\n");
666         }
667         if (iq)
668                 iks_delete(iq);
669         if (query)
670                 iks_delete(query);
671         if (item)
672                 iks_delete(item);
673         ASTOBJ_UNREF(client, aji_client_destroy);
674         return IKS_FILTER_EAT;
675 }
676
677 static int aji_register_query_handler(void *data, ikspak *pak)
678 {
679         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
680         char *node = NULL;
681
682         client = (struct aji_client *) data;
683
684         if (!(node = iks_find_attrib(pak->query, "node"))) {
685                 iks *iq = NULL, *query = NULL, *instructions = NULL;
686                 char *explain = "Welcome to Asterisk - the Open Source PBX.\n";
687                 iq = iks_new("iq");
688                 query = iks_new("query");
689                 instructions = iks_new("instructions");
690                 if (iq && query && instructions && client) {
691                         iks_insert_attrib(iq, "from", client->user);
692                         iks_insert_attrib(iq, "to", pak->from->full);
693                         iks_insert_attrib(iq, "id", pak->id);
694                         iks_insert_attrib(iq, "type", "result");
695                         iks_insert_attrib(query, "xmlns", "jabber:iq:register");
696                         iks_insert_cdata(instructions, explain, 0);
697                         iks_insert_node(iq, query);
698                         iks_insert_node(query, instructions);
699                         iks_send(client->p, iq);
700                 } else {
701                         ast_log(LOG_ERROR, "Out of memory.\n");
702                 }
703                 if (iq)
704                         iks_delete(iq);
705                 if (query)
706                         iks_delete(query);
707                 if (instructions)
708                         iks_delete(instructions);
709         }
710         ASTOBJ_UNREF(client, aji_client_destroy);
711         return IKS_FILTER_EAT;
712 }
713
714 static int aji_ditems_handler(void *data, ikspak *pak)
715 {
716         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
717         char *node = NULL;
718
719         if (!(node = iks_find_attrib(pak->query, "node"))) {
720                 iks *iq = NULL, *query = NULL, *item = NULL;
721                 iq = iks_new("iq");
722                 query = iks_new("query");
723                 item = iks_new("item");
724
725                 if (iq && query && item) {
726                         iks_insert_attrib(iq, "from", client->user);
727                         iks_insert_attrib(iq, "to", pak->from->full);
728                         iks_insert_attrib(iq, "id", pak->id);
729                         iks_insert_attrib(iq, "type", "result");
730                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
731                         iks_insert_attrib(item, "node", "http://jabber.org/protocol/commands");
732                         iks_insert_attrib(item, "name", "Million Dollar Asterisk Commands");
733                         iks_insert_attrib(item, "jid", client->user);
734
735                         iks_insert_node(iq, query);
736                         iks_insert_node(query, item);
737                         iks_send(client->p, iq);
738                 } else {
739                         ast_log(LOG_ERROR, "Out of memory.\n");
740                 }
741                 if (iq)
742                         iks_delete(iq);
743                 if (query)
744                         iks_delete(query);
745                 if (item)
746                         iks_delete(item);
747
748         } else if (!strcasecmp(node, "http://jabber.org/protocol/commands")) {
749                 iks *iq, *query, *confirm;
750                 iq = iks_new("iq");
751                 query = iks_new("query");
752                 confirm = iks_new("item");
753                 if (iq && query && confirm && client) {
754                         iks_insert_attrib(iq, "from", client->user);
755                         iks_insert_attrib(iq, "to", pak->from->full);
756                         iks_insert_attrib(iq, "id", pak->id);
757                         iks_insert_attrib(iq, "type", "result");
758                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
759                         iks_insert_attrib(query, "node", "http://jabber.org/protocol/commands");
760                         iks_insert_attrib(confirm, "node", "confirmaccount");
761                         iks_insert_attrib(confirm, "name", "Confirm AIM account");
762                         iks_insert_attrib(confirm, "jid", "blog.astjab.org");
763
764                         iks_insert_node(iq, query);
765                         iks_insert_node(query, confirm);
766                         iks_send(client->p, iq);
767                 } else {
768                         ast_log(LOG_ERROR, "Out of memory.\n");
769                 }
770                 if (iq)
771                         iks_delete(iq);
772                 if (query)
773                         iks_delete(query);
774                 if (confirm)
775                         iks_delete(confirm);
776
777         } else if (!strcasecmp(node, "confirmaccount")) {
778                 iks *iq = NULL, *query = NULL, *feature = NULL;
779
780                 iq = iks_new("iq");
781                 query = iks_new("query");
782                 feature = iks_new("feature");
783
784                 if (iq && query && feature && client) {
785                         iks_insert_attrib(iq, "from", client->user);
786                         iks_insert_attrib(iq, "to", pak->from->full);
787                         iks_insert_attrib(iq, "id", pak->id);
788                         iks_insert_attrib(iq, "type", "result");
789                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
790                         iks_insert_attrib(feature, "var", "http://jabber.org/protocol/commands");
791                         iks_insert_node(iq, query);
792                         iks_insert_node(query, feature);
793                         iks_send(client->p, iq);
794                 } else {
795                         ast_log(LOG_ERROR, "Out of memory.\n");
796                 }
797                 if (iq)
798                         iks_delete(iq);
799                 if (query)
800                         iks_delete(query);
801                 if (feature)
802                         iks_delete(feature);
803         }
804
805         ASTOBJ_UNREF(client, aji_client_destroy);
806         return IKS_FILTER_EAT;
807
808 }
809
810 static int aji_client_info_handler(void *data, ikspak *pak)
811 {
812         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
813         struct aji_resource *resource = NULL;
814         struct aji_buddy *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, *query, *identity, *disco, *reg, *commands, *gateway, *version, *vcard, *search;
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, *query, *confirm;
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, *query, *feature;
972
973                 iq = iks_new("iq");
974                 query = iks_new("query");
975                 feature = iks_new("feature");
976
977                 if (iq && query && feature && client) {
978                         iks_insert_attrib(iq, "from", client->user);
979                         iks_insert_attrib(iq, "to", pak->from->full);
980                         iks_insert_attrib(iq, "id", pak->id);
981                         iks_insert_attrib(iq, "type", "result");
982                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
983                         iks_insert_attrib(feature, "var", "http://jabber.org/protocol/commands");
984                         iks_insert_node(iq, query);
985                         iks_insert_node(query, feature);
986                         iks_send(client->p, iq);
987                 } else {
988                         ast_log(LOG_ERROR, "Out of memory.\n");
989                 }
990                 if (iq)
991                         iks_delete(iq);
992                 if (query)
993                         iks_delete(query);
994                 if (feature)
995                         iks_delete(feature);
996         }
997
998         ASTOBJ_UNREF(client, aji_client_destroy);
999         return IKS_FILTER_EAT;
1000 }
1001
1002 /*!
1003  * \brief Handles <iq> tags.
1004  * \param client structure and the iq node.
1005  * \return void.
1006  */
1007 static void aji_handle_iq(struct aji_client *client, iks *node)
1008 {
1009         /*Nothing to see here */
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;
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
1136                 if (!found) {
1137                         ast_log(LOG_ERROR, "Out of memory!\n");
1138                         return;
1139                 }
1140                 ast_copy_string(found->resource, pak->from->resource, sizeof(found->resource));
1141                 found->status = status;
1142                 found->description = descrip;
1143                 found->priority = priority;
1144                 found->next = NULL;
1145                 last = NULL;
1146                 tmp = buddy->resources;
1147                 while (tmp) {
1148                         if (found->priority > tmp->priority) {
1149                                 if (last)
1150                                         last->next = found;
1151                                 found->next = tmp;
1152                                 if (!last)
1153                                         buddy->resources = found;
1154                                 break;
1155                         }
1156                         if (!tmp->next) {
1157                                 tmp->next = found;
1158                                 break;
1159                         }
1160                         last = tmp;
1161                         tmp = tmp->next;
1162                 }
1163                 if (!tmp)
1164                         buddy->resources = found;
1165         }
1166         ASTOBJ_UNLOCK(buddy);
1167         ASTOBJ_UNREF(buddy, aji_buddy_destroy);
1168
1169         node = iks_find_attrib(iks_find(pak->x, "c"), "node");
1170         ver = iks_find_attrib(iks_find(pak->x, "c"), "ver");
1171
1172         if(status !=6 && !found->cap) {
1173                 found->cap = aji_find_version(node, ver, pak);
1174                 if(gtalk_yuck(pak->x)) /* gtalk should do discover */
1175                         found->cap->jingle = 1;
1176                 if(found->cap->jingle && option_debug > 4)
1177                         ast_log(LOG_DEBUG,"Special case for google till they support discover.\n");
1178                 else {
1179                         iks *iq, *query;
1180                         iq = iks_new("iq");
1181                         query = iks_new("query");
1182                         if(query && iq)  {
1183                                 iks_insert_attrib(iq, "type", "get");
1184                                 iks_insert_attrib(iq, "to", pak->from->full);
1185                                 iks_insert_attrib(iq, "id", client->mid);
1186                                 ast_aji_increment_mid(client->mid);
1187                                 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
1188                                 iks_insert_node(iq, query);
1189                                 iks_send(client->p, iq);
1190                                 
1191                         } else
1192                                 ast_log(LOG_ERROR, "Out of memory.\n");
1193                         if(query)
1194                                 iks_delete(query);
1195                         if(iq)
1196                                 iks_delete(iq);
1197                 }
1198         }
1199         if (option_verbose > 4) {
1200                 switch (pak->subtype) {
1201                 case IKS_TYPE_AVAILABLE:
1202                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I am available ^_* %i\n", pak->subtype);
1203                         break;
1204                 case IKS_TYPE_UNAVAILABLE:
1205                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I am unavailable ^_* %i\n", pak->subtype);
1206                         break;
1207                 default:
1208                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: Ohh sexy and the wrong type: %i\n", pak->subtype);
1209                 }
1210                 switch (pak->show) {
1211                 case IKS_SHOW_UNAVAILABLE:
1212                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1213                         break;
1214                 case IKS_SHOW_AVAILABLE:
1215                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type is available\n");
1216                         break;
1217                 case IKS_SHOW_CHAT:
1218                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1219                         break;
1220                 case IKS_SHOW_AWAY:
1221                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type is away\n");
1222                         break;
1223                 case IKS_SHOW_XA:
1224                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1225                         break;
1226                 case IKS_SHOW_DND:
1227                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1228                         break;
1229                 default:
1230                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: Kinky! how did that happen %i\n", pak->show);
1231                 }
1232         }
1233 }
1234
1235 /*!
1236  * \brief handles subscription requests.
1237  * \param aji_client struct and xml packet.
1238  * \return void.
1239  */
1240 static void aji_handle_subscribe(struct aji_client *client, ikspak *pak)
1241 {
1242         if(pak->subtype == IKS_TYPE_SUBSCRIBE)
1243                 iks_send(client->p, iks_make_s10n(IKS_TYPE_SUBSCRIBED, iks_find_attrib(pak->x, "from"), "Asterisk has approved subscription"));
1244         if (option_verbose > 4) {
1245                 switch (pak->subtype) {
1246                 case IKS_TYPE_SUBSCRIBE:
1247                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1248                         break;
1249                 case IKS_TYPE_SUBSCRIBED:
1250                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1251                         break;
1252                 case IKS_TYPE_UNSUBSCRIBE:
1253                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1254                         break;
1255                 case IKS_TYPE_UNSUBSCRIBED:
1256                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1257                         break;
1258                 default:                                /*IKS_TYPE_ERROR: */
1259                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1260                         break;
1261                 }
1262         }
1263 }
1264
1265 /*!
1266  * \brief sends messages.
1267  * \param aji_client struct , reciever, message.
1268  * \return 1.
1269  */
1270 int ast_aji_send(struct aji_client *client, char *address, char *message)
1271 {
1272         int res = 0;
1273         iks *message_packet = NULL;
1274         if (client->state == AJI_CONNECTED) {
1275                 message_packet = iks_make_msg(IKS_TYPE_CHAT, address, message);
1276                 if (message_packet) {
1277                         iks_insert_attrib(message_packet, "from", client->jid->full);
1278                         res = iks_send(client->p, message_packet);
1279                 } else {
1280                         ast_log(LOG_ERROR, "Out of memory.\n");
1281                 }
1282                 if (message_packet)
1283                         iks_delete(message_packet);
1284         } else
1285                 ast_log(LOG_WARNING, "JABBER: Not connected can't send\n");
1286         return 1;
1287 }
1288
1289 /*!
1290  * \brief create a chatroom.
1291  * \param aji_client struct , room, server, topic for the room.
1292  * \return 0.
1293  */
1294 int ast_aji_create_chat(struct aji_client *client, char *room, char *server, char *topic)
1295 {
1296         int res = 0;
1297         iks *iq = NULL;
1298         iq = iks_new("iq");
1299         if (iq && client) {
1300                 iks_insert_attrib(iq, "type", "get");
1301                 iks_insert_attrib(iq, "to", server);
1302                 iks_insert_attrib(iq, "id", client->mid);
1303                 ast_aji_increment_mid(client->mid);
1304                 iks_send(client->p, iq);
1305         } else 
1306                 ast_log(LOG_ERROR, "Out of memory.\n");
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         if (presence)
1332                 iks_delete(presence);
1333         if (priority)
1334                 iks_delete(priority);
1335         return res;
1336 }
1337
1338 /*!
1339  * \brief invite to a chatroom.
1340  * \param aji_client struct ,user, room, message.
1341  * \return res.
1342  */
1343 int ast_aji_invite_chat(struct aji_client *client, char *user, char *room, char *message)
1344 {
1345         int res = 0;
1346         iks *invite, *body, *namespace;
1347
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         if (body)
1364                 iks_delete(body);
1365         if (namespace)
1366                 iks_delete(namespace);
1367         if (invite)
1368                 iks_delete(invite);
1369         return res;
1370 }
1371
1372
1373 /*!
1374  * \brief receive message loop.
1375  * \param aji_client struct.
1376  * \return void.
1377  */
1378 static void *aji_recv_loop(void *data)
1379 {
1380         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1381         int res = IKS_HOOK;
1382         do {
1383                 if (res != IKS_OK) {
1384                         while(res != IKS_OK) {
1385                                 if(option_verbose > 3)
1386                                         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         } while (client);
1404         ASTOBJ_UNREF(client, aji_client_destroy);
1405         return 0;
1406 }
1407
1408 /*!
1409  * \brief increments the mid field for messages and other events.
1410  * \param message id.
1411  * \return void.
1412  */
1413 void ast_aji_increment_mid(char *mid)
1414 {
1415         int i = 0;
1416
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 = iks_make_iq(IKS_TYPE_GET, "jabber:iq:register");
1438
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
1475         iks *regiq = iks_new("iq");
1476         iks *regquery = iks_new("query");
1477         iks *reguser = iks_new("username");
1478         iks *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         if (regiq)
1502                 iks_delete(regiq);
1503         if (regquery)
1504                 iks_delete(regquery);
1505         if (reguser)
1506                 iks_delete(reguser);
1507         if (regpass)
1508                 iks_delete(regpass);
1509         ASTOBJ_UNREF(client, aji_client_destroy);
1510         return IKS_FILTER_EAT;
1511 }
1512
1513 /*!
1514  * \brief goes through roster and prunes users not needed in list, or adds them accordingly.
1515  * \param aji_client struct.
1516  * \return void.
1517  */
1518 static void aji_pruneregister(struct aji_client *client)
1519 {
1520         int res = 0;
1521         iks *removeiq = iks_new("iq");
1522         iks *removequery = iks_new("query");
1523         iks *removeitem = iks_new("item");
1524         iks *send = iks_make_iq(IKS_TYPE_GET, "http://jabber.org/protocol/disco#items");
1525
1526         if (client && removeiq && removequery && removeitem && send) {
1527                 iks_insert_node(removeiq, removequery);
1528                 iks_insert_node(removequery, removeitem);
1529                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1530                         ASTOBJ_RDLOCK(iterator);
1531                         /* For an aji_buddy, both AUTOPRUNE and AUTOREGISTER will never
1532                          * be called at the same time */
1533                         if (ast_test_flag(iterator, AJI_AUTOPRUNE)) {
1534                                 res = iks_send(client->p, iks_make_s10n(IKS_TYPE_UNSUBSCRIBE, iterator->name,
1535                                                 "GoodBye your status is no longer needed by Asterisk the Open Source PBX"
1536                                                 " so I am no longer subscribing to your presence.\n"));
1537                                 res = iks_send(client->p, iks_make_s10n(IKS_TYPE_UNSUBSCRIBED, iterator->name,
1538                                                 "GoodBye you are no longer in the asterisk config file so I am removing"
1539                                                 " your access to my presence.\n"));
1540                                 iks_insert_attrib(removeiq, "from", client->jid->full); 
1541                                 iks_insert_attrib(removeiq, "type", "set"); 
1542                                 iks_insert_attrib(removequery, "xmlns", "jabber:iq:roster");
1543                                 iks_insert_attrib(removeitem, "jid", iterator->name);
1544                                 iks_insert_attrib(removeitem, "subscription", "remove");
1545                                 res = iks_send(client->p, removeiq);
1546                         } else if (ast_test_flag(iterator, AJI_AUTOREGISTER)) {
1547                                 if (iterator->btype == AJI_USER) {      /*if it is not a transport */
1548                                         res = iks_send(client->p, iks_make_s10n(IKS_TYPE_SUBSCRIBE, iterator->name, 
1549                                                         "Greetings I am the Asterisk Open Source PBX and I want to subscribe to your presence\n"));
1550                                 } else {
1551                                         iks_filter_add_rule(client->f, aji_register_transport, client,
1552                                                                   IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_SUBTYPE, IKS_TYPE_RESULT, IKS_RULE_NS,
1553                                                                   "http://jabber.org/protocol/disco#items", IKS_RULE_DONE);
1554                                         iks_insert_attrib(send, "to", iterator->host);
1555                                         iks_insert_attrib(send, "from", client->jid->full);
1556                                         res = iks_send(client->p, send);
1557                                 }
1558                                 ast_clear_flag(iterator, AJI_AUTOREGISTER);
1559                         }
1560                         ASTOBJ_UNLOCK(iterator);
1561                 });
1562         } else
1563                 ast_log(LOG_ERROR, "Out of memory.\n");
1564         if (removeiq)
1565                 iks_delete(removeiq);
1566         if (removequery)
1567                 iks_delete(removequery);
1568         if (removeitem)
1569                 iks_delete(removeitem);
1570         if (send)
1571                 iks_delete(send);
1572         ASTOBJ_CONTAINER_PRUNE_MARKED(&client->buddies, aji_buddy_destroy);
1573 }
1574
1575 /*!
1576  * \brief filters the roster packet we get back from server.
1577  * \param aji_client struct, and xml packet.
1578  * \return IKS_FILTER_EAT.
1579  */
1580 static int aji_filter_roster(void *data, ikspak *pak)
1581 {
1582         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1583         int flag = 0;
1584         iks *x = NULL;
1585         struct aji_buddy *buddy;
1586         
1587         client->state = AJI_CONNECTED;
1588         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1589                 ASTOBJ_RDLOCK(iterator);
1590                 x = iks_child(pak->query);
1591                 flag = 0;
1592                 while (x) {
1593                         if (!iks_strcmp(iks_name(x), "item")) {
1594                                 if (!ast_strlen_zero(iterator->pass)) {
1595                                         if (!strcasecmp(iterator->host, iks_find_attrib(x, "jid"))) {
1596                                                   ast_clear_flag(iterator, AJI_AUTOPRUNE | AJI_AUTOREGISTER); 
1597                                                   flag = 1;
1598                                         }
1599                                 } else {
1600                                         if (!strcasecmp(iterator->name, iks_find_attrib(x, "jid"))) {
1601                                                   flag = 1;
1602                                                   ast_clear_flag(iterator, AJI_AUTOPRUNE | AJI_AUTOREGISTER);
1603                                         }
1604                                 }
1605                         }
1606                         x = iks_next(x);
1607                 }
1608                 if (!flag)
1609                         ast_copy_flags(iterator, client, AJI_AUTOREGISTER);
1610                 if (x)
1611                         iks_delete(x);
1612                 ASTOBJ_UNLOCK(iterator);
1613         });
1614
1615         x = iks_child(pak->query);
1616         while (x) {
1617                 flag = 0;
1618                 if (iks_strcmp(iks_name(x), "item") == 0) {
1619                         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1620                                 ASTOBJ_RDLOCK(iterator);
1621                                 if (!ast_strlen_zero(iterator->pass)) {
1622                                         if (!strcasecmp(iterator->host, iks_find_attrib(x, "jid")))
1623                                         flag = 1;
1624                                 } else {
1625                                         if (!strcasecmp(iterator->name, iks_find_attrib(x, "jid")))
1626                                                 flag = 1;
1627                                 }
1628                                 ASTOBJ_UNLOCK(iterator);
1629                         });
1630
1631                         if (!flag) {
1632                                 buddy = (struct aji_buddy *) malloc(sizeof(struct aji_buddy));
1633                                 if (!buddy) {
1634                                         ast_log(LOG_WARNING, "Out of memory\n");
1635                                         return 0;
1636                                 }
1637                                 memset(buddy, 0, sizeof(struct aji_buddy));
1638                                 ASTOBJ_INIT(buddy);
1639                                 ASTOBJ_WRLOCK(buddy);
1640                                 ast_copy_string(buddy->name, iks_find_attrib(x, "jid"), sizeof(buddy->name));
1641                                 ast_clear_flag(buddy, AST_FLAGS_ALL);
1642                                 if(ast_test_flag(client, AJI_AUTOPRUNE)) {
1643                                         ast_set_flag(buddy, AJI_AUTOPRUNE);
1644                                         buddy->objflags |= ASTOBJ_FLAG_MARKED;
1645                                 } else
1646                                         ast_set_flag(buddy, AJI_AUTOREGISTER);
1647                                 ASTOBJ_UNLOCK(buddy);
1648                                 if (buddy) {
1649                                         ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
1650                                         ASTOBJ_UNREF(buddy, aji_buddy_destroy);
1651                                 }
1652                         }
1653                 }
1654                 x = iks_next(x);
1655         }
1656         if (x)
1657                 iks_delete(x);
1658         aji_pruneregister(client);
1659
1660         ASTOBJ_UNREF(client, aji_client_destroy);
1661         return IKS_FILTER_EAT;
1662 }
1663
1664 static int aji_reconnect(struct aji_client *client)
1665 {
1666         int res = 0;
1667
1668         if (client->state)
1669                 client->state = AJI_DISCONNECTED;
1670         client->timeout=20;
1671         if (client->p)
1672                 iks_parser_reset(client->p);
1673         if (client->authorized)
1674                 client->authorized = 0;
1675
1676         switch (client->component) {
1677         case AJI_COMPONENT:
1678                 res = aji_component_initialize(client);
1679                 break;
1680         case AJI_CLIENT:
1681                 res = aji_client_initialize(client);
1682                 break;
1683         }
1684         return res;
1685 }
1686
1687 static int aji_get_roster(struct aji_client *client)
1688 {
1689         iks *roster = NULL;
1690         roster = iks_make_iq(IKS_TYPE_GET, IKS_NS_ROSTER);
1691         if(roster) {
1692                 iks_insert_attrib(roster, "id", "roster");
1693                 aji_set_presence(client, client->jid->full, 1, client->statusmessage);
1694                 iks_send(client->p, roster);
1695         }
1696         if (roster)
1697                 iks_delete(roster);
1698         return 1;
1699 }
1700
1701 /*!
1702  * \brief connects as a client to jabber server.
1703  * \param aji_client struct, and xml packet.
1704  * \return res.
1705  */
1706 static int aji_client_connect(void *data, ikspak *pak)
1707 {
1708         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1709         int res = 0;
1710
1711         if (client) {
1712                 if (client->state == AJI_DISCONNECTED) {
1713                         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);
1714                         client->state = AJI_CONNECTING;
1715                         client->jid = (iks_find_cdata(pak->query, "jid")) ? iks_id_new(client->stack, iks_find_cdata(pak->query, "jid")) : client->jid;
1716                         iks_filter_remove_hook(client->f, aji_client_connect);
1717                         if(client->component == AJI_CLIENT)
1718                                 aji_get_roster(client);
1719                 }
1720         } else
1721                 ast_log(LOG_ERROR, "Out of memory.\n");
1722
1723         ASTOBJ_UNREF(client, aji_client_destroy);
1724         return res;
1725 }
1726
1727 /*!
1728  * \brief prepares client for connect.
1729  * \param aji_client struct.
1730  * \return 1.
1731  */
1732 static int aji_client_initialize(struct aji_client *client)
1733 {
1734         int connected = 0;
1735
1736         connected = iks_connect_via(client->p, S_OR(client->serverhost, client->jid->server), client->port, client->jid->server);
1737
1738         if (connected == IKS_NET_NOCONN) {
1739                 ast_log(LOG_ERROR, "JABBER ERROR: No Connection\n");
1740                 return IKS_HOOK;
1741         } else  if (connected == IKS_NET_NODNS) {
1742                 ast_log(LOG_ERROR, "JABBER ERROR: No DNS %s for client to  %s\n", client->name, S_OR(client->serverhost, client->jid->server));
1743                 return IKS_HOOK;
1744         } else
1745                 iks_recv(client->p, 30);
1746         return IKS_OK;
1747 }
1748
1749 /*!
1750  * \brief prepares component for connect.
1751  * \param aji_client struct.
1752  * \return 1.
1753  */
1754 static int aji_component_initialize(struct aji_client *client)
1755 {
1756         int connected = 1;
1757         connected = iks_connect_via(client->p, client->jid->server, client->port, client->user);
1758         if (connected == IKS_NET_NOCONN)
1759                 ast_log(LOG_ERROR, "JABBER ERROR: No Connection\n");
1760         else if (connected == IKS_NET_NODNS)
1761                 ast_log(LOG_ERROR, "JABBER ERROR: No DNS\n");
1762         else if (!connected)
1763                 iks_recv(client->p, 30);
1764         return 1;
1765 }
1766
1767 /*!
1768  * \brief disconnect from jabber server.
1769  * \param aji_client struct.
1770  * \return 1.
1771  */
1772 int ast_aji_disconnect(struct aji_client *client)
1773 {
1774         if (client) {
1775                 if (option_verbose > 3)
1776                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: Disconnecting\n");
1777                 iks_disconnect(client->p);
1778                 iks_parser_delete(client->p);
1779                 ASTOBJ_UNREF(client, aji_client_destroy);
1780         }
1781
1782         return 1;
1783 }
1784
1785 /*!
1786  * \brief set presence of client.
1787  * \param aji_client struct, user to send it to, level, description.
1788  * \return void.
1789  */
1790 static void aji_set_presence(struct aji_client *client, char *user, int level, char *desc)
1791 {
1792         int res = 0;
1793         iks *presence = iks_make_pres(level, desc);
1794         iks *cnode = iks_new("c");
1795         iks *priority = iks_new("priority");
1796
1797         iks_insert_cdata(priority, "0", 1);
1798         if (presence && cnode && client) {
1799                 iks_insert_attrib(cnode, "node", "http://www.asterisk.org/xmpp/client/caps");
1800                 iks_insert_attrib(cnode, "ver", "asterisk-xmpp");
1801                 iks_insert_attrib(cnode, "ext", "voice-v1");
1802                 iks_insert_attrib(cnode, "xmlns", "http://jabber.org/protocol/caps");
1803                 iks_insert_node(presence, cnode);
1804                 res = iks_send(client->p, presence);
1805         } else
1806                 ast_log(LOG_ERROR, "Out of memory.\n");
1807         if (cnode)
1808                 iks_delete(cnode);
1809         if (presence)
1810                 iks_delete(presence);
1811 }
1812
1813 /*!
1814  * \brief turnon console debugging.
1815  * \param fd, number of args, args.
1816  * \return RESULT_SUCCESS.
1817  */
1818 static int aji_do_debug(int fd, int argc, char *argv[])
1819 {
1820         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
1821                 ASTOBJ_RDLOCK(iterator); 
1822                 iterator->debug = 1;
1823                 ASTOBJ_UNLOCK(iterator);
1824         });
1825         ast_cli(fd, "Jabber Debugging Enabled.\n");
1826         return RESULT_SUCCESS;
1827 }
1828
1829 /*!
1830  * \brief reload jabber module.
1831  * \param fd, number of args, args.
1832  * \return RESULT_SUCCESS.
1833  */
1834 static int aji_do_reload(int fd, int argc, char *argv[])
1835 {
1836         aji_reload();
1837         ast_cli(fd, "Jabber Reloaded.\n");
1838         return RESULT_SUCCESS;
1839 }
1840
1841 /*!
1842  * \brief turnoff console debugging.
1843  * \param fd, number of args, args.
1844  * \return RESULT_SUCCESS.
1845  */
1846 static int aji_no_debug(int fd, int argc, char *argv[])
1847 {
1848         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
1849                 ASTOBJ_RDLOCK(iterator);
1850                 iterator->debug = 0;
1851                 ASTOBJ_UNLOCK(iterator);
1852         });
1853         ast_cli(fd, "Jabber Debugging Disabled.\n");
1854         return RESULT_SUCCESS;
1855 }
1856
1857 /*!
1858  * \brief show client status.
1859  * \param fd, number of args, args.
1860  * \return RESULT_SUCCESS.
1861  */
1862 static int aji_show_clients(int fd, int argc, char *argv[])
1863 {
1864         char *status;
1865         int count = 0;
1866         ast_cli(fd, "Jabber Users and their status:\n");
1867         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
1868                 ASTOBJ_RDLOCK(iterator);
1869                 count++;
1870                 switch (iterator->state) {
1871                 case AJI_DISCONNECTED:
1872                         status = "Disconnected";
1873                         break;
1874                 case AJI_CONNECTING:
1875                         status = "Connecting";
1876                         break;
1877                 case AJI_CONNECTED:
1878                         status = "Connected";
1879                         break;
1880                 default:
1881                         status = "Unknown";
1882                 }
1883                 ast_cli(fd, "       User: %s     - %s\n", iterator->user, status);
1884                 ASTOBJ_UNLOCK(iterator);
1885         });
1886         ast_cli(fd, "----\n");
1887         ast_cli(fd, "   Number of users: %d\n", count);
1888         return RESULT_SUCCESS;
1889 }
1890
1891 /*!
1892  * \brief send test message for debugging.
1893  * \param fd, number of args, args.
1894  * \return RESULT_SUCCESS.
1895  */
1896 static int aji_test(int fd, int argc, char *argv[])
1897 {
1898         struct aji_client *client;
1899         struct aji_resource *resource;
1900         const char *name = "asterisk";
1901         struct aji_message *tmp;
1902
1903         if (argc > 3)
1904                 return RESULT_SHOWUSAGE;
1905         else if (argc == 3)
1906                 name = argv[2];
1907
1908         if (!(client = ASTOBJ_CONTAINER_FIND(&clients, name))) {
1909                 ast_cli(fd, "Unable to find client '%s'!\n", name);
1910                 return RESULT_FAILURE;
1911         }
1912
1913         /* XXX Does Matt really want everyone to use his personal address for tests? */ /* XXX yes he does */
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
1953         client = ASTOBJ_CONTAINER_FIND(&clients,label);
1954         if (!client) {
1955                 flag = 1;
1956                 client = (struct aji_client *) malloc(sizeof(struct aji_client));
1957                 if (!client) {
1958                         ast_log(LOG_ERROR, "Out of memory!\n");
1959                         return 0;
1960                 }
1961                 memset(client, 0, sizeof(struct aji_client));
1962                 ASTOBJ_INIT(client);
1963                 ASTOBJ_WRLOCK(client);
1964                 ASTOBJ_CONTAINER_INIT(&client->buddies);
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) {
1987                 client->authorized = 0;
1988                 client->state = AJI_DISCONNECTED;
1989         }
1990         while (var) {
1991                 if (!strcasecmp(var->name, "username"))
1992                         ast_copy_string(client->user, var->value, sizeof(client->user));
1993                 else if (!strcasecmp(var->name, "serverhost"))
1994                         ast_copy_string(client->serverhost, var->value, sizeof(client->serverhost));
1995                 else if (!strcasecmp(var->name, "secret"))
1996                         ast_copy_string(client->password, var->value, sizeof(client->password));
1997                 else if (!strcasecmp(var->name, "statusmessage"))
1998                         ast_copy_string(client->statusmessage, var->value, sizeof(client->statusmessage));
1999                 else if (!strcasecmp(var->name, "port"))
2000                         client->port = atoi(var->value);
2001                 else if (!strcasecmp(var->name, "timeout"))
2002                         client->message_timeout = atoi(var->value);
2003                 else if (!strcasecmp(var->name, "debug"))
2004                         client->debug = (ast_false(var->value)) ? 0 : 1;
2005                 else if (!strcasecmp(var->name, "type")) {
2006                         if (!strcasecmp(var->value, "component"))
2007                                 client->component = AJI_COMPONENT;
2008                 } else if (!strcasecmp(var->name, "usetls")) {
2009                         client->usetls = (ast_false(var->value)) ? 0 : 1;
2010                 } else if (!strcasecmp(var->name, "usesasl")) {
2011                         client->usesasl = (ast_false(var->value)) ? 0 : 1;
2012                 } else if (!strcasecmp(var->name, "forceoldssl"))
2013                         client->forcessl = (ast_false(var->value)) ? 0 : 1;
2014                 else if (!strcasecmp(var->name, "keepalive"))
2015                         client->keepalive = (ast_false(var->value)) ? 0 : 1;
2016                 else if (!strcasecmp(var->name, "autoprune"))
2017                         ast_set2_flag(client, ast_true(var->value), AJI_AUTOPRUNE);
2018                 else if (!strcasecmp(var->name, "autoregister"))
2019                         ast_set2_flag(client, ast_true(var->value), AJI_AUTOREGISTER);
2020                 else if (!strcasecmp(var->name, "buddy"))
2021                                 aji_create_buddy(var->value, client);
2022                 else if (!strcasecmp(var->name, "transport"))
2023                                 aji_create_transport(var->value, client);
2024                 var = var->next;
2025         }
2026         if (!flag) {
2027                 ASTOBJ_UNLOCK(client);
2028                 ASTOBJ_UNREF(client, aji_client_destroy);
2029                 return 1;
2030         }
2031         client->p = iks_stream_new(((client->component == AJI_CLIENT) ? "jabber:client" : "jabber:component:accept"), client, aji_act_hook);
2032         if (!client->p) {
2033                 ast_log(LOG_ERROR, "Failed to create stream for client '%s'!\n", client->name);
2034                 return 0;
2035         }
2036         client->stack = iks_stack_new(8192, 8192);
2037         if (!client->stack) {
2038                 ast_log(LOG_ERROR, "Failed to allocate stack for client '%s'\n", client->name);
2039                 return 0;
2040         }
2041         client->f = iks_filter_new();
2042         if (!client->f) {
2043                 ast_log(LOG_ERROR, "Failed to create filter for client '%s'\n", client->name);
2044                 return 0;
2045         }
2046         if (!strchr(client->user, '/') && client->component == AJI_CLIENT) {
2047                 resource = NULL;
2048                 asprintf(&resource, "%s/asterisk", client->user);
2049                 if (resource) {
2050                         client->jid = iks_id_new(client->stack, resource);
2051                         free(resource);
2052                 }
2053         } else
2054                 client->jid = iks_id_new(client->stack, client->user);
2055         if (client->component == AJI_COMPONENT) {
2056                 iks_filter_add_rule(client->f, aji_dinfo_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
2057                 iks_filter_add_rule(client->f, aji_ditems_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#items", IKS_RULE_DONE);
2058                 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);
2059                 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);
2060         } else {
2061                 iks_filter_add_rule(client->f, aji_client_info_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
2062         }
2063         if (!strchr(client->user, '/') && client->component == AJI_CLIENT) {
2064                 resource = NULL;
2065                 asprintf(&resource, "%s/asterisk", client->user);
2066                 if (resource) {
2067                         client->jid = iks_id_new(client->stack, resource);
2068                         free(resource);
2069                 }
2070         } else
2071                 client->jid = iks_id_new(client->stack, client->user);
2072         iks_set_log_hook(client->p, aji_log_hook);
2073         ASTOBJ_UNLOCK(client);
2074         ASTOBJ_CONTAINER_LINK(&clients,client);
2075         return 1;
2076 }
2077
2078 /*!
2079  * \brief creates transport.
2080  * \param label, buddy to dump it into. 
2081  * \return 0.
2082  */
2083 static int aji_create_transport(char *label, struct aji_client *client)
2084 {
2085         char *server = NULL, *buddyname = NULL, *user = NULL, *pass = NULL;
2086         struct aji_buddy *buddy = NULL;
2087
2088         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies,label);
2089         if (!buddy) {
2090                 buddy = malloc(sizeof(struct aji_buddy));
2091                 if(!buddy) {
2092                         ast_log(LOG_WARNING, "Out of memory\n");
2093                         return 0;
2094                 }
2095                 memset(buddy, 0, sizeof(struct aji_buddy));
2096                 ASTOBJ_INIT(buddy);
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                 }
2144                 memset(buddy, 0, sizeof(struct aji_buddy));
2145                 ASTOBJ_INIT(buddy);
2146         }
2147         ASTOBJ_WRLOCK(buddy);
2148         ast_copy_string(buddy->name, label, sizeof(buddy->name));
2149         ASTOBJ_UNLOCK(buddy);
2150         if(flag)
2151                 ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
2152         else {
2153                 ASTOBJ_UNMARK(buddy);
2154                 ASTOBJ_UNREF(buddy, aji_buddy_destroy);
2155         }
2156         return 1;
2157 }
2158
2159 /*!
2160  * \brief load config file.
2161  * \param void. 
2162  * \return 1.
2163  */
2164 static int aji_load_config(void)
2165 {
2166         char *cat = NULL;
2167         int debug = 1;
2168         struct ast_config *cfg = NULL;
2169         struct ast_variable *var = NULL;
2170
2171         cfg = ast_config_load(JABBER_CONFIG);
2172         if (!cfg) {
2173                 ast_log(LOG_WARNING, "No such configuration file %s\n", JABBER_CONFIG);
2174                 return 0;
2175         }
2176
2177         cat = ast_category_browse(cfg, NULL);
2178         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
2179                 if (!strcasecmp(var->name, "debug"))
2180                         debug = (ast_false(ast_variable_retrieve(cfg, "general", "debug"))) ? 0 : 1;
2181                 else if (!strcasecmp(var->name, "autoprune"))
2182                         ast_set2_flag(&globalflags, ast_true(var->value), AJI_AUTOPRUNE);
2183                 else if (!strcasecmp(var->name, "autoregister"))
2184                         ast_set2_flag(&globalflags, ast_true(var->value), AJI_AUTOREGISTER);
2185         }
2186
2187         while (cat) {
2188                 if (strcasecmp(cat, "general")) {
2189                                 var = ast_variable_browse(cfg, cat);
2190                                 aji_create_client(cat, var, debug);
2191                 }
2192                 cat = ast_category_browse(cfg, cat);
2193         }
2194         return 1;
2195 }
2196
2197 /*!
2198  * \brief grab a aji_client structure by label name.
2199  * \param void. 
2200  * \return 1.
2201  */
2202 struct aji_client *ast_aji_get_client(char *name)
2203 {
2204         struct aji_client *client = NULL;
2205
2206         client = ASTOBJ_CONTAINER_FIND(&clients, name);
2207         if (!client && !strchr(name, '@'))
2208                 client = ASTOBJ_CONTAINER_FIND_FULL(&clients, name, user,,, strcasecmp);
2209         return client;
2210 }
2211
2212 struct aji_client_container *ast_aji_get_clients(void)
2213 {
2214         return &clients;
2215 }
2216
2217 static char mandescr_jabber_send[] =
2218 "Description: Sends a message to a Jabber Client.\n"
2219 "Variables: \n"
2220 "  Jabber:      Client or transport Asterisk uses to connect to JABBER.\n"
2221 "  ScreenName:  User Name to message.\n"
2222 "  Message:     Message to be sent to the buddy\n";
2223
2224 /*! \brief  Send a Jabber Message via call from the Manager */
2225 static int manager_jabber_send( struct mansession *s, struct message *m )
2226 {
2227         struct aji_client *client = NULL;
2228         char *id = astman_get_header(m,"ActionID");
2229         char *jabber = astman_get_header(m,"Jabber");
2230         char *screenname = astman_get_header(m,"ScreenName");
2231         char *message = astman_get_header(m,"Message");
2232
2233         if (ast_strlen_zero(jabber)) {
2234                 astman_send_error(s, m, "No transport specified");
2235                 return 0;
2236         }
2237         if (ast_strlen_zero(screenname)) {
2238                 astman_send_error(s, m, "No ScreenName specified");
2239                 return 0;
2240         }
2241         if (ast_strlen_zero(message)) {
2242                 astman_send_error(s, m, "No Message specified");
2243                 return 0;
2244         }
2245
2246         astman_send_ack(s, m, "Attempting to send Jabber Message");
2247         client = ast_aji_get_client(jabber);
2248         if (!client) {
2249                 astman_send_error(s, m, "Could not find Sender");
2250                 return 0;
2251         }       
2252         if (strchr(screenname, '@') && message){
2253                 ast_aji_send(client, screenname, message);      
2254                 if (!ast_strlen_zero(id))
2255                         astman_append(s, "ActionID: %s\r\n",id);
2256                 astman_append(s, "Response: Success\r\n");
2257                 return 0;
2258         }
2259         if (!ast_strlen_zero(id))
2260                 astman_append(s, "ActionID: %s\r\n",id);
2261         astman_append(s, "Response: Failure\r\n");
2262         return 0;
2263 }
2264
2265
2266 static int aji_reload()
2267 {
2268         ASTOBJ_CONTAINER_MARKALL(&clients);
2269         if (!aji_load_config()) {
2270                 ast_log(LOG_ERROR, "JABBER: Failed to load config.\n");
2271                 return 0;
2272         }
2273         ASTOBJ_CONTAINER_PRUNE_MARKED(&clients, aji_client_destroy);
2274         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2275                 ASTOBJ_RDLOCK(iterator);
2276                 if(iterator->state == AJI_DISCONNECTED) {
2277                         if (!iterator->thread)
2278                                 ast_pthread_create(&iterator->thread, NULL, aji_recv_loop, iterator);
2279                 } else if (iterator->state == AJI_CONNECTING)
2280                         aji_get_roster(iterator);
2281                 ASTOBJ_UNLOCK(iterator);
2282         });
2283         
2284         return 1;
2285 }
2286
2287 static int unload_module(void)
2288 {
2289         ast_cli_unregister_multiple(aji_cli, sizeof(aji_cli) / sizeof(aji_cli[0]));
2290         ast_unregister_application(app_ajisend);
2291         ast_manager_unregister("JabberSend");
2292         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2293                 ASTOBJ_RDLOCK(iterator);
2294                 if (option_verbose > 2)
2295                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: %s\n", iterator->name);
2296                 iterator->state = AJI_DISCONNECTED;
2297                 ast_aji_disconnect(iterator);
2298                 pthread_join(iterator->thread, NULL);
2299                 ASTOBJ_UNLOCK(iterator);
2300         });
2301
2302         ASTOBJ_CONTAINER_DESTROYALL(&clients, aji_client_destroy);
2303         ASTOBJ_CONTAINER_DESTROY(&clients);
2304
2305         ast_log(LOG_NOTICE, "res_jabber unloaded.\n");
2306         return 0;
2307 }
2308
2309 static int load_module(void)
2310 {
2311         ASTOBJ_CONTAINER_INIT(&clients);
2312         if(!aji_reload())
2313                 return AST_MODULE_LOAD_DECLINE;
2314         ast_manager_register2("JabberSend", EVENT_FLAG_SYSTEM, manager_jabber_send,
2315                         "Sends a message to a Jabber Client", mandescr_jabber_send);
2316         ast_register_application(app_ajisend, aji_send_exec, ajisend_synopsis, ajisend_descrip);
2317         ast_register_application(app_ajistatus, aji_status_exec, ajistatus_synopsis, ajistatus_descrip);
2318         ast_cli_register_multiple(aji_cli, sizeof(aji_cli) / sizeof(aji_cli[0]));
2319
2320         ast_log(LOG_NOTICE, "res_jabber.so loaded.\n");
2321         return 0;
2322 }
2323
2324 static int reload(void)
2325 {
2326         aji_reload();
2327         return 0;
2328 }
2329
2330 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "AJI - Asterisk Jabber Interface",
2331                 .load = load_module,
2332                 .unload = unload_module,
2333                 .reload = reload,
2334                );