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