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