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