735d7b5959bd21820e4d0df254345b80dfe58412
[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 XMPP/Jabber compliant server.
22  *
23  * References:
24  * - http://www.xmpp.org - The XMPP standards foundation
25  *
26  * \extref Iksemel http://code.google.com/p/iksemel/
27  *
28  * \todo If you unload this module, chan_gtalk/jingle will be dead. How do we handle that?
29  * \todo Dialplan applications need RETURN variable, like JABBERSENDSTATUS
30  *
31  */
32
33 /*** MODULEINFO
34         <depend>iksemel</depend>
35         <use>openssl</use>
36  ***/
37
38 #include "asterisk.h"
39
40 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
41
42 #include <ctype.h>
43 #include <iksemel.h>
44
45 #include "asterisk/channel.h"
46 #include "asterisk/jabber.h"
47 #include "asterisk/file.h"
48 #include "asterisk/config.h"
49 #include "asterisk/callerid.h"
50 #include "asterisk/lock.h"
51 #include "asterisk/cli.h"
52 #include "asterisk/app.h"
53 #include "asterisk/pbx.h"
54 #include "asterisk/md5.h"
55 #include "asterisk/acl.h"
56 #include "asterisk/utils.h"
57 #include "asterisk/module.h"
58 #include "asterisk/astobj.h"
59 #include "asterisk/astdb.h"
60 #include "asterisk/manager.h"
61
62 /*** DOCUMENTATION
63         <application name="JabberSend" language="en_US">
64                 <synopsis>
65                         Send a Jabber Message
66                 </synopsis>
67                 <syntax>
68                         <parameter name="Jabber" required="true">
69                                 <para>Client or transport Asterisk uses to connect to Jabber.</para>
70                         </parameter>
71                         <parameter name="JID" required="true">
72                                 <para>XMPP/Jabber JID (Name) of recipient.</para>
73                         </parameter>
74                         <parameter name="Message" required="true">
75                                 <para>Message to be sent to the buddy.</para>
76                         </parameter>
77                 </syntax>
78                 <description>
79                         <para>Allows user to send a message to a receipent via XMPP.</para>
80                 </description>
81         </application>
82         <application name="JabberStatus" language="en_US">
83                 <synopsis>
84                         Retrieve the status of a jabber list member
85                 </synopsis>
86                 <syntax>
87                         <parameter name="Jabber" required="true">
88                                 <para>Client or transport Asterisk users to connect to Jabber.</para>
89                         </parameter>
90                         <parameter name="JID" required="true">
91                                 <para>XMPP/Jabber JID (Name) of recipient.</para>
92                         </parameter>
93                         <parameter name="Variable" required="true">
94                                 <para>Variable to store the status of requested user.</para>
95                         </parameter>
96                 </syntax>
97                 <description>
98                         <para>This application is deprecated. Please use the JABBER_STATUS() function instead.</para>
99                         <para>Retrieves the numeric status associated with the specified buddy <replaceable>JID</replaceable>.
100                         The return value in the <replaceable>Variable</replaceable>will be one of the following.</para>
101                         <enumlist>
102                                 <enum name="1">
103                                         <para>Online.</para>
104                                 </enum>
105                                 <enum name="2">
106                                         <para>Chatty.</para>
107                                 </enum>
108                                 <enum name="3">
109                                         <para>Away.</para>
110                                 </enum>
111                                 <enum name="4">
112                                         <para>Extended Away.</para>
113                                 </enum>
114                                 <enum name="5">
115                                         <para>Do Not Disturb.</para>
116                                 </enum>
117                                 <enum name="6">
118                                         <para>Offline.</para>
119                                 </enum>
120                                 <enum name="7">
121                                         <para>Not In Roster.</para>
122                                 </enum>
123                         </enumlist>
124                 </description>
125         </application>
126         <function name="JABBER_STATUS" language="en_US">
127                 <synopsis>
128                         Retrieve the status of a jabber list member
129                 </synopsis>
130                 <syntax>
131                         <parameter name="sender" required="true">
132                                 <para>XMPP/Jabber ID (Name) of sender.</para>
133                         </parameter>
134                         <parameter name="buddy" required="true">
135                                 <para>XMPP/Jabber JID (Name) of recipient.</para>
136                         </parameter>
137                         <parameter name="resource">
138                                 <para>Client or transport Asterisk users to connect to Jabber.</para>
139                         </parameter>
140                 </syntax>
141                 <description>
142                         <para>Retrieves the numeric status associated with the specified buddy <replaceable>JID</replaceable>.
143                         The return value will be one of the following.</para>
144                         <enumlist>
145                                 <enum name="1">
146                                         <para>Online.</para>
147                                 </enum>
148                                 <enum name="2">
149                                         <para>Chatty.</para>
150                                 </enum>
151                                 <enum name="3">
152                                         <para>Away.</para>
153                                 </enum>
154                                 <enum name="4">
155                                         <para>Extended Away.</para>
156                                 </enum>
157                                 <enum name="5">
158                                         <para>Do Not Disturb.</para>
159                                 </enum>
160                                 <enum name="6">
161                                         <para>Offline.</para>
162                                 </enum>
163                                 <enum name="7">
164                                         <para>Not In Roster.</para>
165                                 </enum>
166                         </enumlist>
167                 </description>
168         </function>
169  ***/
170
171 /*! \todo This should really be renamed to xmpp.conf. For backwards compatibility, we
172         need to read both files */
173 #define JABBER_CONFIG "jabber.conf"
174
175 #ifndef FALSE
176 #define FALSE 0
177 #endif
178
179 #ifndef TRUE
180 #define TRUE 1
181 #endif
182
183 /*-- Forward declarations */
184 static void aji_buddy_destroy(struct aji_buddy *obj);
185 static void aji_client_destroy(struct aji_client *obj);
186 static int aji_is_secure(struct aji_client *client);
187 #ifdef HAVE_OPENSSL
188 static int aji_start_tls(struct aji_client *client);
189 static int aji_tls_handshake(struct aji_client *client);
190 #endif
191 static int aji_io_recv(struct aji_client *client, char *buffer, size_t buf_len, int timeout);
192 static int aji_recv(struct aji_client *client, int timeout);
193 static int aji_send_header(struct aji_client *client, const char *to);
194 static int aji_send_raw(struct aji_client *client, const char *xmlstr);
195 static void aji_log_hook(void *data, const char *xmpp, size_t size, int is_incoming);
196 static int aji_start_sasl(struct aji_client *client, enum ikssasltype type, char *username, char *pass);
197 static int aji_act_hook(void *data, int type, iks *node);
198 static void aji_handle_iq(struct aji_client *client, iks *node);
199 static void aji_handle_message(struct aji_client *client, ikspak *pak);
200 static void aji_handle_presence(struct aji_client *client, ikspak *pak);
201 static void aji_handle_subscribe(struct aji_client *client, ikspak *pak);
202 static void *aji_recv_loop(void *data);
203 static int aji_initialize(struct aji_client *client);
204 static int aji_client_connect(void *data, ikspak *pak);
205 static void aji_set_presence(struct aji_client *client, char *to, char *from, int level, char *desc);
206 static char *aji_do_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
207 static char *aji_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
208 static char *aji_show_clients(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
209 static char *aji_show_buddies(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
210 static char *aji_test(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
211 static int aji_create_client(char *label, struct ast_variable *var, int debug);
212 static int aji_create_buddy(char *label, struct aji_client *client);
213 static int aji_reload(int reload);
214 static int aji_load_config(int reload);
215 static void aji_pruneregister(struct aji_client *client);
216 static int aji_filter_roster(void *data, ikspak *pak);
217 static int aji_get_roster(struct aji_client *client);
218 static int aji_client_info_handler(void *data, ikspak *pak);
219 static int aji_dinfo_handler(void *data, ikspak *pak);
220 static int aji_ditems_handler(void *data, ikspak *pak);
221 static int aji_register_query_handler(void *data, ikspak *pak);
222 static int aji_register_approve_handler(void *data, ikspak *pak);
223 static int aji_reconnect(struct aji_client *client);
224 static iks *jabber_make_auth(iksid * id, const char *pass, const char *sid);
225 /* No transports in this version */
226 /*
227 static int aji_create_transport(char *label, struct aji_client *client);
228 static int aji_register_transport(void *data, ikspak *pak);
229 static int aji_register_transport2(void *data, ikspak *pak);
230 */
231
232 static struct ast_cli_entry aji_cli[] = {
233         AST_CLI_DEFINE(aji_do_set_debug, "Enable/Disable Jabber debug"),
234         AST_CLI_DEFINE(aji_do_reload, "Reload Jabber configuration"),
235         AST_CLI_DEFINE(aji_show_clients, "Show state of clients and components"),
236         AST_CLI_DEFINE(aji_show_buddies, "Show buddy lists of our clients"),
237         AST_CLI_DEFINE(aji_test, "Shows roster, but is generally used for mog's debugging."),
238 };
239
240 static char *app_ajisend = "JabberSend";
241
242 static char *app_ajistatus = "JabberStatus";
243
244 struct aji_client_container clients;
245 struct aji_capabilities *capabilities = NULL;
246
247 /*! \brief Global flags, initialized to default values */
248 static struct ast_flags globalflags = { AJI_AUTOREGISTER };
249
250 /*!
251  * \brief Deletes the aji_client data structure.
252  * \param obj aji_client The structure we will delete.
253  * \return void.
254  */
255 static void aji_client_destroy(struct aji_client *obj)
256 {
257         struct aji_message *tmp;
258         ASTOBJ_CONTAINER_DESTROYALL(&obj->buddies, aji_buddy_destroy);
259         ASTOBJ_CONTAINER_DESTROY(&obj->buddies);
260         iks_filter_delete(obj->f);
261         iks_parser_delete(obj->p);
262         iks_stack_delete(obj->stack);
263         AST_LIST_LOCK(&obj->messages);
264         while ((tmp = AST_LIST_REMOVE_HEAD(&obj->messages, list))) {
265                 if (tmp->from)
266                         ast_free(tmp->from);
267                 if (tmp->message)
268                         ast_free(tmp->message);
269         }
270         AST_LIST_HEAD_DESTROY(&obj->messages);
271         ast_free(obj);
272 }
273
274 /*!
275  * \brief Deletes the aji_buddy data structure.
276  * \param obj aji_buddy The structure we will delete.
277  * \return void.
278  */
279 static void aji_buddy_destroy(struct aji_buddy *obj)
280 {
281         struct aji_resource *tmp;
282
283         while ((tmp = obj->resources)) {
284                 obj->resources = obj->resources->next;
285                 ast_free(tmp->description);
286                 ast_free(tmp);
287         }
288
289         ast_free(obj);
290 }
291
292 /*!
293  * \brief Find version in XML stream and populate our capabilities list
294  * \param node the node attribute in the caps element we'll look for or add to 
295  * our list
296  * \param version the version attribute in the caps element we'll look for or 
297  * add to our list
298  * \param pak struct The XML stanza we're processing
299  * \return a pointer to the added or found aji_version structure
300  */ 
301 static struct aji_version *aji_find_version(char *node, char *version, ikspak *pak)
302 {
303         struct aji_capabilities *list = NULL;
304         struct aji_version *res = NULL;
305
306         list = capabilities;
307
308         if(!node)
309                 node = pak->from->full;
310         if(!version)
311                 version = "none supplied.";
312         while(list) {
313                 if(!strcasecmp(list->node, node)) {
314                         res = list->versions;
315                         while(res) {
316                                  if(!strcasecmp(res->version, version))
317                                          return res;
318                                  res = res->next;
319                         }
320                         /* Specified version not found. Let's add it to 
321                            this node in our capabilities list */
322                         if(!res) {
323                                 res = ast_malloc(sizeof(*res));
324                                 if(!res) {
325                                         ast_log(LOG_ERROR, "Out of memory!\n");
326                                         return NULL;
327                                 }
328                                 res->jingle = 0;
329                                 res->parent = list;
330                                 ast_copy_string(res->version, version, sizeof(res->version));
331                                 res->next = list->versions;
332                                 list->versions = res;
333                                 return res;
334                         }
335                 }
336                 list = list->next;
337         }
338         /* Specified node not found. Let's add it our capabilities list */
339         if(!list) {
340                 list = ast_malloc(sizeof(*list));
341                 if(!list) {
342                         ast_log(LOG_ERROR, "Out of memory!\n");
343                         return NULL;
344                 }
345                 res = ast_malloc(sizeof(*res));
346                 if(!res) {
347                         ast_log(LOG_ERROR, "Out of memory!\n");
348                         ast_free(list);
349                         return NULL;
350                 }
351                 ast_copy_string(list->node, node, sizeof(list->node));
352                 ast_copy_string(res->version, version, sizeof(res->version));
353                 res->jingle = 0;
354                 res->parent = list;
355                 res->next = NULL;
356                 list->versions = res;
357                 list->next = capabilities;
358                 capabilities = list;
359         }
360         return res;
361 }
362 /*!
363  * \brief Find the aji_resource we want
364  * \param buddy aji_buddy A buddy
365  * \param name 
366  * \return aji_resource object
367 */
368 static struct aji_resource *aji_find_resource(struct aji_buddy *buddy, char *name)
369 {
370         struct aji_resource *res = NULL;
371         if (!buddy || !name)
372                 return res;
373         res = buddy->resources;
374         while (res) {
375                 if (!strcasecmp(res->resource, name)) {
376                         break;
377                 }
378                 res = res->next;
379         }
380         return res;
381 }
382
383 /*!
384  * \brief Jabber GTalk function
385  * \param node iks
386  * \return 1 on success, 0 on failure.
387 */
388 static int gtalk_yuck(iks *node)
389 {
390         if (iks_find_with_attrib(node, "c", "node", "http://www.google.com/xmpp/client/caps"))
391                 return 1;
392         return 0;
393 }
394
395 /*!
396  * \brief Setup the authentication struct
397  * \param id iksid 
398  * \param pass password
399  * \param sid
400  * \return x iks
401 */
402 static iks *jabber_make_auth(iksid * id, const char *pass, const char *sid)
403 {
404         iks *x, *y;
405         x = iks_new("iq");
406         iks_insert_attrib(x, "type", "set");
407         y = iks_insert(x, "query");
408         iks_insert_attrib(y, "xmlns", IKS_NS_AUTH);
409         iks_insert_cdata(iks_insert(y, "username"), id->user, 0);
410         iks_insert_cdata(iks_insert(y, "resource"), id->resource, 0);
411         if (sid) {
412                 char buf[41];
413                 char sidpass[100];
414                 snprintf(sidpass, sizeof(sidpass), "%s%s", sid, pass);
415                 ast_sha1_hash(buf, sidpass);
416                 iks_insert_cdata(iks_insert(y, "digest"), buf, 0);
417         } else {
418                 iks_insert_cdata(iks_insert(y, "password"), pass, 0);
419         }
420         return x;
421 }
422
423 /*!
424  * \brief Dial plan function status(). puts the status of watched user 
425    into a channel variable.
426  * \param chan ast_channel
427  * \param data
428  * \return 0 on success, -1 on error
429  */
430 static int aji_status_exec(struct ast_channel *chan, const char *data)
431 {
432         struct aji_client *client = NULL;
433         struct aji_buddy *buddy = NULL;
434         struct aji_resource *r = NULL;
435         char *s = NULL;
436         int stat = 7;
437         char status[2];
438         static int deprecation_warning = 0;
439         AST_DECLARE_APP_ARGS(args,
440                 AST_APP_ARG(sender);
441                 AST_APP_ARG(jid);
442                 AST_APP_ARG(variable);
443         );
444         AST_DECLARE_APP_ARGS(jid,
445                 AST_APP_ARG(screenname);
446                 AST_APP_ARG(resource);
447         );
448
449         if (deprecation_warning++ % 10 == 0)
450                 ast_log(LOG_WARNING, "JabberStatus is deprecated.  Please use the JABBER_STATUS dialplan function in the future.\n");
451
452         if (!data) {
453                 ast_log(LOG_ERROR, "Usage: JabberStatus(<sender>,<jid>[/<resource>],<varname>\n");
454                 return 0;
455         }
456         s = ast_strdupa(data);
457         AST_STANDARD_APP_ARGS(args, s);
458
459         if (args.argc != 3) {
460                 ast_log(LOG_ERROR, "JabberStatus() requires 3 arguments.\n");
461                 return -1;
462         }
463
464         AST_NONSTANDARD_APP_ARGS(jid, args.jid, '/');
465
466         if (!(client = ast_aji_get_client(args.sender))) {
467                 ast_log(LOG_WARNING, "Could not find sender connection: '%s'\n", args.sender);
468                 return -1;
469         }
470         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, jid.screenname);
471         if (!buddy) {
472                 ast_log(LOG_WARNING, "Could not find buddy in list: '%s'\n", jid.screenname);
473                 return -1;
474         }
475         r = aji_find_resource(buddy, jid.resource);
476         if (!r && buddy->resources) 
477                 r = buddy->resources;
478         if (!r)
479                 ast_log(LOG_NOTICE, "Resource '%s' of buddy '%s' was not found\n", jid.resource, jid.screenname);
480         else
481                 stat = r->status;
482         snprintf(status, sizeof(status), "%d", stat);
483         pbx_builtin_setvar_helper(chan, args.variable, status);
484         return 0;
485 }
486
487 static int acf_jabberstatus_read(struct ast_channel *chan, const char *name, char *data, char *buf, size_t buflen)
488 {
489         struct aji_client *client = NULL;
490         struct aji_buddy *buddy = NULL;
491         struct aji_resource *r = NULL;
492         int stat = 7;
493         AST_DECLARE_APP_ARGS(args,
494                 AST_APP_ARG(sender);
495                 AST_APP_ARG(jid);
496         );
497         AST_DECLARE_APP_ARGS(jid,
498                 AST_APP_ARG(screenname);
499                 AST_APP_ARG(resource);
500         );
501
502         if (!data) {
503                 ast_log(LOG_ERROR, "Usage: JABBER_STATUS(<sender>,<jid>[/<resource>])\n");
504                 return 0;
505         }
506         AST_STANDARD_APP_ARGS(args, data);
507
508         if (args.argc != 2) {
509                 ast_log(LOG_ERROR, "JABBER_STATUS requires 2 arguments: sender and jid.\n");
510                 return -1;
511         }
512
513         AST_NONSTANDARD_APP_ARGS(jid, args.jid, '/');
514
515         if (!(client = ast_aji_get_client(args.sender))) {
516                 ast_log(LOG_WARNING, "Could not find sender connection: '%s'\n", args.sender);
517                 return -1;
518         }
519         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, jid.screenname);
520         if (!buddy) {
521                 ast_log(LOG_WARNING, "Could not find buddy in list: '%s'\n", jid.screenname);
522                 return -1;
523         }
524         r = aji_find_resource(buddy, jid.resource);
525         if (!r && buddy->resources) 
526                 r = buddy->resources;
527         if (!r)
528                 ast_log(LOG_NOTICE, "Resource %s of buddy %s was not found.\n", jid.resource, jid.screenname);
529         else
530                 stat = r->status;
531         snprintf(buf, buflen, "%d", stat);
532         return 0;
533 }
534
535 static struct ast_custom_function jabberstatus_function = {
536         .name = "JABBER_STATUS",
537         .read = acf_jabberstatus_read,
538 };
539
540 /*!
541  * \brief Dial plan function to send a message.
542  * \param chan ast_channel
543  * \param data  Data is sender|reciever|message.
544  * \return 0 on success,-1 on error.
545  */
546 static int aji_send_exec(struct ast_channel *chan, const char *data)
547 {
548         struct aji_client *client = NULL;
549         char *s;
550         AST_DECLARE_APP_ARGS(args,
551                 AST_APP_ARG(sender);
552                 AST_APP_ARG(recipient);
553                 AST_APP_ARG(message);
554         );
555
556         if (!data) {
557                 ast_log(LOG_ERROR, "Usage:  JabberSend(<sender>,<recipient>,<message>)\n");
558                 return 0;
559         }
560         s = ast_strdupa(data);
561
562         AST_STANDARD_APP_ARGS(args, s);
563         if (args.argc < 3) {
564                 ast_log(LOG_ERROR, "JabberSend requires 3 arguments: '%s'\n", data);
565                 return -1;
566         }
567
568         if (!(client = ast_aji_get_client(args.sender))) {
569                 ast_log(LOG_WARNING, "Could not find sender connection: '%s'\n", args.sender);
570                 return -1;
571         }
572         if (strchr(args.recipient, '@') && !ast_strlen_zero(args.message))
573                 ast_aji_send_chat(client, args.recipient, args.message);
574         return 0;
575 }
576
577 /*! 
578  * \brief Tests whether the connection is secured or not
579  * \return 0 if the connection is not secured
580  */
581 static int aji_is_secure(struct aji_client *client)
582 {
583 #ifdef HAVE_OPENSSL
584         return client->stream_flags & SECURE;
585 #else
586         return 0;
587 #endif
588 }
589
590 #ifdef HAVE_OPENSSL
591 /*!
592  * \brief Starts the TLS procedure
593  * \param client the configured XMPP client we use to connect to a XMPP server
594  * \return IKS_OK on success, an error code if sending failed, IKS_NET_TLSFAIL
595  * if OpenSSL is not installed
596  */
597 static int aji_start_tls(struct aji_client *client)
598 {
599         int ret;
600
601         /* This is sent not encrypted */
602         ret = iks_send_raw(client->p, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
603         if (ret)
604                 return ret;
605
606         client->stream_flags |= TRY_SECURE;
607         return IKS_OK;
608 }
609
610 /*! 
611  * \brief TLS handshake, OpenSSL initialization
612  * \param client the configured XMPP client we use to connect to a XMPP server
613  * \return IKS_OK on success, IKS_NET_TLSFAIL on failure 
614  */
615 static int aji_tls_handshake(struct aji_client *client)
616 {
617         int ret;
618         int sock;
619         
620         ast_debug(1, "Starting TLS handshake\n"); 
621
622         /* Load encryption, hashing algorithms and error strings */
623         SSL_library_init();
624         SSL_load_error_strings();
625
626         /* Choose an SSL/TLS protocol version, create SSL_CTX */
627         client->ssl_method = SSLv3_method();
628         client->ssl_context = SSL_CTX_new(client->ssl_method);                
629         if (!client->ssl_context)
630                 return IKS_NET_TLSFAIL;
631
632         /* Create new SSL session */
633         client->ssl_session = SSL_new(client->ssl_context);
634         if (!client->ssl_session)
635                 return IKS_NET_TLSFAIL;
636
637         /* Enforce TLS on our XMPP connection */
638         sock = iks_fd(client->p);
639         ret = SSL_set_fd(client->ssl_session, sock);
640         if (!ret)
641                 return IKS_NET_TLSFAIL;
642
643         /* Perform SSL handshake */
644         ret = SSL_connect(client->ssl_session);
645         if (!ret)
646                 return IKS_NET_TLSFAIL;
647
648         client->stream_flags &= (~TRY_SECURE);
649         client->stream_flags |= SECURE;
650
651         /* Sent over the established TLS connection */
652         ret = aji_send_header(client, client->jid->server);
653         if (ret != IKS_OK)
654                 return IKS_NET_TLSFAIL;
655
656         ast_debug(1, "TLS started with server\n"); 
657
658         return IKS_OK;
659 }
660 #endif /* HAVE_OPENSSL */
661
662 /*! 
663  * \brief Secured or unsecured IO socket receiving function
664  * \param client the configured XMPP client we use to connect to a XMPP server
665  * \param buffer the reception buffer
666  * \param buf_len the size of the buffer
667  * \param timeout the select timer
668  * \return the number of read bytes on success, 0 on timeout expiration, 
669  * -1 on  error
670  */
671 static int aji_io_recv(struct aji_client *client, char *buffer, size_t buf_len, int timeout)
672 {
673         int sock;
674         fd_set fds;
675         struct timeval tv, *tvptr = NULL;
676         int len, res;
677
678 #ifdef HAVE_OPENSSL
679         if (aji_is_secure(client)) {
680                 sock = SSL_get_fd(client->ssl_session);
681                 if (sock < 0)
682                         return -1;              
683         } else
684 #endif /* HAVE_OPENSSL */
685                 sock = iks_fd(client->p);       
686
687         memset(&tv, 0, sizeof(struct timeval));
688         FD_ZERO(&fds);
689         FD_SET(sock, &fds);
690         tv.tv_sec = timeout;
691
692         /* NULL value for tvptr makes ast_select wait indefinitely */
693         tvptr = (timeout != -1) ? &tv : NULL;
694
695         /* ast_select emulates linux behaviour in terms of timeout handling */
696         res = ast_select(sock + 1, &fds, NULL, NULL, tvptr);
697         if (res > 0) {
698 #ifdef HAVE_OPENSSL
699                 if (aji_is_secure(client)) {
700                         len = SSL_read(client->ssl_session, buffer, buf_len);
701                 } else
702 #endif /* HAVE_OPENSSL */
703                         len = recv(sock, buffer, buf_len, 0);
704
705                 if (len > 0) {
706                         return len;
707                 } else if (len <= 0) {
708                         return -1;
709                 }
710         }
711         return res;
712 }
713
714 /*! 
715  * \brief Tries to receive data from the Jabber server
716  * \param client the configured XMPP client we use to connect to a XMPP server
717  * \param timeout the timeout value
718  * This function receives (encrypted or unencrypted) data from the XMPP server,
719  * and passes it to the parser.
720  * \return IKS_OK on success, IKS_NET_RWERR on IO error, IKS_NET_NOCONN, if no
721  * connection available, IKS_NET_EXPIRED on timeout expiration
722  */
723 static int aji_recv (struct aji_client *client, int timeout)
724 {
725         int len, ret;
726         char buf[NET_IO_BUF_SIZE - 1];
727         char newbuf[NET_IO_BUF_SIZE - 1];
728         int pos = 0;
729         int newbufpos = 0;
730         unsigned char c;
731
732         memset(buf, 0, sizeof(buf));
733         memset(newbuf, 0, sizeof(newbuf));
734
735         while (1) {
736                 len = aji_io_recv(client, buf, NET_IO_BUF_SIZE - 2, timeout);
737                 if (len < 0) return IKS_NET_RWERR;
738                 if (len == 0) return IKS_NET_EXPIRED;
739                 buf[len] = '\0';
740
741                 /* our iksemel parser won't work as expected if we feed
742                    it with XML packets that contain multiple whitespace 
743                    characters between tags */
744                 while (pos < len) {
745                         c = buf[pos];
746                         /* if we stumble on the ending tag character,
747                            we skip any whitespace that follows it*/
748                         if (c == '>') {
749                                 while (isspace(buf[pos+1])) {
750                                         pos++;
751                                 }
752                         }
753                         newbuf[newbufpos] = c;
754                         newbufpos ++;
755                         pos++;
756                 }
757                 pos = 0;
758                 newbufpos = 0;
759
760                 /* Log the message here, because iksemel's logHook is 
761                    unaccessible */
762                 aji_log_hook(client, buf, len, 1);
763
764                 /* let iksemel deal with the string length, 
765                    and reset our buffer */
766                 ret = iks_parse(client->p, newbuf, 0, 0);
767                 memset(newbuf, 0, sizeof(newbuf));
768
769                 switch (ret) {
770                 case IKS_NOMEM:
771                         ast_log(LOG_WARNING, "Parsing failure: Out of memory.\n");
772                         break;
773                 case IKS_BADXML:
774                         ast_log(LOG_WARNING, "Parsing failure: Invalid XML.\n");
775                         break;
776                 case IKS_HOOK:
777                         ast_log(LOG_WARNING, "Parsing failure: Hook returned an error.\n");
778                         break;
779                 }
780                 if (ret != IKS_OK) {
781                         return ret;
782                 }
783                 ast_debug(3, "XML parsing successful\n");       
784         }
785         return IKS_OK;
786 }
787
788 /*! 
789  * \brief Sends XMPP header to the server
790  * \param client the configured XMPP client we use to connect to a XMPP server
791  * \param to the target XMPP server
792  * \return IKS_OK on success, any other value on failure
793  */
794 static int aji_send_header(struct aji_client *client, const char *to)
795 {
796         char *msg;
797         int len, err;
798
799         len = 91 + strlen(client->name_space) + 6 + strlen(to) + 16 + 1;
800         msg = iks_malloc(len);
801         if (!msg)
802                 return IKS_NOMEM;
803         sprintf(msg, "<?xml version='1.0'?>"
804                 "<stream:stream xmlns:stream='http://etherx.jabber.org/streams' xmlns='"
805                 "%s' to='%s' version='1.0'>", client->name_space, to);
806         err = aji_send_raw(client, msg);
807         iks_free(msg);
808         if (err != IKS_OK)
809                 return err;
810
811         return IKS_OK;
812 }
813
814 /*! 
815  * \brief Wraps raw sending
816  * \param client the configured XMPP client we use to connect to a XMPP server
817  * \param x the XMPP packet to send
818  * \return IKS_OK on success, any other value on failure
819  */
820 int ast_aji_send(struct aji_client *client, iks *x)
821 {
822         return aji_send_raw(client, iks_string(iks_stack(x), x));
823 }
824
825 /*! 
826  * \brief Sends an XML string over an XMPP connection
827  * \param client the configured XMPP client we use to connect to a XMPP server
828  * \param xmlstr the XML string to send
829  * The XML data is sent whether the connection is secured or not. In the 
830  * latter case, we just call iks_send_raw().
831  * \return IKS_OK on success, any other value on failure
832  */
833 static int aji_send_raw(struct aji_client *client, const char *xmlstr)
834 {
835         int ret;
836 #ifdef HAVE_OPENSSL
837         int len = strlen(xmlstr);
838
839         if (aji_is_secure(client)) {
840                 ret = SSL_write(client->ssl_session, xmlstr, len);
841                 if (ret) {
842                         /* Log the message here, because iksemel's logHook is 
843                            unaccessible */
844                         aji_log_hook(client, xmlstr, len, 0);
845                         return IKS_OK;
846                 }
847         }
848 #endif
849         /* If needed, data will be sent unencrypted, and logHook will 
850            be called inside iks_send_raw */
851         ret = iks_send_raw(client->p, xmlstr);
852         if (ret != IKS_OK)
853                 return ret;     
854
855         return IKS_OK;
856 }
857
858 /*!
859  * \brief the debug loop.
860  * \param data void
861  * \param xmpp xml data as string
862  * \param size size of string
863  * \param is_incoming direction of packet 1 for inbound 0 for outbound.
864  */
865 static void aji_log_hook(void *data, const char *xmpp, size_t size, int is_incoming)
866 {
867         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
868
869         if (!ast_strlen_zero(xmpp))
870                 manager_event(EVENT_FLAG_USER, "JabberEvent", "Account: %s\r\nPacket: %s\r\n", client->name, xmpp);
871
872         if (client->debug) {
873                 if (is_incoming)
874                         ast_verbose("\nJABBER: %s INCOMING: %s\n", client->name, xmpp);
875                 else {
876                         if( strlen(xmpp) == 1) {
877                                 if(option_debug > 2  && xmpp[0] == ' ') {
878                                         ast_verbose("\nJABBER: Keep alive packet\n");
879                                 }
880                         } else
881                                 ast_verbose("\nJABBER: %s OUTGOING: %s\n", client->name, xmpp);
882                 }
883
884         }
885         ASTOBJ_UNREF(client, aji_client_destroy);
886 }
887
888 /*!
889  * \brief A wrapper function for iks_start_sasl
890  * \param client the configured XMPP client we use to connect to a XMPP server
891  * \param type the SASL authentication type. Supported types are PLAIN and MD5
892  * \param username
893  * \param pass password.
894  *
895  * \return IKS_OK on success, IKSNET_NOTSUPP on failure.
896  */
897 static int aji_start_sasl(struct aji_client *client, enum ikssasltype type, char *username, char *pass)
898 {
899         iks *x = NULL;
900         int len;
901         char *s;
902         char *base64;
903
904         /* trigger SASL DIGEST-MD5 only over an unsecured connection.
905            iks_start_sasl is an iksemel API function and relies on GnuTLS,
906            whereas we use OpenSSL */
907         if ((type & IKS_STREAM_SASL_MD5) && !aji_is_secure(client))
908                 return iks_start_sasl(client->p, IKS_SASL_DIGEST_MD5, username, pass); 
909         if (!(type & IKS_STREAM_SASL_PLAIN)) {
910                 ast_log(LOG_ERROR, "Server does not support SASL PLAIN authentication\n");
911                 return IKS_NET_NOTSUPP;
912         }
913
914         x = iks_new("auth"); 
915         if (!x) {
916                 ast_log(LOG_ERROR, "Out of memory.\n");
917                 return IKS_NET_NOTSUPP;
918         }
919
920         iks_insert_attrib(x, "xmlns", IKS_NS_XMPP_SASL);
921         len = strlen(username) + strlen(pass) + 3;
922         s = alloca(len);
923         base64 = alloca((len + 2) * 4 / 3);
924         iks_insert_attrib(x, "mechanism", "PLAIN");
925         snprintf(s, len, "%c%s%c%s", 0, username, 0, pass);
926
927         /* exclude the NULL training byte from the base64 encoding operation
928            as some XMPP servers will refuse it.
929            The format for authentication is [authzid]\0authcid\0password
930            not [authzid]\0authcid\0password\0 */
931         ast_base64encode(base64, (const unsigned char *) s, len - 1, (len + 2) * 4 / 3);
932         iks_insert_cdata(x, base64, 0);
933         ast_aji_send(client, x);
934         iks_delete(x);
935
936         return IKS_OK;
937 }
938
939 /*!
940  * \brief The action hook parses the inbound packets, constantly running.
941  * \param data aji client structure 
942  * \param type type of packet 
943  * \param node the actual packet.
944  * \return IKS_OK or IKS_HOOK .
945  */
946 static int aji_act_hook(void *data, int type, iks *node)
947 {
948         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
949         ikspak *pak = NULL;
950         iks *auth = NULL;
951         int features = 0;
952
953         if(!node) {
954                 ast_log(LOG_ERROR, "aji_act_hook was called with out a packet\n"); /* most likely cause type is IKS_NODE_ERROR lost connection */
955                 ASTOBJ_UNREF(client, aji_client_destroy);
956                 return IKS_HOOK;
957         }
958
959         if (client->state == AJI_DISCONNECTING) {
960                 ASTOBJ_UNREF(client, aji_client_destroy);
961                 return IKS_HOOK;
962         }
963
964         pak = iks_packet(node);
965
966         if (!client->component) { /*client */
967                 switch (type) {
968                 case IKS_NODE_START:
969                         if (client->usetls && !aji_is_secure(client)) {
970 #ifndef HAVE_OPENSSL
971                                 ast_log(LOG_ERROR, "OpenSSL not installed. You need to install OpenSSL on this system, or disable the TLS option in your configuration file\n");
972                                 ASTOBJ_UNREF(client, aji_client_destroy);
973                                 return IKS_HOOK;
974 #else
975                                 if (aji_start_tls(client) == IKS_NET_TLSFAIL) {
976                                         ast_log(LOG_ERROR, "Could not start TLS\n");
977                                         ASTOBJ_UNREF(client, aji_client_destroy);
978                                         return IKS_HOOK;                
979                                 }
980 #endif
981                                 break;
982                         }
983                         if (!client->usesasl) {
984                                 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);
985                                 auth = jabber_make_auth(client->jid, client->password, iks_find_attrib(node, "id"));
986                                 if (auth) {
987                                         iks_insert_attrib(auth, "id", client->mid);
988                                         iks_insert_attrib(auth, "to", client->jid->server);
989                                         ast_aji_increment_mid(client->mid);
990                                         ast_aji_send(client, auth);
991                                         iks_delete(auth);
992                                 } else
993                                         ast_log(LOG_ERROR, "Out of memory.\n");
994                         }
995                         break;
996
997                 case IKS_NODE_NORMAL:
998 #ifdef HAVE_OPENSSL
999                         if (client->stream_flags & TRY_SECURE) {
1000                                 if (!strcmp("proceed", iks_name(node))) {
1001                                         return aji_tls_handshake(client);
1002                                 }
1003                         }
1004 #endif
1005                         if (!strcmp("stream:features", iks_name(node))) {
1006                                 features = iks_stream_features(node);
1007                                 if (client->usesasl) {
1008                                         if (client->usetls && !aji_is_secure(client))
1009                                                 break;
1010                                         if (client->authorized) {
1011                                                 if (features & IKS_STREAM_BIND) {
1012                                                         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);
1013                                                         auth = iks_make_resource_bind(client->jid);
1014                                                         if (auth) {
1015                                                                 iks_insert_attrib(auth, "id", client->mid);
1016                                                                 ast_aji_increment_mid(client->mid);
1017                                                                 ast_aji_send(client, auth);
1018                                                                 iks_delete(auth);
1019                                                         } else {
1020                                                                 ast_log(LOG_ERROR, "Out of memory.\n");
1021                                                                 break;
1022                                                         }
1023                                                 }
1024                                                 if (features & IKS_STREAM_SESSION) {
1025                                                         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);
1026                                                         auth = iks_make_session();
1027                                                         if (auth) {
1028                                                                 iks_insert_attrib(auth, "id", "auth");
1029                                                                 ast_aji_increment_mid(client->mid);
1030                                                                 ast_aji_send(client, auth);
1031                                                                 iks_delete(auth);
1032                                                         } else {
1033                                                                 ast_log(LOG_ERROR, "Out of memory.\n");
1034                                                         }
1035                                                 }
1036                                         } else {
1037                                                 int ret;
1038                                                 if (!client->jid->user) {
1039                                                         ast_log(LOG_ERROR, "Malformed Jabber ID : %s (domain missing?)\n", client->jid->full);
1040                                                         break;
1041                                                 }
1042
1043                                                 ret = aji_start_sasl(client, features, client->jid->user, client->password);
1044                                                 if (ret != IKS_OK) {
1045                                                         ASTOBJ_UNREF(client, aji_client_destroy);
1046                                                         return IKS_HOOK;
1047                                                 }
1048                                                 break;
1049                                         }
1050                                 }
1051                         } else if (!strcmp("failure", iks_name(node))) {
1052                                 ast_log(LOG_ERROR, "JABBER: encryption failure. possible bad password.\n");
1053                         } else if (!strcmp("success", iks_name(node))) {
1054                                 client->authorized = 1;
1055                                 aji_send_header(client, client->jid->server);
1056                         }
1057                         break;
1058                 case IKS_NODE_ERROR: 
1059                                 ast_log(LOG_ERROR, "JABBER: Node Error\n");
1060                                 ASTOBJ_UNREF(client, aji_client_destroy);
1061                                 return IKS_HOOK;
1062                                 break;
1063                 case IKS_NODE_STOP: 
1064                                 ast_log(LOG_WARNING, "JABBER: Disconnected\n");
1065                                 ASTOBJ_UNREF(client, aji_client_destroy);
1066                                 return IKS_HOOK;
1067                                 break;
1068                 }
1069         } else if (client->state != AJI_CONNECTED && client->component) {
1070                 switch (type) {
1071                 case IKS_NODE_START:
1072                         if (client->state == AJI_DISCONNECTED) {
1073                                 char secret[160], shasum[320], *handshake;
1074
1075                                 sprintf(secret, "%s%s", pak->id, client->password);
1076                                 ast_sha1_hash(shasum, secret);
1077                                 handshake = NULL;
1078                                 if (asprintf(&handshake, "<handshake>%s</handshake>", shasum) >= 0) {
1079                                         aji_send_raw(client, handshake);
1080                                         ast_free(handshake);
1081                                         handshake = NULL;
1082                                 }
1083                                 client->state = AJI_CONNECTING;
1084                                 if(aji_recv(client, 1) == 2) /*XXX proper result for iksemel library on iks_recv of <handshake/> XXX*/
1085                                         client->state = AJI_CONNECTED;
1086                                 else
1087                                         ast_log(LOG_WARNING, "Jabber didn't seem to handshake, failed to authenticate.\n");
1088                                 break;
1089                         }
1090                         break;
1091
1092                 case IKS_NODE_NORMAL:
1093                         break;
1094
1095                 case IKS_NODE_ERROR:
1096                         ast_log(LOG_ERROR, "JABBER: Node Error\n");
1097                         ASTOBJ_UNREF(client, aji_client_destroy);
1098                         return IKS_HOOK;
1099
1100                 case IKS_NODE_STOP:
1101                         ast_log(LOG_WARNING, "JABBER: Disconnected\n");
1102                         ASTOBJ_UNREF(client, aji_client_destroy);
1103                         return IKS_HOOK;
1104                 }
1105         }
1106
1107         switch (pak->type) {
1108         case IKS_PAK_NONE:
1109                 ast_debug(1, "JABBER: I don't know what to do with paktype NONE.\n");
1110                 break;
1111         case IKS_PAK_MESSAGE:
1112                 aji_handle_message(client, pak);
1113                 ast_debug(1, "JABBER: Handling paktype MESSAGE.\n");
1114                 break;
1115         case IKS_PAK_PRESENCE:
1116                 aji_handle_presence(client, pak);
1117                 ast_debug(1, "JABBER: Handling paktype PRESENCE\n");
1118                 break;
1119         case IKS_PAK_S10N:
1120                 aji_handle_subscribe(client, pak);
1121                 ast_debug(1, "JABBER: Handling paktype S10N\n");
1122                 break;
1123         case IKS_PAK_IQ:
1124                 ast_debug(1, "JABBER: Handling paktype IQ\n");
1125                 aji_handle_iq(client, node);
1126                 break;
1127         default:
1128                 ast_debug(1, "JABBER: I don't know anything about paktype '%d'\n", pak->type);
1129                 break;
1130         }
1131         
1132         iks_filter_packet(client->f, pak);
1133
1134         if (node)
1135                 iks_delete(node);
1136
1137         ASTOBJ_UNREF(client, aji_client_destroy);
1138         return IKS_OK;
1139 }
1140 /*!
1141  * \brief Unknown
1142  * \param data void
1143  * \param pak ikspak
1144  * \return IKS_FILTER_EAT.
1145 */
1146 static int aji_register_approve_handler(void *data, ikspak *pak)
1147 {
1148         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1149         iks *iq = NULL, *presence = NULL, *x = NULL;
1150
1151         iq = iks_new("iq");
1152         presence = iks_new("presence");
1153         x = iks_new("x");
1154         if (client && iq && presence && x) {
1155                 if (!iks_find(pak->query, "remove")) {
1156                         iks_insert_attrib(iq, "from", client->jid->full);
1157                         iks_insert_attrib(iq, "to", pak->from->full);
1158                         iks_insert_attrib(iq, "id", pak->id);
1159                         iks_insert_attrib(iq, "type", "result");
1160                         ast_aji_send(client, iq);
1161
1162                         iks_insert_attrib(presence, "from", client->jid->full);
1163                         iks_insert_attrib(presence, "to", pak->from->partial);
1164                         iks_insert_attrib(presence, "id", client->mid);
1165                         ast_aji_increment_mid(client->mid);
1166                         iks_insert_attrib(presence, "type", "subscribe");
1167                         iks_insert_attrib(x, "xmlns", "vcard-temp:x:update");
1168                         iks_insert_node(presence, x);
1169                         ast_aji_send(client, presence); 
1170                 }
1171         } else {
1172                 ast_log(LOG_ERROR, "Out of memory.\n");
1173         }
1174
1175
1176         iks_delete(iq);
1177         iks_delete(presence);
1178         iks_delete(x);
1179         
1180         ASTOBJ_UNREF(client, aji_client_destroy);
1181         return IKS_FILTER_EAT;
1182 }
1183 /*!
1184  * \brief register handler for incoming querys (IQ's)
1185  * \param data incoming aji_client request
1186  * \param pak ikspak
1187  * \return IKS_FILTER_EAT.
1188 */
1189 static int aji_register_query_handler(void *data, ikspak *pak)
1190 {
1191         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1192         struct aji_buddy *buddy = NULL; 
1193         char *node = NULL;
1194         iks *iq = NULL, *query = NULL;
1195
1196         client = (struct aji_client *) data;
1197
1198         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
1199         if (!buddy) {
1200                 iks  *error = NULL, *notacceptable = NULL;
1201
1202                 ast_log(LOG_ERROR, "Someone.... %s tried to register but they aren't allowed\n", pak->from->partial);
1203                 iq = iks_new("iq");
1204                 query = iks_new("query");
1205                 error = iks_new("error");
1206                 notacceptable = iks_new("not-acceptable");
1207                 if(iq && query && error && notacceptable) {
1208                         iks_insert_attrib(iq, "type", "error");
1209                         iks_insert_attrib(iq, "from", client->user);
1210                         iks_insert_attrib(iq, "to", pak->from->full);
1211                         iks_insert_attrib(iq, "id", pak->id);
1212                         iks_insert_attrib(query, "xmlns", "jabber:iq:register");
1213                         iks_insert_attrib(error, "code" , "406");
1214                         iks_insert_attrib(error, "type", "modify");
1215                         iks_insert_attrib(notacceptable, "xmlns", "urn:ietf:params:xml:ns:xmpp-stanzas");
1216                         iks_insert_node(iq, query);
1217                         iks_insert_node(iq, error);
1218                         iks_insert_node(error, notacceptable);
1219                         ast_aji_send(client, iq);
1220                 } else {
1221                         ast_log(LOG_ERROR, "Out of memory.\n");
1222                 }
1223
1224                 iks_delete(error);
1225                 iks_delete(notacceptable);
1226         } else  if (!(node = iks_find_attrib(pak->query, "node"))) {
1227                 iks *instructions = NULL;
1228                 char *explain = "Welcome to Asterisk - the Open Source PBX.\n";
1229                 iq = iks_new("iq");
1230                 query = iks_new("query");
1231                 instructions = iks_new("instructions");
1232                 if (iq && query && instructions && client) {
1233                         iks_insert_attrib(iq, "from", client->user);
1234                         iks_insert_attrib(iq, "to", pak->from->full);
1235                         iks_insert_attrib(iq, "id", pak->id);
1236                         iks_insert_attrib(iq, "type", "result");
1237                         iks_insert_attrib(query, "xmlns", "jabber:iq:register");
1238                         iks_insert_cdata(instructions, explain, 0);
1239                         iks_insert_node(iq, query);
1240                         iks_insert_node(query, instructions);
1241                         ast_aji_send(client, iq);
1242                 } else {
1243                         ast_log(LOG_ERROR, "Out of memory.\n");
1244                 }
1245
1246                 iks_delete(instructions);
1247         }
1248         iks_delete(iq);
1249         iks_delete(query);
1250         ASTOBJ_UNREF(client, aji_client_destroy);
1251         return IKS_FILTER_EAT;
1252 }
1253
1254 /*!
1255  * \brief Handles stuff
1256  * \param data void
1257  * \param pak ikspak 
1258  * \return IKS_FILTER_EAT.
1259 */
1260 static int aji_ditems_handler(void *data, ikspak *pak)
1261 {
1262         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1263         char *node = NULL;
1264
1265         if (!(node = iks_find_attrib(pak->query, "node"))) {
1266                 iks *iq = NULL, *query = NULL, *item = NULL;
1267                 iq = iks_new("iq");
1268                 query = iks_new("query");
1269                 item = iks_new("item");
1270
1271                 if (iq && query && item) {
1272                         iks_insert_attrib(iq, "from", client->user);
1273                         iks_insert_attrib(iq, "to", pak->from->full);
1274                         iks_insert_attrib(iq, "id", pak->id);
1275                         iks_insert_attrib(iq, "type", "result");
1276                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
1277                         iks_insert_attrib(item, "node", "http://jabber.org/protocol/commands");
1278                         iks_insert_attrib(item, "name", "Million Dollar Asterisk Commands");
1279                         iks_insert_attrib(item, "jid", client->user);
1280
1281                         iks_insert_node(iq, query);
1282                         iks_insert_node(query, item);
1283                         ast_aji_send(client, iq);
1284                 } else {
1285                         ast_log(LOG_ERROR, "Out of memory.\n");
1286                 }
1287
1288                 iks_delete(iq);
1289                 iks_delete(query);
1290                 iks_delete(item);
1291
1292         } else if (!strcasecmp(node, "http://jabber.org/protocol/commands")) {
1293                 iks *iq, *query, *confirm;
1294                 iq = iks_new("iq");
1295                 query = iks_new("query");
1296                 confirm = iks_new("item");
1297                 if (iq && query && confirm && client) {
1298                         iks_insert_attrib(iq, "from", client->user);
1299                         iks_insert_attrib(iq, "to", pak->from->full);
1300                         iks_insert_attrib(iq, "id", pak->id);
1301                         iks_insert_attrib(iq, "type", "result");
1302                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
1303                         iks_insert_attrib(query, "node", "http://jabber.org/protocol/commands");
1304                         iks_insert_attrib(confirm, "node", "confirmaccount");
1305                         iks_insert_attrib(confirm, "name", "Confirm AIM account");
1306                         iks_insert_attrib(confirm, "jid", "blog.astjab.org");
1307
1308                         iks_insert_node(iq, query);
1309                         iks_insert_node(query, confirm);
1310                         ast_aji_send(client, iq);
1311                 } else {
1312                         ast_log(LOG_ERROR, "Out of memory.\n");
1313                 }
1314
1315                 iks_delete(iq);
1316                 iks_delete(query);
1317                 iks_delete(confirm);
1318
1319         } else if (!strcasecmp(node, "confirmaccount")) {
1320                 iks *iq = NULL, *query = NULL, *feature = NULL;
1321
1322                 iq = iks_new("iq");
1323                 query = iks_new("query");
1324                 feature = iks_new("feature");
1325
1326                 if (iq && query && feature && client) {
1327                         iks_insert_attrib(iq, "from", client->user);
1328                         iks_insert_attrib(iq, "to", pak->from->full);
1329                         iks_insert_attrib(iq, "id", pak->id);
1330                         iks_insert_attrib(iq, "type", "result");
1331                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
1332                         iks_insert_attrib(feature, "var", "http://jabber.org/protocol/commands");
1333                         iks_insert_node(iq, query);
1334                         iks_insert_node(query, feature);
1335                         ast_aji_send(client, iq);
1336                 } else {
1337                         ast_log(LOG_ERROR, "Out of memory.\n");
1338                 }
1339
1340                 iks_delete(iq);
1341                 iks_delete(query);
1342                 iks_delete(feature);
1343         }
1344
1345         ASTOBJ_UNREF(client, aji_client_destroy);
1346         return IKS_FILTER_EAT;
1347
1348 }
1349 /*!
1350  * \brief Handle add extra info
1351  * \param data void
1352  * \param pak ikspak
1353  * \return IKS_FILTER_EAT
1354 */
1355 static int aji_client_info_handler(void *data, ikspak *pak)
1356 {
1357         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1358         struct aji_resource *resource = NULL;
1359         struct aji_buddy *buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
1360
1361         resource = aji_find_resource(buddy, pak->from->resource);
1362         if (pak->subtype == IKS_TYPE_RESULT) {
1363                 if (!resource) {
1364                         ast_log(LOG_NOTICE, "JABBER: Received client info from %s when not requested.\n", pak->from->full);
1365                         ASTOBJ_UNREF(client, aji_client_destroy);
1366                         return IKS_FILTER_EAT;
1367                 }
1368                 if (iks_find_with_attrib(pak->query, "feature", "var", "http://www.google.com/xmpp/protocol/voice/v1")) {
1369                         resource->cap->jingle = 1;
1370                 } else
1371                         resource->cap->jingle = 0;
1372         } else if (pak->subtype == IKS_TYPE_GET) {
1373                 iks *iq, *disco, *ident, *google, *query;
1374                 iq = iks_new("iq");
1375                 query = iks_new("query");
1376                 ident = iks_new("identity");
1377                 disco = iks_new("feature");
1378                 google = iks_new("feature");
1379                 if (iq && ident && disco && google) {
1380                         iks_insert_attrib(iq, "from", client->jid->full);
1381                         iks_insert_attrib(iq, "to", pak->from->full);
1382                         iks_insert_attrib(iq, "type", "result");
1383                         iks_insert_attrib(iq, "id", pak->id);
1384                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
1385                         iks_insert_attrib(ident, "category", "client");
1386                         iks_insert_attrib(ident, "type", "pc");
1387                         iks_insert_attrib(ident, "name", "asterisk");
1388                         iks_insert_attrib(disco, "var", "http://jabber.org/protocol/disco#info");
1389                         iks_insert_attrib(google, "var", "http://www.google.com/xmpp/protocol/voice/v1");
1390                         iks_insert_node(iq, query);
1391                         iks_insert_node(query, ident);
1392                         iks_insert_node(query, google);
1393                         iks_insert_node(query, disco);
1394                         ast_aji_send(client, iq);
1395                 } else
1396                         ast_log(LOG_ERROR, "Out of Memory.\n");
1397
1398                 iks_delete(iq);
1399                 iks_delete(query);
1400                 iks_delete(ident);
1401                 iks_delete(google);
1402                 iks_delete(disco);
1403         } else if (pak->subtype == IKS_TYPE_ERROR) {
1404                 ast_log(LOG_NOTICE, "User %s does not support discovery.\n", pak->from->full);
1405         }
1406         ASTOBJ_UNREF(client, aji_client_destroy);
1407         return IKS_FILTER_EAT;
1408 }
1409 /*!
1410  * \brief Handler of the return info packet
1411  * \param data aji_client
1412  * \param pak ikspak
1413  * \return IKS_FILTER_EAT
1414 */
1415 static int aji_dinfo_handler(void *data, ikspak *pak)
1416 {
1417         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1418         char *node = NULL;
1419         struct aji_resource *resource = NULL;
1420         struct aji_buddy *buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
1421
1422         resource = aji_find_resource(buddy, pak->from->resource);
1423         if (pak->subtype == IKS_TYPE_ERROR) {
1424                 ast_log(LOG_WARNING, "Recieved error from a client, turn on jabber debug!\n");
1425                 return IKS_FILTER_EAT;
1426         }
1427         if (pak->subtype == IKS_TYPE_RESULT) {
1428                 if (!resource) {
1429                         ast_log(LOG_NOTICE,"JABBER: Received client info from %s when not requested.\n", pak->from->full);
1430                         ASTOBJ_UNREF(client, aji_client_destroy);
1431                         return IKS_FILTER_EAT;
1432                 }
1433                 if (iks_find_with_attrib(pak->query, "feature", "var", "http://www.google.com/xmpp/protocol/voice/v1")) {
1434                         resource->cap->jingle = 1;
1435                 } else
1436                         resource->cap->jingle = 0;
1437         } else if (pak->subtype == IKS_TYPE_GET && !(node = iks_find_attrib(pak->query, "node"))) {
1438                 iks *iq, *query, *identity, *disco, *reg, *commands, *gateway, *version, *vcard, *search;
1439
1440                 iq = iks_new("iq");
1441                 query = iks_new("query");
1442                 identity = iks_new("identity");
1443                 disco = iks_new("feature");
1444                 reg = iks_new("feature");
1445                 commands = iks_new("feature");
1446                 gateway = iks_new("feature");
1447                 version = iks_new("feature");
1448                 vcard = iks_new("feature");
1449                 search = iks_new("feature");
1450
1451                 if (iq && query && identity && disco && reg && commands && gateway && version && vcard && search && client) {
1452                         iks_insert_attrib(iq, "from", client->user);
1453                         iks_insert_attrib(iq, "to", pak->from->full);
1454                         iks_insert_attrib(iq, "id", pak->id);
1455                         iks_insert_attrib(iq, "type", "result");
1456                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
1457                         iks_insert_attrib(identity, "category", "gateway");
1458                         iks_insert_attrib(identity, "type", "pstn");
1459                         iks_insert_attrib(identity, "name", "Asterisk The Open Source PBX");
1460                         iks_insert_attrib(disco, "var", "http://jabber.org/protocol/disco");
1461                         iks_insert_attrib(reg, "var", "jabber:iq:register");
1462                         iks_insert_attrib(commands, "var", "http://jabber.org/protocol/commands");
1463                         iks_insert_attrib(gateway, "var", "jabber:iq:gateway");
1464                         iks_insert_attrib(version, "var", "jabber:iq:version");
1465                         iks_insert_attrib(vcard, "var", "vcard-temp");
1466                         iks_insert_attrib(search, "var", "jabber:iq:search");
1467
1468                         iks_insert_node(iq, query);
1469                         iks_insert_node(query, identity);
1470                         iks_insert_node(query, disco);
1471                         iks_insert_node(query, reg);
1472                         iks_insert_node(query, commands);
1473                         iks_insert_node(query, gateway);
1474                         iks_insert_node(query, version);
1475                         iks_insert_node(query, vcard);
1476                         iks_insert_node(query, search);
1477                         ast_aji_send(client, iq);
1478                 } else {
1479                         ast_log(LOG_ERROR, "Out of memory.\n");
1480                 }
1481
1482                 iks_delete(iq);
1483                 iks_delete(query);
1484                 iks_delete(identity);
1485                 iks_delete(disco);
1486                 iks_delete(reg);
1487                 iks_delete(commands);
1488                 iks_delete(gateway);
1489                 iks_delete(version);
1490                 iks_delete(vcard);
1491                 iks_delete(search);
1492
1493         } else if (pak->subtype == IKS_TYPE_GET && !strcasecmp(node, "http://jabber.org/protocol/commands")) {
1494                 iks *iq, *query, *confirm;
1495                 iq = iks_new("iq");
1496                 query = iks_new("query");
1497                 confirm = iks_new("item");
1498
1499                 if (iq && query && confirm && client) {
1500                         iks_insert_attrib(iq, "from", client->user);
1501                         iks_insert_attrib(iq, "to", pak->from->full);
1502                         iks_insert_attrib(iq, "id", pak->id);
1503                         iks_insert_attrib(iq, "type", "result");
1504                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#items");
1505                         iks_insert_attrib(query, "node", "http://jabber.org/protocol/commands");
1506                         iks_insert_attrib(confirm, "node", "confirmaccount");
1507                         iks_insert_attrib(confirm, "name", "Confirm AIM account");
1508                         iks_insert_attrib(confirm, "jid", client->user);
1509                         iks_insert_node(iq, query);
1510                         iks_insert_node(query, confirm);
1511                         ast_aji_send(client, iq);
1512                 } else {
1513                         ast_log(LOG_ERROR, "Out of memory.\n");
1514                 }
1515
1516                 iks_delete(iq);
1517                 iks_delete(query);
1518                 iks_delete(confirm);
1519
1520         } else if (pak->subtype == IKS_TYPE_GET && !strcasecmp(node, "confirmaccount")) {
1521                 iks *iq, *query, *feature;
1522
1523                 iq = iks_new("iq");
1524                 query = iks_new("query");
1525                 feature = iks_new("feature");
1526
1527                 if (iq && query && feature && client) {
1528                         iks_insert_attrib(iq, "from", client->user);
1529                         iks_insert_attrib(iq, "to", pak->from->full);
1530                         iks_insert_attrib(iq, "id", pak->id);
1531                         iks_insert_attrib(iq, "type", "result");
1532                         iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
1533                         iks_insert_attrib(feature, "var", "http://jabber.org/protocol/commands");
1534                         iks_insert_node(iq, query);
1535                         iks_insert_node(query, feature);
1536                         ast_aji_send(client, iq);
1537                 } else {
1538                         ast_log(LOG_ERROR, "Out of memory.\n");
1539                 }
1540
1541                 iks_delete(iq);
1542                 iks_delete(query);
1543                 iks_delete(feature);
1544         }
1545
1546         ASTOBJ_UNREF(client, aji_client_destroy);
1547         return IKS_FILTER_EAT;
1548 }
1549
1550 /*!
1551  * \brief Handles \verbatim <iq> \endverbatim tags.
1552  * \param client the configured XMPP client we use to connect to a XMPP server
1553  * \param node iks 
1554  * \return void.
1555  */
1556 static void aji_handle_iq(struct aji_client *client, iks *node)
1557 {
1558         /*Nothing to see here */
1559 }
1560
1561 /*!
1562  * \brief Handles presence packets.
1563  * \param client the configured XMPP client we use to connect to a XMPP server
1564  * \param pak ikspak the node
1565  */
1566 static void aji_handle_message(struct aji_client *client, ikspak *pak)
1567 {
1568         struct aji_message *insert, *tmp;
1569         int flag = 0;
1570         
1571         if (!(insert = ast_calloc(1, sizeof(*insert))))
1572                 return;
1573         time(&insert->arrived);
1574         if (iks_find_cdata(pak->x, "body"))
1575                 insert->message = ast_strdup(iks_find_cdata(pak->x, "body"));
1576         if (pak->id)
1577                 ast_copy_string(insert->id, pak->id, sizeof(insert->message));
1578         if (pak->from)
1579                 insert->from = ast_strdup(pak->from->full);
1580         AST_LIST_LOCK(&client->messages);
1581         AST_LIST_TRAVERSE_SAFE_BEGIN(&client->messages, tmp, list) {
1582                 if (flag) {
1583                         AST_LIST_REMOVE_CURRENT(list);
1584                         if (tmp->from)
1585                                 ast_free(tmp->from);
1586                         if (tmp->message)
1587                                 ast_free(tmp->message);
1588                 } else if (difftime(time(NULL), tmp->arrived) >= client->message_timeout) {
1589                         flag = 1;
1590                         AST_LIST_REMOVE_CURRENT(list);
1591                         if (tmp->from)
1592                                 ast_free(tmp->from);
1593                         if (tmp->message)
1594                                 ast_free(tmp->message);
1595                 }
1596         }
1597         AST_LIST_TRAVERSE_SAFE_END;
1598         AST_LIST_INSERT_HEAD(&client->messages, insert, list);
1599         AST_LIST_UNLOCK(&client->messages);
1600 }
1601 /*!
1602  * \brief Check the presence info
1603  * \param client the configured XMPP client we use to connect to a XMPP server
1604  * \param pak ikspak
1605 */
1606 static void aji_handle_presence(struct aji_client *client, ikspak *pak)
1607 {
1608         int status, priority;
1609         struct aji_buddy *buddy;
1610         struct aji_resource *tmp = NULL, *last = NULL, *found = NULL;
1611         char *ver, *node, *descrip, *type;
1612         
1613         if(client->state != AJI_CONNECTED)
1614                 aji_create_buddy(pak->from->partial, client);
1615
1616         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
1617         if (!buddy && pak->from->partial) {
1618                 /* allow our jid to be used to log in with another resource */
1619                 if (!strcmp((const char *)pak->from->partial, (const char *)client->jid->partial))
1620                         aji_create_buddy(pak->from->partial, client);
1621                 else
1622                         ast_log(LOG_NOTICE, "Got presence packet from %s, someone not in our roster!!!!\n", pak->from->partial);
1623                 return;
1624         }
1625         type = iks_find_attrib(pak->x, "type");
1626         if(client->component && type &&!strcasecmp("probe", type)) {
1627                 aji_set_presence(client, pak->from->full, iks_find_attrib(pak->x, "to"), client->status, client->statusmessage);
1628                 ast_verbose("what i was looking for \n");
1629         }
1630         ASTOBJ_WRLOCK(buddy);
1631         status = (pak->show) ? pak->show : 6;
1632         priority = atoi((iks_find_cdata(pak->x, "priority")) ? iks_find_cdata(pak->x, "priority") : "0");
1633         tmp = buddy->resources;
1634         descrip = ast_strdup(iks_find_cdata(pak->x,"status"));
1635
1636         while (tmp && pak->from->resource) {
1637                 if (!strcasecmp(tmp->resource, pak->from->resource)) {
1638                         tmp->status = status;
1639                         if (tmp->description) ast_free(tmp->description);
1640                         tmp->description = descrip;
1641                         found = tmp;
1642                         if (status == 6) {      /* Sign off Destroy resource */
1643                                 if (last && found->next) {
1644                                         last->next = found->next;
1645                                 } else if (!last) {
1646                                         if (found->next)
1647                                                 buddy->resources = found->next;
1648                                         else
1649                                                 buddy->resources = NULL;
1650                                 } else if (!found->next) {
1651                                         if (last)
1652                                                 last->next = NULL;
1653                                         else
1654                                                 buddy->resources = NULL;
1655                                 }
1656                                 ast_free(found);
1657                                 found = NULL;
1658                                 break;
1659                         }
1660                         /* resource list is sorted by descending priority */
1661                         if (tmp->priority != priority) {
1662                                 found->priority = priority;
1663                                 if (!last && !found->next)
1664                                         /* resource was found to be unique,
1665                                            leave loop */
1666                                         break;
1667                                 /* search for resource in our list
1668                                    and take it out for the moment */
1669                                 if (last)
1670                                         last->next = found->next;
1671                                 else
1672                                         buddy->resources = found->next;
1673
1674                                 last = NULL;
1675                                 tmp = buddy->resources;
1676                                 if (!buddy->resources)
1677                                         buddy->resources = found;
1678                                 /* priority processing */
1679                                 while (tmp) {
1680                                         /* insert resource back according to 
1681                                            its priority value */
1682                                         if (found->priority > tmp->priority) {
1683                                                 if (last)
1684                                                         /* insert within list */
1685                                                         last->next = found;
1686                                                 found->next = tmp;
1687                                                 if (!last)
1688                                                         /* insert on top */
1689                                                         buddy->resources = found;
1690                                                 break;
1691                                         }
1692                                         if (!tmp->next) {
1693                                                 /* insert at the end of the list */
1694                                                 tmp->next = found;
1695                                                 found->next = NULL;
1696                                                 break;
1697                                         }
1698                                         last = tmp;
1699                                         tmp = tmp->next;
1700                                 }
1701                         }
1702                         break;
1703                 }
1704                 last = tmp;
1705                 tmp = tmp->next;
1706         }
1707
1708         /* resource not found in our list, create it */
1709         if (!found && status != 6 && pak->from->resource) {
1710                 found = ast_calloc(1, sizeof(*found));
1711
1712                 if (!found) {
1713                         ast_log(LOG_ERROR, "Out of memory!\n");
1714                         return;
1715                 }
1716                 ast_copy_string(found->resource, pak->from->resource, sizeof(found->resource));
1717                 found->status = status;
1718                 found->description = descrip;
1719                 found->priority = priority;
1720                 found->next = NULL;
1721                 last = NULL;
1722                 tmp = buddy->resources;
1723                 while (tmp) {
1724                         if (found->priority > tmp->priority) {
1725                                 if (last)
1726                                         last->next = found;
1727                                 found->next = tmp;
1728                                 if (!last)
1729                                         buddy->resources = found;
1730                                 break;
1731                         }
1732                         if (!tmp->next) {
1733                                 tmp->next = found;
1734                                 break;
1735                         }
1736                         last = tmp;
1737                         tmp = tmp->next;
1738                 }
1739                 if (!tmp)
1740                         buddy->resources = found;
1741         }
1742         
1743         ASTOBJ_UNLOCK(buddy);
1744         ASTOBJ_UNREF(buddy, aji_buddy_destroy);
1745
1746         node = iks_find_attrib(iks_find(pak->x, "c"), "node");
1747         ver = iks_find_attrib(iks_find(pak->x, "c"), "ver");
1748
1749         /* handle gmail client's special caps:c tag */
1750         if (!node && !ver) {
1751                 node = iks_find_attrib(iks_find(pak->x, "caps:c"), "node");
1752                 ver = iks_find_attrib(iks_find(pak->x, "caps:c"), "ver");
1753         }
1754
1755         /* retrieve capabilites of the new resource */
1756         if(status !=6 && found && !found->cap) {
1757                 found->cap = aji_find_version(node, ver, pak);
1758                 if(gtalk_yuck(pak->x)) /* gtalk should do discover */
1759                         found->cap->jingle = 1;
1760                 if(found->cap->jingle && option_debug > 4) {
1761                         ast_debug(1,"Special case for google till they support discover.\n");
1762                 }
1763                 else {
1764                         iks *iq, *query;
1765                         iq = iks_new("iq");
1766                         query = iks_new("query");
1767                         if(query && iq)  {
1768                                 iks_insert_attrib(iq, "type", "get");
1769                                 iks_insert_attrib(iq, "to", pak->from->full);
1770                                 iks_insert_attrib(iq,"from", client->jid->full);
1771                                 iks_insert_attrib(iq, "id", client->mid);
1772                                 ast_aji_increment_mid(client->mid);
1773                                 iks_insert_attrib(query, "xmlns", "http://jabber.org/protocol/disco#info");
1774                                 iks_insert_node(iq, query);
1775                                 ast_aji_send(client, iq);
1776                                 
1777                         } else
1778                                 ast_log(LOG_ERROR, "Out of memory.\n");
1779                         
1780                         iks_delete(query);
1781                         iks_delete(iq);
1782                 }
1783         }
1784         switch (pak->subtype) {
1785         case IKS_TYPE_AVAILABLE:
1786                 ast_debug(3, "JABBER: I am available ^_* %i\n", pak->subtype);
1787                 break;
1788         case IKS_TYPE_UNAVAILABLE:
1789                 ast_debug(3, "JABBER: I am unavailable ^_* %i\n", pak->subtype);
1790                 break;
1791         default:
1792                 ast_debug(3, "JABBER: Ohh sexy and the wrong type: %i\n", pak->subtype);
1793         }
1794         switch (pak->show) {
1795         case IKS_SHOW_UNAVAILABLE:
1796                 ast_debug(3, "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1797                 break;
1798         case IKS_SHOW_AVAILABLE:
1799                 ast_debug(3, "JABBER: type is available\n");
1800                 break;
1801         case IKS_SHOW_CHAT:
1802                 ast_debug(3, "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1803                 break;
1804         case IKS_SHOW_AWAY:
1805                 ast_debug(3, "JABBER: type is away\n");
1806                 break;
1807         case IKS_SHOW_XA:
1808                 ast_debug(3, "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1809                 break;
1810         case IKS_SHOW_DND:
1811                 ast_debug(3, "JABBER: type: %i subtype %i\n", pak->subtype, pak->show);
1812                 break;
1813         default:
1814                 ast_debug(3, "JABBER: Kinky! how did that happen %i\n", pak->show);
1815         }
1816 }
1817
1818 /*!
1819  * \brief handles subscription requests.
1820  * \param client the configured XMPP client we use to connect to a XMPP server
1821  * \param pak ikspak iksemel packet.
1822  * \return void.
1823  */
1824 static void aji_handle_subscribe(struct aji_client *client, ikspak *pak)
1825 {
1826         iks *presence = NULL, *status = NULL;
1827         struct aji_buddy* buddy = NULL;
1828
1829         switch (pak->subtype) { 
1830         case IKS_TYPE_SUBSCRIBE:
1831                 presence = iks_new("presence");
1832                 status = iks_new("status");
1833                 if (presence && status) {
1834                         iks_insert_attrib(presence, "type", "subscribed");
1835                         iks_insert_attrib(presence, "to", pak->from->full);
1836                         iks_insert_attrib(presence, "from", client->jid->full);
1837                         if (pak->id)
1838                                 iks_insert_attrib(presence, "id", pak->id);
1839                         iks_insert_cdata(status, "Asterisk has approved subscription", 0);
1840                         iks_insert_node(presence, status);
1841                         ast_aji_send(client, presence);
1842                 } else
1843                         ast_log(LOG_ERROR, "Unable to allocate nodes\n");
1844
1845                 iks_delete(presence);
1846                 iks_delete(status);
1847
1848                 if (client->component)
1849                         aji_set_presence(client, pak->from->full, iks_find_attrib(pak->x, "to"), client->status, client->statusmessage);
1850         case IKS_TYPE_SUBSCRIBED:
1851                 buddy = ASTOBJ_CONTAINER_FIND(&client->buddies, pak->from->partial);
1852                 if (!buddy && pak->from->partial) {
1853                         aji_create_buddy(pak->from->partial, client);
1854                 }
1855         default:
1856                 if (option_verbose > 4) {
1857                         ast_verbose(VERBOSE_PREFIX_3 "JABBER: This is a subcription of type %i\n", pak->subtype);
1858                 }
1859         }
1860 }
1861
1862 /*!
1863  * \brief sends messages.
1864  * \param client the configured XMPP client we use to connect to a XMPP server
1865  * \param address
1866  * \param message
1867  * \return 1.
1868  */
1869 int ast_aji_send_chat(struct aji_client *client, const char *address, const char *message)
1870 {
1871         int res = 0;
1872         iks *message_packet = NULL;
1873         if (client->state == AJI_CONNECTED) {
1874                 message_packet = iks_make_msg(IKS_TYPE_CHAT, address, message);
1875                 if (message_packet) {
1876                         iks_insert_attrib(message_packet, "from", client->jid->full);
1877                         res = ast_aji_send(client, message_packet);
1878                 } else {
1879                         ast_log(LOG_ERROR, "Out of memory.\n");
1880                 }
1881
1882                 iks_delete(message_packet);
1883         } else
1884                 ast_log(LOG_WARNING, "JABBER: Not connected can't send\n");
1885         return 1;
1886 }
1887
1888 /*!
1889  * \brief create a chatroom.
1890  * \param client the configured XMPP client we use to connect to a XMPP server
1891  * \param room name of room
1892  * \param server name of server
1893  * \param topic topic for the room.
1894  * \return 0.
1895  */
1896 int ast_aji_create_chat(struct aji_client *client, char *room, char *server, char *topic)
1897 {
1898         int res = 0;
1899         iks *iq = NULL;
1900         iq = iks_new("iq");
1901
1902         if (iq && client) {
1903                 iks_insert_attrib(iq, "type", "get");
1904                 iks_insert_attrib(iq, "to", server);
1905                 iks_insert_attrib(iq, "id", client->mid);
1906                 ast_aji_increment_mid(client->mid);
1907                 ast_aji_send(client, iq);
1908         } else 
1909                 ast_log(LOG_ERROR, "Out of memory.\n");
1910
1911         iks_delete(iq);
1912
1913         return res;
1914 }
1915
1916 /*!
1917  * \brief join a chatroom.
1918  * \param client the configured XMPP client we use to connect to a XMPP server
1919  * \param room room to join
1920  * \return res.
1921  */
1922 int ast_aji_join_chat(struct aji_client *client, char *room)
1923 {
1924         int res = 0;
1925         iks *presence = NULL, *priority = NULL;
1926         presence = iks_new("presence");
1927         priority = iks_new("priority");
1928         if (presence && priority && client) {
1929                 iks_insert_cdata(priority, "0", 1);
1930                 iks_insert_attrib(presence, "to", room);
1931                 iks_insert_node(presence, priority);
1932                 res = ast_aji_send(client, presence);
1933                 iks_insert_cdata(priority, "5", 1);
1934                 iks_insert_attrib(presence, "to", room);
1935                 res = ast_aji_send(client, presence);
1936         } else 
1937                 ast_log(LOG_ERROR, "Out of memory.\n");
1938         
1939         iks_delete(presence);
1940         iks_delete(priority);
1941         
1942         return res;
1943 }
1944
1945 /*!
1946  * \brief invite to a chatroom.
1947  * \param client the configured XMPP client we use to connect to a XMPP server
1948  * \param user 
1949  * \param room
1950  * \param message
1951  * \return res.
1952  */
1953 int ast_aji_invite_chat(struct aji_client *client, char *user, char *room, char *message)
1954 {
1955         int res = 0;
1956         iks *invite, *body, *namespace;
1957
1958         invite = iks_new("message");
1959         body = iks_new("body");
1960         namespace = iks_new("x");
1961         if (client && invite && body && namespace) {
1962                 iks_insert_attrib(invite, "to", user);
1963                 iks_insert_attrib(invite, "id", client->mid);
1964                 ast_aji_increment_mid(client->mid);
1965                 iks_insert_cdata(body, message, 0);
1966                 iks_insert_attrib(namespace, "xmlns", "jabber:x:conference");
1967                 iks_insert_attrib(namespace, "jid", room);
1968                 iks_insert_node(invite, body);
1969                 iks_insert_node(invite, namespace);
1970                 res = ast_aji_send(client, invite);
1971         } else 
1972                 ast_log(LOG_ERROR, "Out of memory.\n");
1973
1974         iks_delete(body);
1975         iks_delete(namespace);
1976         iks_delete(invite);
1977         
1978         return res;
1979 }
1980
1981
1982 /*!
1983  * \brief receive message loop.
1984  * \param data void
1985  * \return void.
1986  */
1987 static void *aji_recv_loop(void *data)
1988 {
1989         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
1990         int res = IKS_HOOK;
1991
1992         while(res != IKS_OK) {
1993                 ast_debug(3, "JABBER: Connecting.\n");
1994                 res = aji_reconnect(client);
1995                 sleep(4);
1996         }
1997
1998         do {
1999                 if (res == IKS_NET_RWERR || client->timeout == 0) {
2000                         while(res != IKS_OK) {
2001                                 ast_debug(3, "JABBER: reconnecting.\n");
2002                                 res = aji_reconnect(client);
2003                                 sleep(4);
2004                         }
2005                 }
2006
2007                 res = aji_recv(client, 1);
2008                 
2009                 if (client->state == AJI_DISCONNECTING) {
2010                         ast_debug(2, "Ending our Jabber client's thread due to a disconnect\n");
2011                         pthread_exit(NULL);
2012                 }
2013
2014                 /* Decrease timeout if no data received */
2015                 if (res == IKS_NET_EXPIRED)
2016                         client->timeout--;
2017
2018                 if (res == IKS_HOOK) 
2019                         ast_log(LOG_WARNING, "JABBER: Got hook event.\n");
2020                 else if (res == IKS_NET_TLSFAIL)
2021                         ast_log(LOG_ERROR, "JABBER:  Failure in TLS.\n");
2022                 else if (client->timeout == 0 && client->state == AJI_CONNECTED) {
2023                         res = client->keepalive ? aji_send_raw(client, " ") : IKS_OK;
2024                         if(res == IKS_OK)
2025                                 client->timeout = 50;
2026                         else
2027                                 ast_log(LOG_WARNING, "JABBER:  Network Timeout\n");
2028                 } else if (res == IKS_NET_RWERR)
2029                         ast_log(LOG_WARNING, "JABBER: socket read error\n");
2030         } while (client);
2031         ASTOBJ_UNREF(client, aji_client_destroy);
2032         return 0;
2033 }
2034
2035 /*!
2036  * \brief increments the mid field for messages and other events.
2037  * \param mid char.
2038  * \return void.
2039  */
2040 void ast_aji_increment_mid(char *mid)
2041 {
2042         int i = 0;
2043
2044         for (i = strlen(mid) - 1; i >= 0; i--) {
2045                 if (mid[i] != 'z') {
2046                         mid[i] = mid[i] + 1;
2047                         i = 0;
2048                 } else
2049                         mid[i] = 'a';
2050         }
2051 }
2052
2053 #if 0
2054 /*!
2055  * \brief attempts to register to a transport.
2056  * \param aji_client struct, and xml packet.
2057  * \return IKS_FILTER_EAT.
2058  */
2059 /*allows for registering to transport , was too sketch and is out for now. */
2060 static int aji_register_transport(void *data, ikspak *pak)
2061 {
2062         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
2063         int res = 0;
2064         struct aji_buddy *buddy = NULL;
2065         iks *send = iks_make_iq(IKS_TYPE_GET, "jabber:iq:register");
2066
2067         if (client && send) {
2068                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
2069                         ASTOBJ_RDLOCK(iterator); 
2070                         if (iterator->btype == AJI_TRANS) {
2071                                   buddy = iterator;
2072                         }
2073                         ASTOBJ_UNLOCK(iterator);
2074                 });
2075                 iks_filter_remove_hook(client->f, aji_register_transport);
2076                 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);
2077                 iks_insert_attrib(send, "to", buddy->host);
2078                 iks_insert_attrib(send, "id", client->mid);
2079                 ast_aji_increment_mid(client->mid);
2080                 iks_insert_attrib(send, "from", client->user);
2081                 res = ast_aji_send(client, send);
2082         } else 
2083                 ast_log(LOG_ERROR, "Out of memory.\n");
2084
2085         if (send)
2086                 iks_delete(send);
2087         ASTOBJ_UNREF(client, aji_client_destroy);
2088         return IKS_FILTER_EAT;
2089
2090 }
2091 /*!
2092  * \brief attempts to register to a transport step 2.
2093  * \param aji_client struct, and xml packet.
2094  * \return IKS_FILTER_EAT.
2095  */
2096 /* more of the same blob of code, too wonky for now*/
2097 static int aji_register_transport2(void *data, ikspak *pak)
2098 {
2099         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
2100         int res = 0;
2101         struct aji_buddy *buddy = NULL;
2102
2103         iks *regiq = iks_new("iq");
2104         iks *regquery = iks_new("query");
2105         iks *reguser = iks_new("username");
2106         iks *regpass = iks_new("password");
2107
2108         if (client && regquery && reguser && regpass && regiq) {
2109                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
2110                         ASTOBJ_RDLOCK(iterator);
2111                         if (iterator->btype == AJI_TRANS)
2112                                 buddy = iterator; ASTOBJ_UNLOCK(iterator);
2113                 });
2114                 iks_filter_remove_hook(client->f, aji_register_transport2);
2115                 iks_insert_attrib(regiq, "to", buddy->host);
2116                 iks_insert_attrib(regiq, "type", "set");
2117                 iks_insert_attrib(regiq, "id", client->mid);
2118                 ast_aji_increment_mid(client->mid);
2119                 iks_insert_attrib(regiq, "from", client->user);
2120                 iks_insert_attrib(regquery, "xmlns", "jabber:iq:register");
2121                 iks_insert_cdata(reguser, buddy->user, 0);
2122                 iks_insert_cdata(regpass, buddy->pass, 0);
2123                 iks_insert_node(regiq, regquery);
2124                 iks_insert_node(regquery, reguser);
2125                 iks_insert_node(regquery, regpass);
2126                 res = ast_aji_send(client, regiq);
2127         } else
2128                 ast_log(LOG_ERROR, "Out of memory.\n");
2129         if (regiq)
2130                 iks_delete(regiq);
2131         if (regquery)
2132                 iks_delete(regquery);
2133         if (reguser)
2134                 iks_delete(reguser);
2135         if (regpass)
2136                 iks_delete(regpass);
2137         ASTOBJ_UNREF(client, aji_client_destroy);
2138         return IKS_FILTER_EAT;
2139 }
2140 #endif
2141
2142 /*!
2143  * \brief goes through roster and prunes users not needed in list, or adds them accordingly.
2144  * \param client the configured XMPP client we use to connect to a XMPP server
2145  * \return void.
2146  * \note The messages here should be configurable.
2147  */
2148 static void aji_pruneregister(struct aji_client *client)
2149 {
2150         int res = 0;
2151         iks *removeiq = iks_new("iq");
2152         iks *removequery = iks_new("query");
2153         iks *removeitem = iks_new("item");
2154         iks *send = iks_make_iq(IKS_TYPE_GET, "http://jabber.org/protocol/disco#items");
2155         if (!client || !removeiq || !removequery || !removeitem || !send) {
2156                 ast_log(LOG_ERROR, "Out of memory.\n");
2157                 goto safeout;
2158         }
2159
2160         iks_insert_node(removeiq, removequery);
2161         iks_insert_node(removequery, removeitem);
2162         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
2163                 ASTOBJ_RDLOCK(iterator);
2164                 /* For an aji_buddy, both AUTOPRUNE and AUTOREGISTER will never
2165                  * be called at the same time */
2166                 if (ast_test_flag(&iterator->flags, AJI_AUTOPRUNE)) { /* If autoprune is set on jabber.conf */
2167                         res = ast_aji_send(client, iks_make_s10n(IKS_TYPE_UNSUBSCRIBE, iterator->name,
2168                                                                  "GoodBye. Your status is no longer needed by Asterisk the Open Source PBX"
2169                                                                  " so I am no longer subscribing to your presence.\n"));
2170                         res = ast_aji_send(client, iks_make_s10n(IKS_TYPE_UNSUBSCRIBED, iterator->name,
2171                                                                  "GoodBye.  You are no longer in the Asterisk config file so I am removing"
2172                                                                  " your access to my presence.\n"));
2173                         iks_insert_attrib(removeiq, "from", client->jid->full); 
2174                         iks_insert_attrib(removeiq, "type", "set"); 
2175                         iks_insert_attrib(removequery, "xmlns", "jabber:iq:roster");
2176                         iks_insert_attrib(removeitem, "jid", iterator->name);
2177                         iks_insert_attrib(removeitem, "subscription", "remove");
2178                         res = ast_aji_send(client, removeiq);
2179                 } else if (ast_test_flag(&iterator->flags, AJI_AUTOREGISTER)) {
2180                         res = ast_aji_send(client, iks_make_s10n(IKS_TYPE_SUBSCRIBE, iterator->name, 
2181                                                                  "Greetings! I am the Asterisk Open Source PBX and I want to subscribe to your presence\n"));
2182                         ast_clear_flag(&iterator->flags, AJI_AUTOREGISTER);
2183                 }
2184                 ASTOBJ_UNLOCK(iterator);
2185         });
2186
2187  safeout:
2188         iks_delete(removeiq);
2189         iks_delete(removequery);
2190         iks_delete(removeitem);
2191         iks_delete(send);
2192         
2193         ASTOBJ_CONTAINER_PRUNE_MARKED(&client->buddies, aji_buddy_destroy);
2194 }
2195
2196 /*!
2197  * \brief filters the roster packet we get back from server.
2198  * \param data void
2199  * \param pak ikspak iksemel packet.
2200  * \return IKS_FILTER_EAT.
2201  */
2202 static int aji_filter_roster(void *data, ikspak *pak)
2203 {
2204         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
2205         int flag = 0;
2206         iks *x = NULL;
2207         struct aji_buddy *buddy;
2208         
2209         client->state = AJI_CONNECTED;
2210         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
2211                 ASTOBJ_RDLOCK(iterator);
2212                 x = iks_child(pak->query);
2213                 flag = 0;
2214                 while (x) {
2215                         if (!iks_strcmp(iks_name(x), "item")) {
2216                                 if (!strcasecmp(iterator->name, iks_find_attrib(x, "jid"))) {
2217                                         flag = 1;
2218                                         ast_clear_flag(&iterator->flags, AJI_AUTOPRUNE | AJI_AUTOREGISTER);
2219                                 }
2220                         }
2221                         x = iks_next(x);
2222                 }
2223                 if (!flag)
2224                         ast_copy_flags(&iterator->flags, &client->flags, AJI_AUTOREGISTER);
2225                 iks_delete(x);
2226                 
2227                 ASTOBJ_UNLOCK(iterator);
2228         });
2229
2230         x = iks_child(pak->query);
2231         while (x) {
2232                 flag = 0;
2233                 if (iks_strcmp(iks_name(x), "item") == 0) {
2234                         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
2235                                 ASTOBJ_RDLOCK(iterator);
2236                                 if (!strcasecmp(iterator->name, iks_find_attrib(x, "jid")))
2237                                         flag = 1;
2238                                 ASTOBJ_UNLOCK(iterator);
2239                         });
2240
2241                         if (flag) {
2242                                 /* found buddy, don't create a new one */
2243                                 x = iks_next(x);
2244                                 continue;
2245                         }
2246                         
2247                         buddy = ast_calloc(1, sizeof(*buddy));
2248                         if (!buddy) {
2249                                 ast_log(LOG_WARNING, "Out of memory\n");
2250                                 return 0;
2251                         }
2252                         ASTOBJ_INIT(buddy);
2253                         ASTOBJ_WRLOCK(buddy);
2254                         ast_copy_string(buddy->name, iks_find_attrib(x, "jid"), sizeof(buddy->name));
2255                         ast_clear_flag(&buddy->flags, AST_FLAGS_ALL);
2256                         if(ast_test_flag(&client->flags, AJI_AUTOPRUNE)) {
2257                                 ast_set_flag(&buddy->flags, AJI_AUTOPRUNE);
2258                                 ASTOBJ_MARK(buddy);
2259                         } else if (!iks_strcmp(iks_find_attrib(x, "subscription"), "none") || !iks_strcmp(iks_find_attrib(x, "subscription"), "from")) {
2260                                 /* subscribe to buddy's presence only 
2261                                    if we really need to */
2262                                 ast_set_flag(&buddy->flags, AJI_AUTOREGISTER);
2263                         }
2264                         ASTOBJ_UNLOCK(buddy);
2265                         if (buddy) {
2266                                 ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
2267                                 ASTOBJ_UNREF(buddy, aji_buddy_destroy);
2268                         }
2269                 }
2270                 x = iks_next(x);
2271         }
2272
2273         iks_delete(x);
2274         aji_pruneregister(client);
2275
2276         ASTOBJ_UNREF(client, aji_client_destroy);
2277         return IKS_FILTER_EAT;
2278 }
2279
2280 /*!
2281  * \brief reconnect to jabber server
2282  * \param client the configured XMPP client we use to connect to a XMPP server
2283  * \return res.
2284 */
2285 static int aji_reconnect(struct aji_client *client)
2286 {
2287         int res = 0;
2288
2289         if (client->state)
2290                 client->state = AJI_DISCONNECTED;
2291         client->timeout=50;
2292         if (client->p)
2293                 iks_parser_reset(client->p);
2294         if (client->authorized)
2295                 client->authorized = 0;
2296
2297         res = aji_initialize(client);
2298
2299         return res;
2300 }
2301
2302 /*!
2303  * \brief Get the roster of jabber users
2304  * \param client the configured XMPP client we use to connect to a XMPP server
2305  * \return 1.
2306 */
2307 static int aji_get_roster(struct aji_client *client)
2308 {
2309         iks *roster = NULL;
2310         roster = iks_make_iq(IKS_TYPE_GET, IKS_NS_ROSTER);
2311
2312         if(roster) {
2313                 iks_insert_attrib(roster, "id", "roster");
2314                 aji_set_presence(client, NULL, client->jid->full, client->status, client->statusmessage);
2315                 ast_aji_send(client, roster);
2316         }
2317
2318         iks_delete(roster);
2319         
2320         return 1;
2321 }
2322
2323 /*!
2324  * \brief connects as a client to jabber server.
2325  * \param data void
2326  * \param pak ikspak iksemel packet
2327  * \return res.
2328  */
2329 static int aji_client_connect(void *data, ikspak *pak)
2330 {
2331         struct aji_client *client = ASTOBJ_REF((struct aji_client *) data);
2332         int res = 0;
2333
2334         if (client) {
2335                 if (client->state == AJI_DISCONNECTED) {
2336                         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);
2337                         client->state = AJI_CONNECTING;
2338                         client->jid = (iks_find_cdata(pak->query, "jid")) ? iks_id_new(client->stack, iks_find_cdata(pak->query, "jid")) : client->jid;
2339                         iks_filter_remove_hook(client->f, aji_client_connect);
2340                         if(!client->component) /*client*/
2341                                 aji_get_roster(client);
2342                 }
2343         } else
2344                 ast_log(LOG_ERROR, "Out of memory.\n");
2345
2346         ASTOBJ_UNREF(client, aji_client_destroy);
2347         return res;
2348 }
2349
2350 /*!
2351  * \brief prepares client for connect.
2352  * \param client the configured XMPP client we use to connect to a XMPP server
2353  * \return 1.
2354  */
2355 static int aji_initialize(struct aji_client *client)
2356 {
2357         int connected = IKS_NET_NOCONN;
2358
2359 #ifdef HAVE_OPENSSL     
2360         /* reset stream flags */
2361         client->stream_flags = 0;
2362 #endif
2363         /* If it's a component, connect to user, otherwise, connect to server */
2364         connected = iks_connect_via(client->p, S_OR(client->serverhost, client->jid->server), client->port, client->component ? client->user : client->jid->server);
2365
2366         if (connected == IKS_NET_NOCONN) {
2367                 ast_log(LOG_ERROR, "JABBER ERROR: No Connection\n");
2368                 return IKS_HOOK;
2369         } else  if (connected == IKS_NET_NODNS) {
2370                 ast_log(LOG_ERROR, "JABBER ERROR: No DNS %s for client to  %s\n", client->name, S_OR(client->serverhost, client->jid->server));
2371                 return IKS_HOOK;
2372         }
2373
2374         return IKS_OK;
2375 }
2376
2377 /*!
2378  * \brief disconnect from jabber server.
2379  * \param client the configured XMPP client we use to connect to a XMPP server
2380  * \return 1.
2381  */
2382 int ast_aji_disconnect(struct aji_client *client)
2383 {
2384         if (client) {
2385                 ast_verb(4, "JABBER: Disconnecting\n");
2386 #ifdef HAVE_OPENSSL
2387                 if (client->stream_flags & SECURE) {
2388                         SSL_shutdown(client->ssl_session);
2389                         SSL_CTX_free(client->ssl_context);
2390                         SSL_free(client->ssl_session);
2391                 }
2392 #endif
2393                 iks_disconnect(client->p);
2394                 iks_parser_delete(client->p);
2395                 ASTOBJ_UNREF(client, aji_client_destroy);
2396         }
2397
2398         return 1;
2399 }
2400
2401 /*!
2402  * \brief set presence of client.
2403  * \param client the configured XMPP client we use to connect to a XMPP server
2404  * \param to user send it to
2405  * \param from user it came from
2406  * \param level
2407  * \param desc
2408  * \return void.
2409  */
2410 static void aji_set_presence(struct aji_client *client, char *to, char *from, int level, char *desc)
2411 {
2412         int res = 0;
2413         iks *presence = iks_make_pres(level, desc);
2414         iks *cnode = iks_new("c");
2415         iks *priority = iks_new("priority");
2416         char priorityS[10];
2417
2418         if (presence && cnode && client && priority) {
2419                 if(to)
2420                         iks_insert_attrib(presence, "to", to);
2421                 if(from)
2422                         iks_insert_attrib(presence, "from", from);
2423                 snprintf(priorityS, sizeof(priorityS), "%d", client->priority);
2424                 iks_insert_cdata(priority, priorityS, strlen(priorityS));
2425                 iks_insert_node(presence, priority);
2426                 iks_insert_attrib(cnode, "node", "http://www.asterisk.org/xmpp/client/caps");
2427                 iks_insert_attrib(cnode, "ver", "asterisk-xmpp");
2428                 iks_insert_attrib(cnode, "ext", "voice-v1");
2429                 iks_insert_attrib(cnode, "xmlns", "http://jabber.org/protocol/caps");
2430                 iks_insert_node(presence, cnode);
2431                 res = ast_aji_send(client, presence);
2432         } else
2433                 ast_log(LOG_ERROR, "Out of memory.\n");
2434
2435         iks_delete(cnode);
2436         iks_delete(presence);
2437         iks_delete(priority);
2438 }
2439
2440 /*!
2441  * \brief Turn on/off console debugging.
2442  * \return CLI_SUCCESS.
2443  */
2444 static char *aji_do_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2445 {
2446         switch (cmd) {
2447         case CLI_INIT:
2448                 e->command = "jabber set debug {on|off}";
2449                 e->usage =
2450                         "Usage: jabber set debug {on|off}\n"
2451                         "       Enables/disables dumping of XMPP/Jabber packets for debugging purposes.\n";
2452                 return NULL;
2453         case CLI_GENERATE:
2454                 return NULL;
2455         }
2456
2457         if (a->argc != e->args)
2458                 return CLI_SHOWUSAGE;
2459
2460         if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
2461                 ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2462                         ASTOBJ_RDLOCK(iterator); 
2463                         iterator->debug = 1;
2464                         ASTOBJ_UNLOCK(iterator);
2465                 });
2466                 ast_cli(a->fd, "Jabber Debugging Enabled.\n");
2467                 return CLI_SUCCESS;
2468         } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
2469                 ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2470                         ASTOBJ_RDLOCK(iterator); 
2471                         iterator->debug = 0;
2472                         ASTOBJ_UNLOCK(iterator);
2473                 });
2474                 ast_cli(a->fd, "Jabber Debugging Disabled.\n");
2475                 return CLI_SUCCESS;
2476         }
2477         return CLI_SHOWUSAGE; /* defaults to invalid */
2478 }
2479
2480 /*!
2481  * \brief Reload jabber module.
2482  * \return CLI_SUCCESS.
2483  */
2484 static char *aji_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2485 {
2486         switch (cmd) {
2487         case CLI_INIT:
2488                 e->command = "jabber reload";
2489                 e->usage =
2490                         "Usage: jabber reload\n"
2491                         "       Reloads the Jabber module.\n";
2492                 return NULL;
2493         case CLI_GENERATE:
2494                 return NULL;
2495         }
2496
2497         aji_reload(1);
2498         ast_cli(a->fd, "Jabber Reloaded.\n");
2499         return CLI_SUCCESS;
2500 }
2501
2502 /*!
2503  * \brief Show client status.
2504  * \return CLI_SUCCESS.
2505  */
2506 static char *aji_show_clients(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2507 {
2508         char *status;
2509         int count = 0;
2510         
2511         switch (cmd) {
2512         case CLI_INIT:
2513                 e->command = "jabber show connected";
2514                 e->usage =
2515                         "Usage: jabber show connected\n"
2516                         "       Shows state of clients and components\n";
2517                 return NULL;
2518         case CLI_GENERATE:
2519                 return NULL;
2520         }
2521
2522         ast_cli(a->fd, "Jabber Users and their status:\n");
2523         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2524                 ASTOBJ_RDLOCK(iterator);
2525                 count++;
2526                 switch (iterator->state) {
2527                 case AJI_DISCONNECTED:
2528                         status = "Disconnected";
2529                         break;
2530                 case AJI_CONNECTING:
2531                         status = "Connecting";
2532                         break;
2533                 case AJI_CONNECTED:
2534                         status = "Connected";
2535                         break;
2536                 default:
2537                         status = "Unknown";
2538                 }
2539                 ast_cli(a->fd, "       User: %s     - %s\n", iterator->user, status);
2540                 ASTOBJ_UNLOCK(iterator);
2541         });
2542         ast_cli(a->fd, "----\n");
2543         ast_cli(a->fd, "   Number of users: %d\n", count);
2544         return CLI_SUCCESS;
2545 }
2546
2547 /*!
2548  * \brief Show buddy lists
2549  * \return CLI_SUCCESS.
2550  */
2551 static char *aji_show_buddies(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2552 {
2553         struct aji_resource *resource;
2554         struct aji_client *client;
2555
2556         switch (cmd) {
2557         case CLI_INIT:
2558                 e->command = "jabber show buddies";
2559                 e->usage =
2560                         "Usage: jabber show buddies\n"
2561                         "       Shows buddy lists of our clients\n";
2562                 return NULL;
2563         case CLI_GENERATE:
2564                 return NULL;
2565         }
2566
2567         ast_cli(a->fd, "Jabber buddy lists\n");
2568         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2569                 ast_cli(a->fd,"Client: %s\n", iterator->user);
2570                 client = iterator;
2571                 ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
2572                         ASTOBJ_RDLOCK(iterator);
2573                         ast_cli(a->fd,"\tBuddy:\t%s\n", iterator->name);
2574                         if (!iterator->resources)
2575                                 ast_cli(a->fd,"\t\tResource: None\n");  
2576                         for (resource = iterator->resources; resource; resource = resource->next) {
2577                                 ast_cli(a->fd,"\t\tResource: %s\n", resource->resource);
2578                                 if(resource->cap) {
2579                                         ast_cli(a->fd,"\t\t\tnode: %s\n", resource->cap->parent->node);
2580                                         ast_cli(a->fd,"\t\t\tversion: %s\n", resource->cap->version);
2581                                         ast_cli(a->fd,"\t\t\tJingle capable: %s\n", resource->cap->jingle ? "yes" : "no");
2582                                 }
2583                                 ast_cli(a->fd,"\t\tStatus: %d\n", resource->status);
2584                                 ast_cli(a->fd,"\t\tPriority: %d\n", resource->priority);
2585                         }
2586                         ASTOBJ_UNLOCK(iterator);
2587                 });
2588                 iterator = client;
2589         });
2590         return CLI_SUCCESS;
2591 }
2592
2593 /*!
2594  * \brief Send test message for debugging.
2595  * \return CLI_SUCCESS,CLI_FAILURE.
2596  */
2597 static char *aji_test(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2598 {
2599         struct aji_client *client;
2600         struct aji_resource *resource;
2601         const char *name = "asterisk";
2602         struct aji_message *tmp;
2603
2604         switch (cmd) {
2605         case CLI_INIT:
2606                 e->command = "jabber test";
2607                 e->usage =
2608                         "Usage: jabber test [client]\n"
2609                         "       Sends test message for debugging purposes.  A specific client\n"
2610                         "       as configured in jabber.conf can be optionally specified.\n";
2611                 return NULL;
2612         case CLI_GENERATE:
2613                 return NULL;
2614         }
2615
2616         if (a->argc > 3)
2617                 return CLI_SHOWUSAGE;
2618         else if (a->argc == 3)
2619                 name = a->argv[2];
2620
2621         if (!(client = ASTOBJ_CONTAINER_FIND(&clients, name))) {
2622                 ast_cli(a->fd, "Unable to find client '%s'!\n", name);
2623                 return CLI_FAILURE;
2624         }
2625
2626         /* XXX Does Matt really want everyone to use his personal address for tests? */ /* XXX yes he does */
2627         ast_aji_send_chat(client, "mogorman@astjab.org", "blahblah");
2628         ASTOBJ_CONTAINER_TRAVERSE(&client->buddies, 1, {
2629                 ASTOBJ_RDLOCK(iterator);
2630                 ast_verbose("User: %s\n", iterator->name);
2631                 for (resource = iterator->resources; resource; resource = resource->next) {
2632                         ast_verbose("Resource: %s\n", resource->resource);
2633                         if(resource->cap) {
2634                                 ast_verbose("   client: %s\n", resource->cap->parent->node);
2635                                 ast_verbose("   version: %s\n", resource->cap->version);
2636                                 ast_verbose("   Jingle Capable: %d\n", resource->cap->jingle);
2637                         }
2638                         ast_verbose("   Priority: %d\n", resource->priority);
2639                         ast_verbose("   Status: %d\n", resource->status); 
2640                         ast_verbose("   Message: %s\n", S_OR(resource->description,"")); 
2641                 }
2642                 ASTOBJ_UNLOCK(iterator);
2643         });
2644         ast_verbose("\nOooh a working message stack!\n");
2645         AST_LIST_LOCK(&client->messages);
2646         AST_LIST_TRAVERSE(&client->messages, tmp, list) {
2647                 ast_verbose("   Message from: %s with id %s @ %s        %s\n",tmp->from, S_OR(tmp->id,""), ctime(&tmp->arrived), S_OR(tmp->message, ""));
2648         }
2649         AST_LIST_UNLOCK(&client->messages);
2650         ASTOBJ_UNREF(client, aji_client_destroy);
2651
2652         return CLI_SUCCESS;
2653 }
2654
2655 /*!
2656  * \brief creates aji_client structure.
2657  * \param label
2658  * \param var ast_variable
2659  * \param debug 
2660  * \return 0.
2661  */
2662 static int aji_create_client(char *label, struct ast_variable *var, int debug)
2663 {
2664         char *resource;
2665         struct aji_client *client = NULL;
2666         int flag = 0;
2667
2668         client = ASTOBJ_CONTAINER_FIND(&clients,label);
2669         if (!client) {
2670                 flag = 1;
2671                 client = ast_calloc(1, sizeof(*client));
2672                 if (!client) {
2673                         ast_log(LOG_ERROR, "Out of memory!\n");
2674                         return 0;
2675                 }
2676                 ASTOBJ_INIT(client);
2677                 ASTOBJ_WRLOCK(client);
2678                 ASTOBJ_CONTAINER_INIT(&client->buddies);
2679         } else {
2680                 ASTOBJ_WRLOCK(client);
2681                 ASTOBJ_UNMARK(client);
2682         }
2683         ASTOBJ_CONTAINER_MARKALL(&client->buddies);
2684         ast_copy_string(client->name, label, sizeof(client->name));
2685         ast_copy_string(client->mid, "aaaaa", sizeof(client->mid));
2686
2687         /* Set default values for the client object */
2688         client->debug = debug;
2689         ast_copy_flags(&client->flags, &globalflags, AST_FLAGS_ALL);
2690         client->port = 5222;
2691         client->usetls = 1;
2692         client->usesasl = 1;
2693         client->forcessl = 0;
2694         client->keepalive = 1;
2695         client->timeout = 50;
2696         client->message_timeout = 100;
2697         AST_LIST_HEAD_INIT(&client->messages);
2698         client->component = 0;
2699         ast_copy_string(client->statusmessage, "Online and Available", sizeof(client->statusmessage));
2700         client->priority = 0;
2701         client->status = IKS_SHOW_AVAILABLE;
2702
2703         if (flag) {
2704                 client->authorized = 0;
2705                 client->state = AJI_DISCONNECTED;
2706         }
2707         while (var) {
2708                 if (!strcasecmp(var->name, "username"))
2709                         ast_copy_string(client->user, var->value, sizeof(client->user));
2710                 else if (!strcasecmp(var->name, "serverhost"))
2711                         ast_copy_string(client->serverhost, var->value, sizeof(client->serverhost));
2712                 else if (!strcasecmp(var->name, "secret"))
2713                         ast_copy_string(client->password, var->value, sizeof(client->password));
2714                 else if (!strcasecmp(var->name, "statusmessage"))
2715                         ast_copy_string(client->statusmessage, var->value, sizeof(client->statusmessage));
2716                 else if (!strcasecmp(var->name, "port"))
2717                         client->port = atoi(var->value);
2718                 else if (!strcasecmp(var->name, "timeout"))
2719                         client->message_timeout = atoi(var->value);
2720                 else if (!strcasecmp(var->name, "debug"))
2721                         client->debug = (ast_false(var->value)) ? 0 : 1;
2722                 else if (!strcasecmp(var->name, "type")) {
2723                         if (!strcasecmp(var->value, "component"))
2724                                 client->component = 1;
2725                 } else if (!strcasecmp(var->name, "usetls")) {
2726                         client->usetls = (ast_false(var->value)) ? 0 : 1;
2727                 } else if (!strcasecmp(var->name, "usesasl")) {
2728                         client->usesasl = (ast_false(var->value)) ? 0 : 1;
2729                 } else if (!strcasecmp(var->name, "forceoldssl"))
2730                         client->forcessl = (ast_false(var->value)) ? 0 : 1;
2731                 else if (!strcasecmp(var->name, "keepalive"))
2732                         client->keepalive = (ast_false(var->value)) ? 0 : 1;
2733                 else if (!strcasecmp(var->name, "autoprune"))
2734                         ast_set2_flag(&client->flags, ast_true(var->value), AJI_AUTOPRUNE);
2735                 else if (!strcasecmp(var->name, "autoregister"))
2736                         ast_set2_flag(&client->flags, ast_true(var->value), AJI_AUTOREGISTER);
2737                 else if (!strcasecmp(var->name, "buddy"))
2738                         aji_create_buddy((char *)var->value, client);
2739                 else if (!strcasecmp(var->name, "priority"))
2740                         client->priority = atoi(var->value);
2741                 else if (!strcasecmp(var->name, "status")) {
2742                         if (!strcasecmp(var->value, "unavailable"))
2743                                 client->status = IKS_SHOW_UNAVAILABLE;
2744                         else
2745                         if (!strcasecmp(var->value, "available")
2746                          || !strcasecmp(var->value, "online"))
2747                                 client->status = IKS_SHOW_AVAILABLE;
2748                         else
2749                         if (!strcasecmp(var->value, "chat")
2750                          || !strcasecmp(var->value, "chatty"))
2751                                 client->status = IKS_SHOW_CHAT;
2752                         else
2753                         if (!strcasecmp(var->value, "away"))
2754                                 client->status = IKS_SHOW_AWAY;
2755                         else
2756                         if (!strcasecmp(var->value, "xa")
2757                          || !strcasecmp(var->value, "xaway"))
2758                                 client->status = IKS_SHOW_XA;
2759                         else
2760                         if (!strcasecmp(var->value, "dnd"))
2761                                 client->status = IKS_SHOW_DND;
2762                         else
2763                         if (!strcasecmp(var->value, "invisible"))
2764                         #ifdef IKS_SHOW_INVISIBLE
2765                                 client->status = IKS_SHOW_INVISIBLE;
2766                         #else
2767                         {
2768                                 ast_log(LOG_WARNING, "Your iksemel doesn't support invisible status: falling back to DND\n");
2769                                 client->status = IKS_SHOW_DND;
2770                         }
2771                         #endif
2772                         else
2773                                 ast_log(LOG_WARNING, "Unknown presence status: %s\n", var->value);
2774                 }
2775         /* no transport support in this version */
2776         /*      else if (!strcasecmp(var->name, "transport"))
2777                                 aji_create_transport(var->value, client);
2778         */
2779                 var = var->next;
2780         }
2781         if (!flag) {
2782                 ASTOBJ_UNLOCK(client);
2783                 ASTOBJ_UNREF(client, aji_client_destroy);
2784                 return 1;
2785         }
2786
2787         ast_copy_string(client->name_space, (client->component) ? "jabber:component:accept" : "jabber:client", sizeof(client->name_space));
2788         client->p = iks_stream_new(client->name_space, client, aji_act_hook);
2789         if (!client->p) {
2790                 ast_log(LOG_ERROR, "Failed to create stream for client '%s'!\n", client->name);
2791                 return 0;
2792         }
2793         client->stack = iks_stack_new(8192, 8192);
2794         if (!client->stack) {
2795                 ast_log(LOG_ERROR, "Failed to allocate stack for client '%s'\n", client->name);
2796                 return 0;
2797         }
2798         client->f = iks_filter_new();
2799         if (!client->f) {
2800                 ast_log(LOG_ERROR, "Failed to create filter for client '%s'\n", client->name);
2801                 return 0;
2802         }
2803         if (!strchr(client->user, '/') && !client->component) { /*client */
2804                 resource = NULL;
2805                 if (asprintf(&resource, "%s/asterisk", client->user) >= 0) {
2806                         client->jid = iks_id_new(client->stack, resource);
2807                         ast_free(resource);
2808                 }
2809         } else
2810                 client->jid = iks_id_new(client->stack, client->user);
2811         if (client->component) {
2812                 iks_filter_add_rule(client->f, aji_dinfo_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
2813                 iks_filter_add_rule(client->f, aji_ditems_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#items", IKS_RULE_DONE);
2814                 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);
2815                 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);
2816         } else {
2817                 iks_filter_add_rule(client->f, aji_client_info_handler, client, IKS_RULE_NS, "http://jabber.org/protocol/disco#info", IKS_RULE_DONE);
2818         }
2819         iks_set_log_hook(client->p, aji_log_hook);
2820         ASTOBJ_UNLOCK(client);
2821         ASTOBJ_CONTAINER_LINK(&clients,client);
2822         return 1;
2823 }
2824
2825 #if 0
2826 /*!
2827  * \brief creates transport.
2828  * \param label, buddy to dump it into. 
2829  * \return 0.
2830  */
2831 /* no connecting to transports today */
2832 static int aji_create_transport(char *label, struct aji_client *client)
2833 {
2834         char *server = NULL, *buddyname = NULL, *user = NULL, *pass = NULL;
2835         struct aji_buddy *buddy = NULL;
2836
2837         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies,label);
2838         if (!buddy) {
2839                 buddy = ast_calloc(1, sizeof(*buddy));
2840                 if(!buddy) {
2841                         ast_log(LOG_WARNING, "Out of memory\n");
2842                         return 0;
2843                 }
2844                 ASTOBJ_INIT(buddy);
2845         }
2846         ASTOBJ_WRLOCK(buddy);
2847         server = label;
2848         if ((buddyname = strchr(label, ','))) {
2849                 *buddyname = '\0';
2850                 buddyname++;
2851                 if (buddyname && buddyname[0] != '\0') {
2852                         if ((user = strchr(buddyname, ','))) {
2853                                 *user = '\0';
2854                                 user++;
2855                                 if (user && user[0] != '\0') {
2856                                         if ((pass = strchr(user, ','))) {
2857                                                 *pass = '\0';
2858                                                 pass++;
2859                                                 ast_copy_string(buddy->pass, pass, sizeof(buddy->pass));
2860                                                 ast_copy_string(buddy->user, user, sizeof(buddy->user));
2861                                                 ast_copy_string(buddy->name, buddyname, sizeof(buddy->name));
2862                                                 ast_copy_string(buddy->server, server, sizeof(buddy->server));
2863                                                 return 1;
2864                                         }
2865                                 }
2866                         }
2867                 }
2868         }
2869         ASTOBJ_UNLOCK(buddy);
2870         ASTOBJ_UNMARK(buddy);
2871         ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
2872         return 0;
2873 }
2874 #endif
2875
2876 /*!
2877  * \brief creates buddy.
2878  * \param label char.
2879  * \param client the configured XMPP client we use to connect to a XMPP server 
2880  * \return 1 on success, 0 on failure.
2881  */
2882 static int aji_create_buddy(char *label, struct aji_client *client)
2883 {
2884         struct aji_buddy *buddy = NULL;
2885         int flag = 0;
2886         buddy = ASTOBJ_CONTAINER_FIND(&client->buddies,label);
2887         if (!buddy) {
2888                 flag = 1;
2889                 buddy = ast_calloc(1, sizeof(*buddy));
2890                 if(!buddy) {
2891                         ast_log(LOG_WARNING, "Out of memory\n");
2892                         return 0;
2893                 }
2894                 ASTOBJ_INIT(buddy);
2895         }
2896         ASTOBJ_WRLOCK(buddy);
2897         ast_copy_string(buddy->name, label, sizeof(buddy->name));
2898         ASTOBJ_UNLOCK(buddy);
2899         if(flag)
2900                 ASTOBJ_CONTAINER_LINK(&client->buddies, buddy);
2901         else {
2902                 ASTOBJ_UNMARK(buddy);
2903                 ASTOBJ_UNREF(buddy, aji_buddy_destroy);
2904         }
2905         return 1;
2906 }
2907
2908 /*!< load config file. \return 1. */
2909 static int aji_load_config(int reload)
2910 {
2911         char *cat = NULL;
2912         int debug = 1;
2913         struct ast_config *cfg = NULL;
2914         struct ast_variable *var = NULL;
2915         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
2916
2917         if ((cfg = ast_config_load(JABBER_CONFIG, config_flags)) == CONFIG_STATUS_FILEUNCHANGED)
2918                 return -1;
2919
2920         /* Reset flags to default value */
2921         ast_set_flag(&globalflags, AJI_AUTOREGISTER);
2922
2923         if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEINVALID) {
2924                 ast_log(LOG_WARNING, "No such configuration file %s\n", JABBER_CONFIG);
2925                 return 0;
2926         }
2927
2928         cat = ast_category_browse(cfg, NULL);
2929         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
2930                 if (!strcasecmp(var->name, "debug")) {
2931                         debug = (ast_false(ast_variable_retrieve(cfg, "general", "debug"))) ? 0 : 1;
2932                 } else if (!strcasecmp(var->name, "autoprune")) {
2933                         ast_set2_flag(&globalflags, ast_true(var->value), AJI_AUTOPRUNE);
2934                 } else if (!strcasecmp(var->name, "autoregister")) {
2935                         ast_set2_flag(&globalflags, ast_true(var->value), AJI_AUTOREGISTER);
2936                 }
2937         }
2938
2939         while (cat) {
2940                 if (strcasecmp(cat, "general")) {
2941                                 var = ast_variable_browse(cfg, cat);
2942                                 aji_create_client(cat, var, debug);
2943                 }
2944                 cat = ast_category_browse(cfg, cat);
2945         }
2946         ast_config_destroy(cfg); /* or leak memory */
2947         return 1;
2948 }
2949
2950 /*!
2951  * \brief grab a aji_client structure by label name or JID 
2952  * (without the resource string)
2953  * \param name label or JID 
2954  * \return aji_client.
2955  */
2956 struct aji_client *ast_aji_get_client(const char *name)
2957 {
2958         struct aji_client *client = NULL;
2959         char *aux = NULL;
2960
2961         client = ASTOBJ_CONTAINER_FIND(&clients, name);
2962         if (!client && strchr(name, '@')) {
2963                 ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
2964                         aux = ast_strdupa(iterator->user);
2965                         if (strchr(aux, '/')) {
2966                                 /* strip resource for comparison */
2967                                 aux = strsep(&aux, "/");
2968                         }
2969                         if (!strncasecmp(aux, name, strlen(aux))) {
2970                                 client = iterator;
2971                         }                               
2972                 });
2973         }
2974
2975         return client;
2976 }
2977
2978 struct aji_client_container *ast_aji_get_clients(void)
2979 {
2980         return &clients;
2981 }
2982
2983 static const char mandescr_jabber_send[] =
2984 "Description: Sends a message to a Jabber Client.\n"
2985 "Variables: \n"
2986 "  Jabber:    Client or transport Asterisk uses to connect to JABBER\n"
2987 "  JID:       XMPP/Jabber JID (Name) of recipient\n" 
2988 "  Message:   Message to be sent to the buddy\n";
2989
2990 /*! 
2991  * \brief  Send a Jabber Message via call from the Manager 
2992  * \param s mansession Manager session
2993  * \param m message Message to send
2994  * \return  0
2995 */
2996 static int manager_jabber_send(struct mansession *s, const struct message *m)
2997 {
2998         struct aji_client *client = NULL;
2999         const char *id = astman_get_header(m,"ActionID");
3000         const char *jabber = astman_get_header(m,"Jabber");
3001         const char *screenname = astman_get_header(m,"ScreenName");
3002         const char *message = astman_get_header(m,"Message");
3003
3004         if (ast_strlen_zero(jabber)) {
3005                 astman_send_error(s, m, "No transport specified");
3006                 return 0;
3007         }
3008         if (ast_strlen_zero(screenname)) {
3009                 astman_send_error(s, m, "No ScreenName specified");
3010                 return 0;
3011         }
3012         if (ast_strlen_zero(message)) {
3013                 astman_send_error(s, m, "No Message specified");
3014                 return 0;
3015         }
3016
3017         astman_send_ack(s, m, "Attempting to send Jabber Message");
3018         client = ast_aji_get_client(jabber);
3019         if (!client) {
3020                 astman_send_error(s, m, "Could not find Sender");
3021                 return 0;
3022         }
3023         if (strchr(screenname, '@') && message) {
3024                 ast_aji_send_chat(client, screenname, message);
3025                 astman_append(s, "Response: Success\r\n");
3026         } else {
3027                 astman_append(s, "Response: Error\r\n");
3028         }
3029         if (!ast_strlen_zero(id)) {
3030                 astman_append(s, "ActionID: %s\r\n",id);
3031         }
3032         astman_append(s, "\r\n");
3033         return 0;
3034 }
3035
3036 /*! \brief Reload the jabber module */
3037 static int aji_reload(int reload)
3038 {
3039         int res;
3040
3041         ASTOBJ_CONTAINER_MARKALL(&clients);
3042         if (!(res = aji_load_config(reload))) {
3043                 ast_log(LOG_ERROR, "JABBER: Failed to load config.\n");
3044                 return 0;
3045         } else if (res == -1)
3046                 return 1;
3047
3048         ASTOBJ_CONTAINER_PRUNE_MARKED(&clients, aji_client_destroy);
3049         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
3050                 ASTOBJ_RDLOCK(iterator);
3051                 if(iterator->state == AJI_DISCONNECTED) {
3052                         if (!iterator->thread)
3053                                 ast_pthread_create_background(&iterator->thread, NULL, aji_recv_loop, iterator);
3054                 } else if (iterator->state == AJI_CONNECTING)
3055                         aji_get_roster(iterator);
3056                 ASTOBJ_UNLOCK(iterator);
3057         });
3058         
3059         return 1;
3060 }
3061
3062 /*! \brief Unload the jabber module */
3063 static int unload_module(void)
3064 {
3065
3066         ast_cli_unregister_multiple(aji_cli, ARRAY_LEN(aji_cli));
3067         ast_unregister_application(app_ajisend);
3068         ast_unregister_application(app_ajistatus);
3069         ast_manager_unregister("JabberSend");
3070         ast_custom_function_unregister(&jabberstatus_function);
3071         
3072         ASTOBJ_CONTAINER_TRAVERSE(&clients, 1, {
3073                 ASTOBJ_RDLOCK(iterator);
3074                 ast_debug(3, "JABBER: Releasing and disconnecting client: %s\n", iterator->name);
3075                 iterator->state = AJI_DISCONNECTING;
3076                 ast_aji_disconnect(iterator);
3077                 pthread_join(iterator->thread, NULL);
3078                 ASTOBJ_UNLOCK(iterator);
3079         });
3080
3081         ASTOBJ_CONTAINER_DESTROYALL(&clients, aji_client_destroy);
3082         ASTOBJ_CONTAINER_DESTROY(&clients);
3083         return 0;
3084 }
3085
3086 /*! \brief Unload the jabber module */
3087 static int load_module(void)
3088 {
3089         ASTOBJ_CONTAINER_INIT(&clients);
3090         if(!aji_reload(0))
3091                 return AST_MODULE_LOAD_DECLINE;
3092         ast_manager_register2("JabberSend", EVENT_FLAG_SYSTEM, manager_jabber_send,
3093                         "Sends a message to a Jabber Client", mandescr_jabber_send);
3094         ast_register_application_xml(app_ajisend, aji_send_exec);
3095         ast_register_application_xml(app_ajistatus, aji_status_exec);
3096         ast_cli_register_multiple(aji_cli, ARRAY_LEN(aji_cli));
3097         ast_custom_function_register(&jabberstatus_function);
3098
3099         return 0;
3100 }
3101
3102 /*! \brief Wrapper for aji_reload */
3103 static int reload(void)
3104 {
3105         aji_reload(1);
3106         return 0;
3107 }
3108
3109 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "AJI - Asterisk Jabber Interface",
3110                 .load = load_module,
3111                 .unload = unload_module,
3112                 .reload = reload,
3113                );