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