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