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