[asterisk-scf-commits] asterisk-scf/integration/mediatransportudptl.git branch "master" updated.

Commits to the Asterisk SCF project code repositories asterisk-scf-commits at lists.digium.com
Wed Sep 28 08:43:13 CDT 2011


branch "master" has been updated
       via  35178480df903a5e326aaade1c8f0c11a1ff7b81 (commit)
       via  df6cc81d885647e69b43c44390cece5beeb5f9c7 (commit)
      from  5b4099438add60bfe040f67715b78785e0047919 (commit)

Summary of changes:
 config/UdptlConfigurator.py                        |   30 +
 config/test_component.config                       |    1 +
 .../Configuration/UDPTL/UdptlConfigurationIf.ice   |   80 ++
 src/CMakeLists.txt                                 |    8 +
 src/Configuration.h                                |    5 +
 ...PJLibConfiguration.cpp => ICEConfiguration.cpp} |   12 +-
 src/{PJLibConfiguration.h => ICEConfiguration.h}   |   43 +-
 src/ICETransport.cpp                               |  803 ++++++++++++++++++++
 src/ICETransport.h                                 |   89 +++
 src/NATConfig.cpp                                  |   50 ++
 src/NATConfig.h                                    |   76 ++
 src/NATModule.cpp                                  |   84 ++
 src/{PJMediaEndpoint.h => NATModule.h}             |   33 +-
 src/PJMediaEnvironment.h                           |   16 +
 src/UDPTLConfiguration.cpp                         |  274 +++++++
 src/UDPTLSession.cpp                               |   27 +-
 16 files changed, 1588 insertions(+), 43 deletions(-)
 copy src/{PJLibConfiguration.cpp => ICEConfiguration.cpp} (62%)
 copy src/{PJLibConfiguration.h => ICEConfiguration.h} (52%)
 create mode 100644 src/ICETransport.cpp
 create mode 100644 src/ICETransport.h
 create mode 100644 src/NATConfig.cpp
 create mode 100644 src/NATConfig.h
 create mode 100644 src/NATModule.cpp
 copy src/{PJMediaEndpoint.h => NATModule.h} (56%)


- Log -----------------------------------------------------------------
commit 35178480df903a5e326aaade1c8f0c11a1ff7b81
Author: Joshua Colp <jcolp at digium.com>
Date:   Tue Sep 27 12:20:37 2011 -0300

    Use the ICE transport when needed.

diff --git a/src/UDPTLSession.cpp b/src/UDPTLSession.cpp
index b5d2edb..b0203a5 100644
--- a/src/UDPTLSession.cpp
+++ b/src/UDPTLSession.cpp
@@ -22,6 +22,7 @@
 #include "PJMediaTransport.h"
 #include "PJMediaEndpoint.h"
 #include "UDPTransport.h"
+#include "ICETransport.h"
 
 #include <pjlib.h>
 #include <pjmedia.h>
@@ -230,7 +231,22 @@ UDPTLSessionImpl::UDPTLSessionImpl(const Ice::ObjectAdapterPtr& adapter,
     mReplicationContext(replicationContext),
     mUdptl(udptl_create())
 {
-    mTransport = UDPTransport::create(mEndpoint, configurationService, params->ipv6);
+    UDPTLOverICEServiceLocatorParamsPtr iceParams(UDPTLOverICEServiceLocatorParamsPtr::dynamicCast(params));
+    if (iceParams && iceParams->enableICE)
+    {
+        if (mEnvironment->natConfig() && mEnvironment->natConfig()->isSTUNEnabled())
+        {
+            mTransport = ICETransport::create(mEndpoint, env);
+        }
+        else
+        {
+            throw SessionAllocationFailure("ICE/NAT features not enabled for this component instance");
+        }
+    }
+    else
+    {
+        mTransport = UDPTransport::create(mEndpoint, configurationService, params->ipv6);
+    }
 
     // Initialize our session state item enough so that the state items for the source and sink can also be initialized.
     mSessionStateItem->key = mSessionStateItem->sessionId = IceUtil::generateUUID();
@@ -256,7 +272,14 @@ UDPTLSessionImpl::UDPTLSessionImpl(const Ice::ObjectAdapterPtr& adapter,
     mReplicationContext(replicationContext),
     mUdptl(udptl_create())
 {
-    mTransport = UDPTransport::create(mEndpoint, configurationService, port, ipv6);
+    if (mEnvironment->natConfig() && mEnvironment->natConfig()->isSTUNEnabled())
+    {
+        mTransport = ICETransport::create(mEndpoint, env);
+    }
+    else
+    {
+        mTransport = UDPTransport::create(mEndpoint, configurationService, port, ipv6);
+    }
 }
 
 /**

commit df6cc81d885647e69b43c44390cece5beeb5f9c7
Author: Joshua Colp <jcolp at digium.com>
Date:   Tue Sep 27 12:07:51 2011 -0300

    Bring over ICE/STUN transport stuff from RTP to be used with UDPTL.

diff --git a/config/UdptlConfigurator.py b/config/UdptlConfigurator.py
index bde1039..7be2ea0 100755
--- a/config/UdptlConfigurator.py
+++ b/config/UdptlConfigurator.py
@@ -54,6 +54,36 @@ class UdptlSectionVisitors(Configurator.SectionVisitors):
 
         self.groups.append(group)
 
+        def visit_udptloverice(self, config, section):
+            group = AsteriskSCF.Configuration.UDPTL.V1.UDPTLICEConfigurationGroup()
+            group.configurationItems = { }
+
+            mapper = Configurator.OptionMapper()
+
+            stunServerItem = AsteriskSCF.Configuration.UDPTL.V1.STUNServerItem()
+            mapper.map('stunserverhost', stunServerItem, 'address', AsteriskSCF.Configuration.UDPTL.V1.STUNServerItemName, config.get, None)
+            mapper.map('stunserverport', stunServerItem, 'port', AsteriskSCF.Configuration.UDPTL.V1.STUNServerItemName, config.getint, 3478)
+
+            turnServerItem = AsteriskSCF.Configuration.UDPTL.V1.TURNServerItem()
+            mapper.map('turnserverhost', turnServerItem, 'address', AsteriskSCF.Configuration.UDPTL.V1.TURNServerItemName, config.get, None)
+            mapper.map('turnserverport', turnServerItem, 'port', AsteriskSCF.Configuration.UDPTL.V1.TURNServerItemName, config.getint, 3478)
+
+            udptlOverICEItem = AsteriskSCF.Configuration.UDPTL.V1.UDPTLICETransportFlagsItem()
+            mapper.map('udptlovericeenable', udptlOverICEItem, 'enableICE', AsteriskSCF.Configuration.UDPTL.V1.UDPTLICETransportFlagsItemName, config.get, None)
+            mapper.map('udptlovericewithturn', udptlOverICEItem, 'enableTURN', AsteriskSCF.Configuration.UDPTL.V1.UDPTLICETransportFlagsItemName, config.get, None)
+
+            udptlICELimits = AsteriskSCF.Configuration.UDPTL.V1.UDPTLICETransportLimitsItem()
+            mapper.map('udptlicemaxcandidates', udptlICELimits, 'maxCandidates', AsteriskSCF.Configuration.UDPTL.V1.UDPTLICELimitsItemName, config.getint, 10)
+            mapper.map('udptlicemaxcalls', udptlICELimits, 'maxCalls', AsteriskSCF.Configuration.UDPTL.V1.UDPTLICELimitsItemName, config.getint, 50)
+
+            for option in config.options(section):
+                mapper.execute(group, section, option)
+                
+            mapper.finish(group)
+                
+            self.groups.append(group)
+
+
 # In order to do service locator based lookup we need to pass in a params object
 serviceLocatorParams = AsteriskSCF.Core.Discovery.V1.ServiceLocatorParams()
 serviceLocatorParams.category = AsteriskSCF.Configuration.UDPTL.V1.ConfigurationDiscoveryCategory
diff --git a/config/test_component.config b/config/test_component.config
index c4bc8a3..241a91c 100644
--- a/config/test_component.config
+++ b/config/test_component.config
@@ -60,5 +60,6 @@ UdptlStateReplicator.IceStorm.Flush.Timeout=2000
 
 ServiceDiscovery.Management.ServiceAdapter.Endpoints=tcp -p 4412
 ServiceDiscovery.Locator.ServiceAdapter.Endpoints=tcp -p 4411
+ServiceDiscovery.BackplaneAdapter.Endpoints=default
 
 LoggerAdapter.Endpoints=default
diff --git a/slice/AsteriskSCF/Configuration/UDPTL/UdptlConfigurationIf.ice b/slice/AsteriskSCF/Configuration/UDPTL/UdptlConfigurationIf.ice
index 3b4a9dd..4dd1ccd 100644
--- a/slice/AsteriskSCF/Configuration/UDPTL/UdptlConfigurationIf.ice
+++ b/slice/AsteriskSCF/Configuration/UDPTL/UdptlConfigurationIf.ice
@@ -159,6 +159,86 @@ module V1
         int fecEntries;
     };
 
+    /*
+     * Configuration group for ICE enabled UDPTL.
+     */
+    class UDPTLICEConfigurationGroup extends UdptlConfigurationGroup
+    {
+    };
+
+    /**
+     * Name that the STUN server configuration item should be inserted as.
+     */
+    const string STUNServerItemName = "stunServer";
+
+    /**
+     * Hostname for the STUN server.
+     */
+    class STUNServerItem extends UdptlConfigurationItem
+    {
+        string address;
+        int port;
+    };
+
+    /**
+     * Name that the TURN server configuration item should be inserted as.
+     */
+    const string TURNServerItemName = "turnServer";
+
+    /**
+     * Hostname for the TURN server.
+     */
+    class TURNServerItem extends UdptlConfigurationItem
+    {
+        string address;
+        int port;
+    };
+
+    /**
+     * Name that the ICE transport configuration flags item should be inserted as.
+     */
+    const string UDPTLICETransportFlagsItemName = "iceFlags";
+
+    /**
+     * Configuration item with option flags for the ICE transport.
+     */
+    class UDPTLICETransportFlagsItem extends UdptlConfigurationItem
+    {
+        /**
+         * If the configuration option is present, it's most likely
+         * because we want to enable STUN and ICE
+         */
+        bool enableICE = true;
+
+        /**
+         * Using a TURN server as a candidate should be a selectable option
+         * since a TURN server isn't always available. Setting this to true
+         * while enableICE is false has no effect.
+         */
+        bool enableTURN = true;
+    };
+
+    /**
+     * Name that ICE option items should be inserted as.
+     */
+    const string UDPTLICELimitsItemName = "iceLimits";
+
+    /**
+     * Configuration item for configurable limits for the ICE transport.
+     */
+    class UDPTLICETransportLimitsItem extends UdptlConfigurationItem
+    {
+        /**
+         * The maximum number of candidates to gather and publish.
+         */
+        int maxCandidates;
+
+        /**
+         * The maximum number of ICE negotiated flows to allow.
+         */
+        int maxCalls;
+    };
+
 }; /* module V1 */
 
 }; /* module UDPTL */
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 348e029..9f196d1 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -30,6 +30,14 @@ astscf_component_add_files(MediaTransportUDPTL PJMediaEndpoint.h)
 astscf_component_add_files(MediaTransportUDPTL PJUtil.h)
 astscf_component_add_files(MediaTransportUDPTL UDPTransport.cpp)
 astscf_component_add_files(MediaTransportUDPTL UDPTransport.h)
+astscf_component_add_files(MediaTransportUDPTL ICETransport.cpp)
+astscf_component_add_files(MediaTransportUDPTL ICETransport.h)
+astscf_component_add_files(MediaTransportUDPTL NATModule.cpp)
+astscf_component_add_files(MediaTransportUDPTL NATModule.h)
+astscf_component_add_files(MediaTransportUDPTL NATConfig.cpp)
+astscf_component_add_files(MediaTransportUDPTL NATConfig.h)
+astscf_component_add_files(MediaTransportUDPTL ICEConfiguration.cpp)
+astscf_component_add_files(MediaTransportUDPTL ICEConfiguration.h)
 astscf_component_add_slices(MediaTransportUDPTL PROJECT AsteriskSCF/Replication/UDPTL/UdptlStateReplicationIf.ice)
 astscf_component_add_slices(MediaTransportUDPTL PROJECT AsteriskSCF/Configuration/UDPTL/UdptlConfigurationIf.ice)
 astscf_component_add_boost_libraries(MediaTransportUDPTL core thread)
diff --git a/src/Configuration.h b/src/Configuration.h
index 0bed468..ef179c9 100755
--- a/src/Configuration.h
+++ b/src/Configuration.h
@@ -21,6 +21,8 @@
 #include <IceUtil/Shared.h>
 
 #include "PJLibConfiguration.h"
+#include "NATConfig.h"
+#include "ICEConfiguration.h"
 
 namespace AsteriskSCF
 {
@@ -37,6 +39,9 @@ class UDPTLConfiguration : public virtual IceUtil::Shared
 public:
     virtual ~UDPTLConfiguration() {}
 
+    virtual NATConfigPtr natConfig() const = 0;
+    virtual ICEConfigurationPtr ICEConfig() const = 0;
+
     virtual int getStartPort() = 0;
     virtual int getEndPort() = 0;
     virtual std::string getBindIPv4Address() = 0;
diff --git a/src/ICEConfiguration.cpp b/src/ICEConfiguration.cpp
new file mode 100644
index 0000000..5ed3aed
--- /dev/null
+++ b/src/ICEConfiguration.cpp
@@ -0,0 +1,32 @@
+/*
+ * Asterisk SCF -- An open-source communications framework.
+ *
+ * Copyright (C) 2010, Digium, Inc.
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk SCF project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE.txt file
+ * at the top of the source tree.
+ */
+
+#include "ICEConfiguration.h"
+#include <Ice/Properties.h>
+
+using namespace std;
+using namespace AsteriskSCF::UDPTL;
+
+ICEConfigurationPtr AsteriskSCF::UDPTL::ICEConfiguration::create(int maxCand, int maxClls)
+{
+    return ICEConfigurationPtr(new ICEConfiguration(maxCand, maxClls));
+}
+
+ICEConfiguration::ICEConfiguration(int maxCand, int maxClls) :
+    mMaxCandidates(maxCand),
+    mMaxCalls(maxClls)
+{
+}
diff --git a/src/ICEConfiguration.h b/src/ICEConfiguration.h
new file mode 100644
index 0000000..597b973
--- /dev/null
+++ b/src/ICEConfiguration.h
@@ -0,0 +1,68 @@
+/*
+ * Asterisk SCF -- An open-source communications framework.
+ *
+ * Copyright (C) 2010, Digium, Inc.
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk SCF project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE.txt file
+ * at the top of the source tree.
+ */
+
+#pragma once
+
+#include <Ice/PropertiesF.h>
+#include <string>
+#include <boost/shared_ptr.hpp>
+
+namespace AsteriskSCF
+{
+namespace UDPTL
+{
+
+class ICEConfiguration;
+typedef boost::shared_ptr<ICEConfiguration> ICEConfigurationPtr;
+
+/**
+ * ICEConfiguration is fairly minimal at the moment, but may grow in the future. The intent is to reduce code
+ * duplication when dealing with pjproject related configuration. 
+ **/
+class ICEConfiguration
+{
+public:
+
+    int maxCandidates() const
+    {
+        return mMaxCandidates;
+    }
+
+    int maxCalls() const
+    {
+        return mMaxCalls;
+    }
+
+    /**
+     * Create configuration instance!
+     **/
+    static ICEConfigurationPtr create(int maxCand, int maxClls);
+    
+private:
+    int mMaxCandidates;
+    int mMaxCalls;
+
+    ICEConfiguration(int maxCandidates, int maxCalls);
+
+    //
+    // Hidden and not implemented.
+    //
+    ICEConfiguration(const ICEConfiguration&);
+    void operator=(const ICEConfiguration&);
+};
+
+} /* End of namespace UDPTL */
+} /* End of namespace AsteriskSCF */
diff --git a/src/ICETransport.cpp b/src/ICETransport.cpp
new file mode 100644
index 0000000..7c083f2
--- /dev/null
+++ b/src/ICETransport.cpp
@@ -0,0 +1,803 @@
+/*
+ * Asterisk SCF -- An open-source communications framework.
+ *
+ * Copyright (C) 2010, Digium, Inc.
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk SCF project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE.txt file
+ * at the top of the source tree.
+ */
+
+#include "ICETransport.h"
+#include "PJUtil.h"
+
+#include <pjmedia.h>
+#include <pjlib.h>
+#include <pjnath.h>
+
+#include <AsteriskSCF/System/ExceptionsIf.h>
+#include <map>
+#include <boost/thread.hpp>
+#include <boost/thread/shared_mutex.hpp>
+
+#include <AsteriskSCF/System/NAT/NATTraversalIf.h>
+#include <Ice/Ice.h>
+#include <sstream>
+#include <AsteriskSCF/logger.h>
+#include <IceUtil/UUID.h>
+
+using namespace AsteriskSCF::UDPTL;
+using namespace AsteriskSCF::System::V1;
+using namespace AsteriskSCF::PJUtil;
+using namespace std;
+using namespace AsteriskSCF::Helpers;
+using namespace AsteriskSCF::System::Logging;
+using namespace AsteriskSCF::System::NAT::V1;
+
+namespace
+{
+Logger logger = getLoggerFactory().getLogger("AsteriskSCF.MediaUDPTL");
+}
+
+namespace 
+{
+
+class ICEAgentImpl : public InteractiveConnectionAgent
+{
+public:
+
+    ICEAgentImpl(const Ice::ObjectAdapterPtr& adapter, const Ice::Identity& id, const PJMediaEnvironmentPtr& env,
+        const PJMediaEndpointPtr& ep) :
+        mAdapter(adapter),
+        mId(id),
+        mShuttingDown(false),
+        mNATType(AsteriskSCF::System::NAT::V1::Unknown),
+        mRole(UndefinedRole),
+        mEnv(env),
+        mEndpoint(ep),
+        mTransport(0)
+    {
+    }
+
+    AgentType getAgentType(const Ice::Current&)
+    {
+        return Full;
+    }
+
+    DetectedNATType getNATType(const Ice::Current&)
+    {
+        boost::shared_lock<boost::shared_mutex> lock(mLock);
+        stateCheck();
+        return mNATType;
+    }
+
+    Role getRole(const Ice::Current&)
+    {
+        boost::shared_lock<boost::shared_mutex> lock(mLock);
+        stateCheck();
+        return mRole;
+    }
+
+    void negotiate_async(const AMD_InteractiveConnectionAgent_negotiatePtr& callback,
+        const string& hostname, Ice::Int port, const CandidateSeq& candidates,
+        const Ice::Current&)
+    {
+
+        boost::unique_lock<boost::shared_mutex> lock(mLock);
+        stateCheck();
+        if (mCurrentNegotiation)
+        {
+            pjmedia_transport_media_stop(mTransport);
+            mCurrentNegotiation->ice_exception(NegotiationInterrupted("New negotiate() request"));
+            //
+            // TODO: are we going to support cancellable negotiations.
+            //
+        }
+        mCurrentNegotiation = callback;
+
+        //
+        // So how this works is we create a remote SDP and call pjmedia_transport_start() easy peasy. (Same deal 
+        //
+        pjmedia_sdp_session* remoteSDPSession = 
+            static_cast<pjmedia_sdp_session*>(pj_pool_zalloc(mEnv->memoryPool(), sizeof(pjmedia_sdp_session)));
+
+
+        //
+        // TODO: I think the ICE transport ignores a lot of this stuff, but I'm going to add it for the time
+        // being anyways.
+        //
+
+        //
+        // Missing details, user, id, version, net type?
+        //
+        pj_strdup2(mEnv->memoryPool(), &remoteSDPSession->name, "ASCFMEDIA");
+        pj_strdup2(mEnv->memoryPool(), &remoteSDPSession->origin.user, "");
+        AddressPtr remoteHost(new Address(hostname, port));
+
+        remoteSDPSession->conn = static_cast<pjmedia_sdp_conn*>(pj_pool_zalloc(mEnv->memoryPool(), sizeof(pjmedia_sdp_conn)));
+        pj_strdup2(mEnv->memoryPool(), &remoteSDPSession->conn->net_type, "IN");
+        pj_strdup2(mEnv->memoryPool(), &remoteSDPSession->origin.net_type, "IN");
+
+        //
+        // TODO: Look at whether the members can point to the same memory without issues.
+        //
+        if (remoteHost->isIPV6())
+        {
+            pj_strdup2(mEnv->memoryPool(), &remoteSDPSession->origin.addr_type, "IP6");
+            pj_strdup2(mEnv->memoryPool(), &remoteSDPSession->conn->addr_type, "IP6");
+        }
+        else
+        {
+            pj_strdup2(mEnv->memoryPool(), &remoteSDPSession->origin.addr_type, "IP4");
+            pj_strdup2(mEnv->memoryPool(), &remoteSDPSession->conn->addr_type, "IP4");
+        }
+        pj_strdup2(mEnv->memoryPool(), &remoteSDPSession->origin.addr, remoteHost->address().c_str());
+        pj_strdup2(mEnv->memoryPool(), &remoteSDPSession->conn->addr, remoteHost->address().c_str());
+        remoteSDPSession->attr_count = 0;
+
+        //
+        // Cut n' paste from current SIP session manager... icky. TODO: sift through and see what of this
+        // can be discarded for this purpose.
+        //
+        remoteSDPSession->media_count = 1;
+        pjmedia_sdp_media* media =
+            static_cast<pjmedia_sdp_media*>(pj_pool_zalloc(mEnv->memoryPool(), sizeof(pjmedia_sdp_media)));
+        remoteSDPSession->media[0] = media;
+        pj_strdup2(mEnv->memoryPool(), &media->desc.media, "audio");
+        media->desc.port = (pj_uint16_t) port; // XXX --- this is not going to be correct here.. we don't actually have this!
+        media->desc.port_count = 1;
+        pj_strdup2(mEnv->memoryPool(), &media->desc.transport, "RTP/AVP");
+
+        // Populate the stream with codec details
+        remoteSDPSession->media[0]->desc.fmt_count = 1;
+        remoteSDPSession->media[0]->attr_count = 0;
+
+        // TODO: We should iterate over the formats to produce this instead of hardcoding
+        pjmedia_sdp_rtpmap rtpmap;
+        pjmedia_sdp_attr *attr;
+
+        // This is hardcoded value for ULAW for now
+        pj_strdup2(mEnv->memoryPool(), &media->desc.fmt[0], "0");
+        rtpmap.pt = media->desc.fmt[0];
+        rtpmap.clock_rate = 8000;
+        pj_strdup2(mEnv->memoryPool(), &rtpmap.enc_name, "PCMU");
+        rtpmap.param.slen = 0;
+        pjmedia_sdp_rtpmap_to_attr(mEnv->memoryPool(), &rtpmap, &attr);
+        remoteSDPSession->media[0]->attr[remoteSDPSession->media[0]->attr_count++] = attr;
+
+        // Might as well add sendrecv
+        attr = static_cast<pjmedia_sdp_attr*>(pj_pool_zalloc(mEnv->memoryPool(), sizeof(pjmedia_sdp_attr)));
+        pj_strdup2(mEnv->memoryPool(), &attr->name, "sendrecv");
+        remoteSDPSession->media[0]->attr[remoteSDPSession->media[0]->attr_count++] = attr;
+
+        //
+        // I was concerned about the fact that for a given SIP session, there might be multiple media
+        // streams and multiple candidates. I'm not sure that its actually too much of an issue even 
+        // if multiple media types are muxed on a single ICE negotiated flow, but there will need to be
+        // some redesign to pull in the multiple media streams associated with the session. For the moment
+        // we will operation under the premise that we are dealing with a single media stream.
+        // TODO: the SIP session gateway contains similar code, but from the offer perspective. This stuff
+        // should be refactored into a pjproject utility library.
+        //
+        //
+        pjmedia_sdp_media* currentMedia = remoteSDPSession->media[0];
+        for (CandidateSeq::const_iterator i = candidates.begin(); i != candidates.end(); ++i)
+        {
+            CandidatePtr candidate = *i;
+            ostringstream os;
+            os << "candidate:" << candidate->foundation << ' ' << candidate->componentId <<  " UDP " << 
+                candidate->priority << ' ' << candidate->mappedAddress << ' ' << candidate->mappedPort << " typ ";
+            string hostType;
+            switch (candidate->type)
+            {
+            case Host:
+                hostType = "host";
+                break;
+            case ServerReflexive:
+                hostType = "srflx";
+                break;
+            case PeerReflexive:
+                hostType = "prflx";
+                break;
+            case Relayed:
+                hostType = "relay";
+                break;
+            }
+            os << hostType;
+            if (candidate->type != Host)
+            {
+                os << " raddr " << candidate->baseAddress << " rport " << candidate->basePort;
+            }
+            string t = os.str();
+            pj_str_t candidateStr = pj_str(const_cast<char*>(t.c_str()));
+            pjmedia_sdp_attr* newAttribute = pjmedia_sdp_attr_create(mEnv->memoryPool(), 
+                "candidate", &candidateStr);
+            pjmedia_sdp_attr_add(&currentMedia->attr_count, currentMedia->attr, newAttribute);
+        }
+        pjmedia_sdp_session localSession;
+        pjmedia_transport_encode_sdp(mTransport, mEnv->memoryPool(), &localSession, 0, 0);
+        pjmedia_transport_media_start(mTransport, mEnv->memoryPool(), &localSession, remoteSDPSession, 0);
+    }
+
+    CandidateSeq getCandidates(const Ice::Current&)
+    {
+        boost::shared_lock<boost::shared_mutex> lock(mLock);
+        return mCandidates;
+    }
+
+    void onSetupComplete(pjmedia_transport* transport, pj_status_t status)
+    {
+        if (fail(status))
+        {
+            ostringstream err;
+            err << "Setup/negotiation failed with pj_status_t value of " << status;
+            throw NegotiationError(err.str());
+        }
+
+        pjmedia_transport_info info;
+        pjmedia_transport_info_init(&info);
+        pjmedia_transport_get_info(transport, &info);
+
+        pjmedia_ice_transport_info* iceInfo = 0;
+        for (unsigned i = 0; i < info.specific_info_cnt; ++i)
+        {
+            if (info.spc_info[i].type == PJMEDIA_TRANSPORT_TYPE_ICE)
+            {
+                iceInfo = (pjmedia_ice_transport_info*)(info.spc_info[i].buffer);
+            }
+        }
+
+        assert(iceInfo != 0);
+
+        //
+        // While we just did the assert, we use an if statement as well to
+        // prevent crashing in release builds.
+        //
+        if (iceInfo)
+        {
+            boost::unique_lock<boost::shared_mutex> lock(mLock);
+            if (mTransport)
+            {
+                //
+                // duplicate call.
+                //
+                return;
+            }
+            mTransport = transport;
+            if (iceInfo->role == PJ_ICE_SESS_ROLE_CONTROLLING)
+            {
+                setRole(Controlling);
+            }
+            else
+            {
+                setRole(Controlled);
+            }
+
+            pjmedia_transport_media_create(mTransport, mEnv->memoryPool(), 0, 0, 0);
+
+            //
+            // Ok, so the pjmedia ice transport won't let use get at the actual
+            // candidate structures, so what we have to do is get the SDP from
+            // the transport and convert what we find there to our Ice structures.
+            //
+            pjmedia_sdp_session* sdpSession;
+            unsigned streamCount = 1; // The 1 doesn't matter, this is just to initialize the basic structure.
+            pjmedia_endpt_create_sdp(mEndpoint->endpoint(), mEnv->memoryPool(), streamCount, &info.sock_info, &sdpSession);
+            pjmedia_transport_encode_sdp(mTransport, mEnv->memoryPool(), sdpSession, 0, 0);
+            for (size_t i = 0; i < sdpSession->media_count; ++i)
+            {
+                const string candidateName("candidate");
+                pjmedia_sdp_media* media = sdpSession->media[i];
+                ostringstream errorMessage;
+                for (size_t j = 0; j < media->attr_count; ++j)
+                {
+                    pjmedia_sdp_attr* attr = media->attr[j];
+                    if (string(attr->name.ptr, attr->name.slen) == candidateName)
+                    {
+                        //
+                        // Now we get to parse a candidate string!
+                        //
+                        string value(attr->value.ptr, attr->value.slen);
+                        istringstream is(value);
+                        string foundation;
+                        if (!(is >> foundation))
+                        {
+                            errorMessage << "Unable to parse ICE candidate value (foundation) : " << value;
+                            break;
+                        }
+
+                        int componentId;
+                        if (!(is >> componentId))
+                        {
+                            errorMessage << "Unable to parse ICE candidate value (component id) : " << value;
+                            break;
+                        }
+
+                        //
+                        // We don't care about the transport right now.. we are assuming UDP.
+                        //
+                        string transportDummy;
+                        if (!(is >> transportDummy))
+                        {
+                            errorMessage << "Unable to parse ICE candidate value (transport) : " << value;
+                            break;
+                        }
+
+                        int priority;
+                        if (!(is >> priority))
+                        {
+                            errorMessage << "Unable to parse ICE candidate value (priority) : " << value;
+                            break;
+                        }
+
+                        string connectionAddress;
+                        if (!(is >> connectionAddress))
+                        {
+                            errorMessage << "Unable to parse ICE candidate value (connection address) : " << value;
+                            break;
+                        }
+
+                        unsigned port;
+                        if (!(is >> port))
+                        {
+                            errorMessage << "Unable to parse ICE candidate value (connection port) : " << value;
+                            break;
+                        }
+
+                        string candidateTypePrefix;
+                        if (!(is >> candidateTypePrefix))
+                        {
+                            errorMessage << "Unable to parse ICE candidate constant (typ) : " << value;
+                            break;
+                        }
+
+                        string candidateType;
+                        if (!(is >> candidateType))
+                        {
+                            errorMessage << "Unable to parse ICE candidate value (candidate type) : " << value;
+                            break;
+                        }
+
+
+                        CandidatePtr candidateObj = new Candidate;
+                        candidateObj->sessionId = IceUtil::generateUUID(); // this should be the object id.
+                        candidateObj->componentId = 1; // At least until we implement RTCP.
+                        candidateObj->priority = priority;
+                        candidateObj->baseAddress = connectionAddress;
+                        candidateObj->basePort = port;
+                        candidateObj->transport = UDP;
+
+                        if (candidateType == "host")
+                        {
+                            candidateObj->type = Host;
+                        }
+                        else if (candidateType == "srflx")
+                        {
+                            candidateObj->type = ServerReflexive;
+                        }
+                        else if (candidateType == "prflx")
+                        {
+                            candidateObj->type = PeerReflexive;
+                        }
+                        else if (candidateType == "relay")
+                        {
+                            candidateObj->type = Relayed;
+                        }
+                        else
+                        {
+                            errorMessage << "Unable to determine the candidate type, skipping : " << value;
+                        }
+
+                        if (candidateType != "host")
+                        {
+                            string dummy;
+                            if (!(is >> dummy))
+                            {
+                                errorMessage << "Unable to parse ICE candidate constant (raddr) : " << value;
+                                break;
+                            }
+
+                            string baseAddress;
+                            if (!(is >> baseAddress))
+                            {
+                                errorMessage << "Unable to parse ICE candidate value (rel-addr) : " << value;
+                                break;
+                            }
+
+                            if (!(is >> dummy))
+                            {
+                                errorMessage << "Unable to parse ICE candidate constant (rport) : " << value;
+                                break;
+                            }
+
+                            unsigned basePort;
+                            if (!(is >> basePort))
+                            {
+                                errorMessage << "Unable to parse ICE candidate value (rel-port) : " << value;
+                                break;
+                            }
+                            candidateObj->mappedAddress = candidateObj->baseAddress;
+                            candidateObj->mappedPort = candidateObj->basePort;
+                            candidateObj->baseAddress = baseAddress;
+                            candidateObj->basePort = basePort; 
+                        }
+                        else
+                        {
+                            candidateObj->mappedAddress = "";
+                            candidateObj->mappedPort = 0;
+                        }
+                        //
+                        // And we ignore the rest.
+                        //
+                        mCandidates.push_back(candidateObj);
+                    }
+                    string err(errorMessage.str());
+                    if (!err.empty())
+                    {
+                        throw invalid_argument(err);
+                    }
+                }
+            }
+            if (mCurrentNegotiation)
+            {
+                if (mCandidates.size() == 0)
+                {
+                    logger(Error) << "No candidates after negotiation, looks like fail";
+                    mCurrentNegotiation->ice_exception(NoValidCandidates());
+                    throw invalid_argument("no valid candidates, did negotiation fail?");
+                }
+                mCurrentNegotiation->ice_response(mCandidates[0]);
+                mCurrentNegotiation = 0;
+                if (mCandidates.size() > 1)
+                {
+                    logger(Warning) << "More than one candidate after negotiation!";
+                }
+            }
+        }
+    }
+
+    void shutdown()
+    {
+        {
+            boost::unique_lock<boost::shared_mutex> lock(mLock);
+            if (mShuttingDown)
+            {
+                return;
+            }
+            mShuttingDown = true;
+            if (mCurrentNegotiation)
+            {
+                pjmedia_transport_media_stop(mTransport);
+                mCurrentNegotiation->ice_exception(NegotiationInterrupted("Shutting down."));
+            }
+        }
+        mAdapter->removeFacet(mId, "ICEAgent");
+    }
+
+    void setNATType(DetectedNATType natType)
+    {
+        boost::unique_lock<boost::shared_mutex> lock(mLock);
+        mNATType = natType;
+    }
+
+    void setRole(Role role)
+    {
+        mRole = role;
+    }
+
+private:
+    boost::shared_mutex mLock;
+    Ice::ObjectAdapterPtr mAdapter;
+    Ice::Identity mId;
+    bool mShuttingDown;
+    DetectedNATType mNATType;
+    Role mRole;
+    CandidateSeq mCandidates;
+    PJMediaEnvironmentPtr mEnv;
+    PJMediaEndpointPtr mEndpoint;
+    pjmedia_transport* mTransport;
+    AMD_InteractiveConnectionAgent_negotiatePtr mCurrentNegotiation;
+
+    void stateCheck()
+    {
+        if (mShuttingDown)
+        {
+            throw Ice::ObjectNotExistException(__FILE__, __LINE__);
+        }
+    }
+};
+
+typedef IceUtil::Handle<ICEAgentImpl> ICEAgentImplPtr;
+
+class ICECallbackAdapter
+{
+public:
+    static void addEntry(pjmedia_transport* transport, const ICETransportPtr& callback);
+    static void addAgent(pjmedia_transport* transport, const ICEAgentImplPtr& agent);
+    static void removeEntry(pjmedia_transport* transport);
+    static void onICEComplete(pjmedia_transport* transport, pj_ice_strans_op operation, pj_status_t status);
+
+    struct CallbackRecord
+    {
+        bool connected;
+        ICETransportPtr transport;
+        ICEAgentImplPtr agent;
+
+        CallbackRecord() :
+            connected(false)
+        {
+        }
+    };
+    typedef std::map<unsigned long long, CallbackRecord> TransportMap;
+
+private:
+    static TransportMap mTransportMap;
+    static boost::shared_mutex mLock;
+};
+
+//
+// Static member initializations.
+//
+ICECallbackAdapter::TransportMap ICECallbackAdapter::mTransportMap;
+boost::shared_mutex ICECallbackAdapter::mLock;
+
+//
+// For some reason the ICE media transport doesn't have the concept of associating user data with a transport, so we
+// have to map it "out of band". The problem is, there is a race condition in that the ICE completion callack could be
+// invoked before we get a chance to add the transport.  The solution to that is to allow an entry to be created when
+// the ICE completion callback arrives and there isn't a table entry. When the addEntry runs, it will see the entry and
+// simply update the appropriate field.
+// 
+void ICECallbackAdapter::addEntry(pjmedia_transport* transport, const ICETransportPtr& callback)
+{
+    bool alreadyKnown = false;
+    {
+        boost::unique_lock<boost::shared_mutex> lock(mLock);
+        TransportMap::iterator i = mTransportMap.find(reinterpret_cast<unsigned long long>(transport));
+        if (i != mTransportMap.end())
+        {
+            i->second.transport = callback;
+            alreadyKnown = true;
+            callback->onSetupComplete(transport, PJ_SUCCESS);
+
+            if (i->second.agent)
+            {
+                i->second.agent->onSetupComplete(transport, PJ_SUCCESS);
+            }
+        }
+        else
+        {
+            CallbackRecord r;
+            r.connected = false;
+            r.transport = callback;
+            mTransportMap.insert(make_pair(reinterpret_cast<unsigned long long>(transport), r));
+        }
+    }
+}
+
+void ICECallbackAdapter::addAgent(pjmedia_transport* transport, const ICEAgentImplPtr& agent)
+{
+    boost::unique_lock<boost::shared_mutex> lock(mLock);
+    TransportMap::iterator i = mTransportMap.find(reinterpret_cast<unsigned long long>(transport));
+
+    if (i != mTransportMap.end())
+    {
+        i->second.agent = agent;
+        if (i->second.connected == true && i->second.transport.get() != 0)
+        {
+            try
+            {
+                agent->onSetupComplete(transport, PJ_SUCCESS);
+            }
+            catch(const invalid_argument& ex)
+            {
+                logger(Error) << "Agent added to map but the setup seems incorrect: " << ex.what();
+            }
+        }
+    }
+    //
+    // The entry really should always be found, but there could be a race
+    // condition if things are shutting down before everything was cleanly
+    // activated.
+    //
+}
+
+void ICECallbackAdapter::removeEntry(pjmedia_transport* t)
+{
+    boost::unique_lock<boost::shared_mutex> lock(mLock);
+    TransportMap::iterator i = mTransportMap.find(reinterpret_cast<unsigned long long>(t));
+    if (i != mTransportMap.end())
+    {
+        if (i->second.agent)
+        {
+            i->second.agent->shutdown();
+        }
+        mTransportMap.erase(i);
+    }
+}
+
+void ICECallbackAdapter::onICEComplete(pjmedia_transport* transport, pj_ice_strans_op operation, pj_status_t status)
+{
+    //
+    // AFAICT, only PJ_ICE_STRANS_OP_NEGOTIATION should get here.
+    // 
+    switch (operation)
+    {
+        case PJ_ICE_STRANS_OP_INIT:
+            //
+            // Initialization is complete. At this point we know what candidates we can offer.
+            //
+            {
+                boost::unique_lock<boost::shared_mutex> lock(mLock);
+                TransportMap::iterator i = mTransportMap.find(reinterpret_cast<unsigned long long>(transport));
+                if (i == mTransportMap.end())
+                {
+                    CallbackRecord r;
+                    r.connected = success(status);
+                    mTransportMap.insert(make_pair(reinterpret_cast<unsigned long long>(transport), r));
+                }
+                else
+                {
+                    i->second.connected = success(status);
+                    i->second.transport->onSetupComplete(transport, status);
+                    if (i->second.agent)
+                    {
+                        i->second.agent->onSetupComplete(transport, status);
+                    }
+                }
+            }
+            break;
+        case PJ_ICE_STRANS_OP_NEGOTIATION:
+            //
+            // Negotiation is complete.
+            //
+            {
+                boost::unique_lock<boost::shared_mutex> lock(mLock);
+                TransportMap::iterator i = mTransportMap.find(reinterpret_cast<unsigned long long>(transport));
+                if (i == mTransportMap.end())
+                {
+                    assert(false);
+                    //
+                    // This is a problem, it is very unlikely that this should
+                    // happen when things are working as they should.
+                    //
+                }
+                else
+                {
+                    //
+                    // We've negotiated a valid flow with on this leg. We should query every
+                    // detail of relevance from the current media session.
+                    //
+                    if (i->second.agent)
+                    {
+                        i->second.agent->onSetupComplete(transport, status);
+                    }
+                }
+            }
+            break;
+        case PJ_ICE_STRANS_OP_KEEP_ALIVE:
+            //
+            // Keep alive has successfully completed. FWICT this should not get here.
+            // 
+            break;
+    };
+}
+
+}
+
+ICETransport::~ICETransport()
+{
+    //
+    // TODO : cleanup ICE transport, the transport itself is closed by the parent class.
+    // 
+    ICECallbackAdapter::removeEntry(mTransport);
+}
+
+void ICETransport::onSetupComplete(pjmedia_transport* transport, int status)
+{
+    if (fail(status))
+    {
+        //
+        // TODO!
+        //
+        return;
+    }
+
+    pjmedia_transport_info info;
+    pjmedia_transport_info_init(&info);
+    pjmedia_transport_get_info(transport, &info);
+
+    pjmedia_ice_transport_info* iceInfo = 0;
+    for (unsigned i = 0; i < info.specific_info_cnt; ++i)
+    {
+        if (info.spc_info[i].type == PJMEDIA_TRANSPORT_TYPE_ICE)
+        {
+            iceInfo = (pjmedia_ice_transport_info*)(info.spc_info[i].buffer);
+        }
+    }
+
+    if (iceInfo != 0 && iceInfo->role == PJ_ICE_SESS_ROLE_CONTROLLING)
+    {
+        if (mLastKnownAddr && pj_sockaddr_cmp(&info.sock_info.rtp_addr_name, mLastKnownAddr.get()))
+        {
+            //
+            // Address has changed! We need to let Session listeners know!
+            // TODO! 
+            //
+            pj_memcpy(mLastKnownAddr.get(), &info.sock_info.rtp_addr_name, sizeof(pj_sockaddr));
+        }
+    }
+    boost::lock_guard<boost::mutex> lock(mLock);
+    mLocalAddress = fromInfo(info);
+    mMonitor.notify_one();
+}
+
+AddressPtr ICETransport::localAddress() 
+{
+    boost::unique_lock<boost::mutex> lock(mLock);
+    if (mLocalAddress)
+    {
+        return mLocalAddress;
+    }
+    for (size_t i = 0; i < 5 && !mLocalAddress; ++i)
+    {
+        mMonitor.wait(lock);
+    }
+    return mLocalAddress;
+}
+
+AddressPtr ICETransport::remoteAddress() 
+{
+    boost::unique_lock<boost::mutex> lock(mLock);
+    return mRemoteAddress;
+}
+
+void ICETransport::addFacets(const Ice::ObjectAdapterPtr& adapter, const Ice::Identity& id)
+{
+    ICEAgentImplPtr agent = new ICEAgentImpl(adapter, id, mConfig, mEndpoint);
+    ICECallbackAdapter::addAgent(mTransport, agent);
+    adapter->addFacet(agent, id, InteractiveConnectionAgentFacetName);
+}
+
+ICETransportPtr ICETransport::create(const PJMediaEndpointPtr& ep, const PJMediaEnvironmentPtr& config)
+{
+    ICETransportPtr transport(new ICETransport(ep, config));
+    transport->start();
+
+    //
+    // TODO: I need to temporarily insert a wait-until-fail loop for the ICE steps so the transport information
+    // is available when the transport create call returns. The source/sink's won't have valid information until then.
+    //
+    return transport;
+}
+
+ICETransport::ICETransport(const PJMediaEndpointPtr& ep, const PJMediaEnvironmentPtr& configObject) :
+    PJMediaTransport(0),
+    mEndpoint(ep),
+    mConfig(configObject)
+{
+}
+
+void ICETransport::start()
+{
+    pjmedia_transport* t = 0;
+    PJICECallbackPtr callback(new pjmedia_ice_cb);
+    callback->on_ice_complete = &ICECallbackAdapter::onICEComplete;
+    NATModulePtr natModule = NATModule::create(mConfig, mEndpoint);
+    pj_status_t result = pjmedia_ice_create(mEndpoint->endpoint(), "ASCF_ICE_MEDIA", 1, 
+        natModule->configuration(), callback.get(), &t);
+    if (fail(result))
+    {
+        throw InternalInitializationException("Unable to create new ICE media transport");
+    }
+    ICECallbackAdapter::addEntry(t, shared_from_this());
+    mTransport = t;
+    mCallback = callback;
+    mNATModule = natModule;
+}
diff --git a/src/ICETransport.h b/src/ICETransport.h
new file mode 100644
index 0000000..e5e8772
--- /dev/null
+++ b/src/ICETransport.h
@@ -0,0 +1,89 @@
+/*
+ * Asterisk SCF -- An open-source communications framework.
+ *
+ * Copyright (C) 2010, Digium, Inc.
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk SCF project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE.txt file
+ * at the top of the source tree.
+ */
+
+#pragma once
+
+#include "PJMediaTransport.h"
+#include "PJMediaEndpoint.h"
+#include "PJMediaEnvironment.h"
+#include <Ice/PropertiesF.h>
+#include <boost/shared_ptr.hpp>
+#include <boost/enable_shared_from_this.hpp>
+#include "NATModule.h"
+
+//
+// Forward declarations.
+// 
+struct pjmedia_transport;
+union pj_sockaddr;
+struct pjmedia_ice_cb;
+
+namespace AsteriskSCF
+{
+namespace UDPTL
+{
+
+class ICETransport;
+typedef boost::shared_ptr<ICETransport> ICETransportPtr;
+typedef boost::shared_ptr<pjmedia_ice_cb> PJICECallbackPtr;
+typedef boost::shared_ptr<pj_sockaddr> PJSockAddrPtr;
+
+class ICETransport : public boost::enable_shared_from_this<ICETransport>,  public PJMediaTransport
+{
+public:
+
+    ~ICETransport();
+    void onSetupComplete(pjmedia_transport* transport, int status);
+
+    //
+    // Overrides of PJMediaTransport
+    //
+    AsteriskSCF::Helpers::AddressPtr localAddress();
+    AsteriskSCF::Helpers::AddressPtr remoteAddress();
+    void addFacets(const Ice::ObjectAdapterPtr& adapter, const Ice::Identity& id);
+
+    /**
+     * The Microsoft VS 2010 C++ compiler doesn't like the forward declaration of ICETransport 
+     * before the enable_shared_from_this<> base class/template instantiation.
+     **/
+    static ICETransportPtr
+        create(const PJMediaEndpointPtr& ep, const PJMediaEnvironmentPtr& configObject);
+
+private:
+    boost::mutex mLock;
+    boost::condition_variable mMonitor;
+    AsteriskSCF::Helpers::AddressPtr mLocalAddress;
+    AsteriskSCF::Helpers::AddressPtr mRemoteAddress;
+    PJICECallbackPtr mCallback;
+    PJSockAddrPtr mLastKnownAddr;
+    NATModulePtr mNATModule;
+    PJMediaEndpointPtr mEndpoint;
+    PJMediaEnvironmentPtr mConfig;
+
+    ICETransport(const PJMediaEndpointPtr& ep, const PJMediaEnvironmentPtr& configObject);
+
+    void start();
+
+    //
+    // Hidden and unimplemented.
+    //
+    ICETransport(const ICETransport&);
+    void operator=(const ICETransport&);
+};
+
+
+} /* End of namespace UDPTL */
+} /* End of namespace AsteriskSCF */
diff --git a/src/NATConfig.cpp b/src/NATConfig.cpp
new file mode 100644
index 0000000..5307156
--- /dev/null
+++ b/src/NATConfig.cpp
@@ -0,0 +1,50 @@
+/*
+ * Asterisk SCF -- An open-source communications framework.
+ *
+ * Copyright (C) 2010, Digium, Inc.
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk SCF project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE.txt file
+ * at the top of the source tree.
+ */
+
+#include "NATConfig.h"
+
+#include <Ice/Properties.h>
+#include <AsteriskSCF/System/ExceptionsIf.h>
+#include <pjnath.h>
+#include <AsteriskSCF/logger.h>
+
+using namespace std;
+using namespace AsteriskSCF::Helpers;
+using namespace AsteriskSCF::System::V1;
+using namespace AsteriskSCF::UDPTL;
+using namespace AsteriskSCF::System::Logging;
+
+namespace
+{
+Logger logger = getLoggerFactory().getLogger("AsteriskSCF.MediaUDPTL");
+}
+
+NATConfigPtr NATConfig::create(const AsteriskSCF::Helpers::AddressPtr& stunSrv, bool enableSTUN,
+        const AsteriskSCF::Helpers::AddressPtr& turnSrv, bool enableTURN)
+{
+    return NATConfigPtr(new NATConfig(stunSrv, turnSrv, enableSTUN, enableTURN));
+}
+
+NATConfig::NATConfig(const AddressPtr& stun, const AddressPtr& turn,
+        bool enableSTUN, bool enableTURN) :
+    mSTUNServer(stun),
+    mTURNServer(turn),
+    mSTUNEnabled(enableSTUN),
+    mTURNEnabled(enableTURN)
+{
+    std::cerr << "creating a NATConfig object with " << (mSTUNServer ? mSTUNServer->toString() : "<no stun>") << " and " <<
+        (mTURNServer ? mTURNServer->toString() : "<no turn>") << std::endl;
+}
diff --git a/src/NATConfig.h b/src/NATConfig.h
new file mode 100644
index 0000000..781dec6
--- /dev/null
+++ b/src/NATConfig.h
@@ -0,0 +1,76 @@
+/*
+ * Asterisk SCF -- An open-source communications framework.
+ *
+ * Copyright (C) 2010, Digium, Inc.
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk SCF project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE.txt file
+ * at the top of the source tree.
+ */
+
+#pragma once
+
+#include <AsteriskSCF/Helpers/Network.h>
+#include <Ice/PropertiesF.h>
+#include <boost/shared_ptr.hpp>
+#include <string>
+
+namespace AsteriskSCF
+{
+namespace UDPTL
+{
+
+class NATConfig;
+typedef boost::shared_ptr<NATConfig> NATConfigPtr;
+
+class NATConfig
+{
+public:
+
+    AsteriskSCF::Helpers::AddressPtr stunServer() const
+    {
+        return mSTUNServer;
+    }
+    
+    bool isSTUNEnabled() const
+    {
+        return mSTUNEnabled;
+    }
+    
+    AsteriskSCF::Helpers::AddressPtr turnServer() const
+    {
+        return mTURNServer;
+    }
+    
+    bool isTURNEnabled() const
+    {
+        return mTURNEnabled;
+    }
+    
+    static NATConfigPtr create(const AsteriskSCF::Helpers::AddressPtr& stunSrv, bool enableSTUN,
+            const AsteriskSCF::Helpers::AddressPtr& turnSrv, bool enableTURN);
+private:
+    AsteriskSCF::Helpers::AddressPtr mSTUNServer;
+    AsteriskSCF::Helpers::AddressPtr mTURNServer;
+    bool mSTUNEnabled;
+    bool mTURNEnabled;
+
+    NATConfig(const AsteriskSCF::Helpers::AddressPtr& stunServer,
+            const AsteriskSCF::Helpers::AddressPtr& turnServer,
+            bool stunEnabled,
+            bool turnEnabled);
+
+    //
+    // Hidden and unimplemented.
+    //
+    NATConfig(const NATConfig&);
+    void operator=(const NATConfig&);
+};
+} /* End of namespace UDPTL */
+} /* End of namespace AsteriskSCF */
diff --git a/src/NATModule.cpp b/src/NATModule.cpp
new file mode 100644
index 0000000..80e6583
--- /dev/null
+++ b/src/NATModule.cpp
@@ -0,0 +1,84 @@
+/*
+ * Asterisk SCF -- An open-source communications framework.
+ *
+ * Copyright (C) 2010, Digium, Inc.
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk SCF project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE.txt file
+ * at the top of the source tree.
+ */
+
+#include "NATModule.h"
+#include <pjmedia.h>
+#include <pjnath.h>
+#include "PJUtil.h"
+#include <AsteriskSCF/System/ExceptionsIf.h>
+
+using namespace AsteriskSCF::UDPTL;
+using namespace AsteriskSCF::System::V1;
+using namespace AsteriskSCF::PJUtil;
+
+NATModulePtr AsteriskSCF::UDPTL::NATModule::create(const PJMediaEnvironmentPtr& env,
+    const PJMediaEndpointPtr& endpoint)
+{
+    boost::shared_ptr<pj_ice_strans_cfg> transcfg(new pj_ice_strans_cfg);
+    pj_ice_strans_cfg_default(transcfg.get());
+    pj_stun_config_init(&transcfg->stun_cfg, env->poolFactory(), 0,
+            pjmedia_endpt_get_ioqueue(endpoint->endpoint()), 0);
+    pj_status_t result = pj_timer_heap_create(env->memoryPool(), env->libConfig()->timerHeapSize(),
+            &transcfg->stun_cfg.timer_heap);
+    if (fail(result))
+    {
+        throw InternalInitializationException("Unable to initialize tier heap.");
+    }
+
+    pj_strdup2(env->memoryPool(), &transcfg->stun.server, env->natConfig()->stunServer()->hostname().c_str());
+    transcfg->stun.port = static_cast<pj_uint16_t>(env->natConfig()->stunServer()->port());
+    ICEConfigurationPtr iceConfig = env->ICEConfig();
+    if (iceConfig)
+    {
+        transcfg->stun.max_host_cands = env->ICEConfig()->maxCandidates();
+    }
+    else
+    {
+        transcfg->stun.max_host_cands = 5; // XX arbitrary.
+    }
+    if (env->natConfig()->isTURNEnabled())
+    {
+        if (env->natConfig()->turnServer())
+        {
+            pj_strdup2(env->memoryPool(), &transcfg->turn.server, env->natConfig()->turnServer()->hostname().c_str());
+            transcfg->turn.port = static_cast<pj_uint16_t>(env->natConfig()->turnServer()->port());
+        }
+    }
+
+    NATModulePtr moduleObj(new NATModule(transcfg));
+    moduleObj->startImpl();
+    return moduleObj;
+}
+
+NATModule::NATModule(const boost::shared_ptr<pj_ice_strans_cfg>& transConfig) :
+    mTransactionConfig(transConfig)
+{
+}
+
+NATModule::~NATModule()
+{
+    destroyImpl();
+}
+
+void NATModule::destroyImpl()
+{
+    pj_timer_heap_destroy(mTransactionConfig->stun_cfg.timer_heap);
+}
+
+void NATModule::startImpl()
+{
+}
+
diff --git a/src/NATModule.h b/src/NATModule.h
new file mode 100644
index 0000000..215b6e3
--- /dev/null
+++ b/src/NATModule.h
@@ -0,0 +1,63 @@
+/*
+ * Asterisk SCF -- An open-source communications framework.
+ *
+ * Copyright (C) 2010, Digium, Inc.
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk SCF project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE.txt file
+ * at the top of the source tree.
+ */
+
+#pragma once
+
+#include "PJMediaEnvironment.h"
+#include "PJMediaEndpoint.h"
+#include <boost/shared_ptr.hpp>
+
+//
+// Forward declarations.
+//
+struct pj_ice_strans_cfg;
+
+namespace AsteriskSCF
+{
+namespace UDPTL
+{
+class NATModule;
+typedef boost::shared_ptr<NATModule> NATModulePtr;
+
+class NATModule
+{
+public:
+    ~NATModule();
+
+    pj_ice_strans_cfg* configuration()
+    {
+        return mTransactionConfig.get();
+    }
+
+    static NATModulePtr create(const PJMediaEnvironmentPtr& environ, const PJMediaEndpointPtr& endpoint);
+
+private:
+    boost::shared_ptr<pj_ice_strans_cfg> mTransactionConfig;
+
+    NATModule(const boost::shared_ptr<pj_ice_strans_cfg>& transactionConfig);
+
+    void destroyImpl();
+    void startImpl();
+
+    //
+    // Hidden and unimplemented.
+    //
+    NATModule(const NATModule&);
+    void operator=(const NATModule&);
+};
+
+} /* End of namespace UDPTL */
+} /* End of namespace AsteriskSCF */
diff --git a/src/PJMediaEnvironment.h b/src/PJMediaEnvironment.h
index b2a404d..be342a7 100644
--- a/src/PJMediaEnvironment.h
+++ b/src/PJMediaEnvironment.h
@@ -68,6 +68,22 @@ public:
     }
 
     /**
+     * Get NAT related configuration object.
+     */
+    NATConfigPtr natConfig() const
+    {
+        return mConfiguration->natConfig();
+    }
+
+    /**
+     * Get ICE transport configuration object.
+     */
+    ICEConfigurationPtr ICEConfig() const
+    {
+        return mConfiguration->ICEConfig();
+    }
+
+    /**
      * Get our library instance's main pool factory. As this function does not return a reference counted pointer, its
      * value should not be cached at all. Its validity is directly related to the lifetime of the PJMediaEnvironment
      * object.
diff --git a/src/UDPTLConfiguration.cpp b/src/UDPTLConfiguration.cpp
index dee3678..4fe9af5 100644
--- a/src/UDPTLConfiguration.cpp
+++ b/src/UDPTLConfiguration.cpp
@@ -64,6 +64,31 @@ public:
 
     ConfigurationServicePrx activate(const Ice::ObjectAdapterPtr& objectAdapter, const string& id);
 
+    NATConfigPtr natConfig() const
+    {
+        return mNATConfig;
+    }
+
+    ICEConfigurationPtr ICEConfig() const
+    {
+        return mICEConfig;
+    }
+
+    void replaceConfig(const ICEConfigurationPtr& newConfig)
+    {
+        mICEConfig = newConfig;
+    }
+
+    void replaceConfig(const NATConfigPtr& newConfig)
+    {
+        mNATConfig = newConfig;
+    }
+
+    UDPTLICEConfigurationGroupPtr getICEConfigurationGroup()
+    {
+        return mICEConfiguration;
+    }
+
     UdptlGeneralGroupPtr getGeneralGroup()
     {
         return mGeneralGroup;
@@ -83,12 +108,22 @@ public:
         }
     }
 
+    void replaceGroup(const UDPTLICEConfigurationGroupPtr& group)
+    {
+        mICEConfiguration = group;
+    }
+
 private:
     /**
      * General UDPTL configuration
      */
     UdptlGeneralGroupPtr mGeneralGroup;
 
+    UDPTLICEConfigurationGroupPtr mICEConfiguration;
+
+    ICEConfigurationPtr mICEConfig;
+    NATConfigPtr mNATConfig;
+
     /**
      * Shared mutex lock which protects the configuration
      */
@@ -148,6 +183,20 @@ ConfigurationGroupSeq ConfigurationServiceServant::getConfiguration(
 
             mGroups.push_back(returnedGroup);
         };
+
+        void visitUDPTLICEConfigurationGroup(const UDPTLICEConfigurationGroupPtr& group)
+        {
+            UDPTLICEConfigurationGroupPtr currentGroup = mImpl->getICEConfigurationGroup();
+
+            if (!currentGroup)
+            {
+                return;
+            }
+            UDPTLICEConfigurationGroupPtr returnedGroup = new UDPTLICEConfigurationGroup;
+            insertRequestedConfigurationItems(group->configurationItems, currentGroup->configurationItems,
+                                              returnedGroup->configurationItems);
+            mGroups.push_back(returnedGroup);
+        }
         
         ConfigurationServiceServantPtr mImpl;
         ConfigurationGroupSeq& mGroups;
@@ -184,6 +233,15 @@ ConfigurationGroupSeq ConfigurationServiceServant::getConfigurationAll(
                 mGroups.push_back(g);
             }
         };
+
+        void visitICEConfigurationGroup(const UDPTLICEConfigurationGroupPtr&)
+        {
+            UDPTLICEConfigurationGroupPtr g = mImpl->getICEConfigurationGroup();
+            if (g)
+            {
+                mGroups.push_back(g);
+            }
+        }
         
         ConfigurationServiceServantPtr mImpl;
         ConfigurationGroupSeq& mGroups;
@@ -212,6 +270,11 @@ ConfigurationGroupSeq ConfigurationServiceServant::getConfigurationGroups(const
         groups.push_back(new UdptlGeneralGroup);
     }
 
+    if (mICEConfiguration)
+    {
+        groups.push_back(new UDPTLICEConfigurationGroup);
+    }
+
     return groups;
 }
 
@@ -285,6 +348,111 @@ void ConfigurationServiceServant::setConfiguration(const ConfigurationGroupSeq&
             mImpl->replaceGroup(g);
         }
 
+        void visitUDPTLICEConfigurationGroup(const UDPTLICEConfigurationGroupPtr& group)
+        {
+            class Visitor : public UdptlConfigurationItemVisitor
+            {
+            public:
+                Visitor(const ConfigurationServiceServantPtr& configObject) :
+                    mImpl(configObject),
+                    mCreateUDPTLICEConfig(false),
+                    mCreateNATConfig(false),
+                    mEnableSTUN(false),
+                    mEnableTURN(false),
+                    mMaxCandidates(0),          // XXX- set some kind of hard code or slice defined default?
+                    mMaxCalls(0)
+                    {
+                    }
+
+                ~Visitor()
+                {
+                    if (mCreateNATConfig)
+                    {
+                        mImpl->replaceConfig(NATConfig::create(mStunHost, mEnableSTUN, mTurnHost, mEnableTURN));
+                    }
+                    if (mCreateUDPTLICEConfig)
+                    {
+                        mImpl->replaceConfig(ICEConfiguration::create(mMaxCandidates, mMaxCalls));
+                    }
+                }
+
+
+                void visitSTUNServerItem(const STUNServerItemPtr& item)
+                {
+                    if (item)
+                    {
+                        mCreateNATConfig = true;
+                        mStunHost = AsteriskSCF::Helpers::AddressPtr(new AsteriskSCF::Helpers::Address(item->address, item->port));
+                    }
+                }
+
+                void visitTURNServerItem(const TURNServerItemPtr& item)
+                {
+                    if (item)
+                    {
+                        mCreateNATConfig = true;
+                        mTurnHost = AsteriskSCF::Helpers::AddressPtr(new AsteriskSCF::Helpers::Address(item->address, item->port));
+                    }
+                }
+
+                void visitUDPTLICETransportFlagsItem(const UDPTLICETransportFlagsItemPtr& item)
+                {
+                    if (item)
+                    {
+                        mCreateNATConfig = true;
+                        mEnableTURN = item->enableTURN;
+                        mEnableSTUN = item->enableICE;
+                    }
+                }
+
+                void visitUDPTLICETransportLimitsItem(const UDPTLICETransportLimitsItemPtr& item)
+                {
+                    if (item)
+                    {
+                        mCreateUDPTLICEConfig = true;
+                        mMaxCalls = item->maxCalls;
+                        mMaxCandidates = item->maxCandidates;
+                    }
+                }
+
+                private:
+
+                ConfigurationServiceServantPtr mImpl;
+
+                bool mCreateUDPTLICEConfig;
+                bool mCreateNATConfig;
+
+                AsteriskSCF::Helpers::AddressPtr mStunHost;
+                AsteriskSCF::Helpers::AddressPtr mTurnHost;
+                bool mEnableSTUN;
+                bool mEnableTURN;
+                int mMaxCandidates;
+                int mMaxCalls;
+            }; // end of Visitor class definition.
+
+            UDPTLICEConfigurationGroupPtr g = mImpl->getICEConfigurationGroup();
+            if (!g)
+            {
+                g = new UDPTLICEConfigurationGroup;
+            }
+            else
+            {
+                performSerialCheck(group->configurationItems, g->configurationItems, group);
+            }
+
+            UdptlConfigurationItemVisitorPtr v(new Visitor(mImpl));
+
+            for (ConfigurationItemDict::const_iterator item = group->configurationItems.begin();
+                 item != group->configurationItems.end();
+                 ++item)
+            {
+                g->configurationItems.erase(item->first);
+                g->configurationItems.insert((*item));
+                item->second->visit(v);
+            }
+            mImpl->replaceGroup(g);
+        }
+
         ConfigurationServiceServantPtr mImpl;
     };
     
@@ -336,6 +504,107 @@ void ConfigurationServiceServant::removeConfigurationItems(
                 removeItems(0, group->configurationItems, g->configurationItems);
             }
         }
+
+        void visitUDPTLICEConfigurationGroup(const UDPTLICEConfigurationGroupPtr& group)
+        {
+            class Visitor : public UdptlConfigurationItemVisitor
+            {
+            public:
+                Visitor(const ConfigurationServiceServantPtr& impl) :
+                    mImpl(impl),
+                    mRemoveSTUNServer(false),
+                    mRemoveTURNServer(false),
+                    mDisable(false),
+                    mResetICEConfig(false)
+                    {
+                    }
+
+                ~Visitor()
+                {
+                    if (mDisable)
+                    {
+                    }
+
+                    NATConfigPtr natCfg = mImpl->natConfig();
+
+                    if (natCfg)
+                    {
+                        if (!mRemoveSTUNServer)
+                        {
+                            stunServer = natCfg->stunServer();
+                        }
+                        if (!mRemoveTURNServer)
+                        {
+                            turnServer = natCfg->turnServer();
+                        }
+                        NATConfigPtr newConfig;
+                        if (mDisable)
+                        {
+                            newConfig = NATConfig::create(stunServer, false, turnServer, false);
+                        }
+                        else
+                        {
+                            newConfig = NATConfig::create(stunServer, natCfg->isSTUNEnabled(), turnServer,
+                                                          natCfg->isTURNEnabled());
+                        }
+                        mImpl->replaceConfig(newConfig);
+                    }
+                    if (mResetICEConfig)
+                    {
+                        mImpl->replaceConfig(ICEConfigurationPtr());
+                    }
+                }
+
+                void visitSTUNServerItem(const STUNServerItemPtr& item)
+                {
+                    if (item)
+                    {
+                        mRemoveSTUNServer = true;
+                    }
+                }
+
+                void visitTURNServerItem(const TURNServerItemPtr& item)
+                {
+                    if (item)
+                    {
+                        mRemoveTURNServer = true;
+                    }
+                }
+
+                void visitUDPTLICETransportFlagsItem(const UDPTLICETransportFlagsItemPtr& item)
+                {
+                    if (item)
+                    {
+                        mDisable = true;
+                    }
+                }
+
+                void visitUDPTLICETransportLimitsItem(const UDPTLICETransportLimitsItemPtr& item)
+                {
+                    if (item)
+                    {
+                        mResetICEConfig = true;
+                    }
+                }
+
+            private:
+                ConfigurationServiceServantPtr mImpl;
+                bool mRemoveSTUNServer;
+                bool mRemoveTURNServer;
+                bool mDisable;
+                bool mResetICEConfig;
+                AsteriskSCF::Helpers::AddressPtr stunServer;
+                AsteriskSCF::Helpers::AddressPtr turnServer;
+            };
+
+            UDPTLICEConfigurationGroupPtr g = mImpl->getICEConfigurationGroup();
+
+            if (g)
+            {
+                UdptlConfigurationItemVisitorPtr v(new Visitor(mImpl));
+                removeItems(v, group->configurationItems, g->configurationItems);
+            }
+        }
  
     private:
         ConfigurationServiceServantPtr mImpl;
@@ -366,6 +635,11 @@ void ConfigurationServiceServant::removeConfigurationGroups(const ConfigurationG
             mImpl->replaceGroup(UdptlGeneralGroupPtr());
         }
 
+        void visitUDPTLConfigurationGroup(const UDPTLICEConfigurationGroupPtr&)
+        {
+            mImpl->replaceGroup(UDPTLICEConfigurationGroupPtr());
+        }
+
         ConfigurationServiceServantPtr mImpl;
     };
     

-----------------------------------------------------------------------


-- 
asterisk-scf/integration/mediatransportudptl.git



More information about the asterisk-scf-commits mailing list