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