handle ast_calloc failure and tweak some formatting to comply with coding
[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(&obj->messages);
165         while ((tmp = AST_LIST_REMOVE_HEAD(&obj->messages, list))) {
166                 if (tmp->from)
167                         free(tmp->from);
168                 if (tmp->message)
169                         free(tmp->message);
170         }
171         AST_LIST_HEAD_DESTROY(&obj->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
1035         if (!(insert = ast_calloc(1, sizeof(struct aji_message))))
1036                 return;
1037         time(&insert->arrived);
1038         insert->message = ast_strdup(iks_find_cdata(pak->x, "body"));
1039         ast_copy_string(insert->id, pak->id, sizeof(insert->message));
1040         insert->from = ast_strdup(pak->from->full);
1041         AST_LIST_LOCK(&client->messages);
1042         AST_LIST_TRAVERSE_SAFE_BEGIN(&client->messages, tmp, list) {
1043                 if (flag) {
1044                         AST_LIST_REMOVE_CURRENT(&client->messages, list);
1045                         if (tmp->from)
1046                                 free(tmp->from);
1047                         if (tmp->message)
1048                                 free(tmp->message);
1049                 } else if (difftime(time(NULL), tmp->arrived) >= client->message_timeout) {
1050                         flag = 1;
1051                         AST_LIST_REMOVE_CURRENT(&client->messages, list);
1052                         if (tmp->from)
1053                                 free(tmp->from);
1054                         if (tmp->message)
1055                                 free(tmp->message);
1056                 }
1057         }
1058         AST_LIST_TRAVERSE_SAFE_END;
1059         AST_LIST_INSERT_HEAD(&client->messages, insert, list);
1060         AST_LIST_UNLOCK(&client->messages);
1061 }
1062
1063 static void aji_handle_presence(struct aji_client *client, ikspak *pak)
1064 {
1065         int status, priority;
1066         struct aji_buddy *buddy = NULL;
1067         struct aji_resource *tmp = NULL, *last = NULL, *found = NULL;
1068         char *ver, *node, *descrip;
1069         
1070         if(client->state != AJI_CONNECTED) {
1071                 aji_create_buddy(pak->from->partial,client);
1072         }
1073         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
1074         if (!buddy) {
1075                 ast_log(LOG_WARNING, "Got presence packet from %s, someone not in our roster!!!!\n", pak->from->partial);
1076                 return;
1077         }
1078         ASTOBJ_WRLOCK(buddy);
1079         status = (pak->show) ? pak->show : 6;
1080         priority = atoi((iks_find_cdata(pak->x, "priority")) ? iks_find_cdata(pak->x, "priority") : "0");
1081         tmp = buddy->resources;
1082         descrip = ast_strdup(iks_find_cdata(pak->x,"status"));
1083
1084         while (tmp) {
1085                 if (!strcasecmp(tmp->resource, pak->from->resource)) {
1086                         tmp->status = status;
1087                         if (tmp->description) free(tmp->description);
1088                         tmp->description = descrip;
1089                         found = tmp;
1090                         if (status == 6) {      /* Sign off Destroy resource */
1091                                 if (last && found->next) {
1092                                         last->next = found->next;
1093                                 } else if (!last) {
1094                                         if (found->next)
1095                                                 buddy->resources = found->next;
1096                                         else
1097                                                 buddy->resources = NULL;
1098                                 } else if (!found->next) {
1099                                         if (last)
1100                                                 last->next = NULL;
1101                                         else
1102                                                 buddy->resources = NULL;
1103                                 }
1104                                 free(found);
1105                                 found = NULL;
1106                                 break;
1107                         }
1108                         if (tmp->priority != priority) {
1109                                 found->priority = priority;
1110                                 if (!last && !found->next)
1111                                         break;
1112                                 if (last)
1113                                         last->next = found->next;
1114                                 else
1115                                         buddy->resources = found->next;
1116                                 last = NULL;
1117                                 tmp = buddy->resources;
1118                                 if (!buddy->resources)
1119                                         buddy->resources = found;
1120                                 while (tmp) {
1121                                         if (found->priority > tmp->priority) {
1122                                                 if (last)
1123                                                         last->next = found;
1124                                                 found->next = tmp;
1125                                                 if (!last)
1126                                                         buddy->resources = found;
1127                                                 break;
1128                                         }
1129                                         if (!tmp->next) {
1130                                                 tmp->next = found;
1131                                                 break;
1132                                         }
1133                                         last = tmp;
1134                                         tmp = tmp->next;
1135                                 }
1136                         }
1137                         break;
1138                 }
1139                 last = tmp;
1140                 tmp = tmp->next;
1141         }
1142
1143         if (!found && status != 6) {
1144                 found = (struct aji_resource *) malloc(sizeof(struct aji_resource));
1145                 memset(found, 0, sizeof(struct aji_resource));
1146                 if (!found) {
1147                         ast_log(LOG_ERROR, "Out of memory!\n");
1148                         return;
1149                 }
1150                 ast_copy_string(found->resource, pak->from->resource, sizeof(found->resource));
1151                 found->status = status;
1152                 found->description = descrip;
1153                 found->priority = priority;
1154                 found->next = NULL;
1155                 last = NULL;
1156                 tmp = buddy->resources;
1157                 while (tmp) {
1158                         if (found->priority > tmp->priority) {
1159                                 if (last)
1160                                         last->next = found;
1161                                 found->next = tmp;
1162                                 if (!last)
1163                                         buddy->resources = found;
1164                                 break;
1165                         }
1166                         if (!tmp->next) {
1167                                 tmp->next = found;
1168                                 break;
1169                         }
1170                         last = tmp;
1171                         tmp = tmp->next;
1172                 }
1173                 if (!tmp)
1174                         buddy->resources = found;
1175         }
1176         ASTOBJ_UNLOCK(buddy);
1177         ASTOBJ_UNREF(buddy, aji_buddy_destroy);
1178
1179         node = iks_find_attrib(iks_find(pak->x, "c"), "node");
1180         ver = iks_find_attrib(iks_find(pak->x, "c"), "ver");
1181
1182         if(status !=6 && !found->cap) {
1183                 found->cap = aji_find_version(node, ver, pak);
1184                 if(gtalk_yuck(pak->x)) /* gtalk should do discover */
1185                         found->cap->jingle = 1;
1186                 if(found->cap->jingle)
1187                         ast_log(LOG_DEBUG,"Special case for google till they support discover.\n");
1188                 else {
1189                         iks *iq, *query;
1190                         iq = iks_new("iq");
1191                         query = iks_new("query");
1192                         if(query && iq)  {
1193                                 iks_insert_attrib(iq, "type", "get");
1194                                 iks_insert_attrib(iq, "to", pak->from->full);
1195                                 iks_insert_attrib(iq, "id", client->mid);
1196                                 ast_aji_increment_mid(client->mid);
1197                                 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
1198                                 iks_insert_node(iq, query);
1199                                 iks_send(client->p, iq);
1200                                 
1201                         } else
1202                                 ast_log(LOG_ERROR, "Out of memory.\n");
1203                         if(query)
1204                                 iks_delete(query);
1205                         if(iq)
1206                                 iks_delete(iq);
1207                 }
1208         }
1209         if (option_verbose > 30) {
1210                 switch (pak->subtype) {
1211                 case IKS_TYPE_AVAILABLE:
1212                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I am available ^_* %i\n", pak->subtype);
1213                         break;
1214                 case IKS_TYPE_UNAVAILABLE:
1215                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: I am unavailable ^_* %i\n", pak->subtype);
1216                         break;
1217                 default:
1218                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: Ohh sexy and the wrong type%i\n", pak->subtype);
1219                 }
1220                 switch (pak->show) {
1221                 case IKS_SHOW_UNAVAILABLE:
1222                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1223                         break;
1224                 case IKS_SHOW_AVAILABLE:
1225                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type is available\n");
1226                         break;
1227                 case IKS_SHOW_CHAT:
1228                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1229                         break;
1230                 case IKS_SHOW_AWAY:
1231                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type is away\n");
1232                         break;
1233                 case IKS_SHOW_XA:
1234                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1235                         break;
1236                 case IKS_SHOW_DND:
1237                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1238                         break;
1239                 default:
1240                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: Kinky! how did that happen %i\n", pak->show);
1241                 }
1242         }
1243 }
1244
1245 /*!
1246  * \brief handles subscription requests.
1247  * \param aji_client struct and xml packet.
1248  * \return void.
1249  */
1250 static void aji_handle_subscribe(struct aji_client *client, ikspak *pak)
1251 {
1252         if(pak->subtype == IKS_TYPE_SUBSCRIBE)
1253                 iks_send(client->p, iks_make_s10n(IKS_TYPE_SUBSCRIBED, iks_find_attrib(pak->x, "from"), "Asterisk has approved subscription"));
1254         if (option_verbose > 30) {
1255                 switch (pak->subtype) {
1256                 case IKS_TYPE_SUBSCRIBE:
1257                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1258                         break;
1259                 case IKS_TYPE_SUBSCRIBED:
1260                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1261                         break;
1262                 case IKS_TYPE_UNSUBSCRIBE:
1263                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1264                         break;
1265                 case IKS_TYPE_UNSUBSCRIBED:
1266                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1267                         break;
1268                 default:                                /*IKS_TYPE_ERROR: */
1269                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1270                         break;
1271                 }
1272         }
1273 }
1274
1275 /*!
1276  * \brief sends messages.
1277  * \param aji_client struct , reciever, message.
1278  * \return 1.
1279  */
1280 int ast_aji_send(struct aji_client *client, char *address, char *message)
1281 {
1282         int res = 0;
1283         iks *message_packet = NULL;
1284         if (client->state == AJI_CONNECTED) {
1285                 message_packet = iks_make_msg(IKS_TYPE_CHAT, address, message);
1286                 if (message_packet) {
1287                         iks_insert_attrib(message_packet, "from", client->jid->full);
1288                         res = iks_send(client->p, message_packet);
1289                 } else {
1290                         ast_log(LOG_ERROR, "Out of memory.\n");
1291                 }
1292                 if (message_packet)
1293                         iks_delete(message_packet);
1294         } else
1295                 ast_log(LOG_WARNING, "JABBER: Not connected can't send\n");
1296         return 1;
1297 }
1298
1299 /*!
1300  * \brief create a chatroom.
1301  * \param aji_client struct , room, server, topic for the room.
1302  * \return 0.
1303  */
1304 int ast_aji_create_chat(struct aji_client *client, char *room, char *server, char *topic)
1305 {
1306         int res = 0;
1307         iks *iq = NULL;
1308         iq = iks_new("iq");
1309         if (iq && client) {
1310                 iks_insert_attrib(iq, "type", "get");
1311                 iks_insert_attrib(iq, "to", server);
1312                 iks_insert_attrib(iq, "id", client->mid);
1313                 ast_aji_increment_mid(client->mid);
1314                 iks_send(client->p, iq);
1315         } else {
1316                 ast_log(LOG_ERROR, "Out of memory.\n");
1317         }
1318         return res;
1319 }
1320
1321 /*!
1322  * \brief join a chatroom.
1323  * \param aji_client struct , room.
1324  * \return res.
1325  */
1326 int ast_aji_join_chat(struct aji_client *client, char *room)
1327 {
1328         int res = 0;
1329         iks *presence = NULL, *priority = NULL;
1330         presence = iks_new("presence");
1331         priority = iks_new("priority");
1332         if (presence && priority && client) {
1333                 iks_insert_cdata(priority, "0", 1);
1334                 iks_insert_attrib(presence, "to", room);
1335                 iks_insert_node(presence, priority);
1336                 res = iks_send(client->p, presence);
1337                 iks_insert_cdata(priority, "5", 1);
1338                 iks_insert_attrib(presence, "to", room);
1339                 res = iks_send(client->p, presence);
1340         } else {
1341                 ast_log(LOG_ERROR, "Out of memory.\n");
1342         }
1343         if (presence)
1344                 iks_delete(presence);
1345         if (priority)
1346                 iks_delete(priority);
1347         return res;
1348 }
1349
1350 /*!
1351  * \brief invite to a chatroom.
1352  * \param aji_client struct ,user, room, message.
1353  * \return res.
1354  */
1355 int ast_aji_invite_chat(struct aji_client *client, char *user, char *room, char *message)
1356 {
1357         int res = 0;
1358         iks *invite = NULL, *body = NULL, *namespace = NULL;
1359         invite = iks_new("message");
1360         body = iks_new("body");
1361         namespace = iks_new("x");
1362         if (client && invite && body && namespace) {
1363                 iks_insert_attrib(invite, "to", user);
1364                 iks_insert_attrib(invite, "id", client->mid);
1365                 ast_aji_increment_mid(client->mid);
1366                 iks_insert_cdata(body, message, strlen(message));
1367                 iks_insert_attrib(namespace, "xmlns", "jabber:x:conference");
1368                 iks_insert_attrib(namespace, "jid", room);
1369                 iks_insert_node(invite, body);
1370                 iks_insert_node(invite, namespace);
1371                 res = iks_send(client->p, invite);
1372         } else {
1373                 ast_log(LOG_ERROR, "Out of memory.\n");
1374         }
1375         if (body)
1376                 iks_delete(body);
1377         if (namespace)
1378                 iks_delete(namespace);
1379         if (invite)
1380                 iks_delete(invite);
1381         return res;
1382 }
1383
1384
1385 /*!
1386  * \brief receive message loop.
1387  * \param aji_client struct.
1388  * \return void.
1389  */
1390 static void *aji_recv_loop(void *data)
1391 {
1392         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1393         int res = IKS_HOOK;
1394         do {
1395                 if (res != IKS_OK) {
1396                         while(res != IKS_OK) {
1397                                 if(option_verbose > 3) ast_verbose("JABBER: reconnecting.\n");
1398                                 res = aji_reconnect(client);
1399                                 sleep(4);
1400                         }
1401                 }
1402
1403                 res = iks_recv(client->p, 1);
1404                 client->timeout--;
1405                 if (res == IKS_HOOK) {
1406                         ast_log(LOG_WARNING, "JABBER: Got hook event.\n");
1407                 } else if (res == IKS_NET_TLSFAIL) {
1408                         ast_log(LOG_WARNING, "JABBER:  Failure in tls.\n");
1409                 } else if (client->timeout == 0 && client->state == AJI_CONNECTED) {
1410                         res = -1;
1411                         ast_log(LOG_WARNING, "JABBER:  Network Timeout\n");
1412                 } else if (res == IKS_NET_RWERR) {
1413                         ast_log(LOG_WARNING, "JABBER: socket read error\n");
1414                 }
1415         } while (client);
1416         ASTOBJ_UNREF(client, aji_client_destroy);
1417         return 0;
1418 }
1419
1420 /*!
1421  * \brief increments the mid field for messages and other events.
1422  * \param message id.
1423  * \return void.
1424  */
1425 void ast_aji_increment_mid(char *mid)
1426 {
1427         int i = 0;
1428         for (i = strlen(mid) - 1; i >= 0; i--) {
1429                 if (mid[i] != 'z') {
1430                         mid[i] = mid[i] + 1;
1431                         i = 0;
1432                 } else
1433                         mid[i] = 'a';
1434         }
1435 }
1436
1437
1438 /*!
1439  * \brief attempts to register to a transport.
1440  * \param aji_client struct, and xml packet.
1441  * \return IKS_FILTER_EAT.
1442  */
1443 static int aji_register_transport(void *data, ikspak *pak)
1444 {
1445         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1446         int res = 0;
1447         struct aji_buddy *buddy = NULL;
1448         iks *send = NULL;
1449         send = iks_make_iq(IKS_TYPE_GET, "jabber:iq:register");
1450         if (client && send) {
1451                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1452                         ASTOBJ_RDLOCK(iterator); 
1453                         if (iterator->btype == AJI_TRANS) {
1454                                   buddy = iterator;
1455                         }
1456                         ASTOBJ_UNLOCK(iterator);
1457                 });
1458                 iks_filter_remove_hook(client->f, aji_register_transport);
1459                 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);
1460                 iks_insert_attrib(send, "to", buddy->host);
1461                 iks_insert_attrib(send, "id", client->mid);
1462                 ast_aji_increment_mid(client->mid);
1463                 iks_insert_attrib(send, "from", client->user);
1464                 res = iks_send(client->p, send);
1465         } else {
1466                 ast_log(LOG_ERROR, "Out of memory.\n");
1467         }
1468         if (send)
1469                 iks_delete(send);
1470         ASTOBJ_UNREF(client, aji_client_destroy);
1471         return IKS_FILTER_EAT;
1472
1473 }
1474
1475 /*!
1476  * \brief attempts to register to a transport step 2.
1477  * \param aji_client struct, and xml packet.
1478  * \return IKS_FILTER_EAT.
1479  */
1480 static int aji_register_transport2(void *data, ikspak *pak)
1481 {
1482         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1483         int res = 0;
1484         struct aji_buddy *buddy = NULL;
1485         iks *regquery = NULL, *reguser = NULL, *regpass = NULL, *regiq = NULL;
1486         regiq = iks_new("iq");
1487         regquery = iks_new("query");
1488         reguser = iks_new("username");
1489         regpass = iks_new("password");
1490
1491         if (client && regquery && reguser && regpass && regiq) {
1492                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1493                         ASTOBJ_RDLOCK(iterator);
1494                         if (iterator->btype == AJI_TRANS)
1495                                 buddy = iterator; ASTOBJ_UNLOCK(iterator);
1496                 });
1497                 iks_filter_remove_hook(client->f, aji_register_transport2);
1498                 iks_insert_attrib(regiq, "to", buddy->host);
1499                 iks_insert_attrib(regiq, "type", "set");
1500                 iks_insert_attrib(regiq, "id", client->mid);
1501                 ast_aji_increment_mid(client->mid);
1502                 iks_insert_attrib(regiq, "from", client->user);
1503                 iks_insert_attrib(regquery, "xmlns", "jabber:iq:register");
1504                 iks_insert_cdata(reguser, buddy->user, strlen(buddy->user));
1505                 iks_insert_cdata(regpass, buddy->pass, strlen(buddy->pass));
1506                 iks_insert_node(regiq, regquery);
1507                 iks_insert_node(regquery, reguser);
1508                 iks_insert_node(regquery, regpass);
1509                 res = iks_send(client->p, regiq);
1510         } else {
1511                 ast_log(LOG_ERROR, "Out of memory.\n");
1512         }
1513         if (regiq)
1514                 iks_delete(regiq);
1515         if (regquery)
1516                 iks_delete(regquery);
1517         if (reguser)
1518                 iks_delete(reguser);
1519         if (regpass)
1520                 iks_delete(regpass);
1521         ASTOBJ_UNREF(client, aji_client_destroy);
1522         return IKS_FILTER_EAT;
1523 }
1524
1525 /*!
1526  * \brief goes through roster and prunes users not needed in list, or adds them accordingly.
1527  * \param aji_client struct.
1528  * \return void.
1529  */
1530 static void aji_pruneregister(struct aji_client *client)
1531 {
1532         int res = 0;
1533         iks *removeiq = NULL, *removequery = NULL, *removeitem = NULL, *send = NULL;
1534         removeiq = iks_new("iq");
1535         removequery = iks_new("query");
1536         removeitem = iks_new("item");
1537         send = iks_make_iq(IKS_TYPE_GET, "http://jabber.org/protocol/disco#items");
1538
1539         if (client && removeiq && removequery && removeitem && send) {
1540                 iks_insert_node(removeiq, removequery);
1541                 iks_insert_node(removequery, removeitem);
1542                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1543                         ASTOBJ_RDLOCK(iterator);
1544                         /* For an aji_buddy, both AUTOPRUNE and AUTOREGISTER will never
1545                          * be called at the same time */
1546                         if (ast_test_flag(iterator, AJI_AUTOPRUNE)) {
1547                                 res = iks_send(client->p, iks_make_s10n(IKS_TYPE_UNSUBSCRIBE, iterator->name,
1548                                                 "GoodBye your status is no longer needed by Asterisk the Open Source PBX"
1549                                                 " so I am no longer subscribing to your presence.\n"));
1550                                 res = iks_send(client->p, iks_make_s10n(IKS_TYPE_UNSUBSCRIBED, iterator->name,
1551                                                 "GoodBye you are no longer in the asterisk config file so I am removing"
1552                                                 " your access to my presence.\n"));
1553                                 iks_insert_attrib(removeiq, "from", client->jid->full); 
1554                                 iks_insert_attrib(removeiq, "type", "set"); 
1555                                 iks_insert_attrib(removequery, "xmlns", "jabber:iq:roster");
1556                                 iks_insert_attrib(removeitem, "jid", iterator->name);
1557                                 iks_insert_attrib(removeitem, "subscription", "remove");
1558                                 res = iks_send(client->p, removeiq);
1559                         } else if (ast_test_flag(iterator, AJI_AUTOREGISTER)) {
1560                                 if (iterator->btype == AJI_USER) {      /*if it is not a transport */
1561                                         res = iks_send(client->p, iks_make_s10n(IKS_TYPE_SUBSCRIBE, iterator->name, 
1562                                                         "Greetings I am the Asterisk Open Source PBX and I want to subscribe to your presence\n"));
1563                                 } else {
1564                                         iks_filter_add_rule(client->f, aji_register_transport, client,
1565                                                                   IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_SUBTYPE, IKS_TYPE_RESULT, IKS_RULE_NS,
1566                                                                   "http://jabber.org/protocol/disco#items", IKS_RULE_DONE);
1567                                         iks_insert_attrib(send, "to", iterator->host);
1568                                         iks_insert_attrib(send, "from", client->jid->full);
1569                                         res = iks_send(client->p, send);
1570                                 }
1571                                 ast_clear_flag(iterator, AJI_AUTOREGISTER);
1572                         }
1573                         ASTOBJ_UNLOCK(iterator);
1574                 });
1575         } else {
1576                 ast_log(LOG_ERROR, "Out of memory.\n");
1577         }
1578         if (removeiq)
1579                 iks_delete(removeiq);
1580         if (removequery)
1581                 iks_delete(removequery);
1582         if (removeitem)
1583                 iks_delete(removeitem);
1584         if (send)
1585                 iks_delete(send);
1586         ASTOBJ_CONTAINER_PRUNE_MARKED(&client->buddies, aji_buddy_destroy);
1587 }
1588
1589 /*!
1590  * \brief filters the roster packet we get back from server.
1591  * \param aji_client struct, and xml packet.
1592  * \return IKS_FILTER_EAT.
1593  */
1594 static int aji_filter_roster(void *data, ikspak *pak)
1595 {
1596         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1597         int flag = 0;
1598         iks *x = NULL;
1599         struct aji_buddy *buddy;
1600         
1601         client->state = AJI_CONNECTED;
1602         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1603                 ASTOBJ_RDLOCK(iterator);
1604                 x = iks_child(pak->query);
1605                 flag = 0;
1606                 while (x) {
1607                         if (!iks_strcmp(iks_name(x), "item")) {
1608                                 if (!ast_strlen_zero(iterator->pass)) {
1609                                         if (!strcasecmp(iterator->host, iks_find_attrib(x, "jid"))) {
1610                                                   ast_clear_flag(iterator, AJI_AUTOPRUNE | AJI_AUTOREGISTER); 
1611                                                   flag = 1;
1612                                         }
1613                                 } else {
1614                                         if (!strcasecmp(iterator->name, iks_find_attrib(x, "jid"))) {
1615                                                   flag = 1;
1616                                                   ast_clear_flag(iterator, AJI_AUTOPRUNE | AJI_AUTOREGISTER);
1617                                         }
1618                                 }
1619                         }
1620                         x = iks_next(x);
1621                 }
1622                 if (!flag)
1623                         ast_copy_flags(iterator, client, AJI_AUTOREGISTER);
1624                 if (x)
1625                         iks_delete(x);
1626                 ASTOBJ_UNLOCK(iterator);
1627         });
1628
1629         x = iks_child(pak->query);
1630         while (x) {
1631                 flag = 0;
1632                 if (iks_strcmp(iks_name(x), "item") == 0) {
1633                         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1634                                 ASTOBJ_RDLOCK(iterator);
1635                                 if (!ast_strlen_zero(iterator->pass)) {
1636                                         if (!strcasecmp(iterator->host, iks_find_attrib(x, "jid")))
1637                                         flag = 1;
1638                                 } else {
1639                                         if (!strcasecmp(iterator->name, iks_find_attrib(x, "jid")))
1640                                                 flag = 1;
1641                                 }
1642                                 ASTOBJ_UNLOCK(iterator);
1643                         });
1644
1645                         if (!flag) {
1646                                 buddy = (struct aji_buddy *) malloc(sizeof(struct aji_buddy));
1647                                 if (!buddy) {
1648                                         ast_log(LOG_WARNING, "Out of memory\n");
1649                                         return 0;
1650                                 }
1651                                 memset(buddy, 0, sizeof(struct aji_buddy));
1652                                 ASTOBJ_INIT(buddy);
1653                                 ASTOBJ_WRLOCK(buddy);
1654                                 ast_copy_string(buddy->name, iks_find_attrib(x, "jid"), sizeof(buddy->name));
1655                                 ast_clear_flag(buddy, AST_FLAGS_ALL);
1656                                 if(ast_test_flag(client, AJI_AUTOPRUNE)) {
1657                                         ast_set_flag(buddy, AJI_AUTOPRUNE);
1658                                         buddy->objflags |= ASTOBJ_FLAG_MARKED;
1659                                 } else
1660                                         ast_set_flag(buddy, AJI_AUTOREGISTER);
1661                                 ASTOBJ_UNLOCK(buddy);
1662                                 if (buddy) {
1663                                         ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
1664                                         ASTOBJ_UNREF(buddy, aji_buddy_destroy);
1665                                 }
1666                         }
1667                 }
1668                 x = iks_next(x);
1669         }
1670         if (x)
1671                 iks_delete(x);
1672         aji_pruneregister(client);
1673
1674         ASTOBJ_UNREF(client, aji_client_destroy);
1675         return IKS_FILTER_EAT;
1676 }
1677
1678 static int aji_reconnect(struct aji_client *client)
1679 {
1680         int res = 0;
1681
1682         if (client->state)
1683                 client->state = AJI_DISCONNECTED;
1684         client->timeout=20;
1685         if (client->p)
1686                 iks_parser_reset(client->p);
1687         if (client->authorized)
1688                 client->authorized = 0;
1689
1690         switch (client->component) {
1691         case AJI_COMPONENT:
1692                 res = aji_component_initialize(client);
1693                 break;
1694         case AJI_CLIENT:
1695                 res = aji_client_initialize(client);
1696                 break;
1697         }
1698         return res;
1699 }
1700
1701 static int aji_get_roster(struct aji_client *client)
1702 {
1703         iks *roster = NULL;
1704         roster = iks_make_iq(IKS_TYPE_GET, IKS_NS_ROSTER);
1705         if(roster) {
1706                 iks_insert_attrib(roster, "id", "roster");
1707                 aji_set_presence(client, client->jid->full, 1, client->statusmessage);
1708                 iks_send(client->p, roster);
1709         }
1710         if (roster)
1711                 iks_delete(roster);
1712         return 1;
1713 }
1714
1715 /*!
1716  * \brief connects as a client to jabber server.
1717  * \param aji_client struct, and xml packet.
1718  * \return res.
1719  */
1720 static int aji_client_connect(void *data, ikspak *pak)
1721 {
1722         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1723         int res = 0;
1724         if (client) {
1725                 if (client->state == AJI_DISCONNECTED) {
1726                         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);
1727                         client->state = AJI_CONNECTING;
1728                         client->jid = (iks_find_cdata(pak->query, "jid")) ? iks_id_new(client->stack, iks_find_cdata(pak->query, "jid")) : client->jid;
1729                         iks_filter_remove_hook(client->f, aji_client_connect);
1730                         if(client->component == AJI_CLIENT)
1731                                 aji_get_roster(client);
1732                 }
1733         } else {
1734                 ast_log(LOG_ERROR, "Out of memory.\n");
1735         }
1736
1737         ASTOBJ_UNREF(client, aji_client_destroy);
1738         return res;
1739 }
1740
1741 /*!
1742  * \brief prepares client for connect.
1743  * \param aji_client struct.
1744  * \return 1.
1745  */
1746 static int aji_client_initialize(struct aji_client *client)
1747 {
1748         int connected = 0;
1749
1750         connected = iks_connect_via(client->p, S_OR(client->serverhost, client->jid->server), client->port, client->jid->server);
1751
1752         if (connected == IKS_NET_NOCONN) {
1753                 ast_log(LOG_ERROR, "JABBER ERROR: No Connection\n");
1754                 return IKS_HOOK;
1755         } else  if (connected == IKS_NET_NODNS) {
1756                 ast_log(LOG_ERROR, "JABBER ERROR: No DNS %s for client to  %s\n", client->name, S_OR(client->serverhost, client->jid->server));
1757                 return IKS_HOOK;
1758         } else
1759                 iks_recv(client->p, 30);
1760         return IKS_OK;
1761 }
1762
1763 /*!
1764  * \brief prepares component for connect.
1765  * \param aji_client struct.
1766  * \return 1.
1767  */
1768 static int aji_component_initialize(struct aji_client *client)
1769 {
1770         int connected = 1;
1771         connected = iks_connect_via(client->p, client->jid->server, client->port, client->user);
1772         if (connected == IKS_NET_NOCONN)
1773                 ast_log(LOG_ERROR, "JABBER ERROR: No Connection");
1774         if (connected == IKS_NET_NODNS)
1775                 ast_log(LOG_ERROR, "JABBER ERROR: No DNS");
1776         if (!connected)
1777                 iks_recv(client->p, 30);
1778         return 1;
1779 }
1780
1781 /*!
1782  * \brief disconnect from jabber server.
1783  * \param aji_client struct.
1784  * \return 1.
1785  */
1786 int ast_aji_disconnect(struct aji_client *client)
1787 {
1788         if (client) {
1789                 if (option_verbose > 3)
1790                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: Disconnecting\n");
1791                 iks_disconnect(client->p);
1792                 iks_parser_delete(client->p);
1793                 ASTOBJ_UNREF(client, aji_client_destroy);
1794         }
1795
1796         return 1;
1797 }
1798
1799 /*!
1800  * \brief set presence of client.
1801  * \param aji_client struct, user to send it to, level, description.
1802  * \return void.
1803  */
1804 static void aji_set_presence(struct aji_client *client, char *user, int level, char *desc)
1805 {
1806         int res = 0;
1807         iks *presence = NULL, *priority, *cnode = NULL;
1808         presence = iks_make_pres(level, desc);
1809         cnode = iks_new("c");
1810         priority = iks_new("priority");
1811         iks_insert_cdata(priority, "0", 1);
1812         if (presence && cnode && client) {
1813                 iks_insert_attrib(cnode, "node", "http://www.asterisk.org/xmpp/client/caps");
1814                 iks_insert_attrib(cnode, "ver", "asterisk-xmpp");
1815                 iks_insert_attrib(cnode, "ext", "voice-v1");
1816                 iks_insert_attrib(cnode, "xmlns", "http://jabber.org/protocol/caps");
1817                 iks_insert_node(presence, cnode);
1818                 res = iks_send(client->p, presence);
1819         } else {
1820                 ast_log(LOG_ERROR, "Out of memory.\n");
1821         }
1822         if (cnode)
1823                 iks_delete(cnode);
1824         if (presence)
1825                 iks_delete(presence);
1826 }
1827
1828 /*!
1829  * \brief turnon console debugging.
1830  * \param fd, number of args, args.
1831  * \return RESULT_SUCCESS.
1832  */
1833 static int aji_do_debug(int fd, int argc, char *argv[])
1834 {
1835         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
1836                 ASTOBJ_RDLOCK(iterator); 
1837                 iterator->debug = 1;
1838                 ASTOBJ_UNLOCK(iterator);
1839         });
1840         if (option_verbose > 3)
1841                 ast_verbose(VERBOSE_PREFIX_3 "JABBER: Debugging Enabled.\n");
1842         return RESULT_SUCCESS;
1843 }
1844
1845 /*!
1846  * \brief reload jabber module.
1847  * \param fd, number of args, args.
1848  * \return RESULT_SUCCESS.
1849  */
1850 static int aji_do_reload(int fd, int argc, char *argv[])
1851 {
1852         aji_reload();
1853         if (option_verbose > 3)
1854                 ast_verbose(VERBOSE_PREFIX_3 "JABBER: Reloaded.\n");
1855         return RESULT_SUCCESS;
1856 }
1857
1858 /*!
1859  * \brief turnoff console debugging.
1860  * \param fd, number of args, args.
1861  * \return RESULT_SUCCESS.
1862  */
1863 static int aji_no_debug(int fd, int argc, char *argv[])
1864 {
1865         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
1866                 ASTOBJ_RDLOCK(iterator);
1867                 iterator->debug = 0;
1868                 ASTOBJ_UNLOCK(iterator);
1869         });
1870         if (option_verbose > 2)
1871                 ast_verbose(VERBOSE_PREFIX_3 "JABBER: Debugging Disabled\n");
1872         return RESULT_SUCCESS;
1873 }
1874
1875 /*!
1876  * \brief show client status.
1877  * \param fd, number of args, args.
1878  * \return RESULT_SUCCESS.
1879  */
1880 static int aji_show_clients(int fd, int argc, char *argv[])
1881 {
1882         char *status = "";
1883         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
1884                 ASTOBJ_RDLOCK(iterator);
1885                 switch (iterator->state) {
1886                 case AJI_DISCONNECTED:
1887                         status = "Disconnected";
1888                         break;
1889                 case AJI_CONNECTING:
1890                         status = "Connecting";
1891                         break;
1892                 case AJI_CONNECTED:
1893                         status = "Connected";
1894                         break;
1895                 default:
1896                         status = "Unknown";
1897                 }
1898                 ast_verbose("JABBER: User: %s is %s\n", iterator->user, status);
1899                 ASTOBJ_UNLOCK(iterator);
1900         });
1901         return RESULT_SUCCESS;
1902 }
1903
1904 /*!
1905  * \brief send test message for debuging.
1906  * \param fd, number of args, args.
1907  * \return RESULT_SUCCESS.
1908  */
1909 static int aji_test(int fd, int argc, char *argv[])
1910 {
1911         struct aji_client *client;
1912         struct aji_resource *resource;
1913         const char *name = "asterisk";
1914         struct aji_message *tmp;
1915         if (argc > 3)
1916                 return RESULT_SHOWUSAGE;
1917         else if (argc == 3)
1918                 name = argv[2];
1919
1920         if (!(client = ASTOBJ_CONTAINER_FIND(&clients, name))) {
1921                 ast_cli(fd, "Unable to find client '%s'!\n", name);
1922                 return RESULT_FAILURE;
1923         }
1924
1925         ast_aji_send(client, "mogorman@astjab.org", "blahblah");
1926         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
1927                 ASTOBJ_RDLOCK(iterator);
1928                 ast_verbose("User: %s\n", iterator->name);
1929                 for (resource = iterator->resources; resource; resource = resource->next) {
1930                         ast_verbose("Resource: %s\n", resource->resource);
1931                         if(resource->cap) {
1932                                 ast_verbose("   client: %s\n", resource->cap->parent->node);
1933                                 ast_verbose("   version: %s\n", resource->cap->version);
1934                                 ast_verbose("   Jingle Capable: %d\n", resource->cap->jingle);
1935                         }
1936                         ast_verbose("   Priority: %d\n", resource->priority);
1937                         ast_verbose("   Status: %d\n", resource->status); 
1938                         ast_verbose("   Message: %s\n", S_OR(resource->description,"")); 
1939                 }
1940                 ASTOBJ_UNLOCK(iterator);
1941         });
1942         ast_verbose("\nOooh a working message stack!\n");
1943         AST_LIST_LOCK(&client->messages);
1944         AST_LIST_TRAVERSE(&client->messages, tmp, list) {
1945                 ast_verbose("   Message from: %s with id %s @ %s        %s\n",tmp->from, tmp->id, ctime(&tmp->arrived), tmp->message);
1946         }
1947         AST_LIST_UNLOCK(&client->messages);
1948         ASTOBJ_UNREF(client, aji_client_destroy);
1949
1950         return RESULT_SUCCESS;
1951 }
1952
1953 /*!
1954  * \brief creates aji_client structure.
1955  * \param label, ast_variable, debug, pruneregister, component/client, aji_client to dump into. 
1956  * \return 0.
1957  */
1958 static int aji_create_client(char *label, struct ast_variable *var, int debug)
1959 {
1960         char *resource;
1961         struct aji_client *client = NULL;
1962         int flag = 0;
1963         client = ASTOBJ_CONTAINER_FIND(&clients,label);
1964         if(!client) {
1965                 flag = 1;
1966                 client = (struct aji_client *) malloc(sizeof(struct aji_client));
1967                 if(client) {
1968                         memset(client, 0, sizeof(struct aji_client));
1969                         ASTOBJ_INIT(client);
1970                         ASTOBJ_WRLOCK(client);
1971                         ASTOBJ_CONTAINER_INIT(&client->buddies);
1972                 } else {
1973                         ast_log(LOG_ERROR, "Out of memory!\n");
1974                         return 0;
1975                 }
1976         } else {
1977                 ASTOBJ_WRLOCK(client);
1978                 ASTOBJ_UNMARK(client);
1979         }
1980         ASTOBJ_CONTAINER_MARKALL(&client->buddies);
1981         ast_copy_string(client->name, label, sizeof(client->name));
1982         ast_copy_string(client->mid, "aaaaa", sizeof(client->mid));
1983
1984         client->debug = debug;
1985         ast_copy_flags(client, &globalflags, AST_FLAGS_ALL);
1986         client->port = 5222;
1987         client->usetls = 1;
1988         client->usesasl = 1;
1989         client->forcessl = 0;
1990         client->keepalive = 1;
1991         client->timeout = 20;
1992         client->message_timeout = 100;
1993         AST_LIST_HEAD_INIT(&client->messages);
1994         client->component = AJI_CLIENT;
1995         ast_copy_string(client->statusmessage, "Online and Available", sizeof(client->statusmessage));
1996
1997         if (flag) client->authorized = 0;
1998         if (flag) client->state = AJI_DISCONNECTED;
1999         while (var) {
2000                 if (!strcasecmp(var->name, "username"))
2001                         ast_copy_string(client->user, var->value, sizeof(client->user));
2002                 else if (!strcasecmp(var->name, "serverhost"))
2003                         ast_copy_string(client->serverhost, var->value, sizeof(client->serverhost));
2004                 else if (!strcasecmp(var->name, "secret"))
2005                         ast_copy_string(client->password, var->value, sizeof(client->password));
2006                 else if (!strcasecmp(var->name, "statusmessage"))
2007                         ast_copy_string(client->statusmessage, var->value, sizeof(client->statusmessage));
2008                 else if (!strcasecmp(var->name, "port"))
2009                         client->port = atoi(var->value);
2010                 else if (!strcasecmp(var->name, "timeout"))
2011                         client->message_timeout = atoi(var->value);
2012                 else if (!strcasecmp(var->name, "debug"))
2013                         client->debug = (ast_false(var->value)) ? 0 : 1;
2014                 else if (!strcasecmp(var->name, "type")){
2015                         if (!strcasecmp(var->value, "component"))
2016                                 client->component = AJI_COMPONENT;
2017                 } else if (!strcasecmp(var->name, "usetls")) {
2018                         client->usetls = (ast_false(var->value)) ? 0 : 1;
2019                 } else if (!strcasecmp(var->name, "usesasl")) {
2020                         client->usesasl = (ast_false(var->value)) ? 0 : 1;
2021                 } else if (!strcasecmp(var->name, "forceoldssl"))
2022                         client->forcessl = (ast_false(var->value)) ? 0 : 1;
2023                 else if (!strcasecmp(var->name, "keepalive"))
2024                         client->keepalive = (ast_false(var->value)) ? 0 : 1;
2025                 else if (!strcasecmp(var->name, "autoprune"))
2026                         ast_set2_flag(client, ast_true(var->value), AJI_AUTOPRUNE);
2027                 else if (!strcasecmp(var->name, "autoregister"))
2028                         ast_set2_flag(client, ast_true(var->value), AJI_AUTOREGISTER);
2029                 else if (!strcasecmp(var->name, "buddy"))
2030                                 aji_create_buddy(var->value, client);
2031                 else if (!strcasecmp(var->name, "transport"))
2032                                 aji_create_transport(var->value, client);
2033                 var = var->next;
2034         }
2035         if(flag) {
2036                 client->p = iks_stream_new(((client->component == AJI_CLIENT) ? "jabber:client" : "jabber:component:accept"), client, aji_act_hook);
2037                 if (!client->p) {
2038                         ast_log(LOG_WARNING, "Failed to create stream for client '%s'!\n", client->name);
2039                         return 0;
2040                 }
2041                 client->stack = iks_stack_new(8192, 8192);
2042                 if (!client->stack) {
2043                         ast_log(LOG_WARNING, "Failed to allocate stack for client '%s'\n", client->name);
2044                         return 0;
2045                 }
2046                 client->f = iks_filter_new();
2047                 if (!client->f) {
2048                         ast_log(LOG_WARNING, "Failed to create filter for client '%s'\n", client->name);
2049                         return 0;
2050                 }
2051                 if (!strchr(client->user, '/') && client->component == AJI_CLIENT) {
2052                         resource = NULL;
2053                         asprintf(&resource, "%s/asterisk", client->user);
2054                         if (resource) {
2055                                 client->jid = iks_id_new(client->stack, resource);
2056                                 free(resource);
2057                         }
2058                 } else
2059                         client->jid = iks_id_new(client->stack, client->user);
2060                 if (client->component == AJI_COMPONENT) {
2061                         iks_filter_add_rule(client->f, aji_dinfo_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
2062                         iks_filter_add_rule(client->f, aji_ditems_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#items", IKS_RULE_DONE);
2063                         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);
2064                         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);
2065                 } else {
2066                         iks_filter_add_rule(client->f, aji_client_info_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
2067                 }
2068                 if (!strchr(client->user, '/') && client->component == AJI_CLIENT) {
2069                         resource = NULL;
2070                         asprintf(&resource, "%s/asterisk", client->user);
2071                         if (resource) {
2072                                 client->jid = iks_id_new(client->stack, resource);
2073                                 free(resource);
2074                         }
2075                 } else
2076                         client->jid = iks_id_new(client->stack, client->user);
2077                 iks_set_log_hook(client->p, aji_log_hook);
2078                 ASTOBJ_UNLOCK(client);
2079                 ASTOBJ_CONTAINER_LINK(&clients,client);
2080         } else {
2081                 ASTOBJ_UNLOCK(client);
2082                 ASTOBJ_UNREF(client, aji_client_destroy);
2083         }
2084         return 1;
2085 }
2086
2087 /*!
2088  * \brief creates transport.
2089  * \param label, buddy to dump it into. 
2090  * \return 0.
2091  */
2092 static int aji_create_transport(char *label, struct aji_client *client)
2093 {
2094         char *server = NULL, *buddyname = NULL, *user = NULL, *pass = NULL;
2095         struct aji_buddy *buddy = NULL;
2096
2097         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies,label);
2098         if (!buddy) {
2099                 buddy = malloc(sizeof(struct aji_buddy));
2100                 if(!buddy) {
2101                         ast_log(LOG_WARNING, "Out of memory\n");
2102                         return 0;
2103                 } else {
2104                         memset(buddy, 0, sizeof(struct aji_buddy));
2105                         ASTOBJ_INIT(buddy);
2106                         
2107                 }
2108         }
2109         ASTOBJ_WRLOCK(buddy);
2110         server = label;
2111         if ((buddyname = strchr(label, ','))) {
2112                 *buddyname = '\0';
2113                 buddyname++;
2114                 if (buddyname && buddyname[0] != '\0') {
2115                         if ((user = strchr(buddyname, ','))) {
2116                                 *user = '\0';
2117                                 user++;
2118                                 if (user && user[0] != '\0') {
2119                                         if ((pass = strchr(user, ','))) {
2120                                                 *pass = '\0';
2121                                                 pass++;
2122                                                 ast_copy_string(buddy->pass, pass, sizeof(buddy->pass));
2123                                                 ast_copy_string(buddy->user, user, sizeof(buddy->user));
2124                                                 ast_copy_string(buddy->name, buddyname, sizeof(buddy->name));
2125                                                 ast_copy_string(buddy->server, server, sizeof(buddy->server));
2126                                                 return 1;
2127                                         }
2128                                 }
2129                         }
2130                 }
2131         }
2132         ASTOBJ_UNLOCK(buddy);
2133         ASTOBJ_UNMARK(buddy);
2134         ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
2135         return 0;
2136 }
2137
2138 /*!
2139  * \brief creates buddy.
2140  * \param label, buddy to dump it into. 
2141  * \return 0.
2142  */
2143 static int aji_create_buddy(char *label, struct aji_client *client)
2144 {
2145         struct aji_buddy *buddy = NULL;
2146         int flag = 0;
2147         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies,label);
2148         if (!buddy) {
2149                 flag = 1;
2150                 buddy = malloc(sizeof(struct aji_buddy));
2151                 if(!buddy) {
2152                         ast_log(LOG_WARNING, "Out of memory\n");
2153                         return 0;
2154                 } else {
2155                         memset(buddy, 0, sizeof(struct aji_buddy));
2156                         ASTOBJ_INIT(buddy);
2157                         
2158                 }
2159         }
2160         ASTOBJ_WRLOCK(buddy);
2161         ast_copy_string(buddy->name, label, sizeof(buddy->name));
2162         ASTOBJ_UNLOCK(buddy);
2163         if(flag)
2164                 ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
2165         else {
2166                 ASTOBJ_UNMARK(buddy);
2167                 ASTOBJ_UNREF(buddy, aji_buddy_destroy);
2168         }
2169         return 1;
2170 }
2171
2172 /*!
2173  * \brief load config file.
2174  * \param void. 
2175  * \return 1.
2176  */
2177 static int aji_load_config(void)
2178 {
2179         char *cat = NULL;
2180         int debug = 1;
2181         struct ast_config *cfg = NULL;
2182         struct ast_variable *var = NULL;
2183
2184         cfg = ast_config_load(JABBER_CONFIG);
2185         if (!cfg) {
2186                 ast_log(LOG_WARNING, "No such configuration file %s\n", JABBER_CONFIG);
2187                 return 0;
2188         }
2189
2190         cat = ast_category_browse(cfg, NULL);
2191         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
2192                 if (!strcasecmp(var->name, "debug"))
2193                         debug = (ast_false(ast_variable_retrieve(cfg, "general", "debug"))) ? 0 : 1;
2194                 else if (!strcasecmp(var->name, "autoprune"))
2195                         ast_set2_flag(&globalflags, ast_true(var->value), AJI_AUTOPRUNE);
2196                 else if (!strcasecmp(var->name, "autoregister"))
2197                         ast_set2_flag(&globalflags, ast_true(var->value), AJI_AUTOREGISTER);
2198         }
2199
2200         while (cat) {
2201                 if (strcasecmp(cat, "general")) {
2202                                 var = ast_variable_browse(cfg, cat);
2203                                 aji_create_client(cat, var, debug);
2204                 }
2205                 cat = ast_category_browse(cfg, cat);
2206         }
2207         return 1;
2208 }
2209
2210 /*!
2211  * \brief grab a aji_client structure by label name.
2212  * \param void. 
2213  * \return 1.
2214  */
2215
2216 struct aji_client *ast_aji_get_client(char *name)
2217 {
2218         struct aji_client *client = NULL;
2219         client = ASTOBJ_CONTAINER_FIND(&clients, name);
2220         if (!client && !strchr(name, '@'))
2221                 client = ASTOBJ_CONTAINER_FIND_FULL(&clients, name, user,,, strcasecmp);
2222         return client;
2223 }
2224
2225 struct aji_client_container *ast_aji_get_clients(void)
2226 {
2227         return &clients;
2228 }
2229
2230 static void aji_reload()
2231 {
2232         ASTOBJ_CONTAINER_MARKALL(&clients);
2233         if (!aji_load_config())
2234                 ast_log(LOG_ERROR, "JABBER: Failed to load config.\n");
2235         else {
2236                 ASTOBJ_CONTAINER_PRUNE_MARKED(&clients, aji_client_destroy);
2237                 ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2238                         ASTOBJ_RDLOCK(iterator);
2239                         if(iterator->state == AJI_DISCONNECTED) {
2240                                 if (!iterator->thread)
2241                                         ast_pthread_create(&iterator->thread, NULL, aji_recv_loop, iterator);
2242                         } else if (iterator->state == AJI_CONNECTING) {
2243                                 aji_get_roster(iterator);
2244                         }
2245                         ASTOBJ_UNLOCK(iterator);
2246                 });
2247         }
2248 }
2249
2250 static int unload_module(void *mod)
2251 {
2252         ast_cli_unregister_multiple(aji_cli, sizeof(aji_cli) / sizeof(aji_cli[0]));
2253         ast_unregister_application(app_ajisend);
2254
2255         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2256                 ASTOBJ_RDLOCK(iterator);
2257                 if (option_verbose > 2)
2258                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: %s\n", iterator->name);
2259                 iterator->state = AJI_DISCONNECTED;
2260                 ast_aji_disconnect(iterator);
2261                 pthread_join(iterator->thread, NULL);
2262                 ASTOBJ_UNLOCK(iterator);
2263         });
2264
2265         ASTOBJ_CONTAINER_DESTROYALL(&clients, aji_client_destroy);
2266         ASTOBJ_CONTAINER_DESTROY(&clients);
2267
2268         ast_log(LOG_NOTICE, "res_jabber unloaded.\n");
2269         return 0;
2270 }
2271
2272 static int load_module(void *mod)
2273 {
2274         ASTOBJ_CONTAINER_INIT(&clients);
2275         aji_reload();
2276         ast_register_application(app_ajisend, aji_send_exec, ajisend_synopsis, ajisend_descrip);
2277         ast_register_application(app_ajistatus, aji_status_exec, ajistatus_synopsis, ajistatus_descrip);
2278         ast_cli_register_multiple(aji_cli, sizeof(aji_cli) / sizeof(aji_cli[0]));
2279         ast_log(LOG_NOTICE, "res_jabber.so loaded.\n");
2280         return 0;
2281 }
2282
2283 static int reload(void *mod)
2284 {
2285         aji_reload();
2286         return 0;
2287 }
2288
2289 static const char *description(void)
2290 {
2291         return tdesc;
2292 }
2293
2294 static const char *key(void)
2295 {
2296         return ASTERISK_GPL_KEY;
2297 }
2298
2299 STD_MOD(MOD_0, reload, NULL, NULL);