Media Project Phase2: SILK 8khz-24khz, SLINEAR 8khz-192khz, SPEEX 32khz, hd audio...
[asterisk/asterisk.git] / channels / chan_gtalk.c
index 0cd2a5b..d8dd736 100644 (file)
@@ -4,6 +4,7 @@
  * Copyright (C) 1999 - 2005, Digium, Inc.
  *
  * Matt O'Gorman <mogorman@digium.com>
+ * Philippe Sultan <philippe.sultan@gmail.com>
  *
  * See http://www.asterisk.org for more information about
  * the Asterisk project. Please do not directly contact
 /*! \file
  *
  * \author Matt O'Gorman <mogorman@digium.com>
+ * \author Philippe Sultan <philippe.sultan@gmail.com>
  *
  * \brief Gtalk Channel Driver, until google/libjingle works with jingle spec
- * 
+ *
  * \ingroup channel_drivers
+ *
+ * ********** General TODO:s
+ * \todo Support config reloading.
+ * \todo Fix native bridging.
  */
 
 /*** MODULEINFO
        <depend>iksemel</depend>
        <depend>res_jabber</depend>
+       <use>openssl</use>
  ***/
 
 #include "asterisk.h"
 
 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
 #include <sys/socket.h>
-#include <errno.h>
-#include <stdlib.h>
 #include <fcntl.h>
 #include <netdb.h>
 #include <netinet/in.h>
 #include <arpa/inet.h>
 #include <sys/signal.h>
 #include <iksemel.h>
+#include <pthread.h>
+#include <ctype.h>
 
 #include "asterisk/lock.h"
 #include "asterisk/channel.h"
 #include "asterisk/config.h"
-#include "asterisk/logger.h"
 #include "asterisk/module.h"
 #include "asterisk/pbx.h"
-#include "asterisk/options.h"
-#include "asterisk/lock.h"
 #include "asterisk/sched.h"
 #include "asterisk/io.h"
-#include "asterisk/rtp.h"
+#include "asterisk/rtp_engine.h"
+#include "asterisk/stun.h"
 #include "asterisk/acl.h"
 #include "asterisk/callerid.h"
 #include "asterisk/file.h"
@@ -72,11 +73,10 @@ ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 #include "asterisk/astobj.h"
 #include "asterisk/abstract_jb.h"
 #include "asterisk/jabber.h"
+#include "asterisk/jingle.h"
+#include "asterisk/features.h"
 
-#define GOOGLE_CONFIG "gtalk.conf"
-
-#define GOOGLE_NS "http://www.google.com/session"
-
+#define GOOGLE_CONFIG          "gtalk.conf"
 
 /*! Global jitterbuffer configuration - by default, jb is disabled */
 static struct ast_jb_conf default_jbconf =
@@ -84,7 +84,8 @@ static struct ast_jb_conf default_jbconf =
        .flags = 0,
        .max_size = -1,
        .resync_threshold = -1,
-       .impl = ""
+       .impl = "",
+       .target_extra = -1,
 };
 static struct ast_jb_conf global_jbconf;
 
@@ -104,13 +105,12 @@ struct gtalk_pvt {
        time_t laststun;
        struct gtalk *parent;            /*!< Parent client */
        char sid[100];
-       char us[100];
-       char them[100];
+       char us[AJI_MAX_JIDLEN];
+       char them[AJI_MAX_JIDLEN];
        char ring[10];                   /*!< Message ID of ring */
        iksrule *ringrule;               /*!< Rule for matching RING request */
        int initiator;                   /*!< If we're the initiator */
        int alreadygone;
-       int capability;
        struct ast_codec_pref prefs;
        struct gtalk_candidate *theircandidates;
        struct gtalk_candidate *ourcandidates;
@@ -118,10 +118,11 @@ struct gtalk_pvt {
        char cid_name[80];               /*!< Caller ID name */
        char exten[80];                  /*!< Called extension */
        struct ast_channel *owner;       /*!< Master Channel */
-       struct ast_rtp *rtp;             /*!< RTP audio session */
-       struct ast_rtp *vrtp;            /*!< RTP video session */
-       int jointcapability;             /*!< Supported capability at both ends (codecs ) */
-       int peercapability;
+       struct ast_rtp_instance *rtp;             /*!< RTP audio session */
+       struct ast_rtp_instance *vrtp;            /*!< RTP video session */
+       struct ast_format_cap *cap;
+       struct ast_format_cap *jointcap;             /*!< Supported capability at both ends (codecs ) */
+       struct ast_format_cap *peercap;
        struct gtalk_pvt *next; /* Next entity */
 };
 
@@ -147,10 +148,11 @@ struct gtalk {
        struct gtalk_pvt *p;
        struct ast_codec_pref prefs;
        int amaflags;                   /*!< AMA Flags */
-       char user[100];
-       char context[100];
+       char user[AJI_MAX_JIDLEN];
+       char context[AST_MAX_CONTEXT];
+       char parkinglot[AST_MAX_CONTEXT];       /*!<  Parkinglot */
        char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
-       int capability;
+       struct ast_format_cap *cap;
        ast_group_t callgroup;  /*!< Call group */
        ast_group_t pickupgroup;        /*!< Pickup group */
        int callingpres;                /*!< Calling presentation */
@@ -163,20 +165,25 @@ struct gtalk_container {
        ASTOBJ_CONTAINER_COMPONENTS(struct gtalk);
 };
 
-static const char desc[] = "Gtalk Channel";
+static const char desc[]               = "Gtalk Channel";
+static const char DEFAULT_CONTEXT[]    = "default";
+static const int DEFAULT_ALLOWGUEST    = 1;
 
-static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
+static struct ast_format_cap *global_capability;
 
 AST_MUTEX_DEFINE_STATIC(gtalklock); /*!< Protect the interface list (of gtalk_pvt's) */
 
 /* Forward declarations */
-static struct ast_channel *gtalk_request(const char *type, int format, void *data, int *cause);
-static int gtalk_digit(struct ast_channel *ast, char digit, unsigned int duration);
+static struct ast_channel *gtalk_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, void *data, int *cause);
+/*static int gtalk_digit(struct ast_channel *ast, char digit, unsigned int duration);*/
+static int gtalk_sendtext(struct ast_channel *ast, const char *text);
 static int gtalk_digit_begin(struct ast_channel *ast, char digit);
 static int gtalk_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
 static int gtalk_call(struct ast_channel *ast, char *dest, int timeout);
 static int gtalk_hangup(struct ast_channel *ast);
 static int gtalk_answer(struct ast_channel *ast);
+static int gtalk_action(struct gtalk *client, struct gtalk_pvt *p, const char *action);
+static void gtalk_free_pvt(struct gtalk *client, struct gtalk_pvt *p);
 static int gtalk_newcall(struct gtalk *client, ikspak *pak);
 static struct ast_frame *gtalk_read(struct ast_channel *ast);
 static int gtalk_write(struct ast_channel *ast, struct ast_frame *f);
@@ -184,23 +191,26 @@ static int gtalk_indicate(struct ast_channel *ast, int condition, const void *da
 static int gtalk_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
 static int gtalk_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen);
 static struct gtalk_pvt *gtalk_alloc(struct gtalk *client, const char *us, const char *them, const char *sid);
-static int gtalk_do_reload(int fd, int argc, char **argv);
-static int gtalk_show_channels(int fd, int argc, char **argv);
-/*----- RTP interface functions */
-static int gtalk_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp,
-                                                          struct ast_rtp *vrtp, struct ast_rtp *trtp, int codecs, int nat_active);
-static enum ast_rtp_get_result gtalk_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
-static int gtalk_get_codec(struct ast_channel *chan);
+static int gtalk_update_stun(struct gtalk *client, struct gtalk_pvt *p);
+/* static char *gtalk_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a); */
+static char *gtalk_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
+static char *gtalk_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
+static int gtalk_update_externip(void);
+static int gtalk_parser(void *data, ikspak *pak);
+static int gtalk_create_candidates(struct gtalk *client, struct gtalk_pvt *p, char *sid, char *from, char *to);
 
 /*! \brief PBX interface structure for channel registration */
-static const struct ast_channel_tech gtalk_tech = {
+static struct ast_channel_tech gtalk_tech = {
        .type = "Gtalk",
        .description = "Gtalk Channel Driver",
-       .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
        .requester = gtalk_request,
+       .send_text = gtalk_sendtext,
        .send_digit_begin = gtalk_digit_begin,
        .send_digit_end = gtalk_digit_end,
-       .bridge = ast_rtp_bridge,
+       /* XXX TODO native bridging is causing odd problems with DTMF pass-through with
+        * the gtalk servers. Enable native bridging once the source of this problem has
+        * been identified.
+       .bridge = ast_rtp_instance_bridge, */
        .call = gtalk_call,
        .hangup = gtalk_hangup,
        .answer = gtalk_answer,
@@ -215,42 +225,29 @@ static const struct ast_channel_tech gtalk_tech = {
 
 static struct sockaddr_in bindaddr = { 0, };   /*!< The address we bind to */
 
-static struct sched_context *sched;    /*!< The scheduling context */
+static struct ast_sched_context *sched;        /*!< The scheduling context */
 static struct io_context *io;  /*!< The IO context */
 static struct in_addr __ourip;
 
-
-/*! \brief RTP driver interface */
-static struct ast_rtp_protocol gtalk_rtp = {
-       type: "Gtalk",
-       get_rtp_info: gtalk_get_rtp_peer,
-       set_rtp_peer: gtalk_set_rtp_peer,
-       get_codec: gtalk_get_codec,
-};
-
-static const char debug_usage[] = 
-"Usage: gtalk show channels\n" 
-"       Shows current state of the Gtalk channels.\n";
-
-static const char reload_usage[] = 
-"Usage: gtalk reload\n" 
-"       Reload gtalk channel driver.\n";
-
-
 static struct ast_cli_entry gtalk_cli[] = {
-       {{ "gtalk", "reload", NULL}, gtalk_do_reload, "Enable Jabber debugging", reload_usage },
-       {{ "gtalk", "show", "channels", NULL}, gtalk_show_channels, "Show GoogleTalk Channels", debug_usage },
- };
-
-
+/*     AST_CLI_DEFINE(gtalk_do_reload, "Reload GoogleTalk configuration"), XXX TODO reloads are not possible yet. */
+       AST_CLI_DEFINE(gtalk_show_channels, "Show GoogleTalk channels"),
+       AST_CLI_DEFINE(gtalk_show_settings, "Show GoogleTalk global settings"),
+};
 
 static char externip[16];
+static char global_context[AST_MAX_CONTEXT];
+static char global_parkinglot[AST_MAX_CONTEXT];
+static int global_allowguest;
+static struct sockaddr_in stunaddr; /*!< the stun server we get the externip from */
+static int global_stunaddr;
 
 static struct gtalk_container gtalk_list;
 
 static void gtalk_member_destroy(struct gtalk *obj)
 {
-       free(obj);
+       obj->cap = ast_format_cap_destroy(obj->cap);
+       ast_free(obj);
 }
 
 static struct gtalk *find_gtalk(char *name, char *connection)
@@ -258,7 +255,7 @@ static struct gtalk *find_gtalk(char *name, char *connection)
        struct gtalk *gtalk = NULL;
        char *domain = NULL , *s = NULL;
 
-       if(strchr(connection, '@')) {
+       if (strchr(connection, '@')) {
                s = ast_strdupa(connection);
                domain = strsep(&s, "@");
                ast_verbose("OOOOH domain = %s\n", domain);
@@ -267,17 +264,12 @@ static struct gtalk *find_gtalk(char *name, char *connection)
        if (!gtalk && strchr(name, '@'))
                gtalk = ASTOBJ_CONTAINER_FIND_FULL(&gtalk_list, name, user,,, strcasecmp);
 
-       if (!gtalk) {                           /* guest call */
+       if (!gtalk) {
+               /* guest call */
                ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
                        ASTOBJ_RDLOCK(iterator);
                        if (!strcasecmp(iterator->name, "guest")) {
-                               if (!strcasecmp(iterator->connection->jid->partial, connection)) {
-                                       gtalk = iterator;
-                               } else if (!strcasecmp(iterator->connection->name, connection)) {
-                                       gtalk = iterator;
-                               } else if (iterator->connection->component && !strcasecmp(iterator->connection->user,domain)) {
-                                       gtalk = iterator;
-                               }
+                               gtalk = iterator;
                        }
                        ASTOBJ_UNLOCK(iterator);
 
@@ -290,20 +282,19 @@ static struct gtalk *find_gtalk(char *name, char *connection)
 }
 
 
-static int add_codec_to_answer(const struct gtalk_pvt *p, int codec, iks *dcodecs)
+static int add_codec_to_answer(const struct gtalk_pvt *p, struct ast_format *codec, iks *dcodecs)
 {
-       char *format = ast_getformatname(codec);
+       int res = 0;
+       const char *format = ast_getformatname(codec);
 
        if (!strcasecmp("ulaw", format)) {
                iks *payload_eg711u, *payload_pcmu;
                payload_pcmu = iks_new("payload-type");
                payload_eg711u = iks_new("payload-type");
-       
+
                if(!payload_eg711u || !payload_pcmu) {
-                       if(payload_pcmu)
-                               iks_delete(payload_pcmu);
-                       if(payload_eg711u)
-                               iks_delete(payload_eg711u);
+                       iks_delete(payload_pcmu);
+                       iks_delete(payload_eg711u);
                        ast_log(LOG_WARNING,"Failed to allocate iks node");
                        return -1;
                }
@@ -317,16 +308,15 @@ static int add_codec_to_answer(const struct gtalk_pvt *p, int codec, iks *dcodec
                iks_insert_attrib(payload_eg711u, "bitrate","64000");
                iks_insert_node(dcodecs, payload_pcmu);
                iks_insert_node(dcodecs, payload_eg711u);
+               res ++;
        }
        if (!strcasecmp("alaw", format)) {
                iks *payload_eg711a, *payload_pcma;
                payload_pcma = iks_new("payload-type");
                payload_eg711a = iks_new("payload-type");
                if(!payload_eg711a || !payload_pcma) {
-                       if(payload_eg711a)
-                               iks_delete(payload_eg711a);
-                       if(payload_pcma)
-                               iks_delete(payload_pcma);
+                       iks_delete(payload_eg711a);
+                       iks_delete(payload_pcma);
                        ast_log(LOG_WARNING,"Failed to allocate iks node");
                        return -1;
                }
@@ -341,6 +331,7 @@ static int add_codec_to_answer(const struct gtalk_pvt *p, int codec, iks *dcodec
                iks_insert_attrib(payload_eg711a, "bitrate","64000");
                iks_insert_node(dcodecs, payload_pcma);
                iks_insert_node(dcodecs, payload_eg711a);
+               res ++;
        }
        if (!strcasecmp("ilbc", format)) {
                iks *payload_ilbc = iks_new("payload-type");
@@ -348,11 +339,12 @@ static int add_codec_to_answer(const struct gtalk_pvt *p, int codec, iks *dcodec
                        ast_log(LOG_WARNING,"Failed to allocate iks node");
                        return -1;
                }
-               iks_insert_attrib(payload_ilbc, "id", "102");
+               iks_insert_attrib(payload_ilbc, "id", "97");
                iks_insert_attrib(payload_ilbc, "name", "iLBC");
                iks_insert_attrib(payload_ilbc, "clockrate","8000");
                iks_insert_attrib(payload_ilbc, "bitrate","13300");
                iks_insert_node(dcodecs, payload_ilbc);
+               res ++;
        }
        if (!strcasecmp("g723", format)) {
                iks *payload_g723 = iks_new("payload-type");
@@ -365,6 +357,7 @@ static int add_codec_to_answer(const struct gtalk_pvt *p, int codec, iks *dcodec
                iks_insert_attrib(payload_g723, "clockrate","8000");
                iks_insert_attrib(payload_g723, "bitrate","6300");
                iks_insert_node(dcodecs, payload_g723);
+               res ++;
        }
        if (!strcasecmp("speex", format)) {
                iks *payload_speex = iks_new("payload-type");
@@ -372,14 +365,26 @@ static int add_codec_to_answer(const struct gtalk_pvt *p, int codec, iks *dcodec
                        ast_log(LOG_WARNING,"Failed to allocate iks node");
                        return -1;
                }
-               iks_insert_attrib(payload_speex, "id", "98");
+               iks_insert_attrib(payload_speex, "id", "110");
                iks_insert_attrib(payload_speex, "name", "speex");
                iks_insert_attrib(payload_speex, "clockrate","8000");
                iks_insert_attrib(payload_speex, "bitrate","11000");
                iks_insert_node(dcodecs, payload_speex);
+               res++;
        }
-       ast_rtp_lookup_code(p->rtp, 1, codec);
-       return 0;
+       if (!strcasecmp("gsm", format)) {
+               iks *payload_gsm = iks_new("payload-type");
+               if(!payload_gsm) {
+                       ast_log(LOG_WARNING,"Failed to allocate iks node");
+                       return -1;
+               }
+               iks_insert_attrib(payload_gsm, "id", "103");
+               iks_insert_attrib(payload_gsm, "name", "gsm");
+               iks_insert_node(dcodecs, payload_gsm);
+               res++;
+       }
+
+       return res;
 }
 
 static int gtalk_invite(struct gtalk_pvt *p, char *to, char *from, char *sid, int initiator)
@@ -387,66 +392,78 @@ static int gtalk_invite(struct gtalk_pvt *p, char *to, char *from, char *sid, in
        struct gtalk *client = p->parent;
        iks *iq, *gtalk, *dcodecs, *payload_telephone, *transport;
        int x;
-       int pref_codec = 0;
-       int alreadysent = 0;
-
+       struct ast_format_cap *alreadysent;
+       int codecs_num = 0;
+       char *lowerto = NULL;
+       struct ast_format tmpfmt;
 
        iq = iks_new("iq");
        gtalk = iks_new("session");
        dcodecs = iks_new("description");
        transport = iks_new("transport");
        payload_telephone = iks_new("payload-type");
-       if (!(iq && gtalk && dcodecs && transport && payload_telephone)){
-               if(iq)
-                       iks_delete(iq);
-               if(gtalk)
-                       iks_delete(gtalk);
-               if(dcodecs)
-                       iks_delete(dcodecs);
-               if(transport)
-                       iks_delete(transport);
-               if(payload_telephone)
-                       iks_delete(payload_telephone);
+       if (!(iq && gtalk && dcodecs && transport && payload_telephone)) {
+               iks_delete(iq);
+               iks_delete(gtalk);
+               iks_delete(dcodecs);
+               iks_delete(transport);
+               iks_delete(payload_telephone);
 
                ast_log(LOG_ERROR, "Could not allocate iksemel nodes\n");
                return 0;
        }
-       iks_insert_attrib(dcodecs, "xmlns", "http://www.google.com/session/phone");
+       iks_insert_attrib(dcodecs, "xmlns", GOOGLE_AUDIO_NS);
        iks_insert_attrib(dcodecs, "xml:lang", "en");
 
-       for (x = 0; x < 32; x++) {
-               if (!(pref_codec = ast_codec_pref_index(&client->prefs, x)))
+       if (!(alreadysent = ast_format_cap_alloc_nolock())) {
+               return 0;
+       }
+       for (x = 0; x < AST_CODEC_PREF_SIZE; x++) {
+               if (!(ast_codec_pref_index(&client->prefs, x, &tmpfmt))) {
                        break;
-               if (!(client->capability & pref_codec))
+               }
+               if (!(ast_format_cap_iscompatible(client->cap, &tmpfmt))) {
                        continue;
-               if (alreadysent & pref_codec)
+               }
+               if (ast_format_cap_iscompatible(alreadysent, &tmpfmt)) {
                        continue;
-               add_codec_to_answer(p, pref_codec, dcodecs);
-               alreadysent |= pref_codec;
-       }
-       
-       iks_insert_attrib(payload_telephone, "id", "106");
-       iks_insert_attrib(payload_telephone, "name", "telephone-event");
-       iks_insert_attrib(payload_telephone, "clockrate", "8000");
-       
-       iks_insert_attrib(transport,"xmlns","http://www.google.com/transport/p2p");
-       
+               }
+               codecs_num = add_codec_to_answer(p, &tmpfmt, dcodecs);
+               ast_format_cap_add(alreadysent, &tmpfmt);
+       }
+       alreadysent = ast_format_cap_destroy(alreadysent);
+
+       if (codecs_num) {
+               /* only propose DTMF within an audio session */
+               iks_insert_attrib(payload_telephone, "id", "101");
+               iks_insert_attrib(payload_telephone, "name", "telephone-event");
+               iks_insert_attrib(payload_telephone, "clockrate", "8000");
+       }
+       iks_insert_attrib(transport,"xmlns",GOOGLE_TRANSPORT_NS);
+
        iks_insert_attrib(iq, "type", "set");
        iks_insert_attrib(iq, "to", to);
        iks_insert_attrib(iq, "from", from);
        iks_insert_attrib(iq, "id", client->connection->mid);
        ast_aji_increment_mid(client->connection->mid);
 
-       iks_insert_attrib(gtalk, "xmlns", "http://www.google.com/session");
+       iks_insert_attrib(gtalk, "xmlns", GOOGLE_NS);
        iks_insert_attrib(gtalk, "type",initiator ? "initiate": "accept");
-       iks_insert_attrib(gtalk, "initiator", initiator ? from : to);
+       /* put the initiator attribute to lower case if we receive the call
+        * otherwise GoogleTalk won't establish the session */
+       if (!initiator) {
+               char c;
+               char *t = lowerto = ast_strdupa(to);
+               while (((c = *t) != '/') && (*t++ = tolower(c)));
+       }
+       iks_insert_attrib(gtalk, "initiator", initiator ? from : lowerto);
        iks_insert_attrib(gtalk, "id", sid);
        iks_insert_node(iq, gtalk);
        iks_insert_node(gtalk, dcodecs);
-       iks_insert_node(gtalk, transport);
        iks_insert_node(dcodecs, payload_telephone);
 
-       iks_send(client->connection->p, iq);
+       ast_aji_send(client->connection, iq);
+
        iks_delete(payload_telephone);
        iks_delete(transport);
        iks_delete(dcodecs);
@@ -455,51 +472,49 @@ static int gtalk_invite(struct gtalk_pvt *p, char *to, char *from, char *sid, in
        return 1;
 }
 
-static int gtalk_invite_response(struct gtalk_pvt *p, char *to , char *from, char *sid, int initiator)
-{
-       iks *iq, *session, *transport;
-       iq = iks_new("iq");
-       session = iks_new("session");
-       transport = iks_new("transport");
-       if(!(iq && session && transport)) {
-               if(iq)
-                       iks_delete(iq);
-               if(session)
-                       iks_delete(session);
-               if(transport)
-                       iks_delete(transport);
-               ast_log(LOG_ERROR, " Unable to allocate IKS node\n");
-               return -1;
-       }
-       iks_insert_attrib(iq, "from", from);
-       iks_insert_attrib(iq, "to", to);
-       iks_insert_attrib(iq, "type", "set");
-       iks_insert_attrib(iq, "id",p->parent->connection->mid);
-       ast_aji_increment_mid(p->parent->connection->mid);
-       iks_insert_attrib(session, "type", "transport-accept");
-       iks_insert_attrib(session, "id", sid);
-       iks_insert_attrib(session, "initiator", initiator ? from : to);
-       iks_insert_attrib(session, "xmlns", "http://www.google.com/session");
-       iks_insert_attrib(transport, "xmlns", "http://www.google.com/transport/p2p");
-       iks_insert_node(iq,session);
-       iks_insert_node(session,transport);
-       iks_send(p->parent->connection->p, iq);
-       iks_delete(transport);
-       iks_delete(session);
-       iks_delete(iq);
-       return 1;
-
-}
-
 static int gtalk_ringing_ack(void *data, ikspak *pak)
 {
        struct gtalk_pvt *p = data;
+       struct ast_channel *owner;
 
-       if (p->ringrule)
+       ast_mutex_lock(&p->lock);
+
+       if (p->ringrule) {
                iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
+       }
        p->ringrule = NULL;
-       if (p->owner)
-               ast_queue_control(p->owner, AST_CONTROL_RINGING);
+
+       /* this may be a redirect */
+       if (!strcmp(S_OR(iks_find_attrib(pak->x, "type"), ""), "error")) {
+               char *name = NULL;
+               char *redirect = NULL;
+               iks *traversenodes = NULL;
+               traversenodes = pak->query;
+               while (traversenodes) {
+                       if (!(name = iks_name(traversenodes))) {
+                               break;
+                       }
+                       if (!strcasecmp(name, "error") &&
+                               (redirect = iks_find_cdata(traversenodes, "redirect")) &&
+                               (redirect = strstr(redirect, "xmpp:"))) {
+                               redirect += 5;
+                               ast_debug(1, "redirect %s\n", redirect);
+                               ast_copy_string(p->them, redirect, sizeof(p->them));
+
+                               gtalk_invite(p, p->them, p->us, p->sid, 1);
+                               break;
+                       }
+                       traversenodes = iks_next_tag(traversenodes);
+               }
+       }
+       gtalk_create_candidates(p->parent, p, p->sid, p->them, p->us);
+       owner = p->owner;
+       ast_mutex_unlock(&p->lock);
+
+       if (owner) {
+               ast_queue_control(owner, AST_CONTROL_RINGING);
+       }
+
        return IKS_FILTER_EAT;
 }
 
@@ -507,40 +522,44 @@ static int gtalk_answer(struct ast_channel *ast)
 {
        struct gtalk_pvt *p = ast->tech_pvt;
        int res = 0;
-       
-       if (option_debug)
-               ast_log(LOG_DEBUG, "Answer!\n");
+
+       ast_debug(1, "Answer!\n");
        ast_mutex_lock(&p->lock);
        gtalk_invite(p, p->them, p->us,p->sid, 0);
+       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate", "Channel: %s\r\nChanneltype: %s\r\nGtalk-SID: %s\r\n",
+               ast->name, "GTALK", p->sid);
        ast_mutex_unlock(&p->lock);
        return res;
 }
 
-static enum ast_rtp_get_result gtalk_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
+static enum ast_rtp_glue_result gtalk_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
 {
        struct gtalk_pvt *p = chan->tech_pvt;
-       enum ast_rtp_get_result res = AST_RTP_GET_FAILED;
+       enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
 
        if (!p)
                return res;
 
        ast_mutex_lock(&p->lock);
        if (p->rtp){
-               *rtp = p->rtp;
-               res = AST_RTP_TRY_PARTIAL;
+               ao2_ref(p->rtp, +1);
+               *instance = p->rtp;
+               res = AST_RTP_GLUE_RESULT_LOCAL;
        }
        ast_mutex_unlock(&p->lock);
 
        return res;
 }
 
-static int gtalk_get_codec(struct ast_channel *chan)
+static void gtalk_get_codec(struct ast_channel *chan, struct ast_format_cap *result)
 {
        struct gtalk_pvt *p = chan->tech_pvt;
-       return p->peercapability;
+       ast_mutex_lock(&p->lock);
+       ast_format_cap_copy(result, p->peercap);
+       ast_mutex_unlock(&p->lock);
 }
 
-static int gtalk_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, struct ast_rtp *trtp, int codecs, int nat_active)
+static int gtalk_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *rtp, struct ast_rtp_instance *vrtp, struct ast_rtp_instance *trtp, const struct ast_format_cap *cap, int nat_active)
 {
        struct gtalk_pvt *p;
 
@@ -560,6 +579,13 @@ static int gtalk_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, str
        return 0;
 }
 
+static struct ast_rtp_glue gtalk_rtp_glue = {
+       .type = "Gtalk",
+       .get_rtp_info = gtalk_get_rtp_peer,
+       .get_codec = gtalk_get_codec,
+       .update_peer = gtalk_set_rtp_peer,
+};
+
 static int gtalk_response(struct gtalk *client, char *from, ikspak *pak, const char *reasonstr, const char *reasonstr2)
 {
        iks *response = NULL, *error = NULL, *reason = NULL;
@@ -569,8 +595,8 @@ static int gtalk_response(struct gtalk *client, char *from, ikspak *pak, const c
        if (response) {
                iks_insert_attrib(response, "type", "result");
                iks_insert_attrib(response, "from", from);
-               iks_insert_attrib(response, "to", iks_find_attrib(pak->x, "from"));
-               iks_insert_attrib(response, "id", iks_find_attrib(pak->x, "id"));
+               iks_insert_attrib(response, "to", S_OR(iks_find_attrib(pak->x, "from"), ""));
+               iks_insert_attrib(response, "id", S_OR(iks_find_attrib(pak->x, "id"), ""));
                if (reasonstr) {
                        error = iks_new("error");
                        if (error) {
@@ -581,38 +607,120 @@ static int gtalk_response(struct gtalk *client, char *from, ikspak *pak, const c
                                iks_insert_node(response, error);
                        }
                }
-               iks_send(client->connection->p, response);
-               if (reason)
-                       iks_delete(reason);
-               if (error)
-                       iks_delete(error);
-               iks_delete(response);
+               ast_aji_send(client->connection, response);
                res = 0;
        }
+
+       iks_delete(reason);
+       iks_delete(error);
+       iks_delete(response);
+
        return res;
 }
 
 static int gtalk_is_answered(struct gtalk *client, ikspak *pak)
 {
+       struct gtalk_pvt *tmp = NULL;
+       char *from;
+       iks *codec;
+       char s1[BUFSIZ], s2[BUFSIZ], s3[BUFSIZ];
+       int peernoncodeccapability;
+
+       ast_debug(1, "The client is %s\n", client->name);
+
+       /* Make sure our new call does exist */
+       for (tmp = client->p; tmp; tmp = tmp->next) {
+               if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid)) {
+                       break;
+               } else if (iks_find_with_attrib(pak->x, "ses:session", "id", tmp->sid)) {
+                       break;
+               }
+       }
+
+       if (!tmp) {
+               ast_log(LOG_WARNING, "Could not find session in iq\n");
+               return -1;
+       }
+
+       /* codec points to the first <payload-type/> tag */
+       codec = iks_first_tag(iks_first_tag(iks_first_tag(pak->x)));
+       while (codec) {
+               char *codec_id = iks_find_attrib(codec, "id");
+               char *codec_name = iks_find_attrib(codec, "name");
+               if (!codec_id || !codec_name) {
+                       codec = iks_next_tag(codec);
+                       continue;
+               }
+
+               ast_rtp_codecs_payloads_set_m_type(
+                       ast_rtp_instance_get_codecs(tmp->rtp),
+                       tmp->rtp,
+                       atoi(codec_id));
+               ast_rtp_codecs_payloads_set_rtpmap_type(
+                       ast_rtp_instance_get_codecs(tmp->rtp),
+                       tmp->rtp,
+                       atoi(codec_id),
+                       "audio",
+                       codec_name,
+                       0);
+               codec = iks_next_tag(codec);
+       }
+
+       /* Now gather all of the codecs that we are asked for */
+       ast_rtp_codecs_payload_formats(ast_rtp_instance_get_codecs(tmp->rtp), tmp->peercap, &peernoncodeccapability);
+
+       /* at this point, we received an answer from the remote Gtalk client,
+          which allows us to compare capabilities */
+       ast_format_cap_joint_copy(tmp->cap, tmp->peercap, tmp->jointcap);
+       if (ast_format_cap_is_empty(tmp->jointcap)) {
+               ast_log(LOG_WARNING, "Capabilities don't match : us - %s, peer - %s, combined - %s \n", ast_getformatname_multiple(s1, BUFSIZ, tmp->cap),
+                       ast_getformatname_multiple(s2, BUFSIZ, tmp->peercap),
+                       ast_getformatname_multiple(s3, BUFSIZ, tmp->jointcap));
+               /* close session if capabilities don't match */
+               ast_queue_hangup(tmp->owner);
+
+               return -1;
+
+       }
+
+       from = iks_find_attrib(pak->x, "to");
+       if (!from) {
+               from = client->connection->jid->full;
+       }
+
+       if (tmp->owner) {
+               ast_queue_control(tmp->owner, AST_CONTROL_ANSWER);
+       }
+       gtalk_update_stun(tmp->parent, tmp);
+       gtalk_response(client, from, pak, NULL, NULL);
+       return 1;
+}
+
+static int gtalk_is_accepted(struct gtalk *client, ikspak *pak)
+{
        struct gtalk_pvt *tmp;
        char *from;
-       if (option_debug)
-               ast_log(LOG_DEBUG, "The client is %s\n", client->name);
-       /* Make sure our new call doesn't exist yet */
+
+       ast_debug(1, "The client is %s\n", client->name);
+       /* find corresponding call */
        for (tmp = client->p; tmp; tmp = tmp->next) {
-               if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid))
+               if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid)) {
                        break;
+               }
        }
-       
+
        from = iks_find_attrib(pak->x, "to");
-       if(!from)
+       if (!from) {
                from = client->connection->jid->full;
+       }
 
        if (tmp) {
-               if (tmp->owner)
-                       ast_queue_control(tmp->owner, AST_CONTROL_ANSWER);
-       } else
-               ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
+               gtalk_update_stun(tmp->parent, tmp);
+       } else {
+               ast_log(LOG_NOTICE, "Whoa, didn't find call during accept?!\n");
+       }
+
+       /* answer 'iq' packet to let the remote peer know that we're alive */
        gtalk_response(client, from, pak, NULL, NULL);
        return 1;
 }
@@ -620,18 +728,18 @@ static int gtalk_is_answered(struct gtalk *client, ikspak *pak)
 static int gtalk_handle_dtmf(struct gtalk *client, ikspak *pak)
 {
        struct gtalk_pvt *tmp;
-       iks *dtmfnode = NULL;
+       iks *dtmfnode = NULL, *dtmfchild = NULL;
        char *dtmf;
        char *from;
        /* Make sure our new call doesn't exist yet */
        for (tmp = client->p; tmp; tmp = tmp->next) {
-               if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid))
+               if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid) || iks_find_with_attrib(pak->x, "gtalk", "sid", tmp->sid))
                        break;
        }
        from = iks_find_attrib(pak->x, "to");
-       if(!from)
+       if (!from) {
                from = client->connection->jid->full;
-
+       }
 
        if (tmp) {
                if(iks_find_with_attrib(pak->x, "dtmf-method", "method", "rtp")) {
@@ -644,69 +752,117 @@ static int gtalk_handle_dtmf(struct gtalk *client, ikspak *pak)
                        if((dtmf = iks_find_attrib(dtmfnode, "code"))) {
                                if(iks_find_with_attrib(pak->x, "dtmf", "action", "button-up")) {
                                        struct ast_frame f = {AST_FRAME_DTMF_BEGIN, };
-                                       f.subclass = dtmf[0];
+                                       f.subclass.integer = dtmf[0];
                                        ast_queue_frame(tmp->owner, &f);
-                                       ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
+                                       ast_verbose("GOOGLE! DTMF-relay event received: %c\n", (int) f.subclass.integer);
                                } else if(iks_find_with_attrib(pak->x, "dtmf", "action", "button-down")) {
                                        struct ast_frame f = {AST_FRAME_DTMF_END, };
-                                       f.subclass = dtmf[0];
+                                       f.subclass.integer = dtmf[0];
                                        ast_queue_frame(tmp->owner, &f);
-                                       ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
+                                       ast_verbose("GOOGLE! DTMF-relay event received: %c\n", (int) f.subclass.integer);
                                } else if(iks_find_attrib(pak->x, "dtmf")) { /* 250 millasecond default */
                                        struct ast_frame f = {AST_FRAME_DTMF, };
-                                       f.subclass = dtmf[0];
+                                       f.subclass.integer = dtmf[0];
                                        ast_queue_frame(tmp->owner, &f);
-                                       ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
+                                       ast_verbose("GOOGLE! DTMF-relay event received: %c\n", (int) f.subclass.integer);
+                               }
+                       }
+               } else if ((dtmfnode = iks_find_with_attrib(pak->x, "gtalk", "action", "session-info"))) {
+                       if((dtmfchild = iks_find(dtmfnode, "dtmf"))) {
+                               if((dtmf = iks_find_attrib(dtmfchild, "code"))) {
+                                       if(iks_find_with_attrib(dtmfnode, "dtmf", "action", "button-up")) {
+                                               struct ast_frame f = {AST_FRAME_DTMF_END, };
+                                               f.subclass.integer = dtmf[0];
+                                               ast_queue_frame(tmp->owner, &f);
+                                               ast_verbose("GOOGLE! DTMF-relay event received: %c\n", (int) f.subclass.integer);
+                                       } else if(iks_find_with_attrib(dtmfnode, "dtmf", "action", "button-down")) {
+                                               struct ast_frame f = {AST_FRAME_DTMF_BEGIN, };
+                                               f.subclass.integer = dtmf[0];
+                                               ast_queue_frame(tmp->owner, &f);
+                                               ast_verbose("GOOGLE! DTMF-relay event received: %c\n", (int) f.subclass.integer);
+                                       }
                                }
                        }
                }
                gtalk_response(client, from, pak, NULL, NULL);
                return 1;
-       } else
+       } else {
                ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
+       }
 
        gtalk_response(client, from, pak, NULL, NULL);
        return 1;
 }
 
-
 static int gtalk_hangup_farend(struct gtalk *client, ikspak *pak)
 {
        struct gtalk_pvt *tmp;
        char *from;
 
-       if (option_debug)
-               ast_log(LOG_DEBUG, "The client is %s\n", client->name);
+       ast_debug(1, "The client is %s\n", client->name);
        /* Make sure our new call doesn't exist yet */
        for (tmp = client->p; tmp; tmp = tmp->next) {
-               if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid))
+               if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid) ||
+                       (iks_find_attrib(pak->query, "id") && !strcmp(iks_find_attrib(pak->query, "id"), tmp->sid))) {
                        break;
+               }
        }
        from = iks_find_attrib(pak->x, "to");
-       if(!from)
+       if (!from) {
                from = client->connection->jid->full;
-
+       }
 
        if (tmp) {
                tmp->alreadygone = 1;
-               ast_queue_hangup(tmp->owner);
-       } else
-               ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
+               if (tmp->owner) {
+                       ast_queue_hangup(tmp->owner);
+               }
+       } else {
+               ast_log(LOG_NOTICE, "Whoa, didn't find call during hangup!\n");
+       }
        gtalk_response(client, from, pak, NULL, NULL);
        return 1;
 }
 
+static int gtalk_get_local_ip(struct ast_sockaddr *ourip)
+{
+       struct ast_sockaddr root;
+       struct ast_sockaddr bindaddr_tmp;
+       struct ast_sockaddr *addrs;
+       int addrs_cnt;
+
+       /* If bind address is not 0.0.0.0, then bindaddr is our local ip. */
+       ast_sockaddr_from_sin(&bindaddr_tmp, &bindaddr);
+       if (!ast_sockaddr_is_any(&bindaddr_tmp)) {
+               ast_sockaddr_copy(ourip, &bindaddr_tmp);
+               return 0;
+       }
+
+       /* If no bind address was provided, lets see what ip we would use to connect to google.com and use that.
+        * If you can't resolve google.com from your network, then this module is useless for you anyway. */
+       if ((addrs_cnt = ast_sockaddr_resolve(&addrs, "google.com", PARSE_PORT_FORBID, AF_INET)) > 0) {
+               ast_sockaddr_copy(&root, &addrs[0]);
+               ast_free(addrs);
+               if (!ast_ouraddrfor(&root, ourip)) {
+                       return 0;
+               }
+       }
+
+       /* As a last resort, use this function to find our local address. */
+       return ast_find_ourip(ourip, &bindaddr_tmp, AF_INET);
+}
+
 static int gtalk_create_candidates(struct gtalk *client, struct gtalk_pvt *p, char *sid, char *from, char *to)
 {
        struct gtalk_candidate *tmp;
        struct aji_client *c = client->connection;
        struct gtalk_candidate *ours1 = NULL, *ours2 = NULL;
-       struct sockaddr_in sin;
-       struct sockaddr_in dest;
-       struct in_addr us;
+       struct sockaddr_in sin = { 0, };
+       struct ast_sockaddr sin_tmp;
+       struct ast_sockaddr us;
        iks *iq, *gtalk, *candidate, *transport;
        char user[17], pass[17], preference[5], port[7];
-
+       char *lowerfrom = NULL;
 
        iq = iks_new("iq");
        gtalk = iks_new("session");
@@ -721,10 +877,10 @@ static int gtalk_create_candidates(struct gtalk *client, struct gtalk_pvt *p, ch
        if (!ours1 || !ours2)
                goto safeout;
 
-       iks_insert_attrib(transport, "xmlns","http://www.google.com/transport/p2p");
+       iks_insert_attrib(transport, "xmlns",GOOGLE_TRANSPORT_NS);
        iks_insert_node(iq, gtalk);
+       iks_insert_node(gtalk,candidate);
        iks_insert_node(gtalk,transport);
-       iks_insert_node(transport, candidate);
 
        for (; p; p = p->next) {
                if (!strcasecmp(p->sid, sid))
@@ -736,8 +892,14 @@ static int gtalk_create_candidates(struct gtalk *client, struct gtalk_pvt *p, ch
                goto safeout;
        }
 
-       ast_rtp_get_us(p->rtp, &sin);
-       ast_find_ourip(&us, bindaddr);
+       ast_rtp_instance_get_local_address(p->rtp, &sin_tmp);
+       ast_sockaddr_to_sin(&sin_tmp, &sin);
+
+       gtalk_get_local_ip(&us);
+
+       if (!strcmp(ast_sockaddr_stringify_addr(&us), "127.0.0.1")) {
+               ast_log(LOG_WARNING, "Found a loopback IP on the system, check your network configuration or set the bindaddr attribute.");
+       }
 
        /* Setup our gtalk candidates */
        ast_copy_string(ours1->name, "rtp", sizeof(ours1->name));
@@ -747,16 +909,18 @@ static int gtalk_create_candidates(struct gtalk *client, struct gtalk_pvt *p, ch
        snprintf(pass, sizeof(pass), "%08lx%08lx", ast_random(), ast_random());
        ast_copy_string(ours1->username, user, sizeof(ours1->username));
        ast_copy_string(ours1->password, pass, sizeof(ours1->password));
-       ast_copy_string(ours1->ip, ast_inet_ntoa(us), sizeof(ours1->ip));
+       ast_copy_string(ours1->ip, ast_sockaddr_stringify_addr(&us),
+                       sizeof(ours1->ip));
        ours1->protocol = AJI_PROTOCOL_UDP;
        ours1->type = AJI_CONNECT_LOCAL;
        ours1->generation = 0;
        p->ourcandidates = ours1;
 
+       /* XXX this is a blocking action.  We send a STUN request to the server
+        * and wait for the response.  If blocking here is a problem the STUN requests/responses
+        * for the externip may need to be done differently. */
+       gtalk_update_externip();
        if (!ast_strlen_zero(externip)) {
-               /* XXX We should really stun for this one not just go with externip XXX */
-               snprintf(user, sizeof(user), "%08lx%08lx", ast_random(), ast_random());
-               snprintf(pass, sizeof(pass), "%08lx%08lx", ast_random(), ast_random());
                ast_copy_string(ours2->username, user, sizeof(ours2->username));
                ast_copy_string(ours2->password, pass, sizeof(ours2->password));
                ast_copy_string(ours2->ip, externip, sizeof(ours2->ip));
@@ -770,9 +934,6 @@ static int gtalk_create_candidates(struct gtalk *client, struct gtalk_pvt *p, ch
                ours2 = NULL;
        }
        ours1 = NULL;
-       dest.sin_addr = __ourip;
-       dest.sin_port = sin.sin_port;
-
 
        for (tmp = p->ourcandidates; tmp; tmp = tmp->next) {
                snprintf(port, sizeof(port), "%d", tmp->port);
@@ -782,9 +943,16 @@ static int gtalk_create_candidates(struct gtalk *client, struct gtalk_pvt *p, ch
                iks_insert_attrib(iq, "type", "set");
                iks_insert_attrib(iq, "id", c->mid);
                ast_aji_increment_mid(c->mid);
-               iks_insert_attrib(gtalk, "type", "transport-info");
+               iks_insert_attrib(gtalk, "type", "candidates");
                iks_insert_attrib(gtalk, "id", sid);
-               iks_insert_attrib(gtalk, "initiator", (p->initiator) ? to : from);
+               /* put the initiator attribute to lower case if we receive the call
+                * otherwise GoogleTalk won't establish the session */
+               if (!p->initiator) {
+                       char c;
+                       char *t = lowerfrom = ast_strdupa(from);
+                       while (((c = *t) != '/') && (*t++ = tolower(c)));
+               }
+               iks_insert_attrib(gtalk, "initiator", (p->initiator) ? to : lowerfrom);
                iks_insert_attrib(gtalk, "xmlns", GOOGLE_NS);
                iks_insert_attrib(candidate, "name", tmp->name);
                iks_insert_attrib(candidate, "address", tmp->ip);
@@ -804,23 +972,20 @@ static int gtalk_create_candidates(struct gtalk *client, struct gtalk_pvt *p, ch
                        iks_insert_attrib(candidate, "type", "relay");
                iks_insert_attrib(candidate, "network", "0");
                iks_insert_attrib(candidate, "generation", "0");
-               iks_send(c->p, iq);
+               ast_aji_send(c, iq);
        }
        p->laststun = 0;
 
 safeout:
        if (ours1)
-               free(ours1);
+               ast_free(ours1);
        if (ours2)
-               free(ours2);
-       if (iq)
-               iks_delete(iq);
-       if (gtalk)
-               iks_delete(gtalk);
-       if (candidate)
-               iks_delete(candidate);
-       if(transport)
-               iks_delete(transport);
+               ast_free(ours2);
+       iks_delete(iq);
+       iks_delete(gtalk);
+       iks_delete(candidate);
+       iks_delete(transport);
+
        return 1;
 }
 
@@ -831,25 +996,30 @@ static struct gtalk_pvt *gtalk_alloc(struct gtalk *client, const char *us, const
        struct aji_buddy *buddy;
        char idroster[200];
        char *data, *exten = NULL;
+       struct ast_sockaddr bindaddr_tmp;
 
-       if (option_debug)
-               ast_log(LOG_DEBUG, "The client is %s for alloc\n", client->name);
+       ast_debug(1, "The client is %s for alloc\n", client->name);
        if (!sid && !strchr(them, '/')) {       /* I started call! */
                if (!strcasecmp(client->name, "guest")) {
                        buddy = ASTOBJ_CONTAINER_FIND(&client->connection->buddies, them);
-                       if (buddy)
+                       if (buddy) {
                                resources = buddy->resources;
-               } else if (client->buddy)
+                       }
+               } else if (client->buddy) {
                        resources = client->buddy->resources;
+               }
+
                while (resources) {
                        if (resources->cap->jingle) {
                                break;
                        }
                        resources = resources->next;
                }
-               if (resources)
+               if (resources) {
                        snprintf(idroster, sizeof(idroster), "%s/%s", them, resources->resource);
-               else {
+               } else if ((*them == '+') || (strstr(them, "@voice.google.com"))) {
+                       snprintf(idroster, sizeof(idroster), "%s", them);
+               } else {
                        ast_log(LOG_ERROR, "no gtalk capable clients to talk to.\n");
                        return NULL;
                }
@@ -857,6 +1027,16 @@ static struct gtalk_pvt *gtalk_alloc(struct gtalk *client, const char *us, const
        if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
                return NULL;
        }
+       tmp->cap = ast_format_cap_alloc_nolock();
+       tmp->jointcap = ast_format_cap_alloc_nolock();
+       tmp->peercap = ast_format_cap_alloc_nolock();
+       if (!tmp->jointcap || !tmp->peercap || !tmp->cap) {
+               tmp->cap = ast_format_cap_destroy(tmp->cap);
+               tmp->jointcap = ast_format_cap_destroy(tmp->jointcap);
+               tmp->peercap = ast_format_cap_destroy(tmp->peercap);
+               ast_free(tmp);
+               return NULL;
+       }
 
        memcpy(&tmp->prefs, &client->prefs, sizeof(struct ast_codec_pref));
 
@@ -870,19 +1050,43 @@ static struct gtalk_pvt *gtalk_alloc(struct gtalk *client, const char *us, const
                ast_copy_string(tmp->us, us, sizeof(tmp->us));
                tmp->initiator = 1;
        }
-       tmp->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
+       /* clear codecs */
+       bindaddr.sin_family = AF_INET;
+       ast_sockaddr_from_sin(&bindaddr_tmp, &bindaddr);
+       if (!(tmp->rtp = ast_rtp_instance_new("asterisk", sched, &bindaddr_tmp, NULL))) {
+         ast_log(LOG_ERROR, "Failed to create a new RTP instance (possibly an invalid bindaddr?)\n");
+         ast_free(tmp);
+         return NULL;
+       }
+       ast_rtp_instance_set_prop(tmp->rtp, AST_RTP_PROPERTY_RTCP, 1);
+       ast_rtp_instance_set_prop(tmp->rtp, AST_RTP_PROPERTY_STUN, 1);
+       ast_rtp_instance_set_prop(tmp->rtp, AST_RTP_PROPERTY_DTMF, 1);
+       ast_rtp_instance_dtmf_mode_set(tmp->rtp, AST_RTP_DTMF_MODE_RFC2833);
+       ast_rtp_codecs_payloads_clear(ast_rtp_instance_get_codecs(tmp->rtp), tmp->rtp);
+
+       /* add user configured codec capabilites */
+       if (!(ast_format_cap_is_empty(client->cap))) {
+               ast_format_cap_copy(tmp->cap, client->cap);
+       } else if (!(ast_format_cap_is_empty(global_capability))) {
+               ast_format_cap_copy(tmp->cap, global_capability);
+       }
+
        tmp->parent = client;
        if (!tmp->rtp) {
                ast_log(LOG_WARNING, "Out of RTP sessions?\n");
-               free(tmp);
+               ast_free(tmp);
                return NULL;
        }
 
+       /* Set CALLERID(name) to the full JID of the remote peer */
+       ast_copy_string(tmp->cid_name, tmp->them, sizeof(tmp->cid_name));
+
        if(strchr(tmp->us, '/')) {
                data = ast_strdupa(tmp->us);
                exten = strsep(&data, "/");
-       } else
+       } else {
                exten = tmp->us;
+       }
        ast_copy_string(tmp->exten,  exten, sizeof(tmp->exten));
        ast_mutex_init(&tmp->lock);
        ast_mutex_lock(&gtalklock);
@@ -893,19 +1097,18 @@ static struct gtalk_pvt *gtalk_alloc(struct gtalk *client, const char *us, const
 }
 
 /*! \brief Start new gtalk channel */
-static struct ast_channel *gtalk_new(struct gtalk *client, struct gtalk_pvt *i, int state, const char *title)
+static struct ast_channel *gtalk_new(struct gtalk *client, struct gtalk_pvt *i, int state, const char *title, const char *linkedid)
 {
        struct ast_channel *tmp;
-       int fmt;
-       int what;
        const char *n2;
-       char *data = NULL, *cid = NULL;
+       struct ast_format_cap *what; /* used as SHALLOW COPY DO NOT DESTROY */
+       struct ast_format tmpfmt;
 
        if (title)
                n2 = title;
        else
                n2 = i->us;
-       tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, client->accountcode, i->exten, client->context, client->amaflags, "Gtalk/%s-%04lx", n2, ast_random() & 0xffff);
+       tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, linkedid, client->accountcode, i->exten, client->context, client->amaflags, "Gtalk/%s-%04lx", n2, ast_random() & 0xffff);
        if (!tmp) {
                ast_log(LOG_WARNING, "Unable to allocate Gtalk channel structure!\n");
                return NULL;
@@ -914,43 +1117,53 @@ static struct ast_channel *gtalk_new(struct gtalk *client, struct gtalk_pvt *i,
 
        /* Select our native format based on codec preference until we receive
           something from another device to the contrary. */
-/*     ast_verbose("XXXXXXXXXXXXX\nXXX i->jointcapability = %X\nXXX i->capability = %X\nXXX global_capability %X\n XXXXXXXXXXXX\n",i->jointcapability,i->capability,global_capability); */
-       if (i->jointcapability)
-               what = i->jointcapability;
-       else if (i->capability)
-               what = i->capability;
-       else
+       if (!(ast_format_cap_is_empty(i->jointcap))) {
+               what = i->jointcap;
+       } else if (i->cap) {
+               what = i->cap;
+       } else {
                what = global_capability;
+       }
 
        /* Set Frame packetization */
-       if (i->rtp)
-               ast_rtp_codec_setpref(i->rtp, &i->prefs);
+       if (i->rtp) {
+               ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(i->rtp), i->rtp, &i->prefs);
+       }
 
-       tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
-       fmt = ast_best_codec(tmp->nativeformats);
+       ast_codec_choose(&i->prefs, what, 1, &tmpfmt);
+       ast_format_cap_add(tmp->nativeformats, &tmpfmt);
+
+       ast_format_cap_iter_start(i->jointcap);
+       while (!(ast_format_cap_iter_next(i->jointcap, &tmpfmt))) {
+               if (AST_FORMAT_GET_TYPE(tmpfmt.id) == AST_FORMAT_TYPE_VIDEO) {
+                       ast_format_cap_add(tmp->nativeformats, &tmpfmt);
+               }
+       }
+       ast_format_cap_iter_end(i->jointcap);
 
        if (i->rtp) {
-               ast_rtp_setstun(i->rtp, 1);
-               tmp->fds[0] = ast_rtp_fd(i->rtp);
-               tmp->fds[1] = ast_rtcp_fd(i->rtp);
+               ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
+               ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
        }
        if (i->vrtp) {
-               ast_rtp_setstun(i->rtp, 1);
-               tmp->fds[2] = ast_rtp_fd(i->vrtp);
-               tmp->fds[3] = ast_rtcp_fd(i->vrtp);
+               ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
+               ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
        }
        if (state == AST_STATE_RING)
                tmp->rings = 1;
        tmp->adsicpe = AST_ADSI_UNAVAILABLE;
-       tmp->writeformat = fmt;
-       tmp->rawwriteformat = fmt;
-       tmp->readformat = fmt;
-       tmp->rawreadformat = fmt;
+
+       ast_best_codec(tmp->nativeformats, &tmpfmt);
+       ast_format_copy(&tmp->writeformat, &tmpfmt);
+       ast_format_copy(&tmp->rawwriteformat, &tmpfmt);
+       ast_format_copy(&tmp->readformat, &tmpfmt);
+       ast_format_copy(&tmp->rawreadformat, &tmpfmt);
        tmp->tech_pvt = i;
 
        tmp->callgroup = client->callgroup;
        tmp->pickupgroup = client->pickupgroup;
-       tmp->cid.cid_pres = client->callingpres;
+       tmp->caller.id.name.presentation = client->callingpres;
+       tmp->caller.id.number.presentation = client->callingpres;
        if (!ast_strlen_zero(client->accountcode))
                ast_string_field_set(tmp, accountcode, client->accountcode);
        if (client->amaflags)
@@ -959,29 +1172,16 @@ static struct ast_channel *gtalk_new(struct gtalk *client, struct gtalk_pvt *i,
                ast_string_field_set(tmp, language, client->language);
        if (!ast_strlen_zero(client->musicclass))
                ast_string_field_set(tmp, musicclass, client->musicclass);
+       if (!ast_strlen_zero(client->parkinglot))
+               ast_string_field_set(tmp, parkinglot, client->parkinglot);
        i->owner = tmp;
        ast_module_ref(ast_module_info->self);
        ast_copy_string(tmp->context, client->context, sizeof(tmp->context));
        ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
-       /* Don't use ast_set_callerid() here because it will
-        * generate a needless NewCallerID event */
-       if (!strcasecmp(client->name, "guest")) {
-               if (strchr(i->them, '/')) {
-                       char *aux;
-                       data = ast_strdupa((char *)i->them);
-                       aux = data;
-                       cid = strsep(&aux, "/");
-               } else
-                       cid = i->them;
-       } else {
-               cid = client->user;
-       }
-       cid = strsep(&cid, "@");
-       tmp->cid.cid_num = ast_strdup(cid);
-       tmp->cid.cid_ani = ast_strdup(cid);
-       tmp->cid.cid_name = ast_strdup(i->them);
-       if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
-               tmp->cid.cid_dnid = ast_strdup(i->exten);
+
+       if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
+               tmp->dialed.number.str = ast_strdup(i->exten);
+       }
        tmp->priority = 1;
        if (i->rtp)
                ast_jb_configure(tmp, &global_jbconf);
@@ -990,8 +1190,11 @@ static struct ast_channel *gtalk_new(struct gtalk *client, struct gtalk_pvt *i,
                tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
                ast_hangup(tmp);
                tmp = NULL;
+       } else {
+               manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
+                       "Channel: %s\r\nChanneltype: %s\r\nGtalk-SID: %s\r\n",
+                       i->owner ? i->owner->name : "", "Gtalk", i->sid);
        }
-
        return tmp;
 }
 
@@ -999,6 +1202,7 @@ static int gtalk_action(struct gtalk *client, struct gtalk_pvt *p, const char *a
 {
        iks *request, *session = NULL;
        int res = -1;
+       char *lowerthem = NULL;
 
        request = iks_new("iq");
        if (request) {
@@ -1011,15 +1215,24 @@ static int gtalk_action(struct gtalk *client, struct gtalk_pvt *p, const char *a
                if (session) {
                        iks_insert_attrib(session, "type", action);
                        iks_insert_attrib(session, "id", p->sid);
-                       iks_insert_attrib(session, "initiator", p->initiator ? p->us : p->them);
-                       iks_insert_attrib(session, "xmlns", "http://www.google.com/session");
+                       /* put the initiator attribute to lower case if we receive the call
+                        * otherwise GoogleTalk won't establish the session */
+                       if (!p->initiator) {
+                               char c;
+                               char *t = lowerthem = ast_strdupa(p->them);
+                               while (((c = *t) != '/') && (*t++ = tolower(c)));
+                       }
+                       iks_insert_attrib(session, "initiator", p->initiator ? p->us : lowerthem);
+                       iks_insert_attrib(session, "xmlns", GOOGLE_NS);
                        iks_insert_node(request, session);
-                       iks_send(client->connection->p, request);
-                       iks_delete(session);
+                       ast_aji_send(client->connection, request);
                        res = 0;
                }
-               iks_delete(request);
        }
+
+       iks_delete(session);
+       iks_delete(request);
+
        return res;
 }
 
@@ -1029,7 +1242,7 @@ static void gtalk_free_candidates(struct gtalk_candidate *candidate)
        while (candidate) {
                last = candidate;
                candidate = candidate->next;
-               free(last);
+               ast_free(last);
        }
 }
 
@@ -1053,11 +1266,14 @@ static void gtalk_free_pvt(struct gtalk *client, struct gtalk_pvt *p)
        if (p->owner)
                ast_log(LOG_WARNING, "Uh oh, there's an owner, this is going to be messy.\n");
        if (p->rtp)
-               ast_rtp_destroy(p->rtp);
+               ast_rtp_instance_destroy(p->rtp);
        if (p->vrtp)
-               ast_rtp_destroy(p->vrtp);
+               ast_rtp_instance_destroy(p->vrtp);
        gtalk_free_candidates(p->theircandidates);
-       free(p);
+       p->cap = ast_format_cap_destroy(p->cap);
+       p->jointcap = ast_format_cap_destroy(p->jointcap);
+       p->peercap = ast_format_cap_destroy(p->peercap);
+       ast_free(p);
 }
 
 
@@ -1068,13 +1284,19 @@ static int gtalk_newcall(struct gtalk *client, ikspak *pak)
        int res;
        iks *codec;
        char *from = NULL;
+       char s1[BUFSIZ], s2[BUFSIZ], s3[BUFSIZ];
+       int peernoncodeccapability;
+       char *sid;
+
        /* Make sure our new call doesn't exist yet */
        from = iks_find_attrib(pak->x,"to");
-       if(!from)
+       if (!from) {
                from = client->connection->jid->full;
-       
+       }
+
        while (tmp) {
-               if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid)) {
+               if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid) ||
+                       (iks_find_attrib(pak->query, "id") && !strcmp(iks_find_attrib(pak->query, "id"), tmp->sid))) {
                        ast_log(LOG_NOTICE, "Ignoring duplicate call setup on SID %s\n", tmp->sid);
                        gtalk_response(client, from, pak, "out-of-order", NULL);
                        return -1;
@@ -1082,61 +1304,162 @@ static int gtalk_newcall(struct gtalk *client, ikspak *pak)
                tmp = tmp->next;
        }
 
-       p = gtalk_alloc(client, from, pak->from->full, iks_find_attrib(pak->query, "id"));
+       if (!strcasecmp(client->name, "guest")){
+               /* the guest account is not tied to any configured XMPP client,
+                  let's set it now */
+               client->connection = ast_aji_get_client(from);
+               if (!client->connection) {
+                       ast_log(LOG_ERROR, "No XMPP client to talk to, us (partial JID) : %s\n", from);
+                       return -1;
+               }
+       }
+
+       if (!(sid = iks_find_attrib(pak->query, "id"))) {
+               ast_log(LOG_WARNING, "Received Initiate without id attribute. Can not start call.\n");
+               return -1;
+       }
+
+       p = gtalk_alloc(client, from, pak->from->full, sid);
        if (!p) {
                ast_log(LOG_WARNING, "Unable to allocate gtalk structure!\n");
                return -1;
        }
-       chan = gtalk_new(client, p, AST_STATE_DOWN, pak->from->user);
-       if (chan) {
-               ast_mutex_lock(&p->lock);
-               ast_copy_string(p->them, pak->from->full, sizeof(p->them));
-               if (iks_find_attrib(pak->query, "id")) {
-                       ast_copy_string(p->sid, iks_find_attrib(pak->query, "id"),
-                                                       sizeof(p->sid));
-               }
 
-               codec = iks_child(iks_child(iks_child(pak->x)));
-               while (codec) {
-                       ast_rtp_set_m_type(p->rtp, atoi(iks_find_attrib(codec, "id")));
-                       ast_rtp_set_rtpmap_type(p->rtp, atoi(iks_find_attrib(codec, "id")), "audio",
-                                               iks_find_attrib(codec, "name"), 0);
-                       codec = iks_next(codec);
-               }
-               
-               ast_mutex_unlock(&p->lock);
-               ast_setstate(chan, AST_STATE_RING);
-               res = ast_pbx_start(chan);
+       chan = gtalk_new(client, p, AST_STATE_DOWN, pak->from->user, NULL);
+       if (!chan) {
+               gtalk_free_pvt(client, p);
+               return -1;
+       }
 
-               switch (res) {
-               case AST_PBX_FAILED:
-                       ast_log(LOG_WARNING, "Failed to start PBX :(\n");
-                       gtalk_response(client, from, pak, "service-unavailable", NULL);
-                       break;
-               case AST_PBX_CALL_LIMIT:
-                       ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
-                       gtalk_response(client, from, pak, "service-unavailable", NULL);
-                       break;
-               case AST_PBX_SUCCESS:
-                       gtalk_response(client, from, pak, NULL, NULL);
-                       gtalk_invite_response(p, p->them, p->us,p->sid, 0);
-                       gtalk_create_candidates(client, p, p->sid, p->them, p->us);
-                       /* nothing to do */
-                       break;
+       ast_mutex_lock(&p->lock);
+       ast_copy_string(p->them, pak->from->full, sizeof(p->them));
+       ast_copy_string(p->sid, sid, sizeof(p->sid));
+
+       /* codec points to the first <payload-type/> tag */
+       codec = iks_first_tag(iks_first_tag(iks_first_tag(pak->x)));
+
+       while (codec) {
+               char *codec_id = iks_find_attrib(codec, "id");
+               char *codec_name = iks_find_attrib(codec, "name");
+               if (!codec_id || !codec_name) {
+                       codec = iks_next_tag(codec);
+                       continue;
                }
-       } else {
-               gtalk_free_pvt(client, p);
+               if (!strcmp(S_OR(iks_name(codec), ""), "vid:payload-type") && p->vrtp) {
+                       ast_rtp_codecs_payloads_set_m_type(
+                               ast_rtp_instance_get_codecs(p->vrtp),
+                               p->vrtp,
+                               atoi(codec_id));
+                       ast_rtp_codecs_payloads_set_rtpmap_type(
+                               ast_rtp_instance_get_codecs(p->vrtp),
+                               p->vrtp,
+                               atoi(codec_id),
+                               "video",
+                               codec_name,
+                               0);
+               } else {
+                       ast_rtp_codecs_payloads_set_m_type(
+                               ast_rtp_instance_get_codecs(p->rtp),
+                               p->rtp,
+                               atoi(codec_id));
+                       ast_rtp_codecs_payloads_set_rtpmap_type(
+                               ast_rtp_instance_get_codecs(p->rtp),
+                               p->rtp,
+                               atoi(codec_id),
+                               "audio",
+                               codec_name,
+                               0);
+               }
+               codec = iks_next_tag(codec);
+       }
+
+       /* Now gather all of the codecs that we are asked for */
+       ast_rtp_codecs_payload_formats(ast_rtp_instance_get_codecs(p->rtp), p->peercap, &peernoncodeccapability);
+       ast_format_cap_joint_copy(p->cap, p->peercap, p->jointcap);
+       ast_mutex_unlock(&p->lock);
+
+       ast_setstate(chan, AST_STATE_RING);
+       if (ast_format_cap_is_empty(p->jointcap)) {
+               ast_log(LOG_WARNING, "Capabilities don't match : us - %s, peer - %s, combined - %s \n", ast_getformatname_multiple(s1, BUFSIZ, p->cap),
+                       ast_getformatname_multiple(s2, BUFSIZ, p->peercap),
+                       ast_getformatname_multiple(s3, BUFSIZ, p->jointcap));
+               /* close session if capabilities don't match */
+               gtalk_action(client, p, "reject");
+               p->alreadygone = 1;
+               gtalk_hangup(chan);
+               ast_channel_release(chan);
+               return -1;
        }
+
+       res = ast_pbx_start(chan);
+
+       switch (res) {
+       case AST_PBX_FAILED:
+               ast_log(LOG_WARNING, "Failed to start PBX :(\n");
+               gtalk_response(client, from, pak, "service-unavailable", NULL);
+               break;
+       case AST_PBX_CALL_LIMIT:
+               ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
+               gtalk_response(client, from, pak, "service-unavailable", NULL);
+               break;
+       case AST_PBX_SUCCESS:
+               gtalk_response(client, from, pak, NULL, NULL);
+               gtalk_create_candidates(client, p, p->sid, p->them, p->us);
+               /* nothing to do */
+               break;
+       }
+
        return 1;
 }
 
+static int gtalk_update_externip(void)
+{
+       int sock;
+       char *newaddr;
+       struct sockaddr_in answer = { 0, };
+       struct sockaddr_in *dst;
+       struct ast_sockaddr tmp_dst;
+
+       if (!stunaddr.sin_addr.s_addr) {
+               return -1;
+       }
+       dst = &stunaddr;
+
+       sock = socket(AF_INET, SOCK_DGRAM, 0);
+       if (sock < 0) {
+               ast_log(LOG_WARNING, "Unable to create STUN socket: %s\n", strerror(errno));
+               return -1;
+       }
+
+       ast_sockaddr_from_sin(&tmp_dst, dst);
+       if (ast_connect(sock, &tmp_dst) != 0) {
+               ast_log(LOG_WARNING, "STUN Failed to connect to %s\n", ast_sockaddr_stringify(&tmp_dst));
+               close(sock);
+               return -1;
+       }
+
+       if ((ast_stun_request(sock, &stunaddr, NULL, &answer))) {
+               close(sock);
+               return -1;
+       }
+
+       newaddr = ast_strdupa(ast_inet_ntoa(answer.sin_addr));
+       memcpy(externip, newaddr, sizeof(externip));
+
+       close(sock);
+       return 0;
+
+}
+
 static int gtalk_update_stun(struct gtalk *client, struct gtalk_pvt *p)
 {
        struct gtalk_candidate *tmp;
        struct hostent *hp;
        struct ast_hostent ahp;
-       struct sockaddr_in sin;
-       struct sockaddr_in aux;
+       struct sockaddr_in sin = { 0, };
+       struct sockaddr_in aux = { 0, };
+       struct ast_sockaddr sin_tmp;
+       struct ast_sockaddr aux_tmp;
 
        if (time(NULL) == p->laststun)
                return 0;
@@ -1147,28 +1470,32 @@ static int gtalk_update_stun(struct gtalk *client, struct gtalk_pvt *p)
                char username[256];
 
                /* Find the IP address of the host */
-               hp = ast_gethostbyname(tmp->ip, &ahp);
+               if (!(hp = ast_gethostbyname(tmp->ip, &ahp))) {
+                       ast_log(LOG_WARNING, "Could not get host by name for %s\n", tmp->ip);
+                       tmp = tmp->next;
+                       continue;
+               }
                sin.sin_family = AF_INET;
                memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
                sin.sin_port = htons(tmp->port);
-               snprintf(username, sizeof(username), "%s%s", tmp->username,
-                        p->ourcandidates->username);
-               
+               snprintf(username, sizeof(username), "%s%s", tmp->username, p->ourcandidates->username);
+
                /* Find out the result of the STUN */
-               ast_rtp_get_peer(p->rtp, &aux);
+               ast_rtp_instance_get_remote_address(p->rtp, &aux_tmp);
+               ast_sockaddr_to_sin(&aux_tmp, &aux);
 
                /* If the STUN result is different from the IP of the hostname,
-                       lock on the stun IP of the hostname advertised by the
-                       remote client */
-               if (aux.sin_addr.s_addr && 
-                   aux.sin_addr.s_addr != sin.sin_addr.s_addr)
-                       ast_rtp_stun_request(p->rtp, &aux, username);
-               else 
-                       ast_rtp_stun_request(p->rtp, &sin, username);
-               
-               if (aux.sin_addr.s_addr && option_debug > 3) {
-                       ast_log(LOG_DEBUG, "Receiving RTP traffic from IP %s, matches with remote candidate's IP %s\n", ast_inet_ntoa(aux.sin_addr), tmp->ip);
-                       ast_log(LOG_DEBUG, "Sending STUN request to %s\n", tmp->ip);
+                * lock on the stun IP of the hostname advertised by the
+                * remote client */
+               if (aux.sin_addr.s_addr && (aux.sin_addr.s_addr != sin.sin_addr.s_addr)) {
+                       ast_rtp_instance_stun_request(p->rtp, &aux_tmp, username);
+               } else {
+                       ast_sockaddr_from_sin(&sin_tmp, &sin);
+                       ast_rtp_instance_stun_request(p->rtp, &sin_tmp, username);
+               }
+               if (aux.sin_addr.s_addr) {
+                       ast_debug(4, "Receiving RTP traffic from IP %s, matches with remote candidate's IP %s\n", ast_inet_ntoa(aux.sin_addr), tmp->ip);
+                       ast_debug(4, "Sending STUN request to %s\n", tmp->ip);
                }
 
                tmp = tmp->next;
@@ -1185,77 +1512,82 @@ static int gtalk_add_candidate(struct gtalk *client, ikspak *pak)
        char *from;
 
        from = iks_find_attrib(pak->x,"to");
-       if(!from)
+       if (!from) {
                from = c->jid->full;
+       }
 
-       newcandidate = ast_calloc(1, sizeof(*newcandidate));
-       if (!newcandidate)
-               return 0;
        for (tmp = client->p; tmp; tmp = tmp->next) {
-               if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid)) {
+               if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid) ||
+                       (iks_find_attrib(pak->query, "id") && !strcmp(iks_find_attrib(pak->query, "id"), tmp->sid))) {
                        p = tmp;
                        break;
                }
        }
 
-       if (!p)
+       if (!p) {
                return -1;
-
+       }
        traversenodes = pak->query;
        while(traversenodes) {
-               if(!strcasecmp(iks_name(traversenodes), "session")) {
-                       traversenodes = iks_child(traversenodes);
+               if(!strcasecmp(S_OR(iks_name(traversenodes), ""), "session")) {
+                       traversenodes = iks_first_tag(traversenodes);
                        continue;
                }
-               if(!strcasecmp(iks_name(traversenodes), "transport")) {
+               if(!strcasecmp(S_OR(iks_name(traversenodes), ""), "ses:session")) {
                        traversenodes = iks_child(traversenodes);
                        continue;
                }
-               if(!strcasecmp(iks_name(traversenodes), "candidate")) {
+               if(!strcasecmp(S_OR(iks_name(traversenodes), ""), "candidate") || !strcasecmp(S_OR(iks_name(traversenodes), ""), "ses:candidate")) {
                        newcandidate = ast_calloc(1, sizeof(*newcandidate));
                        if (!newcandidate)
                                return 0;
-                       ast_copy_string(newcandidate->name, iks_find_attrib(traversenodes, "name"),
-                                                       sizeof(newcandidate->name));
-                       ast_copy_string(newcandidate->ip, iks_find_attrib(traversenodes, "address"),
-                                                       sizeof(newcandidate->ip));
+                       ast_copy_string(newcandidate->name,
+                               S_OR(iks_find_attrib(traversenodes, "name"), ""),
+                               sizeof(newcandidate->name));
+                       ast_copy_string(newcandidate->ip,
+                               S_OR(iks_find_attrib(traversenodes, "address"), ""),
+                               sizeof(newcandidate->ip));
                        newcandidate->port = atoi(iks_find_attrib(traversenodes, "port"));
-                       ast_copy_string(newcandidate->username, iks_find_attrib(traversenodes, "username"),
-                                                       sizeof(newcandidate->username));
-                       ast_copy_string(newcandidate->password, iks_find_attrib(traversenodes, "password"),
-                                                       sizeof(newcandidate->password));
+                       ast_copy_string(newcandidate->username,
+                               S_OR(iks_find_attrib(traversenodes, "username"), ""),
+                               sizeof(newcandidate->username));
+                       ast_copy_string(newcandidate->password,
+                               S_OR(iks_find_attrib(traversenodes, "password"), ""),
+                               sizeof(newcandidate->password));
                        newcandidate->preference = atof(iks_find_attrib(traversenodes, "preference"));
-                       if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "udp"))
+                       if (!strcasecmp(S_OR(iks_find_attrib(traversenodes, "protocol"), ""), "udp"))
                                newcandidate->protocol = AJI_PROTOCOL_UDP;
-                       if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "ssltcp"))
+                       if (!strcasecmp(S_OR(iks_find_attrib(traversenodes, "protocol"), ""), "ssltcp"))
                                newcandidate->protocol = AJI_PROTOCOL_SSLTCP;
-               
-                       if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "stun"))
+
+                       if (!strcasecmp(S_OR(iks_find_attrib(traversenodes, "type"), ""), "stun"))
                                newcandidate->type = AJI_CONNECT_STUN;
-                       if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "local"))
+                       if (!strcasecmp(S_OR(iks_find_attrib(traversenodes, "type"), ""), "local"))
                                newcandidate->type = AJI_CONNECT_LOCAL;
-                       if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "relay"))
+                       if (!strcasecmp(S_OR(iks_find_attrib(traversenodes, "type"), ""), "relay"))
                                newcandidate->type = AJI_CONNECT_RELAY;
-                       ast_copy_string(newcandidate->network, iks_find_attrib(traversenodes, "network"),
-                                                       sizeof(newcandidate->network));
-                       newcandidate->generation = atoi(iks_find_attrib(traversenodes, "generation"));
+                       ast_copy_string(newcandidate->network,
+                               S_OR(iks_find_attrib(traversenodes, "network"), ""),
+                               sizeof(newcandidate->network));
+                       newcandidate->generation = atoi(S_OR(iks_find_attrib(traversenodes, "generation"), "0"));
                        newcandidate->next = NULL;
-               
+
                        newcandidate->next = p->theircandidates;
                        p->theircandidates = newcandidate;
                        p->laststun = 0;
                        gtalk_update_stun(p->parent, p);
                        newcandidate = NULL;
                }
-               traversenodes = iks_next(traversenodes);
+               traversenodes = iks_next_tag(traversenodes);
        }
-       
+
        receipt = iks_new("iq");
        iks_insert_attrib(receipt, "type", "result");
        iks_insert_attrib(receipt, "from", from);
-       iks_insert_attrib(receipt, "to", iks_find_attrib(pak->x, "from"));
-       iks_insert_attrib(receipt, "id", iks_find_attrib(pak->x, "id"));
-       iks_send(c->p, receipt);
+       iks_insert_attrib(receipt, "to", S_OR(iks_find_attrib(pak->x, "from"), ""));
+       iks_insert_attrib(receipt, "id", S_OR(iks_find_attrib(pak->x, "id"), ""));
+       ast_aji_send(c, receipt);
+
        iks_delete(receipt);
 
        return 1;
@@ -1265,27 +1597,26 @@ static struct ast_frame *gtalk_rtp_read(struct ast_channel *ast, struct gtalk_pv
 {
        struct ast_frame *f;
 
-       if (!p->rtp)
+       if (!p->rtp) {
                return &ast_null_frame;
-       f = ast_rtp_read(p->rtp);
+       }
+       f = ast_rtp_instance_read(p->rtp, 0);
        gtalk_update_stun(p->parent, p);
        if (p->owner) {
                /* We already hold the channel lock */
                if (f->frametype == AST_FRAME_VOICE) {
-                       if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
-                               if (option_debug)
-                                       ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
-                               p->owner->nativeformats =
-                                       (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
-                               ast_set_read_format(p->owner, p->owner->readformat);
-                               ast_set_write_format(p->owner, p->owner->writeformat);
+                       if (!ast_format_cap_iscompatible(p->owner->nativeformats, &f->subclass.format)) {
+                               ast_debug(1, "Oooh, format changed to %s\n", ast_getformatname(&f->subclass.format));
+                               ast_format_cap_remove_bytype(p->owner->nativeformats, AST_FORMAT_TYPE_AUDIO);
+                               ast_format_cap_add(p->owner->nativeformats, &f->subclass.format);
+                               ast_set_read_format(p->owner, &p->owner->readformat);
+                               ast_set_write_format(p->owner, &p->owner->writeformat);
                        }
-/*                     if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
+                       /* if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
                                f = ast_dsp_process(p->owner, p->vad, f);
                                if (option_debug && f && (f->frametype == AST_FRAME_DTMF))
-                                       if (option_debug)
-                                               ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
-                       } */
+                                       ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
+               } */
                }
        }
        return f;
@@ -1307,20 +1638,23 @@ static int gtalk_write(struct ast_channel *ast, struct ast_frame *frame)
 {
        struct gtalk_pvt *p = ast->tech_pvt;
        int res = 0;
+       char buf[256];
 
        switch (frame->frametype) {
        case AST_FRAME_VOICE:
-               if (!(frame->subclass & ast->nativeformats)) {
+               if (!(ast_format_cap_iscompatible(ast->nativeformats, &frame->subclass.format))) {
                        ast_log(LOG_WARNING,
-                                       "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
-                                       frame->subclass, ast->nativeformats, ast->readformat,
-                                       ast->writeformat);
+                                       "Asked to transmit frame type %s, while native formats is %s (read/write = %s/%s)\n",
+                                       ast_getformatname(&frame->subclass.format),
+                                       ast_getformatname_multiple(buf, sizeof(buf), ast->nativeformats),
+                                       ast_getformatname(&ast->readformat),
+                                       ast_getformatname(&ast->writeformat));
                        return 0;
                }
                if (p) {
                        ast_mutex_lock(&p->lock);
                        if (p->rtp) {
-                               res = ast_rtp_write(p->rtp, frame);
+                               res = ast_rtp_instance_write(p->rtp, frame);
                        }
                        ast_mutex_unlock(&p->lock);
                }
@@ -1329,7 +1663,7 @@ static int gtalk_write(struct ast_channel *ast, struct ast_frame *frame)
                if (p) {
                        ast_mutex_lock(&p->lock);
                        if (p->vrtp) {
-                               res = ast_rtp_write(p->vrtp, frame);
+                               res = ast_rtp_instance_write(p->vrtp, frame);
                        }
                        ast_mutex_unlock(&p->lock);
                }
@@ -1373,39 +1707,82 @@ static int gtalk_indicate(struct ast_channel *ast, int condition, const void *da
                ast_moh_stop(ast);
                break;
        default:
-               ast_log(LOG_NOTICE, "Don't know how to indicate condition '%d'\n", condition);
+               ast_debug(3, "Don't know how to indicate condition '%d'\n", condition);
                res = -1;
        }
 
        return res;
 }
 
+static int gtalk_sendtext(struct ast_channel *chan, const char *text)
+{
+       int res = 0;
+       struct aji_client *client = NULL;
+       struct gtalk_pvt *p = chan->tech_pvt;
+
+       if (!p->parent) {
+               ast_log(LOG_ERROR, "Parent channel not found\n");
+               return -1;
+       }
+       if (!p->parent->connection) {
+               ast_log(LOG_ERROR, "XMPP client not found\n");
+               return -1;
+       }
+       client = p->parent->connection;
+       res = ast_aji_send_chat(client, p->them, text);
+       return res;
+}
+
 static int gtalk_digit_begin(struct ast_channel *chan, char digit)
 {
-       return gtalk_digit(chan, digit, 0);
+       struct gtalk_pvt *p = chan->tech_pvt;
+       int res = 0;
+
+       ast_mutex_lock(&p->lock);
+       if (p->rtp) {
+               ast_rtp_instance_dtmf_begin(p->rtp, digit);
+       } else {
+               res = -1;
+       }
+       ast_mutex_unlock(&p->lock);
+
+       return res;
 }
 
 static int gtalk_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
 {
-       return gtalk_digit(chan, digit, duration);
+       struct gtalk_pvt *p = chan->tech_pvt;
+       int res = 0;
+
+       ast_mutex_lock(&p->lock);
+       if (p->rtp) {
+               ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
+       } else {
+               res = -1;
+       }
+       ast_mutex_unlock(&p->lock);
+
+       return res;
 }
 
+/* This function is of not in use at the moment, but I am choosing to leave this
+ * within the code base as a reference to how DTMF is possible through
+ * jingle signaling.  However, google currently does DTMF through the RTP. */
+#if 0
 static int gtalk_digit(struct ast_channel *ast, char digit, unsigned int duration)
 {
        struct gtalk_pvt *p = ast->tech_pvt;
        struct gtalk *client = p->parent;
        iks *iq, *gtalk, *dtmf;
        char buffer[2] = {digit, '\0'};
+       char *lowerthem = NULL;
        iq = iks_new("iq");
        gtalk = iks_new("gtalk");
        dtmf = iks_new("dtmf");
        if(!iq || !gtalk || !dtmf) {
-               if(iq)
-                       iks_delete(iq);
-               if(gtalk)
-                       iks_delete(gtalk);
-               if(dtmf)
-                       iks_delete(dtmf);
+               iks_delete(iq);
+               iks_delete(gtalk);
+               iks_delete(dtmf);
                ast_log(LOG_ERROR, "Did not send dtmf do to memory issue\n");
                return -1;
        }
@@ -1416,8 +1793,15 @@ static int gtalk_digit(struct ast_channel *ast, char digit, unsigned int duratio
        iks_insert_attrib(iq, "id", client->connection->mid);
        ast_aji_increment_mid(client->connection->mid);
        iks_insert_attrib(gtalk, "xmlns", "http://jabber.org/protocol/gtalk");
-       iks_insert_attrib(gtalk, "action", "content-info");
-       iks_insert_attrib(gtalk, "initiator", p->initiator ? p->us: p->them);
+       iks_insert_attrib(gtalk, "action", "session-info");
+       // put the initiator attribute to lower case if we receive the call
+       // otherwise GoogleTalk won't establish the session
+       if (!p->initiator) {
+               char c;
+               char *t = lowerthem = ast_strdupa(p->them);
+               while (((c = *t) != '/') && (*t++ = tolower(c)));
+       }
+       iks_insert_attrib(gtalk, "initiator", p->initiator ? p->us: lowerthem);
        iks_insert_attrib(gtalk, "sid", p->sid);
        iks_insert_attrib(dtmf, "xmlns", "http://jabber.org/protocol/gtalk/info/dtmf");
        iks_insert_attrib(dtmf, "code", buffer);
@@ -1425,18 +1809,20 @@ static int gtalk_digit(struct ast_channel *ast, char digit, unsigned int duratio
        iks_insert_node(gtalk, dtmf);
 
        ast_mutex_lock(&p->lock);
-       if (ast->dtmff.frametype == AST_FRAME_DTMF_BEGIN) {
+       if (ast->dtmff.frametype == AST_FRAME_DTMF_BEGIN || duration == 0) {
                iks_insert_attrib(dtmf, "action", "button-down");
-       } else if (ast->dtmff.frametype == AST_FRAME_DTMF_END) {
+       } else if (ast->dtmff.frametype == AST_FRAME_DTMF_END || duration != 0) {
                iks_insert_attrib(dtmf, "action", "button-up");
        }
-       iks_send(client->connection->p, iq);
+       ast_aji_send(client->connection, iq);
+
        iks_delete(iq);
        iks_delete(gtalk);
        iks_delete(dtmf);
        ast_mutex_unlock(&p->lock);
        return 0;
 }
+#endif
 
 static int gtalk_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
 {
@@ -1445,26 +1831,8 @@ static int gtalk_sendhtml(struct ast_channel *ast, int subclass, const char *dat
        return -1;
 }
 
-/* Not in use right now.
-static int gtalk_auto_congest(void *nothing)
-{
-       struct gtalk_pvt *p = nothing;
-
-       ast_mutex_lock(&p->lock);
-       if (p->owner) {
-               if (!ast_channel_trylock(p->owner)) {
-                       ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
-                       ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
-                       ast_channel_unlock(p->owner);
-               }
-       }
-       ast_mutex_unlock(&p->lock);
-       return 0;
-}
-*/
-
-/*! \brief Initiate new call, part of PBX interface 
- *     dest is the dial string */
+/*!\brief Initiate new call, part of PBX interface
+ * dest is the dial string */
 static int gtalk_call(struct ast_channel *ast, char *dest, int timeout)
 {
        struct gtalk_pvt *p = ast->tech_pvt;
@@ -1475,16 +1843,15 @@ static int gtalk_call(struct ast_channel *ast, char *dest, int timeout)
        }
 
        ast_setstate(ast, AST_STATE_RING);
-       p->jointcapability = p->capability;
        if (!p->ringrule) {
                ast_copy_string(p->ring, p->parent->connection->mid, sizeof(p->ring));
                p->ringrule = iks_filter_add_rule(p->parent->connection->f, gtalk_ringing_ack, p,
                                                        IKS_RULE_ID, p->ring, IKS_RULE_DONE);
-       } else
+       } else {
                ast_log(LOG_WARNING, "Whoa, already have a ring rule!\n");
+       }
 
        gtalk_invite(p, p->them, p->us, p->sid, 1);
-       gtalk_create_candidates(p->parent, p, p->sid, p->them, p->us);
 
        return 0;
 }
@@ -1499,8 +1866,9 @@ static int gtalk_hangup(struct ast_channel *ast)
        client = p->parent;
        p->owner = NULL;
        ast->tech_pvt = NULL;
-       if (!p->alreadygone)
+       if (!p->alreadygone) {
                gtalk_action(client, p, "terminate");
+       }
        ast_mutex_unlock(&p->lock);
 
        gtalk_free_pvt(client, p);
@@ -1509,8 +1877,8 @@ static int gtalk_hangup(struct ast_channel *ast)
        return 0;
 }
 
-/*! \brief Part of PBX interface */
-static struct ast_channel *gtalk_request(const char *type, int format, void *data, int *cause)
+/*!\brief Part of PBX interface */
+static struct ast_channel *gtalk_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, void *data, int *cause)
 {
        struct gtalk_pvt *p = NULL;
        struct gtalk *client = NULL;
@@ -1521,121 +1889,199 @@ static struct ast_channel *gtalk_request(const char *type, int format, void *dat
                s = ast_strdupa(data);
                if (s) {
                        sender = strsep(&s, "/");
-                       if (sender && (sender[0] != '\0'))
+                       if (sender && (sender[0] != '\0')) {
                                to = strsep(&s, "/");
+                       }
                        if (!to) {
                                ast_log(LOG_ERROR, "Bad arguments in Gtalk Dialstring: %s\n", (char*) data);
                                return NULL;
                        }
                }
        }
+
        client = find_gtalk(to, sender);
        if (!client) {
                ast_log(LOG_WARNING, "Could not find recipient.\n");
                return NULL;
        }
+       if (!strcasecmp(client->name, "guest")){
+               /* the guest account is not tied to any configured XMPP client,
+                  let's set it now */
+               client->connection = ast_aji_get_client(sender);
+               if (!client->connection) {
+                       ast_log(LOG_ERROR, "No XMPP client to talk to, us (partial JID) : %s\n", sender);
+                       ASTOBJ_UNREF(client, gtalk_member_destroy);
+                       return NULL;
+               }
+       }
+
        ASTOBJ_WRLOCK(client);
        p = gtalk_alloc(client, strchr(sender, '@') ? sender : client->connection->jid->full, strchr(to, '@') ? to : client->user, NULL);
-       if (p)
-               chan = gtalk_new(client, p, AST_STATE_DOWN, to);
-
+       if (p) {
+               chan = gtalk_new(client, p, AST_STATE_DOWN, to, requestor ? requestor->linkedid : NULL);
+       }
        ASTOBJ_UNLOCK(client);
        return chan;
 }
 
 /*! \brief CLI command "gtalk show channels" */
-static int gtalk_show_channels(int fd, int argc, char **argv)
+static char *gtalk_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
-       if (argc != 3)
-               return RESULT_SHOWUSAGE;
+#define FORMAT  "%-30.30s  %-30.30s  %-15.15s  %-5.5s %-5.5s \n"
+       struct gtalk_pvt *p;
+       struct ast_channel *chan;
+       int numchans = 0;
+       char them[AJI_MAX_JIDLEN];
+       char *jid = NULL;
+       char *resource = NULL;
+
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "gtalk show channels";
+               e->usage =
+                       "Usage: gtalk show channels\n"
+                       "       Shows current state of the Gtalk channels.\n";
+               return NULL;
+       case CLI_GENERATE:
+               return NULL;
+       }
+
+       if (a->argc != 3)
+               return CLI_SHOWUSAGE;
+
        ast_mutex_lock(&gtalklock);
-//     if (!gtalk_list->p)
-               ast_cli(fd, "No gtalk channels in use\n");
+       ast_cli(a->fd, FORMAT, "Channel", "Jabber ID", "Resource", "Read", "Write");
+       ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
+               ASTOBJ_WRLOCK(iterator);
+               p = iterator->p;
+               while(p) {
+                       chan = p->owner;
+                       ast_copy_string(them, p->them, sizeof(them));
+                       jid = them;
+                       resource = strchr(them, '/');
+                       if (!resource)
+                               resource = "None";
+                       else {
+                               *resource = '\0';
+                               resource ++;
+                       }
+                       if (chan)
+                               ast_cli(a->fd, FORMAT,
+                                       chan->name,
+                                       jid,
+                                       resource,
+                                       ast_getformatname(&chan->readformat),
+                                       ast_getformatname(&chan->writeformat)
+                                       );
+                       else
+                               ast_log(LOG_WARNING, "No available channel\n");
+                       numchans ++;
+                       p = p->next;
+               }
+               ASTOBJ_UNLOCK(iterator);
+       });
+
        ast_mutex_unlock(&gtalklock);
-       return RESULT_SUCCESS;
+
+       ast_cli(a->fd, "%d active gtalk channel%s\n", numchans, (numchans != 1) ? "s" : "");
+       return CLI_SUCCESS;
+#undef FORMAT
 }
 
-/*! \brief CLI command "gtalk show channels" */
-static int gtalk_do_reload(int fd, int argc, char **argv)
+/*! \brief List global settings for the GoogleTalk channel */
+static char *gtalk_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+{
+       char codec_buf[BUFSIZ];
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "gtalk show settings";
+               e->usage =
+                       "Usage: gtalk show settings\n"
+                       "       Provides detailed list of the configuration on the GoogleTalk channel.\n";
+               return NULL;
+       case CLI_GENERATE:
+               return NULL;
+       }
+
+       if (a->argc != 3) {
+               return CLI_SHOWUSAGE;
+       }
+
+#define FORMAT "  %-25.20s  %-15.30s\n"
+
+       ast_cli(a->fd, "\nGlobal Settings:\n");
+       ast_cli(a->fd, "----------------\n");
+       ast_cli(a->fd, FORMAT, "UDP Bindaddress:", ast_inet_ntoa(bindaddr.sin_addr));
+       ast_cli(a->fd, FORMAT, "Stun Address:", global_stunaddr != 0 ? ast_inet_ntoa(stunaddr.sin_addr) : "Disabled");
+       ast_cli(a->fd, FORMAT, "External IP:", S_OR(externip, "Disabled"));
+       ast_cli(a->fd, FORMAT, "Context:", global_context);
+       ast_cli(a->fd, FORMAT, "Codecs:", ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, global_capability));
+       ast_cli(a->fd, FORMAT, "Parking Lot:", global_parkinglot);
+       ast_cli(a->fd, FORMAT, "Allow Guest:", AST_CLI_YESNO(global_allowguest));
+       ast_cli(a->fd, "\n----\n");
+
+       return CLI_SUCCESS;
+#undef FORMAT
+}
+
+/*! \brief CLI command "gtalk reload"
+ *  \todo XXX TODO make this work. */
+#if 0
+static char *gtalk_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "gtalk reload";
+               e->usage =
+                       "Usage: gtalk reload\n"
+                       "       Reload gtalk channel driver.\n";
+               return NULL;
+       case CLI_GENERATE:
+               return NULL;
+       }
+
        ast_verbose("IT DOES WORK!\n");
-       return RESULT_SUCCESS;
+       return CLI_SUCCESS;
 }
+#endif
 
 static int gtalk_parser(void *data, ikspak *pak)
 {
        struct gtalk *client = ASTOBJ_REF((struct gtalk *) data);
+       int res;
+
+       if (!strcmp(S_OR(iks_find_attrib(pak->x, "type"), ""), "error")) {
+               ast_log(LOG_NOTICE, "Remote peer reported an error, trying to establish the call anyway\n");
+       }
 
-       if (iks_find_with_attrib(pak->x, "session", "type", "initiate")) {
+       if (ast_strlen_zero(iks_find_attrib(pak->query, "type"))) {
+               ast_log(LOG_NOTICE, "No attribute \"type\" found.  Ignoring message.\n");
+       } else if (!strcmp(iks_find_attrib(pak->query, "type"), "initiate")) {
                /* New call */
                gtalk_newcall(client, pak);
-       } else if (iks_find_with_attrib(pak->x, "session", "type", "candidates") || iks_find_with_attrib(pak->x, "session", "type", "transport-info")) {
-               if (option_debug > 2)
-                       ast_log(LOG_DEBUG, "About to add candidate!\n");
-               gtalk_add_candidate(client, pak);
-               if (option_debug > 2)
-                       ast_log(LOG_DEBUG, "Candidate Added!\n");
-       } else if (iks_find_with_attrib(pak->x, "session", "type", "accept") || iks_find_with_attrib(pak->x, "session", "type", "transport-accept")) {
+       } else if (!strcmp(iks_find_attrib(pak->query, "type"), "candidates") || !strcmp(iks_find_attrib(pak->query, "type"), "transport-info")) {
+               ast_debug(3, "About to add candidate!\n");
+               res = gtalk_add_candidate(client, pak);
+               if (!res) {
+                       ast_log(LOG_WARNING, "Could not add any candidate\n");
+               } else {
+                       ast_debug(3, "Candidate Added!\n");
+               }
+       } else if (!strcmp(iks_find_attrib(pak->query, "type"), "accept")) {
                gtalk_is_answered(client, pak);
-       } else if (iks_find_with_attrib(pak->x, "session", "type", "content-info")) {
+       } else if (!strcmp(iks_find_attrib(pak->query, "type"), "transport-accept")) {
+               gtalk_is_accepted(client, pak);
+       } else if (!strcmp(iks_find_attrib(pak->query, "type"), "content-info") || iks_find_with_attrib(pak->x, "gtalk", "action", "session-info")) {
                gtalk_handle_dtmf(client, pak);
-       } else if (iks_find_with_attrib(pak->x, "session", "type", "terminate")) {
+       } else if (!strcmp(iks_find_attrib(pak->query, "type"), "terminate")) {
                gtalk_hangup_farend(client, pak);
-       } else if (iks_find_with_attrib(pak->x, "session", "type", "reject")) {
+       } else if (!strcmp(iks_find_attrib(pak->query, "type"), "reject")) {
                gtalk_hangup_farend(client, pak);
        }
        ASTOBJ_UNREF(client, gtalk_member_destroy);
        return IKS_FILTER_EAT;
 }
 
-/* Not using this anymore probably take out soon 
-static struct gtalk_candidate *gtalk_create_candidate(char *args)
-{
-       char *name, *type, *preference, *protocol;
-       struct gtalk_candidate *res;
-       res = malloc(sizeof(struct gtalk_candidate));
-       memset(res, 0, sizeof(struct gtalk_candidate));
-       if (args)
-               name = args;
-       if ((args = strchr(args, ','))) {
-               *args = '\0';
-               args++;
-               preference = args;
-       }
-       if ((args = strchr(args, ','))) {
-               *args = '\0';
-               args++;
-               protocol = args;
-       }
-       if ((args = strchr(args, ','))) {
-               *args = '\0';
-               args++;
-               type = args;
-       }
-       if (name)
-               ast_copy_string(res->name, name, sizeof(res->name));
-       if (preference) {
-               res->preference = atof(preference);
-       }
-       if (protocol) {
-               if (!strcasecmp("udp", protocol))
-                       res->protocol = AJI_PROTOCOL_UDP;
-               if (!strcasecmp("ssltcp", protocol))
-                       res->protocol = AJI_PROTOCOL_SSLTCP;
-       }
-       if (type) {
-               if (!strcasecmp("stun", type))
-                       res->type = AJI_CONNECT_STUN;
-               if (!strcasecmp("local", type))
-                       res->type = AJI_CONNECT_LOCAL;
-               if (!strcasecmp("relay", type))
-                       res->type = AJI_CONNECT_RELAY;
-       }
-
-       return res;
-}
-*/
-
 static int gtalk_create_member(char *label, struct ast_variable *var, int allowguest,
                                                                struct ast_codec_pref prefs, char *context,
                                                                struct gtalk *member)
@@ -1651,34 +2097,24 @@ static int gtalk_create_member(char *label, struct ast_variable *var, int allowg
        member->allowguest = allowguest;
        member->prefs = prefs;
        while (var) {
-#if 0
-               struct gtalk_candidate *candidate = NULL;
-#endif
                if (!strcasecmp(var->name, "username"))
                        ast_copy_string(member->user, var->value, sizeof(member->user));
                else if (!strcasecmp(var->name, "disallow"))
-                       ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 0);
+                       ast_parse_allow_disallow(&member->prefs, member->cap, var->value, 0);
                else if (!strcasecmp(var->name, "allow"))
-                       ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 1);
+                       ast_parse_allow_disallow(&member->prefs, member->cap, var->value, 1);
                else if (!strcasecmp(var->name, "context"))
                        ast_copy_string(member->context, var->value, sizeof(member->context));
-#if 0
-               else if (!strcasecmp(var->name, "candidate")) {
-                       candidate = gtalk_create_candidate(var->value);
-                       if (candidate) {
-                               candidate->next = member->ourcandidates;
-                               member->ourcandidates = candidate;
-                       }
-               }
-#endif
+               else if (!strcasecmp(var->name, "parkinglot"))
+                       ast_copy_string(member->parkinglot, var->value, sizeof(member->parkinglot));
                else if (!strcasecmp(var->name, "connection")) {
                        if ((client = ast_aji_get_client(var->value))) {
                                member->connection = client;
-                               iks_filter_add_rule(client->f, gtalk_parser, member, IKS_RULE_TYPE,
-                                                                       IKS_PAK_IQ, IKS_RULE_FROM_PARTIAL, member->user,
-                                                                       IKS_RULE_NS, "http://www.google.com/session",
-                                                                       IKS_RULE_DONE);
-
+                               iks_filter_add_rule(client->f, gtalk_parser, member,
+                                                   IKS_RULE_TYPE, IKS_PAK_IQ,
+                                                   IKS_RULE_FROM_PARTIAL, member->user,
+                                                   IKS_RULE_NS, GOOGLE_NS,
+                                                   IKS_RULE_DONE);
                        } else {
                                ast_log(LOG_ERROR, "connection referenced not found!\n");
                                return 0;
@@ -1698,8 +2134,6 @@ static int gtalk_load_config(void)
 {
        char *cat = NULL;
        struct ast_config *cfg = NULL;
-       char context[100];
-       int allowguest = 1;
        struct ast_variable *var;
        struct gtalk *member;
        struct ast_codec_pref prefs;
@@ -1707,80 +2141,88 @@ static int gtalk_load_config(void)
        struct gtalk_candidate *global_candidates = NULL;
        struct hostent *hp;
        struct ast_hostent ahp;
+       struct ast_flags config_flags = { 0 };
 
-       cfg = ast_config_load(GOOGLE_CONFIG);
-       if (!cfg)
+       cfg = ast_config_load(GOOGLE_CONFIG, config_flags);
+       if (!cfg) {
+               return 0;
+       } else if (cfg == CONFIG_STATUS_FILEINVALID) {
+               ast_log(LOG_ERROR, "Config file %s is in an invalid format.  Aborting.\n", GOOGLE_CONFIG);
                return 0;
+       }
 
        /* Copy the default jb config over global_jbconf */
        memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
 
+       /* set defaults */
+       memset(&prefs, 0, sizeof(prefs));
+       memset(&stunaddr, 0, sizeof(stunaddr));
+       global_stunaddr = 0;
+       global_allowguest = DEFAULT_ALLOWGUEST;
+       ast_copy_string(global_context, DEFAULT_CONTEXT, sizeof(global_context));
+       ast_copy_string(global_parkinglot, DEFAULT_PARKINGLOT, sizeof(global_parkinglot));
+
        cat = ast_category_browse(cfg, NULL);
        for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
                /* handle jb conf */
-               if (!ast_jb_read_conf(&global_jbconf, var->name, var->value))
+               if (!ast_jb_read_conf(&global_jbconf, var->name, var->value)) {
                        continue;
+               }
 
-               if (!strcasecmp(var->name, "allowguest"))
-                       allowguest =
-                               (ast_true(ast_variable_retrieve(cfg, "general", "allowguest"))) ? 1 : 0;
-               else if (!strcasecmp(var->name, "disallow"))
-                       ast_parse_allow_disallow(&prefs, &global_capability, var->value, 0);
-               else if (!strcasecmp(var->name, "allow"))
-                       ast_parse_allow_disallow(&prefs, &global_capability, var->value, 1);
-               else if (!strcasecmp(var->name, "context"))
-                       ast_copy_string(context, var->value, sizeof(context));
-               else if (!strcasecmp(var->name, "bindaddr")) {
+               if (!strcasecmp(var->name, "allowguest")) {
+                       global_allowguest = (ast_true(ast_variable_retrieve(cfg, "general", "allowguest"))) ? 1 : 0;
+               } else if (!strcasecmp(var->name, "disallow")) {
+                       ast_parse_allow_disallow(&prefs, global_capability, var->value, 0);
+               } else if (!strcasecmp(var->name, "allow")) {
+                       ast_parse_allow_disallow(&prefs, global_capability, var->value, 1);
+               } else if (!strcasecmp(var->name, "context")) {
+                       ast_copy_string(global_context, var->value, sizeof(global_context));
+               } else if (!strcasecmp(var->name, "externip")) {
+                       ast_copy_string(externip, var->value, sizeof(externip));
+               } else if (!strcasecmp(var->name, "parkinglot")) {
+                       ast_copy_string(global_parkinglot, var->value, sizeof(global_parkinglot));
+               } else if (!strcasecmp(var->name, "bindaddr")) {
                        if (!(hp = ast_gethostbyname(var->value, &ahp))) {
                                ast_log(LOG_WARNING, "Invalid address: %s\n", var->value);
                        } else {
                                memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
                        }
-               }
-/*  Idea to allow for custom candidates  */
-/*
-               else if (!strcasecmp(var->name, "candidate")) {
-                       candidate = gtalk_create_candidate(var->value);
-                       if (candidate) {
-                               candidate->next = global_candidates;
-                               global_candidates = candidate;
+               } else if (!strcasecmp(var->name, "stunaddr")) {
+                       stunaddr.sin_port = htons(STANDARD_STUN_PORT);
+                       global_stunaddr = 1;
+                       if (ast_parse_arg(var->value, PARSE_INADDR, &stunaddr)) {
+                               ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", var->value);
                        }
                }
-*/
        }
        while (cat) {
                if (strcasecmp(cat, "general")) {
                        var = ast_variable_browse(cfg, cat);
-                       member = (struct gtalk *) malloc(sizeof(struct gtalk));
-                       memset(member, 0, sizeof(struct gtalk));
+                       member = ast_calloc(1, sizeof(*member));
                        ASTOBJ_INIT(member);
                        ASTOBJ_WRLOCK(member);
+                       member->cap = ast_format_cap_alloc_nolock();
                        if (!strcasecmp(cat, "guest")) {
                                ast_copy_string(member->name, "guest", sizeof(member->name));
                                ast_copy_string(member->user, "guest", sizeof(member->user));
-                               ast_copy_string(member->context, context, sizeof(member->context));
-                               member->allowguest = allowguest;
+                               ast_copy_string(member->context, global_context, sizeof(member->context));
+                               ast_copy_string(member->parkinglot, global_parkinglot, sizeof(member->parkinglot));
+                               member->allowguest = global_allowguest;
                                member->prefs = prefs;
                                while (var) {
-                                       if (!strcasecmp(var->name, "disallow"))
-                                               ast_parse_allow_disallow(&member->prefs, &member->capability,
+                                       if (!strcasecmp(var->name, "disallow")) {
+                                               ast_parse_allow_disallow(&member->prefs, member->cap,
                                                                                                 var->value, 0);
-                                       else if (!strcasecmp(var->name, "allow"))
-                                               ast_parse_allow_disallow(&member->prefs, &member->capability,
+                                       } else if (!strcasecmp(var->name, "allow")) {
+                                               ast_parse_allow_disallow(&member->prefs, member->cap,
                                                                                                 var->value, 1);
-                                       else if (!strcasecmp(var->name, "context"))
+                                       } else if (!strcasecmp(var->name, "context")) {
                                                ast_copy_string(member->context, var->value,
                                                                                sizeof(member->context));
-/*  Idea to allow for custom candidates  */
-/*
-                                       else if (!strcasecmp(var->name, "candidate")) {
-                                               candidate = gtalk_create_candidate(var->value);
-                                               if (candidate) {
-                                                       candidate->next = member->ourcandidates;
-                                                       member->ourcandidates = candidate;
-                                               }
+                                       } else if (!strcasecmp(var->name, "parkinglot")) {
+                                               ast_copy_string(member->parkinglot, var->value,
+                                                                               sizeof(member->parkinglot));
                                        }
-*/
                                        var = var->next;
                                }
                                ASTOBJ_UNLOCK(member);
@@ -1789,26 +2231,30 @@ static int gtalk_load_config(void)
                                        ASTOBJ_CONTAINER_TRAVERSE(clients, 1, {
                                                ASTOBJ_WRLOCK(iterator);
                                                ASTOBJ_WRLOCK(member);
-                                               member->connection = iterator;
-                                               iks_filter_add_rule(iterator->f, gtalk_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS,
-                                                                               "http://www.google.com/session", IKS_RULE_DONE);
+                                               member->connection = NULL;
+                                               iks_filter_add_rule(iterator->f, gtalk_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, GOOGLE_NS, IKS_RULE_DONE);
+                                               iks_filter_add_rule(iterator->f, gtalk_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, "http://jabber.org/protocol/gtalk", IKS_RULE_DONE);
                                                ASTOBJ_UNLOCK(member);
-                                               ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
                                                ASTOBJ_UNLOCK(iterator);
                                        });
+                                       ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
+                                       ASTOBJ_UNREF(member, gtalk_member_destroy);
                                } else {
                                        ASTOBJ_UNLOCK(member);
                                        ASTOBJ_UNREF(member, gtalk_member_destroy);
                                }
                        } else {
                                ASTOBJ_UNLOCK(member);
-                               if (gtalk_create_member(cat, var, allowguest, prefs, context, member))
+                               if (gtalk_create_member(cat, var, global_allowguest, prefs, global_context, member)) {
                                        ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
+                               }
                                ASTOBJ_UNREF(member, gtalk_member_destroy);
                        }
                }
                cat = ast_category_browse(cfg, cat);
        }
+
+       gtalk_update_externip();
        gtalk_free_candidates(global_candidates);
        return 1;
 }
@@ -1816,27 +2262,60 @@ static int gtalk_load_config(void)
 /*! \brief Load module into PBX, register channel */
 static int load_module(void)
 {
+       struct ast_sockaddr bindaddr_tmp;
+       struct ast_sockaddr ourip_tmp;
+       char *jabber_loaded = ast_module_helper("", "res_jabber.so", 0, 0, 0, 0);
+       struct ast_format tmpfmt;
+
+       if (!(gtalk_tech.capabilities = ast_format_cap_alloc())) {
+               return AST_MODULE_LOAD_DECLINE;
+       }
+       if (!(global_capability = ast_format_cap_alloc())) {
+               return AST_MODULE_LOAD_DECLINE;
+       }
+
+       ast_format_cap_add_all_by_type(gtalk_tech.capabilities, AST_FORMAT_TYPE_AUDIO);
+       ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0));
+       ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_GSM, 0));
+       ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_ALAW, 0));
+       ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_H263, 0));
+
+       free(jabber_loaded);
+       if (!jabber_loaded) {
+               /* If embedded, check for a different module name */
+               jabber_loaded = ast_module_helper("", "res_jabber", 0, 0, 0, 0);
+               free(jabber_loaded);
+               if (!jabber_loaded) {
+                       ast_log(LOG_ERROR, "chan_gtalk.so depends upon res_jabber.so\n");
+                       return AST_MODULE_LOAD_DECLINE;
+               }
+       }
+
        ASTOBJ_CONTAINER_INIT(&gtalk_list);
        if (!gtalk_load_config()) {
                ast_log(LOG_ERROR, "Unable to read config file %s. Not loading module.\n", GOOGLE_CONFIG);
                return 0;
        }
 
-       sched = sched_context_create();
-       if (!sched) 
+       sched = ast_sched_context_create();
+       if (!sched) {
                ast_log(LOG_WARNING, "Unable to create schedule context\n");
+       }
 
        io = io_context_create();
-       if (!io) 
+       if (!io) {
                ast_log(LOG_WARNING, "Unable to create I/O context\n");
+       }
 
-       if (ast_find_ourip(&__ourip, bindaddr)) {
+       ast_sockaddr_from_sin(&bindaddr_tmp, &bindaddr);
+       if (gtalk_get_local_ip(&ourip_tmp)) {
                ast_log(LOG_WARNING, "Unable to get own IP address, Gtalk disabled\n");
                return 0;
        }
+       __ourip.s_addr = htonl(ast_sockaddr_ipv4(&ourip_tmp));
 
-       ast_rtp_proto_register(&gtalk_rtp);
-       ast_cli_register_multiple(gtalk_cli, sizeof(gtalk_cli) / sizeof(gtalk_cli[0]));
+       ast_rtp_glue_register(&gtalk_rtp_glue);
+       ast_cli_register_multiple(gtalk_cli, ARRAY_LEN(gtalk_cli));
 
        /* Make sure we can register our channel type */
        if (ast_channel_register(&gtalk_tech)) {
@@ -1846,20 +2325,22 @@ static int load_module(void)
        return 0;
 }
 
-/*! \brief Reload module */
+/*! \brief Reload module
+ *  \todo XXX TODO make this work. */
+#if 0
 static int reload(void)
 {
        return 0;
 }
-
+#endif
 /*! \brief Unload the gtalk channel from Asterisk */
 static int unload_module(void)
 {
        struct gtalk_pvt *privates = NULL;
-       ast_cli_unregister_multiple(gtalk_cli, sizeof(gtalk_cli) / sizeof(gtalk_cli[0]));
+       ast_cli_unregister_multiple(gtalk_cli, ARRAY_LEN(gtalk_cli));
        /* First, take us out of the channel loop */
        ast_channel_unregister(&gtalk_tech);
-       ast_rtp_proto_unregister(&gtalk_rtp);
+       ast_rtp_glue_unregister(&gtalk_rtp_glue);
 
        if (!ast_mutex_lock(&gtalklock)) {
                /* Hangup all interfaces if they have an owner */
@@ -1881,11 +2362,14 @@ static int unload_module(void)
        }
        ASTOBJ_CONTAINER_DESTROYALL(&gtalk_list, gtalk_member_destroy);
        ASTOBJ_CONTAINER_DESTROY(&gtalk_list);
+       global_capability = ast_format_cap_destroy(global_capability);
+       gtalk_tech.capabilities = ast_format_cap_destroy(gtalk_tech.capabilities);
        return 0;
 }
 
-AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Gtalk Channel Driver",
+AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Gtalk Channel Driver",
                .load = load_module,
                .unload = unload_module,
-               .reload = reload,
-              );
+               /* .reload = reload, */
+               .load_pri = AST_MODPRI_CHANNEL_DRIVER,
+               );