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