fixes bug where server goes away.
[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         resource = strsep(&screenname, "/");
329
330         client = ast_aji_get_client(sender);
331         if (!client) {
332                 ast_log(LOG_WARNING, "Could not find Connection.\n");
333                 return -1;
334         }
335
336         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
337                 ASTOBJ_RDLOCK(iterator); 
338                 if (!strcasecmp(iterator->user, screenname)) {
339                         found = 1; 
340                         r = iterator->resources; 
341                         if (!r) {       /* client hasnt signed on */
342                                 break;
343                         } else {
344                                 if (resource) {
345                                         while (r) {
346                                                 if (!strcasecmp(r->resource, resource)) {
347                                                         stat = r->status; 
348                                                         break;
349                                                 }
350                                                 r = r->next;
351                                         }
352                                         ast_log(LOG_WARNING, "Resource not found %s\n", resource);
353                                 } else {
354                                         stat = r->status; 
355                                         break;
356                                 }
357                         }
358                 }
359         ASTOBJ_UNLOCK(iterator);
360         });
361
362         if (!found) {                           /* just a label */
363                 ast_log(LOG_WARNING, "Could not find Buddy in list.\n");
364                 return -1;
365         }
366         sprintf(status, "%d", stat);
367         pbx_builtin_setvar_helper(chan, variable, status);
368         return 0;
369 }
370
371 /*!
372  * \brief Dial plan function to send a message.
373  * \param channel, and data, data is sender, reciever, message.
374  * \return 0.
375  */
376 static int aji_send_exec(struct ast_channel *chan, void *data)
377 {
378         struct aji_client *client = NULL;
379
380         char *s = NULL, *sender = NULL, *recipiant = NULL, *message = NULL;
381         if (data) {
382                 s = ast_strdupa((char *) data);
383                 if (s) {
384                         sender = strsep(&s, "|");
385                         if (sender && (sender[0] != '\0')) {
386                                 recipiant = strsep(&s, "|");
387                                 if (recipiant && (recipiant[0] != '\0')) {
388                                         message = s;
389                                 } else {
390                                         ast_log(LOG_ERROR, "Bad arguments \n");
391                                         return -1;
392                                 }
393                         }
394                 }
395                 client = ast_aji_get_client(sender);
396                 if (!client) {
397                         ast_log(LOG_WARNING, "Could not find Sender.\n");
398                         return -1;
399                 }
400         } else {
401                 ast_log(LOG_ERROR, "Out of memory\n");
402                 return -1;
403         }
404         if (strchr(recipiant, '@') && message)
405                 ast_aji_send(client, recipiant, message);
406         return 0;
407 }
408
409 /*!
410  * \brief the debug loop.
411  * \param aji_client structure, xml data as string, size of string, direction of packet, 1 for inbound 0 for outbound.
412  */
413 static void aji_log_hook(void *data, const char *xmpp, size_t size, int is_incoming)
414 {
415         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
416         if (client->debug == 1) {
417                 if (is_incoming)
418                         ast_verbose("\nJABBER: %s INCOMING: %s\n", client->name, xmpp);
419                 else
420                         ast_verbose("\nJABBER: %s OUTGOING: %s\n", client->name, xmpp);
421
422         }
423         ASTOBJ_UNREF(client, aji_client_destroy);
424 }
425
426 /*!
427  * \brief The action hook parses the inbound packets, constantly running.
428  * \param aji client structure, type of packet, the actual packet.
429  * \return IKS_OK or IKS_HOOK .
430  */
431 static int aji_act_hook(void *data, int type, iks *node)
432 {
433         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
434         ikspak *pak = NULL;
435         iks *auth = NULL;
436
437         pak = iks_packet(node);
438
439         if (client->component == AJI_CLIENT) {
440                 switch (type) {
441                 case IKS_NODE_START:
442                         if (client->usetls && !iks_is_secure(client->p)) {
443                                 if (iks_has_tls())
444                                         iks_start_tls(client->p);
445                                 else
446                                         ast_log(LOG_ERROR, "gnuTLS not installed.\n");
447                                 break;
448                         }
449                         if (!client->usesasl) {
450                                 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);
451                                 auth = jabber_make_auth(client->jid, client->password, iks_find_attrib(node, "id"));
452                                 if (auth) {
453                                         iks_insert_attrib(auth, "id", client->mid);
454                                         iks_insert_attrib(auth, "to", client->jid->server);
455                                         ast_aji_increment_mid(client->mid);
456                                         iks_send(client->p, auth);
457                                         iks_delete(auth);
458                                 } else
459                                         ast_log(LOG_ERROR, "Out of memory.\n");
460                         }
461                         break;
462
463                 case IKS_NODE_NORMAL:
464                         {
465                                 int features = 0;
466                                 if (!strcmp("stream:features", iks_name(node))) {
467                                         features = iks_stream_features(node);
468                                         if (client->usesasl) {
469                                                 if (client->usetls && !iks_is_secure(client->p))
470                                                         break;
471                                                 if (client->authorized) {
472                                                         if (features & IKS_STREAM_BIND) {
473                                                                 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);
474                                                                 auth = iks_make_resource_bind(client->jid);
475                                                                 if (auth) {
476                                                                         iks_insert_attrib(auth, "id", client->mid);
477                                                                         ast_aji_increment_mid(client->mid);
478                                                                         iks_send(client->p, auth);
479                                                                         iks_delete(auth);
480                                                                 } else {
481                                                                         ast_log(LOG_ERROR, "Out of memory.\n");
482                                                                         break;
483                                                                 }
484                                                         }
485                                                         if (features & IKS_STREAM_SESSION) {
486                                                                 iks_filter_add_rule (client->f, aji_client_connect, client, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_SUBTYPE, IKS_TYPE_RESULT, IKS_RULE_ID, "auth", IKS_RULE_DONE);
487                                                                 auth = iks_make_session();
488                                                                 if (auth) {
489                                                                         iks_insert_attrib(auth, "id", "auth");
490                                                                         ast_aji_increment_mid(client->mid);
491                                                                         iks_send(client->p, auth);
492                                                                         iks_delete(auth);
493                                                                 } else {
494                                                                         ast_log(LOG_ERROR, "Out of memory.\n");
495                                                                 }
496                                                         }
497                                                 } else {
498                                                         features = aji_highest_bit(features);
499                                                         if (features == IKS_STREAM_SASL_MD5)
500                                                                 iks_start_sasl(client->p, IKS_SASL_DIGEST_MD5, client->jid->user, client->password);
501                                                         else {
502                                                                 if (features == IKS_STREAM_SASL_PLAIN) {
503                                                                         iks *x = NULL;
504                                                                         x = iks_new("auth");
505                                                                         if (x) {
506                                                                                 iks_insert_attrib(x, "xmlns", IKS_NS_XMPP_SASL);
507                                                                                 int len = strlen(client->jid->user) + strlen(client->password) + 3;
508                                                                                 /* XXX Check return values XXX */
509                                                                                 char *s = ast_malloc(80 + len);
510                                                                                 char *base64 = ast_malloc(80 + len * 2);
511                                                                                 iks_insert_attrib(x, "mechanism", "PLAIN");
512                                                                                 sprintf(s, "%c%s%c%s", 0, client->jid->user, 0, client->password);
513                                                                                 ast_base64encode(base64, s, len, len * 2);
514                                                                                 iks_insert_cdata(x, base64, 0);
515                                                                                 iks_send(client->p, x);
516                                                                                 iks_delete(x);
517                                                                                 if (base64)
518                                                                                         free(base64);
519                                                                                 if (s)
520                                                                                         free(s);
521                                                                         } else {
522                                                                                 ast_log(LOG_ERROR, "Out of memory.\n");
523                                                                         }
524                                                                 }
525                                                         }
526                                                 }
527                                         }
528                                 } else if (!strcmp("failure", iks_name(node))) {
529                                         ast_log(LOG_ERROR, "JABBER: encryption failure. possible bad password.\n");
530                                 } else if (!strcmp("success", iks_name(node))) {
531                                         client->authorized = 1;
532                                         iks_send_header(client->p, client->jid->server);
533                                 }
534                                 break;
535                         }
536                 case IKS_NODE_ERROR:{
537                                 ast_log(LOG_ERROR, "JABBER: Node Error\n");
538                                 ASTOBJ_UNREF(client, aji_client_destroy);
539                                 return IKS_HOOK;
540                                 break;
541                         }
542                 case IKS_NODE_STOP:{
543                                 ast_log(LOG_WARNING, "JABBER: Disconnected\n");
544                                 ASTOBJ_UNREF(client, aji_client_destroy);
545                                 return IKS_HOOK;
546                                 break;
547                         }
548                 }
549         } else if (client->state != AJI_CONNECTED && client->component == AJI_COMPONENT) {
550                 switch (type) {
551                 case IKS_NODE_START:{
552                                 char secret[160], shasum[320], *handshake;
553                                 switch (client->state) {
554                                 case AJI_DISCONNECTED:
555                                         sprintf(secret, "%s%s", pak->id, client->password);
556                                         ast_sha1_hash(shasum, secret);
557                                         handshake = NULL;
558                                         asprintf(&handshake, "<handshake>%s</handshake>", shasum);
559                                         if (handshake) {
560                                                 iks_send_raw(client->p, handshake);
561                                                 free(handshake);
562                                                 handshake = NULL;
563                                         }
564                                         client->state = AJI_CONNECTED;
565                                         break;
566                                 case AJI_ALMOST:
567                                         client->state = AJI_CONNECTED;
568                                         break;
569                                 case AJI_CONNECTING:
570                                 case AJI_CONNECTED:
571                                         break;
572                                 };
573                                 break;
574                         }
575
576                 case IKS_NODE_NORMAL:{
577                                 break;
578                         }
579
580                 case IKS_NODE_ERROR:{
581                                 ast_log(LOG_ERROR, "JABBER: Node Error\n");
582                                 ASTOBJ_UNREF(client, aji_client_destroy);
583                                 return IKS_HOOK;
584                                 break;
585                         }
586                 case IKS_NODE_STOP:{
587                                 ast_log(LOG_WARNING, "JABBER: Disconnected\n");
588                                 ASTOBJ_UNREF(client, aji_client_destroy);
589                                 return IKS_HOOK;
590                                 break;
591                         }
592                 }
593         }
594
595         switch (pak->type) {
596         case IKS_PAK_NONE:
597                 if (option_verbose > 30)
598                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I Don't know what to do with you NONE\n");
599                 break;
600         case IKS_PAK_MESSAGE:
601                 if (option_verbose > 30)
602                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I Don't know what to do with you MESSAGE\n");
603                 break;
604         case IKS_PAK_PRESENCE:
605                 aji_handle_presence(client, pak);
606                 if (option_verbose > 30)
607                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I Do know how to handle presence!!\n");
608                 break;
609         case IKS_PAK_S10N:
610                 aji_handle_subscribe(client, pak);
611                 if (option_verbose > 30)
612                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I Dont know S10N subscribe!!\n");
613                 break;
614         case IKS_PAK_IQ:
615                 if (option_verbose > 30)
616                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I Dont have an IQ!!!\n");
617                 aji_handle_iq(client, node);
618                 break;
619         default:
620                 if (option_verbose > 30)
621                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I Dont know %i\n", pak->type);
622                 break;
623         }
624
625         iks_filter_packet(client->f, pak);
626
627         if (node)
628                 iks_delete(node);
629
630         ASTOBJ_UNREF(client, aji_client_destroy);
631         return IKS_OK;
632 }
633
634 static int aji_register_approve_handler(void *data, ikspak *pak)
635 {
636         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
637         iks *iq = NULL, *query = NULL, *item = NULL;
638
639         iq = iks_new("iq");
640         query = iks_new("query");
641         item = iks_new("item");
642
643         if (client && iq && query && item) {
644                 if (!iks_find(pak->query, "remove")) {
645                         iks_insert_attrib(iq, "from", client->jid->full);
646                         iks_insert_attrib(iq, "to", pak->from->full);
647                         iks_insert_attrib(iq, "id", pak->id);
648                         iks_insert_attrib(iq, "type", "result");
649                         iks_insert_attrib(query, "xmlns", "jabber:iq:register");
650
651                         iks_insert_node(iq, query);
652                         iks_send(client->p, iq);
653                         iks_insert_attrib(iq, "from", pak->from->full);
654                         iks_insert_attrib(iq, "to", pak->from->full);
655                         iks_insert_attrib(iq, "id", client->mid);
656                         ast_aji_increment_mid(client->mid);
657                         iks_insert_attrib(iq, "type", "set");
658                         iks_insert_attrib(query, "xmlns", "jabber:iq:roster");
659                         iks_insert_attrib(item, "subscription", "none");
660                         iks_insert_attrib(item, "jid", client->jid->full);
661                         iks_insert_node(query, item);
662                         iks_send(client->p, iq);
663                 }
664         } else {
665                 ast_log(LOG_ERROR, "Out of memory.\n");
666         }
667         if (iq)
668                 iks_delete(iq);
669         if (query)
670                 iks_delete(query);
671         if (item)
672                 iks_delete(item);
673         ASTOBJ_UNREF(client, aji_client_destroy);
674         return IKS_FILTER_EAT;
675 }
676
677 static int aji_register_query_handler(void *data, ikspak *pak)
678 {
679         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
680         char *node = NULL;
681
682         client = (struct aji_client *) data;
683
684         if (!(node = iks_find_attrib(pak->query, "node"))) {
685                 iks *iq = NULL, *query = NULL, *instructions = NULL;
686                 char *explain = "Welcome to Asterisk the Open Source PBX.\n";
687                 iq = iks_new("iq");
688                 query = iks_new("query");
689                 instructions = iks_new("instructions");
690                 if (iq && query && instructions && client) {
691                         iks_insert_attrib(iq, "from", client->user);
692                         iks_insert_attrib(iq, "to", pak->from->full);
693                         iks_insert_attrib(iq, "id", pak->id);
694                         iks_insert_attrib(iq, "type", "result");
695                         iks_insert_attrib(query, "xmlns", "jabber:iq:register");
696                         iks_insert_cdata(instructions, explain, 0);
697                         iks_insert_node(iq, query);
698                         iks_insert_node(query, instructions);
699                         iks_send(client->p, iq);
700                 } else {
701                         ast_log(LOG_ERROR, "Out of memory.\n");
702                 }
703                 if (iq)
704                         iks_delete(iq);
705                 if (query)
706                         iks_delete(query);
707                 if (instructions)
708                         iks_delete(instructions);
709         }
710         ASTOBJ_UNREF(client, aji_client_destroy);
711         return IKS_FILTER_EAT;
712 }
713
714 static int aji_ditems_handler(void *data, ikspak *pak)
715 {
716         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
717         char *node = NULL;
718
719         if (!(node = iks_find_attrib(pak->query, "node"))) {
720                 iks *iq = NULL, *query = NULL, *item = NULL;
721                 iq = iks_new("iq");
722                 query = iks_new("query");
723                 item = iks_new("item");
724
725                 if (iq && query && item) {
726                         iks_insert_attrib(iq, "from", client->user);
727                         iks_insert_attrib(iq, "to", pak->from->full);
728                         iks_insert_attrib(iq, "id", pak->id);
729                         iks_insert_attrib(iq, "type", "result");
730                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
731                         iks_insert_attrib(item, "node", "http://jabber.org/protocol/commands");
732                         iks_insert_attrib(item, "name", "Million Dollar Asterisk Commands");
733                         iks_insert_attrib(item, "jid", client->user);
734
735                         iks_insert_node(iq, query);
736                         iks_insert_node(query, item);
737                         iks_send(client->p, iq);
738                 } else {
739                         ast_log(LOG_ERROR, "Out of memory.\n");
740                 }
741                 if (iq)
742                         iks_delete(iq);
743                 if (query)
744                         iks_delete(query);
745                 if (item)
746                         iks_delete(item);
747
748         } else if (!strcasecmp(node, "http://jabber.org/protocol/commands")) {
749                 iks *iq, *query, *confirm;
750                 iq = iks_new("iq");
751                 query = iks_new("query");
752                 confirm = iks_new("item");
753                 if (iq && query && confirm && client) {
754                         iks_insert_attrib(iq, "from", client->user);
755                         iks_insert_attrib(iq, "to", pak->from->full);
756                         iks_insert_attrib(iq, "id", pak->id);
757                         iks_insert_attrib(iq, "type", "result");
758                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
759                         iks_insert_attrib(query, "node", "http://jabber.org/protocol/commands");
760                         iks_insert_attrib(confirm, "node", "confirmaccount");
761                         iks_insert_attrib(confirm, "name", "Confirm AIM account");
762                         iks_insert_attrib(confirm, "jid", "blog.astjab.org");
763
764                         iks_insert_node(iq, query);
765                         iks_insert_node(query, confirm);
766                         iks_send(client->p, iq);
767                 } else {
768                         ast_log(LOG_ERROR, "Out of memory.\n");
769                 }
770                 if (iq)
771                         iks_delete(iq);
772                 if (query)
773                         iks_delete(query);
774                 if (confirm)
775                         iks_delete(confirm);
776
777         } else if (!strcasecmp(node, "confirmaccount")) {
778                 iks *iq = NULL, *query = NULL, *feature = NULL;
779
780                 iq = iks_new("iq");
781                 query = iks_new("query");
782                 feature = iks_new("feature");
783
784                 if (iq && query && feature && client) {
785                         iks_insert_attrib(iq, "from", client->user);
786                         iks_insert_attrib(iq, "to", pak->from->full);
787                         iks_insert_attrib(iq, "id", pak->id);
788                         iks_insert_attrib(iq, "type", "result");
789                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
790                         iks_insert_attrib(feature, "var", "http://jabber.org/protocol/commands");
791                         iks_insert_node(iq, query);
792                         iks_insert_node(query, feature);
793                         iks_send(client->p, iq);
794                 } else {
795                         ast_log(LOG_ERROR, "Out of memory.\n");
796                 }
797                 if (iq)
798                         iks_delete(iq);
799                 if (query)
800                         iks_delete(query);
801                 if (feature)
802                         iks_delete(feature);
803         }
804
805         ASTOBJ_UNREF(client, aji_client_destroy);
806         return IKS_FILTER_EAT;
807
808 }
809
810 static int aji_client_info_handler(void *data, ikspak *pak)
811 {
812         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
813         struct aji_buddy *buddy = NULL;
814         struct aji_resource *resource = NULL;
815         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
816
817         resource = aji_find_resource(buddy, pak->from->resource);
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, disco);
845                         iks_insert_node(query, google);
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         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
1021         if (!buddy) {
1022                 ast_log(LOG_WARNING, "Got presence packet from %s, somone not in our roster!!!!\n", pak->from->partial);
1023                 return;
1024         }
1025         status = (pak->show) ? pak->show : 6;
1026         priority = atoi((iks_find_cdata(pak->x, "priority")) ? iks_find_cdata(pak->x, "priority") : "0");
1027         tmp = buddy->resources;
1028
1029         while (tmp) {
1030                 if (!strcasecmp(tmp->resource, pak->from->resource)) {
1031                         tmp->status = status;
1032                         found = tmp;
1033                         if (status == 6) {      /* Sign off Destroy resource */
1034                                 if (last && found->next) {
1035                                         last->next = found->next;
1036                                 } else if (!last) {
1037                                         if (found->next)
1038                                                 buddy->resources = found->next;
1039                                         else
1040                                                 buddy->resources = NULL;
1041                                 } else if (!found->next) {
1042                                         if (last)
1043                                                 last->next = NULL;
1044                                         else
1045                                                 buddy->resources = NULL;
1046                                 }
1047                                 free(found);
1048                                 found = NULL;
1049                                 break;
1050                         }
1051                         if (tmp->priority != priority) {
1052                                 found->priority = priority;
1053                                 if (!last && !found->next)
1054                                         break;
1055                                 if (last)
1056                                         last->next = found->next;
1057                                 else
1058                                         buddy->resources = found->next;
1059                                 last = NULL;
1060                                 tmp = buddy->resources;
1061                                 if (!buddy->resources)
1062                                         buddy->resources = found;
1063                                 while (tmp) {
1064                                         if (found->priority > tmp->priority) {
1065                                                 if (last)
1066                                                         last->next = found;
1067                                                 found->next = tmp;
1068                                                 if (!last)
1069                                                         buddy->resources = found;
1070                                                 break;
1071                                         }
1072                                         if (!tmp->next) {
1073                                                 tmp->next = found;
1074                                                 break;
1075                                         }
1076                                         last = tmp;
1077                                         tmp = tmp->next;
1078                                 }
1079                         }
1080                         break;
1081                 }
1082                 last = tmp;
1083                 tmp = tmp->next;
1084         }
1085
1086         if (!found && status != 6) {
1087                 found = (struct aji_resource *) malloc(sizeof(struct aji_resource));
1088                 if (!found) {
1089                         ast_log(LOG_ERROR, "Out of memory!\n");
1090                         return;
1091                 }
1092                 ast_copy_string(found->resource, pak->from->resource, sizeof(found->resource));
1093                 found->status = status;
1094                 found->priority = priority;
1095                 found->next = NULL;
1096                 last = NULL;
1097                 tmp = buddy->resources;
1098                 while (tmp) {
1099                         if (found->priority > tmp->priority) {
1100                                 if (last)
1101                                         last->next = found;
1102                                 found->next = tmp;
1103                                 if (!last)
1104                                         buddy->resources = found;
1105                                 break;
1106                         }
1107                         if (!tmp->next) {
1108                                 tmp->next = found;
1109                                 break;
1110                         }
1111                         last = tmp;
1112                         tmp = tmp->next;
1113                 }
1114                 if (!tmp)
1115                         buddy->resources = found;
1116         }
1117
1118         node = iks_find_attrib(iks_find(pak->x, "c"), "node");
1119         ver = iks_find_attrib(iks_find(pak->x, "c"), "ver");
1120
1121         if(status !=6 && !found->cap) {
1122                 found->cap = aji_find_version(node, ver, pak);
1123                 if(gtalk_yuck(pak->x)) /* gtalk should do discover */
1124                         found->cap->jingle = 1;
1125                 if(found->cap->jingle)
1126                         ast_log(LOG_DEBUG,"Special case for google till they support discover.\n");
1127                 else {
1128                         iks *iq, *query;
1129                         iq = iks_new("iq");
1130                         query = iks_new("query");
1131                         if(query && iq)  {
1132                                 iks_insert_attrib(iq, "type", "get");
1133                                 iks_insert_attrib(iq, "to", pak->from->full);
1134                                 iks_insert_attrib(iq, "id", client->mid);
1135                                 ast_aji_increment_mid(client->mid);
1136                                 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
1137                                 iks_insert_node(iq, query);
1138                                 iks_send(client->p, iq);
1139                                 
1140                         } else
1141                                 ast_log(LOG_ERROR, "Out of memory.\n");
1142                         if(query)
1143                                 iks_delete(query);
1144                         if(iq)
1145                                 iks_delete(iq);
1146                 }
1147         }
1148         if (option_verbose > 30) {
1149                 switch (pak->subtype) {
1150                 case IKS_TYPE_AVAILABLE:
1151                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I am available ^_* %i\n", pak->subtype);
1152                         break;
1153                 case IKS_TYPE_UNAVAILABLE:
1154                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I am unavailable ^_* %i\n", pak->subtype);
1155                         break;
1156                 default:
1157                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: Ohh sexy and the wrong type%i\n", pak->subtype);
1158                 }
1159                 switch (pak->show) {
1160                 case IKS_SHOW_UNAVAILABLE:
1161                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1162                         break;
1163                 case IKS_SHOW_AVAILABLE:
1164                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type is available\n");
1165                         break;
1166                 case IKS_SHOW_CHAT:
1167                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1168                         break;
1169                 case IKS_SHOW_AWAY:
1170                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type is away\n");
1171                         break;
1172                 case IKS_SHOW_XA:
1173                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1174                         break;
1175                 case IKS_SHOW_DND:
1176                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1177                         break;
1178                 default:
1179                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: Kinky! how did that happen %i\n", pak->show);
1180                 }
1181         }
1182 }
1183
1184 /*!
1185  * \brief handles subscription requests.
1186  * \param aji_client struct and xml packet.
1187  * \return void.
1188  */
1189 static void aji_handle_subscribe(struct aji_client *client, ikspak *pak)
1190 {
1191         if(pak->subtype == IKS_TYPE_SUBSCRIBE)
1192                 iks_send(client->p, iks_make_s10n(IKS_TYPE_SUBSCRIBED, iks_find_attrib(pak->x, "from"), "Asterisk has approved subscription"));
1193         if (option_verbose > 30) {
1194                 switch (pak->subtype) {
1195                 case IKS_TYPE_SUBSCRIBE:
1196                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1197                         break;
1198                 case IKS_TYPE_SUBSCRIBED:
1199                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1200                         break;
1201                 case IKS_TYPE_UNSUBSCRIBE:
1202                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1203                         break;
1204                 case IKS_TYPE_UNSUBSCRIBED:
1205                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1206                         break;
1207                 default:                                /*IKS_TYPE_ERROR: */
1208                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1209                         break;
1210                 }
1211         }
1212 }
1213
1214 /*!
1215  * \brief sends messages.
1216  * \param aji_client struct , reciever, message.
1217  * \return 1.
1218  */
1219 int ast_aji_send(struct aji_client *client, char *address, char *message)
1220 {
1221         int res = 0;
1222         iks *message_packet = NULL;
1223         if (client->state == AJI_CONNECTED) {
1224                 message_packet = iks_make_msg(IKS_TYPE_CHAT, address, message);
1225                 if (message_packet) {
1226                         iks_insert_attrib(message_packet, "from", client->jid->full);
1227                         res = iks_send(client->p, message_packet);
1228                 } else {
1229                         ast_log(LOG_ERROR, "Out of memory.\n");
1230                 }
1231                 if (message_packet)
1232                         iks_delete(message_packet);
1233         } else
1234                 ast_log(LOG_WARNING, "JABBER: Not connected can't send\n");
1235         return 1;
1236 }
1237
1238 /*!
1239  * \brief create a chatroom.
1240  * \param aji_client struct , room, server, topic for the room.
1241  * \return 0.
1242  */
1243 int ast_aji_create_chat(struct aji_client *client, char *room, char *server, char *topic)
1244 {
1245         int res = 0;
1246         iks *iq = NULL;
1247         iq = iks_new("iq");
1248         if (iq && client) {
1249                 iks_insert_attrib(iq, "type", "get");
1250                 iks_insert_attrib(iq, "to", server);
1251                 iks_insert_attrib(iq, "id", client->mid);
1252                 ast_aji_increment_mid(client->mid);
1253                 iks_send(client->p, iq);
1254         } else {
1255                 ast_log(LOG_ERROR, "Out of memory.\n");
1256         }
1257         return res;
1258 }
1259
1260 /*!
1261  * \brief join a chatroom.
1262  * \param aji_client struct , room.
1263  * \return res.
1264  */
1265 int ast_aji_join_chat(struct aji_client *client, char *room)
1266 {
1267         int res = 0;
1268         iks *presence = NULL, *priority = NULL;
1269         presence = iks_new("presence");
1270         priority = iks_new("priority");
1271         if (presence && priority && client) {
1272                 iks_insert_cdata(priority, "0", 1);
1273                 iks_insert_attrib(presence, "to", room);
1274                 iks_insert_node(presence, priority);
1275                 res = iks_send(client->p, presence);
1276                 iks_insert_cdata(priority, "5", 1);
1277                 iks_insert_attrib(presence, "to", room);
1278                 res = iks_send(client->p, presence);
1279         } else {
1280                 ast_log(LOG_ERROR, "Out of memory.\n");
1281         }
1282         if (presence)
1283                 iks_delete(presence);
1284         if (priority)
1285                 iks_delete(priority);
1286         return res;
1287 }
1288
1289 /*!
1290  * \brief invite to a chatroom.
1291  * \param aji_client struct ,user, room, message.
1292  * \return res.
1293  */
1294 int ast_aji_invite_chat(struct aji_client *client, char *user, char *room, char *message)
1295 {
1296         int res = 0;
1297         iks *invite = NULL, *body = NULL, *namespace = NULL;
1298         invite = iks_new("message");
1299         body = iks_new("body");
1300         namespace = iks_new("x");
1301         if (client && invite && body && namespace) {
1302                 iks_insert_attrib(invite, "to", user);
1303                 iks_insert_attrib(invite, "id", client->mid);
1304                 ast_aji_increment_mid(client->mid);
1305                 iks_insert_cdata(body, message, strlen(message));
1306                 iks_insert_attrib(namespace, "xmlns", "jabber:x:conference");
1307                 iks_insert_attrib(namespace, "jid", room);
1308                 iks_insert_node(invite, body);
1309                 iks_insert_node(invite, namespace);
1310                 res = iks_send(client->p, invite);
1311         } else {
1312                 ast_log(LOG_ERROR, "Out of memory.\n");
1313         }
1314         if (body)
1315                 iks_delete(body);
1316         if (namespace)
1317                 iks_delete(namespace);
1318         if (invite)
1319                 iks_delete(invite);
1320         return res;
1321 }
1322
1323
1324 /*!
1325  * \brief receive message loop.
1326  * \param aji_client struct.
1327  * \return void.
1328  */
1329 static void *aji_recv_loop(void *data)
1330 {
1331         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1332         int res = IKS_HOOK;
1333         do {
1334                 if (res != IKS_OK) {
1335                         while(res != IKS_OK) {
1336                                 if(option_verbose > 3) ast_verbose("JABBER: reconnecting.\n");
1337                                 sleep(4);
1338                                 res = aji_reconnect(client);
1339                         }
1340                 }
1341                 res = iks_recv(client->p, 1);
1342                 client->timeout--;
1343                 if (res == IKS_HOOK) {
1344                         ast_log(LOG_WARNING, "JABBER: Got hook event.\n");
1345                         break;
1346                 } else if (res == IKS_NET_TLSFAIL) {
1347                         ast_log(LOG_WARNING, "JABBER:  Failure in tls.\n");
1348                         break;
1349                 } else if (client->timeout == 0 && client->state != AJI_CONNECTED) {
1350                         res = -1;
1351                         ast_log(LOG_WARNING, "JABBER:  Network Timeout\n");
1352                 } else if (res == IKS_NET_RWERR) {
1353                         ast_log(LOG_WARNING, "JABBER: socket read error\n");
1354                 }
1355         } while (res == IKS_OK);
1356         ASTOBJ_UNREF(client, aji_client_destroy);
1357         return 0;
1358 }
1359
1360 /*!
1361  * \brief increments the mid field for messages and other events.
1362  * \param message id.
1363  * \return void.
1364  */
1365 void ast_aji_increment_mid(char *mid)
1366 {
1367         int i = 0;
1368         for (i = strlen(mid) - 1; i >= 0; i--) {
1369                 if (mid[i] != 'z') {
1370                         mid[i] = mid[i] + 1;
1371                         i = 0;
1372                 } else
1373                         mid[i] = 'a';
1374         }
1375 }
1376
1377
1378 /*!
1379  * \brief attempts to register to a transport.
1380  * \param aji_client struct, and xml packet.
1381  * \return IKS_FILTER_EAT.
1382  */
1383 static int aji_register_transport(void *data, ikspak *pak)
1384 {
1385         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1386         int res = 0;
1387         struct aji_buddy *buddy = NULL;
1388         iks *send = NULL;
1389         send = iks_make_iq(IKS_TYPE_GET, "jabber:iq:register");
1390         if (client && send) {
1391                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1392                         ASTOBJ_RDLOCK(iterator); 
1393                         if (iterator->btype == AJI_TRANS) {
1394                                   buddy = iterator;
1395                         }
1396                         ASTOBJ_UNLOCK(iterator);
1397                 });
1398                 iks_filter_remove_hook(client->f, aji_register_transport);
1399                 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);
1400                 iks_insert_attrib(send, "to", buddy->host);
1401                 iks_insert_attrib(send, "id", client->mid);
1402                 ast_aji_increment_mid(client->mid);
1403                 iks_insert_attrib(send, "from", client->user);
1404                 res = iks_send(client->p, send);
1405         } else {
1406                 ast_log(LOG_ERROR, "Out of memory.\n");
1407         }
1408         if (send)
1409                 iks_delete(send);
1410         ASTOBJ_UNREF(client, aji_client_destroy);
1411         return IKS_FILTER_EAT;
1412
1413 }
1414
1415 /*!
1416  * \brief attempts to register to a transport step 2.
1417  * \param aji_client struct, and xml packet.
1418  * \return IKS_FILTER_EAT.
1419  */
1420 static int aji_register_transport2(void *data, ikspak *pak)
1421 {
1422         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1423         int res = 0;
1424         struct aji_buddy *buddy = NULL;
1425         iks *regquery = NULL, *reguser = NULL, *regpass = NULL, *regiq = NULL;
1426         regiq = iks_new("iq");
1427         regquery = iks_new("query");
1428         reguser = iks_new("username");
1429         regpass = iks_new("password");
1430
1431         if (client && regquery && reguser && regpass && regiq) {
1432                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1433                         ASTOBJ_RDLOCK(iterator);
1434                         if (iterator->btype == AJI_TRANS)
1435                                 buddy = iterator; ASTOBJ_UNLOCK(iterator);
1436                 });
1437                 iks_filter_remove_hook(client->f, aji_register_transport2);
1438                 iks_insert_attrib(regiq, "to", buddy->host);
1439                 iks_insert_attrib(regiq, "type", "set");
1440                 iks_insert_attrib(regiq, "id", client->mid);
1441                 ast_aji_increment_mid(client->mid);
1442                 iks_insert_attrib(regiq, "from", client->user);
1443                 iks_insert_attrib(regquery, "xmlns", "jabber:iq:register");
1444                 iks_insert_cdata(reguser, buddy->user, strlen(buddy->user));
1445                 iks_insert_cdata(regpass, buddy->pass, strlen(buddy->pass));
1446                 iks_insert_node(regiq, regquery);
1447                 iks_insert_node(regquery, reguser);
1448                 iks_insert_node(regquery, regpass);
1449                 res = iks_send(client->p, regiq);
1450         } else {
1451                 ast_log(LOG_ERROR, "Out of memory.\n");
1452         }
1453         if (regiq)
1454                 iks_delete(regiq);
1455         if (regquery)
1456                 iks_delete(regquery);
1457         if (reguser)
1458                 iks_delete(reguser);
1459         if (regpass)
1460                 iks_delete(regpass);
1461         ASTOBJ_UNREF(client, aji_client_destroy);
1462         return IKS_FILTER_EAT;
1463 }
1464
1465 /*!
1466  * \brief goes through roster and prunes users not needed in list, or adds them accordingly.
1467  * \param aji_client struct.
1468  * \return void.
1469  */
1470 static void aji_pruneregister(struct aji_client *client)
1471 {
1472         int res = 0;
1473         iks *removeiq = NULL, *removequery = NULL, *removeitem = NULL, *send = NULL;
1474         removeiq = iks_new("iq");
1475         removequery = iks_new("query");
1476         removeitem = iks_new("item");
1477         send = iks_make_iq(IKS_TYPE_GET, "http://jabber.org/protocol/disco#items");
1478
1479         if (client && removeiq && removequery && removeitem && send) {
1480                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1481                         ASTOBJ_RDLOCK(iterator);
1482                         /* For an aji_buddy, both AUTOPRUNE and AUTOREGISTER will never
1483                          * be called at the same time */
1484                         if (ast_test_flag(iterator, AJI_AUTOPRUNE)) {
1485                                 res = iks_send(client->p, iks_make_s10n(IKS_TYPE_UNSUBSCRIBE, iterator->name,
1486                                                 "GoodBye your status is no longer needed by Asterisk the Open Source PBX"
1487                                                 " so I am no longer subscribing to your presence.\n"));
1488                                 res = iks_send(client->p, iks_make_s10n(IKS_TYPE_UNSUBSCRIBED, iterator->name,
1489                                                 "GoodBye you are no longer in the asterisk config file so I am removing"
1490                                                 " your access to my presence.\n"));
1491                                 iks_insert_attrib(removeiq, "from", client->jid->full); 
1492                                 iks_insert_attrib(removeiq, "type", "set"); 
1493                                 iks_insert_attrib(removequery, "xmlns", "jabber:iq:roster");
1494                                 iks_insert_attrib(removeitem, "jid", iterator->name);
1495                                 iks_insert_attrib(removeitem, "subscription", "remove");
1496                                 iks_insert_node(removeiq, removequery);
1497                                 iks_insert_node(removequery, removeitem);
1498                                 res = iks_send(client->p, removeiq);
1499                         } else if (ast_test_flag(iterator, AJI_AUTOREGISTER)) {
1500                                 if (iterator->btype == AJI_USER) {      /*if it is not a transport */
1501                                         res = iks_send(client->p, iks_make_s10n(IKS_TYPE_SUBSCRIBE, iterator->name, 
1502                                                         "Greetings I am the Asterisk Open Source PBX and I want to subscribe to your presence\n"));
1503                                 } else {
1504                                         iks_filter_add_rule(client->f, aji_register_transport, client,
1505                                                                   IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_SUBTYPE, IKS_TYPE_RESULT, IKS_RULE_NS,
1506                                                                   "http://jabber.org/protocol/disco#items", IKS_RULE_DONE);
1507                                         iks_insert_attrib(send, "to", iterator->host);
1508                                         iks_insert_attrib(send, "from", client->jid->full);
1509                                         res = iks_send(client->p, send);
1510                                 }
1511                                 ast_clear_flag(iterator, AJI_AUTOREGISTER);
1512                         }
1513                         ASTOBJ_UNLOCK(iterator);
1514                 });
1515         } else {
1516                 ast_log(LOG_ERROR, "Out of memory.\n");
1517         }
1518         if (removeiq)
1519                 iks_delete(removeiq);
1520         if (removequery)
1521                 iks_delete(removequery);
1522         if (removeitem)
1523                 iks_delete(removeitem);
1524         if (send)
1525                 iks_delete(send);
1526         ASTOBJ_CONTAINER_PRUNE_MARKED(&client->buddies, aji_buddy_destroy);
1527 }
1528
1529 /*!
1530  * \brief filters the roster packet we get back from server.
1531  * \param aji_client struct, and xml packet.
1532  * \return IKS_FILTER_EAT.
1533  */
1534 static int aji_filter_roster(void *data, ikspak *pak)
1535 {
1536         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1537         int flag = 0;
1538         iks *x = NULL;
1539         struct aji_buddy *buddy;
1540
1541         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1542                 ASTOBJ_RDLOCK(iterator);
1543                 x = iks_child(pak->query);
1544                 flag = 0;
1545                 while (x) {
1546                         if (!iks_strcmp(iks_name(x), "item")) {
1547                                 if (!ast_strlen_zero(iterator->pass)) {
1548                                         if (!strcasecmp(iterator->host, iks_find_attrib(x, "jid"))) {
1549                                                   ast_clear_flag(iterator, AJI_AUTOPRUNE | AJI_AUTOREGISTER); 
1550                                                   flag = 1;
1551                                         }
1552                                 } else {
1553                                         if (!strcasecmp(iterator->name, iks_find_attrib(x, "jid"))) {
1554                                                   flag = 1;
1555                                                   ast_clear_flag(iterator, AJI_AUTOPRUNE | AJI_AUTOREGISTER);
1556                                         }
1557                                 }
1558                         }
1559                         x = iks_next(x);
1560                 }
1561                 if (!flag)
1562                         ast_copy_flags(iterator, client, AJI_AUTOREGISTER);
1563                 if (x)
1564                         iks_delete(x);
1565                 ASTOBJ_UNLOCK(iterator);
1566         });
1567
1568         x = iks_child(pak->query);
1569         while (x) {
1570                 flag = 0;
1571                 if (iks_strcmp(iks_name(x), "item") == 0) {
1572                         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1573                                 ASTOBJ_RDLOCK(iterator);
1574                                 if (!ast_strlen_zero(iterator->pass)) {
1575                                         if (!strcasecmp(iterator->host, iks_find_attrib(x, "jid")))
1576                                         flag = 1;
1577                                 } else {
1578                                         if (!strcasecmp(iterator->name, iks_find_attrib(x, "jid")))
1579                                                 flag = 1;
1580                                 }
1581                                 ASTOBJ_UNLOCK(iterator);
1582                         });
1583
1584                         if (!flag) {
1585                                 if (ast_test_flag(client, AJI_AUTOPRUNE)) {
1586                                         buddy = (struct aji_buddy *) malloc(sizeof(struct aji_buddy));
1587                                         if (!buddy)
1588                                                 ast_log(LOG_WARNING, "Out of memory\n");
1589                                         memset(buddy, 0, sizeof(struct aji_buddy));
1590                                         ASTOBJ_INIT(buddy);
1591                                         ASTOBJ_WRLOCK(buddy);
1592                                         ast_copy_string(buddy->name, iks_find_attrib(x, "jid"), sizeof(buddy->name));
1593                                         ast_copy_string(buddy->user, iks_find_attrib(x, "jid"), sizeof(buddy->user));
1594                                         ast_clear_flag(buddy, AST_FLAGS_ALL);
1595                                         ast_set_flag(buddy, AJI_AUTOPRUNE);
1596                                         buddy->objflags |= ASTOBJ_FLAG_MARKED;
1597                                         ASTOBJ_UNLOCK(buddy);
1598                                         if (buddy) {
1599                                                 ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
1600                                                 ASTOBJ_UNREF(buddy, aji_buddy_destroy);
1601                                         }
1602                                 }
1603                         }
1604                 }
1605                 x = iks_next(x);
1606         }
1607         if (x)
1608                 iks_delete(x);
1609         aji_pruneregister(client);
1610
1611         ASTOBJ_UNREF(client, aji_client_destroy);
1612         return IKS_FILTER_EAT;
1613 }
1614
1615 static int aji_reconnect(struct aji_client *client)
1616 {
1617         int res = 0;
1618
1619         if (client->state)
1620                 client->state = AJI_DISCONNECTED;
1621         if (client->p)
1622                 iks_parser_reset(client->p);
1623         if (client->authorized)
1624                 client->authorized = 0;
1625
1626         switch (client->component) {
1627         case AJI_COMPONENT:
1628                 res = aji_component_initialize(client);
1629                 break;
1630         case AJI_CLIENT:
1631                 res = aji_client_initialize(client);
1632                 break;
1633         }
1634         return res;
1635 }
1636
1637 static int aji_get_roster(struct aji_client *client)
1638 {
1639         iks *roster = NULL;
1640         roster = iks_make_iq(IKS_TYPE_GET, IKS_NS_ROSTER);
1641         if(roster) {
1642                 iks_insert_attrib(roster, "id", "roster");
1643                 aji_set_presence(client, client->jid->full, 1, "im available");
1644                 iks_send(client->p, roster);
1645         }
1646         if (roster)
1647                 iks_delete(roster);
1648         return 1;
1649 }
1650
1651 /*!
1652  * \brief connects as a client to jabber server.
1653  * \param aji_client struct, and xml packet.
1654  * \return res.
1655  */
1656 static int aji_client_connect(void *data, ikspak *pak)
1657 {
1658         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1659         int res = 0;
1660         if (client) {
1661                 if (client->state == AJI_DISCONNECTED) {
1662                         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);
1663                         client->state = AJI_CONNECTED;
1664                         client->jid = (iks_find_cdata(pak->query, "jid")) ? iks_id_new(client->stack, iks_find_cdata(pak->query, "jid")) : client->jid;
1665                         iks_filter_remove_hook(client->f, aji_client_connect);
1666                         if(client->component == AJI_CLIENT)
1667                                 aji_get_roster(client);
1668                 }
1669         } else {
1670                 ast_log(LOG_ERROR, "Out of memory.\n");
1671         }
1672
1673         ASTOBJ_UNREF(client, aji_client_destroy);
1674         return res;
1675 }
1676
1677 /*!
1678  * \brief prepares client for connect.
1679  * \param aji_client struct.
1680  * \return 1.
1681  */
1682 static int aji_client_initialize(struct aji_client *client)
1683 {
1684         int connected = 0;
1685
1686         connected = iks_connect_via(client->p, client->serverhost, client->port, client->jid->server);
1687
1688         if (connected == IKS_NET_NOCONN) {
1689                 ast_log(LOG_ERROR, "JABBER ERROR: No Connection\n");
1690                 return IKS_HOOK;
1691         } else  if (connected == IKS_NET_NODNS) {
1692                 ast_log(LOG_ERROR, "JABBER ERROR: No DNS\n");
1693                 return IKS_HOOK;
1694         } else
1695                 iks_recv(client->p, 30);
1696         return IKS_OK;
1697 }
1698
1699 /*!
1700  * \brief prepares component for connect.
1701  * \param aji_client struct.
1702  * \return 1.
1703  */
1704 static int aji_component_initialize(struct aji_client *client)
1705 {
1706         int connected = 1;
1707         connected = iks_connect_via(client->p, client->jid->server, client->port, client->user);
1708         if (connected == IKS_NET_NOCONN)
1709                 ast_log(LOG_ERROR, "JABBER ERROR: No Connection");
1710         if (connected == IKS_NET_NODNS)
1711                 ast_log(LOG_ERROR, "JABBER ERROR: No DNS");
1712         if (!connected)
1713                 iks_recv(client->p, 30);
1714         return 1;
1715 }
1716
1717 /*!
1718  * \brief disconnect from jabber server.
1719  * \param aji_client struct.
1720  * \return 1.
1721  */
1722 int ast_aji_disconnect(struct aji_client *client)
1723 {
1724         if (client) {
1725                 if (option_verbose > 3)
1726                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: Disconnecting\n");
1727                 iks_disconnect(client->p);
1728                 iks_parser_delete(client->p);
1729                 ASTOBJ_UNREF(client, aji_client_destroy);
1730         }
1731
1732         return 1;
1733 }
1734
1735 /*!
1736  * \brief set presence of client.
1737  * \param aji_client struct, user to send it to, level, description.
1738  * \return void.
1739  */
1740 static void aji_set_presence(struct aji_client *client, char *user, int level, char *desc)
1741 {
1742         int res = 0;
1743         iks *presence = NULL, *priority, *cnode = NULL;
1744         presence = iks_make_pres(level, desc);
1745         cnode = iks_new("c");
1746         priority = iks_new("priority");
1747         iks_insert_cdata(priority, "0", 1);
1748         if (presence && cnode && client) {
1749                 iks_insert_attrib(cnode, "node", "http://www.asterisk.org/xmpp/client/caps");
1750                 iks_insert_attrib(cnode, "ver", "asterisk-xmpp");
1751                 iks_insert_attrib(cnode, "ext", "voice-v1");
1752                 iks_insert_attrib(cnode, "xmlns", "http://jabber.org/protocol/caps");
1753                 iks_insert_node(presence, cnode);
1754                 res = iks_send(client->p, presence);
1755         } else {
1756                 ast_log(LOG_ERROR, "Out of memory.\n");
1757         }
1758         if (cnode)
1759                 iks_delete(cnode);
1760         if (presence)
1761                 iks_delete(presence);
1762 }
1763
1764 /*!
1765  * \brief turnon console debugging.
1766  * \param fd, number of args, args.
1767  * \return RESULT_SUCCESS.
1768  */
1769 static int aji_do_debug(int fd, int argc, char *argv[])
1770 {
1771         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
1772                 ASTOBJ_RDLOCK(iterator); 
1773                 iterator->debug = 1;
1774                 ASTOBJ_UNLOCK(iterator);
1775         });
1776         if (option_verbose > 3)
1777                 ast_verbose(VERBOSE_PREFIX_3 "JABBER: Debugging Enabled.\n");
1778         return RESULT_SUCCESS;
1779 }
1780
1781 /*!
1782  * \brief reload jabber module.
1783  * \param fd, number of args, args.
1784  * \return RESULT_SUCCESS.
1785  */
1786 static int aji_do_reload(int fd, int argc, char *argv[])
1787 {
1788         aji_reload();
1789         if (option_verbose > 3)
1790                 ast_verbose(VERBOSE_PREFIX_3 "JABBER: Reloaded.\n");
1791         return RESULT_SUCCESS;
1792 }
1793
1794 /*!
1795  * \brief turnoff console debugging.
1796  * \param fd, number of args, args.
1797  * \return RESULT_SUCCESS.
1798  */
1799 static int aji_no_debug(int fd, int argc, char *argv[])
1800 {
1801         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
1802                 ASTOBJ_RDLOCK(iterator);
1803                 iterator->debug = 0;
1804                 ASTOBJ_UNLOCK(iterator);
1805         });
1806         if (option_verbose > 2)
1807                 ast_verbose(VERBOSE_PREFIX_3 "JABBER: Debugging Disabled\n");
1808         return RESULT_SUCCESS;
1809 }
1810
1811 /*!
1812  * \brief show client status.
1813  * \param fd, number of args, args.
1814  * \return RESULT_SUCCESS.
1815  */
1816 static int aji_show_clients(int fd, int argc, char *argv[])
1817 {
1818         char *status = "";
1819         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
1820                 ASTOBJ_RDLOCK(iterator);
1821                 switch (iterator->state) {
1822                 case AJI_DISCONNECTED:
1823                         status = "Disconnected";
1824                         break;
1825                 case AJI_CONNECTING:
1826                 case AJI_ALMOST:
1827                         status = "Connecting";
1828                         break;
1829                 case AJI_CONNECTED:
1830                         status = "Connected";
1831                         break;
1832                 default:
1833                         status = "Unknown";
1834                 }
1835                 ast_verbose("JABBER: User: %s is %s\n", iterator->user, status);
1836                 ASTOBJ_UNLOCK(iterator);
1837         });
1838         return RESULT_SUCCESS;
1839 }
1840
1841 /*!
1842  * \brief send test message for debuging.
1843  * \param fd, number of args, args.
1844  * \return RESULT_SUCCESS.
1845  */
1846 static int aji_test(int fd, int argc, char *argv[])
1847 {
1848         struct aji_client *client;
1849         struct aji_resource *resource;
1850         const char *name = "asterisk";
1851
1852         if (argc > 3)
1853                 return RESULT_SHOWUSAGE;
1854         else if (argc == 3)
1855                 name = argv[2];
1856
1857         if (!(client = ASTOBJ_CONTAINER_FIND(&clients, name))) {
1858                 ast_cli(fd, "Unable to find client '%s'!\n", name);
1859                 return RESULT_FAILURE;
1860         }
1861
1862         ast_aji_send(client, "mogorman@astjab.org", "blahblah");
1863         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1864                 ASTOBJ_RDLOCK(iterator);
1865                 ast_verbose("User: %s\n", iterator->name);
1866                 ast_verbose("User: %s\n", iterator->user);
1867                 ast_verbose("Pass: %s\n", iterator->pass);
1868                 ast_verbose("Host: %s\n", iterator->host);
1869                 for (resource = iterator->resources; resource; resource = resource->next) {
1870                         ast_verbose("Resource: %s\n", resource->resource);
1871                         if(resource->cap) {
1872                                 ast_verbose("   client: %s\n", resource->cap->parent->node);
1873                                 ast_verbose("   version: %s\n", resource->cap->version);
1874                                 ast_verbose("   Jingle Capable: %d\n", resource->cap->jingle);
1875                         }
1876                         ast_verbose("   Priority: %d\n", resource->priority);
1877                         ast_verbose("   Status: %d\n", resource->status); 
1878                         ast_verbose("   Message: %s\n", resource->description); 
1879                 }
1880                 ASTOBJ_UNLOCK(iterator);
1881         });
1882
1883         ASTOBJ_UNREF(client, aji_client_destroy);
1884
1885         return RESULT_SUCCESS;
1886 }
1887
1888 /*!
1889  * \brief creates aji_client structure.
1890  * \param label, ast_variable, debug, pruneregister, component/client, aji_client to dump into. 
1891  * \return 0.
1892  */
1893 static int aji_create_client(char *label, struct ast_variable *var, int debug)
1894 {
1895         char *resource;
1896         struct aji_client *client = NULL;
1897         int flag = 0;
1898         client = ASTOBJ_CONTAINER_FIND(&clients,label);
1899         if(!client) {
1900                 flag = 1;
1901                 client = (struct aji_client *) malloc(sizeof(struct aji_client));
1902                 if(client) {
1903                         memset(client, 0, sizeof(struct aji_client));
1904                         ASTOBJ_INIT(client);
1905                         ASTOBJ_WRLOCK(client);
1906                         ASTOBJ_CONTAINER_INIT(&client->buddies);
1907                 } else {
1908                         ast_log(LOG_ERROR, "Out of memory!\n");
1909                         return 0;
1910                 }
1911         } else {
1912                 ASTOBJ_WRLOCK(client);
1913                 ASTOBJ_UNMARK(client);
1914         }
1915         ASTOBJ_CONTAINER_MARKALL(&client->buddies);
1916         ast_copy_string(client->name, label, sizeof(client->name));
1917         ast_copy_string(client->mid, "aaaaa", sizeof(client->mid));
1918
1919         client->debug = debug;
1920         ast_copy_flags(client, &globalflags, AST_FLAGS_ALL);
1921         client->port = 5222;
1922         client->usetls = 1;
1923         client->forcessl = 0;
1924         client->keepalive = 1;
1925         client->timeout = 20;
1926         client->component = AJI_CLIENT;
1927         if (flag) client->authorized = 0;
1928         client->usesasl = 0;
1929         if (flag) client->state = AJI_DISCONNECTED;
1930         while (var) {
1931                 if (!strcasecmp(var->name, "username"))
1932                         ast_copy_string(client->user, var->value, sizeof(client->user));
1933                 else if (!strcasecmp(var->name, "serverhost"))
1934                         ast_copy_string(client->serverhost, var->value, sizeof(client->serverhost));
1935                 else if (!strcasecmp(var->name, "secret"))
1936                         ast_copy_string(client->password, var->value, sizeof(client->password));
1937                 else if (!strcasecmp(var->name, "port"))
1938                         client->port = atoi(var->value);
1939                 else if (!strcasecmp(var->name, "debug"))
1940                         client->debug = (ast_false(var->value)) ? 0 : 1;
1941                 else if (!strcasecmp(var->name, "type")){
1942                         if (!strcasecmp(var->value, "component"))
1943                                 client->component = AJI_COMPONENT;
1944                 } else if (!strcasecmp(var->name, "usetls")) {
1945                         client->usetls = (ast_false(var->value)) ? 0 : 1;
1946                 } else if (!strcasecmp(var->name, "usesasl")) {
1947                         client->usesasl = (ast_false(var->value)) ? 0 : 1;
1948                 } else if (!strcasecmp(var->name, "forceoldssl"))
1949                         client->forcessl = (ast_false(var->value)) ? 0 : 1;
1950                 else if (!strcasecmp(var->name, "keepalive"))
1951                         client->keepalive = (ast_false(var->value)) ? 0 : 1;
1952                 else if (!strcasecmp(var->name, "autoprune"))
1953                         ast_set2_flag(client, ast_true(var->value), AJI_AUTOPRUNE);
1954                 else if (!strcasecmp(var->name, "autoregister"))
1955                         ast_set2_flag(client, ast_true(var->value), AJI_AUTOREGISTER);
1956                 else if (!strcasecmp(var->name, "buddy"))
1957                                 aji_create_buddy(var->value, client);
1958                 else if (!strcasecmp(var->name, "transport"))
1959                                 aji_create_transport(var->value, client);
1960                 var = var->next;
1961         }
1962         if(flag) {
1963                 client->p = iks_stream_new(((client->component == AJI_CLIENT) ? "jabber:client" : "jabber:component:accept"), client, aji_act_hook);
1964                 if (!client->p) {
1965                         ast_log(LOG_WARNING, "Failed to create stream for client '%s'!\n", client->name);
1966                         return 0;
1967                 }
1968                 client->stack = iks_stack_new(8192, 8192);
1969                 if (!client->stack) {
1970                         ast_log(LOG_WARNING, "Failed to allocate stack for client '%s'\n", client->name);
1971                         return 0;
1972                 }
1973                 client->f = iks_filter_new();
1974                 if (!client->f) {
1975                         ast_log(LOG_WARNING, "Failed to create filter for client '%s'\n", client->name);
1976                         return 0;
1977                 }
1978                 if (!strchr(client->user, '/') && client->component == AJI_CLIENT) {
1979                         resource = NULL;
1980                         asprintf(&resource, "%s/asterisk", client->user);
1981                         if (resource) {
1982                                 client->jid = iks_id_new(client->stack, resource);
1983                                 free(resource);
1984                         }
1985                 } else
1986                         client->jid = iks_id_new(client->stack, client->user);
1987                 if (client->component == AJI_COMPONENT) {
1988                         iks_filter_add_rule(client->f, aji_dinfo_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
1989                         iks_filter_add_rule(client->f, aji_ditems_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#items", IKS_RULE_DONE);
1990                         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);
1991                         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);
1992                 } else {
1993                         iks_filter_add_rule(client->f, aji_client_info_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
1994                 }
1995                 if (!strchr(client->user, '/') && client->component == AJI_CLIENT) {
1996                         resource = NULL;
1997                         asprintf(&resource, "%s/asterisk", client->user);
1998                         if (resource) {
1999                                 client->jid = iks_id_new(client->stack, resource);
2000                                 free(resource);
2001                         }
2002                 } else
2003                         client->jid = iks_id_new(client->stack, client->user);
2004                 iks_set_log_hook(client->p, aji_log_hook);
2005                 ASTOBJ_UNLOCK(client);
2006                 ASTOBJ_CONTAINER_LINK(&clients,client);
2007         } else {
2008                 ASTOBJ_UNLOCK(client);
2009                 ASTOBJ_UNREF(client, aji_client_destroy);
2010         }
2011         return 1;
2012 }
2013
2014 /*!
2015  * \brief creates transport.
2016  * \param label, buddy to dump it into. 
2017  * \return 0.
2018  */
2019 static int aji_create_transport(char *label, struct aji_client *client)
2020 {
2021         char *server = NULL, *buddyname = NULL, *user = NULL, *pass = NULL;
2022         struct aji_buddy *buddy = NULL;
2023
2024         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies,label);
2025         if (!buddy) {
2026                 buddy = malloc(sizeof(struct aji_buddy));
2027                 if(!buddy) {
2028                         ast_log(LOG_WARNING, "Out of memory\n");
2029                         return 0;
2030                 } else {
2031                         memset(buddy, 0, sizeof(struct aji_buddy));
2032                         ASTOBJ_INIT(buddy);
2033                         
2034                 }
2035         }
2036         ASTOBJ_WRLOCK(buddy);
2037         server = label;
2038         if ((buddyname = strchr(label, ','))) {
2039                 *buddyname = '\0';
2040                 buddyname++;
2041                 if (buddyname && buddyname[0] != '\0') {
2042                         if ((user = strchr(buddyname, ','))) {
2043                                 *user = '\0';
2044                                 user++;
2045                                 if (user && user[0] != '\0') {
2046                                         if ((pass = strchr(user, ','))) {
2047                                                 *pass = '\0';
2048                                                 pass++;
2049                                                 ast_copy_string(buddy->pass, pass, sizeof(buddy->pass));
2050                                                 ast_copy_string(buddy->user, user, sizeof(buddy->user));
2051                                                 ast_copy_string(buddy->name, buddyname, sizeof(buddy->name));
2052                                                 ast_copy_string(buddy->server, server, sizeof(buddy->server));
2053                                                 return 1;
2054                                         }
2055                                 }
2056                         }
2057                 }
2058         }
2059         ASTOBJ_UNLOCK(buddy);
2060         ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
2061         return 0;
2062 }
2063
2064 /*!
2065  * \brief creates buddy.
2066  * \param label, buddy to dump it into. 
2067  * \return 0.
2068  */
2069 static int aji_create_buddy(char *label, struct aji_client *client)
2070 {
2071         struct aji_buddy *buddy = NULL;
2072         int flag = 0;
2073         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies,label);
2074         if (!buddy) {
2075                 flag = 1;
2076                 buddy = malloc(sizeof(struct aji_buddy));
2077                 if(!buddy) {
2078                         ast_log(LOG_WARNING, "Out of memory\n");
2079                         return 0;
2080                 } else {
2081                         memset(buddy, 0, sizeof(struct aji_buddy));
2082                         ASTOBJ_INIT(buddy);
2083                         
2084                 }
2085         }
2086         ASTOBJ_WRLOCK(buddy);
2087         ast_copy_string(buddy->name, label, sizeof(buddy->name));
2088         ASTOBJ_UNLOCK(buddy);
2089         if(flag)
2090                 ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
2091         else
2092                 ASTOBJ_UNREF(buddy, aji_buddy_destroy);
2093         return 1;
2094 }
2095
2096 /*!
2097  * \brief load config file.
2098  * \param void. 
2099  * \return 1.
2100  */
2101 static int aji_load_config(void)
2102 {
2103         char *cat = NULL;
2104         int debug = 1;
2105         struct ast_config *cfg = NULL;
2106         struct ast_variable *var = NULL;
2107
2108         cfg = ast_config_load(JABBER_CONFIG);
2109         if (!cfg) {
2110                 ast_log(LOG_WARNING, "No such configuration file %s\n", JABBER_CONFIG);
2111                 return 0;
2112         }
2113
2114         cat = ast_category_browse(cfg, NULL);
2115         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
2116                 if (!strcasecmp(var->name, "debug"))
2117                         debug = (ast_false(ast_variable_retrieve(cfg, "general", "debug"))) ? 0 : 1;
2118                 else if (!strcasecmp(var->name, "autoprune"))
2119                         ast_set2_flag(&globalflags, ast_true(var->value), AJI_AUTOPRUNE);
2120                 else if (!strcasecmp(var->name, "autoregister"))
2121                         ast_set2_flag(&globalflags, ast_true(var->value), AJI_AUTOREGISTER);
2122         }
2123
2124         while (cat) {
2125                 if (strcasecmp(cat, "general")) {
2126                                 var = ast_variable_browse(cfg, cat);
2127                                 aji_create_client(cat, var, debug);
2128                 }
2129                 cat = ast_category_browse(cfg, cat);
2130         }
2131         return 1;
2132 }
2133
2134 /*!
2135  * \brief grab a aji_client structure by label name.
2136  * \param void. 
2137  * \return 1.
2138  */
2139
2140 struct aji_client *ast_aji_get_client(char *name)
2141 {
2142         struct aji_client *client = NULL;
2143         client = ASTOBJ_CONTAINER_FIND(&clients, name);
2144         if (!client && !strchr(name, '@'))
2145                 client = ASTOBJ_CONTAINER_FIND_FULL(&clients, name, user,,, strcasecmp);
2146         return client;
2147 }
2148
2149 struct aji_client_container *ast_aji_get_clients(void)
2150 {
2151         return &clients;
2152 }
2153
2154 static void aji_reload()
2155 {
2156         int res = -1;
2157         ASTOBJ_CONTAINER_MARKALL(&clients);
2158         if (!aji_load_config())
2159                 ast_log(LOG_ERROR, "JABBER: Failed to load config.\n");
2160         else {
2161                 ASTOBJ_CONTAINER_PRUNE_MARKED(&clients, aji_client_destroy);
2162                 ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2163                         ASTOBJ_RDLOCK(iterator);
2164                         if(iterator->state == AJI_DISCONNECTED) {
2165                                 if (!iterator->thread)
2166                                         ast_pthread_create(&iterator->thread, NULL, aji_recv_loop, iterator);
2167                         } else if (iterator->state == AJI_CONNECTED) {
2168                                 aji_get_roster(iterator);
2169                         }
2170                         ASTOBJ_UNLOCK(iterator);
2171                 });
2172         }
2173 }
2174
2175 static int unload_module(void *mod)
2176 {
2177         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2178                 ASTOBJ_RDLOCK(iterator);
2179                 if (option_verbose > 2)
2180                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: %s\n", iterator->name);
2181                 iterator->state = AJI_DISCONNECTED;
2182                 ast_aji_disconnect(iterator);
2183                 pthread_join(iterator->thread, NULL);
2184                 ASTOBJ_UNLOCK(iterator);
2185         });
2186
2187         ASTOBJ_CONTAINER_DESTROYALL(&clients, aji_client_destroy);
2188         ASTOBJ_CONTAINER_DESTROY(&clients);
2189
2190         STANDARD_HANGUP_LOCALUSERS;
2191         ast_cli_unregister_multiple(aji_cli, sizeof(aji_cli) / sizeof(aji_cli[0]));
2192         ast_unregister_application(app_ajisend);
2193         ast_log(LOG_NOTICE, "res_jabber unloaded.\n");
2194         return 0;
2195 }
2196
2197 static int load_module(void *mod)
2198 {
2199         ASTOBJ_CONTAINER_INIT(&clients);
2200         aji_reload();
2201         ast_register_application(app_ajisend, aji_send_exec, ajisend_synopsis, ajisend_descrip);
2202         ast_register_application(app_ajistatus, aji_status_exec, ajistatus_synopsis, ajistatus_descrip);
2203         ast_cli_register_multiple(aji_cli, sizeof(aji_cli) / sizeof(aji_cli[0]));
2204         ast_log(LOG_NOTICE, "res_jabber.so loaded.\n");
2205         return 0;
2206 }
2207
2208 static int reload(void *mod)
2209 {
2210         aji_reload();
2211         return 0;
2212 }
2213
2214 static const char *description(void)
2215 {
2216         return tdesc;
2217 }
2218
2219 static const char *key(void)
2220 {
2221         return ASTERISK_GPL_KEY;
2222 }
2223
2224 STD_MOD(MOD_0, reload, NULL, NULL);