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