Record number of each type of request received.
        //private SIPNotifyManager m_notifyManager;

        public SIPAppServerCore(
            SIPTransport sipTransport,
            GetCanonicalDomainDelegate getCanonicalDomain,
            SIPAssetGetDelegate<SIPAccount> getSIPAccount,
            SIPMonitorLogDelegate proxyLog,
            SIPCallManager callManager,
            SIPDialogueManager sipDialogueManager,
            //SIPNotifyManager notifyManager,
            SIPAuthenticateRequestDelegate sipAuthenticateRequest,
            SIPEndPoint outboundProxy)
        {
            try
            {
                m_sipTransport = sipTransport;
                m_callManager = callManager;
                m_sipDialogueManager = sipDialogueManager;
                //m_notifyManager = notifyManager;

                m_sipTransport.SIPTransportRequestReceived += GotRequest;
                m_sipTransport.SIPTransportResponseReceived += GotResponse;

                m_outboundProxy = outboundProxy;

                GetCanonicalDomain_External = getCanonicalDomain;
                GetSIPAccount_External = getSIPAccount;
                SIPMonitorLogEvent_External = proxyLog;
                SIPRequestAuthenticator_External = sipAuthenticateRequest;
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPAppServerCore (ctor). " + excp.Message);
                throw excp;
            }
        }
        public AppServerDispatcher(SIPTransport sipTransport, XmlNode configNode)
            : base(sipTransport, configNode)
        {
            try
            {

                XmlNodeList appServerNodes = configNode.SelectNodes("appserver");
                foreach (XmlNode appServerNode in appServerNodes)
                {
                    int priority = Convert.ToInt32(appServerNode.Attributes.GetNamedItem("priority").Value);
                    SIPURI serverURI = SIPURI.ParseSIPURIRelaxed(appServerNode.InnerText);
                    AppServerEntry appServerEntry = new AppServerEntry(priority, serverURI);
                    m_appServerEntries.Add(appServerEntry);
                }

                //if (configNode.SelectSingleNode("outboundproxy") != null && !configNode.SelectSingleNode("outboundproxy").InnerText.IsNullOrBlank()) {
                //    m_outboundProxy = SIPEndPoint.ParseSIPEndPoint(configNode.SelectSingleNode("outboundproxy").InnerText);
                //}

                if (configNode.SelectSingleNode("interval") != null && !configNode.SelectSingleNode("interval").InnerText.IsNullOrBlank())
                {
                    if (!TimeSpan.TryParse(configNode.SelectSingleNode("interval").InnerText, out m_interval))
                    {
                        logger.Warn("AppServerDispatcher interval could not be parsed from " + configNode.SelectSingleNode("interval").InnerText + ".");
                    }
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception AppServerDispatcher. " + excp.Message);
                throw;
            }
        }
        internal UASInviteTransaction(
            SIPTransport sipTransport,
            SIPRequest sipRequest,
            SIPEndPoint dstEndPoint,
            SIPEndPoint localSIPEndPoint,
            SIPEndPoint outboundProxy)
            : base(sipTransport, sipRequest, dstEndPoint, localSIPEndPoint, outboundProxy)
        {
            TransactionType = SIPTransactionTypesEnum.Invite;
            m_remoteTag = sipRequest.Header.From.FromTag;

            if (sipRequest.Header.To.ToTag == null)
            {
                // This UAS needs to set the To Tag.
                m_localTag = CallProperties.CreateNewTag();
            }
            else
            {
                // This is a re-INVITE.
                m_localTag = sipRequest.Header.To.ToTag;
            }

            //logger.Debug("New UASTransaction (" + TransactionId + ") for " + TransactionRequest.URI.ToString() + " to " + RemoteEndPoint + ".");

            CDR = new SIPCDR(SIPCallDirection.In, sipRequest.URI, sipRequest.Header.From, sipRequest.Header.CallId, LocalSIPEndPoint, dstEndPoint);

            //UpdateTransactionState(SIPTransactionStatesEnum.Proceeding);

            TransactionRequestReceived += UASInviteTransaction_TransactionRequestReceived;
            TransactionInformationResponseReceived += UASInviteTransaction_TransactionResponseReceived;
            TransactionFinalResponseReceived += UASInviteTransaction_TransactionResponseReceived;
            TransactionTimedOut += UASInviteTransaction_TransactionTimedOut;
            TransactionRemoved += UASInviteTransaction_TransactionRemoved;
        }
        public static SIPDispatcherJob CreateJob(string jobClass, XmlNode configNode, SIPTransport sipTransport) {

            SIPDispatcherJob job = null;

            if (jobClass != null) {
                try {
                    Type jobType = Type.GetType(jobClass);
                    job = (SIPDispatcherJob)Activator.CreateInstance(jobType, new object[] { sipTransport, configNode });
                    logger.Debug("A SIPDispatcherJob of type, " + jobClass + ", was created.");
                }
                catch (ArgumentNullException nullExcp) {
                    logger.Error("ArgumentNullException attempting to create a SIPDispatcherJob instance of type, " + jobClass + ". " + nullExcp.Message);
                    throw new ApplicationException("Unable to create SIPDispatcherJob of type " + jobClass + ". Check that the assembly is available and the class exists.");
                }
                catch (Exception excp) {
                    logger.Error("Exception attempting to create a SIPDispatcherJobinstance of type, " + jobClass + ". " + excp.Message);
                    throw excp;
                }
            }
            else {
                throw new ApplicationException("No class element existed to create a SIPDispatcherJob from.");
            }

            return job;
        }
        public void Start()
        {
            try
            {
                logger.Debug("WatchTowerDaemon starting...");

                // Send events from this process to the monitoring socket.
                if (m_monitorEventLoopbackPort != 0)
                {
                    m_monitorEventWriter = new SIPMonitorEventWriter(m_monitorEventLoopbackPort);
                }

                List<SIPChannel> sipChannels = SIPTransportConfig.ParseSIPChannelsNode(m_transportNode);
                m_sipTransport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine());
                m_sipTransport.AddSIPChannel(sipChannels);

                if (m_sipAppServerWorkersNode != null)
                {
                    m_appServerManager = new SIPAppServerManager(
                        FireSIPMonitorEvent,
                        m_sipTransport,
                        m_sipAppServerWorkersNode,
                        m_proxyAppServerEndPointsPath);
                }

                //m_sipTransport.SIPTransportRequestReceived += GotRequest;
                //m_sipTransport.SIPTransportResponseReceived += GotResponse;
            }
            catch (Exception excp)
            {
                logger.Error("Exception WatchTowerDaemon Start. " + excp.Message);
            }
        }
Example #6
0
        public void Start()
        {
            try
            {
                logger.Debug("RTCC Daemon starting...");

                // Pre-flight checks.
                if (m_rtccSIPSocketsNode == null || m_rtccSIPSocketsNode.ChildNodes.Count == 0)
                {
                    throw new ApplicationException("The RTCC server cannot start without a SIP socket, please check config file.");
                }

                // Send events from this process to the monitoring socket.
                if (m_monitorLoopbackPort != 0)
                {
                    // Events will be sent by the monitor channel to the loopback interface and this port.
                    m_monitorEventWriter = new SIPMonitorEventWriter(m_monitorLoopbackPort);
                    logger.Debug("Monitor channel initialised for 127.0.0.1:" + m_monitorLoopbackPort + ".");
                }

                // Configure the SIP transport layer.
                m_sipTransport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine(), false);
                List<SIPChannel> sipChannels = SIPTransportConfig.ParseSIPChannelsNode(m_rtccSIPSocketsNode);
                m_sipTransport.AddSIPChannel(sipChannels);

                if (m_cdrDataLayer != null)
                {
                    SIPCDR.CDRCreated += m_cdrDataLayer.Add;
                    SIPCDR.CDRAnswered += m_cdrDataLayer.Update;
                    SIPCDR.CDRHungup += m_cdrDataLayer.Update;
                    SIPCDR.CDRUpdated += m_cdrDataLayer.Update;
                }

                m_sipDialogueManager = new SIPDialogueManager(
                     m_sipTransport,
                     m_outboundProxy,
                     FireSIPMonitorEvent,
                     m_sipSorceryPersistor.SIPDialoguePersistor,
                     m_sipSorceryPersistor.SIPCDRPersistor,
                     SIPRequestAuthenticator.AuthenticateSIPRequest,
                     m_sipSorceryPersistor.SIPAccountsPersistor.Get,
                     m_sipSorceryPersistor.SIPDomainManager.GetDomain);

                m_rtccCore = new RTCCCore(
                    FireSIPMonitorEvent,
                    m_sipDialogueManager,
                    m_sipSorceryPersistor.SIPDialoguePersistor);
                m_rtccCore.Start();

                m_rateUpdater = new RateBulkUpdater(FireSIPMonitorEvent);
                m_rateUpdater.Start();

                logger.Debug("RTCC Daemon successfully started.");
            }
            catch (Exception excp)
            {
                logger.Error("Exception RTCCDaemon Start. " + excp.Message);
            }
        }
 internal SIPCancelTransaction(SIPTransport sipTransport, SIPRequest sipRequest, SIPEndPoint dstEndPoint, SIPEndPoint localSIPEndPoint, UASInviteTransaction originalTransaction)
     : base(sipTransport, sipRequest, dstEndPoint, localSIPEndPoint, originalTransaction.OutboundProxy)
 {
     m_originalTransaction = originalTransaction;
     TransactionType = SIPTransactionTypesEnum.NonInvite;
     TransactionRequestReceived += SIPCancelTransaction_TransactionRequestReceived;
     TransactionFinalResponseReceived += SIPCancelTransaction_TransactionFinalResponseReceived;
     TransactionRemoved += SIPCancelTransaction_TransactionRemoved;
 }
 public SIPProxyScriptFacade(
     SIPMonitorLogDelegate proxyLogger,
     SIPTransport sipTransport,
     SIPProxyDispatcher dispatcher,
     GetAppServerDelegate getAppServer)
 {
     m_proxyLogger = proxyLogger;
     m_sipTransport = sipTransport;
     m_dispatcher = dispatcher;
     GetAppServer_External = getAppServer;
 }
 internal SIPNonInviteTransaction(SIPTransport sipTransport, SIPRequest sipRequest, SIPEndPoint dstEndPoint, SIPEndPoint localSIPEndPoint, SIPEndPoint outboundProxy)
     : base(sipTransport, sipRequest, dstEndPoint, localSIPEndPoint, outboundProxy)
 {
     TransactionType = SIPTransactionTypesEnum.NonInvite;
     TransactionRequestReceived += SIPNonInviteTransaction_TransactionRequestReceived;
     TransactionInformationResponseReceived += SIPNonInviteTransaction_TransactionInformationResponseReceived;
     TransactionFinalResponseReceived += SIPNonInviteTransaction_TransactionFinalResponseReceived;
     TransactionTimedOut += SIPNonInviteTransaction_TransactionTimedOut;
     TransactionRemoved += SIPNonInviteTransaction_TransactionRemoved;
     TransactionRequestRetransmit += SIPNonInviteTransaction_TransactionRequestRetransmit;
 }
Example #10
0
        public SIPToXMPPCall(SIPServerUserAgent uas, XMPPPhoneSession xmppCall, SIPTransport sipTransport, IPAddress ipAddress)
        {
            m_uas = uas;
            m_xmppCall = xmppCall;
            m_sipTransport = sipTransport;
            m_ipAddress = ipAddress;

            m_uas.CallCancelled += SIPCallCancelled;
            m_xmppCall.Accepted += Answered;
            m_xmppCall.Rejected += CallFailed;
            m_xmppCall.Hungup += Hangup;
        }
        internal UACInviteTransaction(SIPTransport sipTransport, SIPRequest sipRequest, SIPEndPoint dstEndPoint, SIPEndPoint localSIPEndPoint, SIPEndPoint outboundProxy)
            : base(sipTransport, sipRequest, dstEndPoint, localSIPEndPoint, outboundProxy)
        {
            TransactionType = SIPTransactionTypesEnum.Invite;
            m_localTag = sipRequest.Header.From.FromTag;
            CDR = new SIPCDR(SIPCallDirection.Out, sipRequest.URI, sipRequest.Header.From, sipRequest.Header.CallId, localSIPEndPoint, dstEndPoint);

            TransactionFinalResponseReceived += UACInviteTransaction_TransactionFinalResponseReceived;
            TransactionInformationResponseReceived += UACInviteTransaction_TransactionInformationResponseReceived;
            TransactionTimedOut += UACInviteTransaction_TransactionTimedOut;
            TransactionRequestReceived += UACInviteTransaction_TransactionRequestReceived;
            TransactionRemoved += UACInviteTransaction_TransactionRemoved;
        }
 public GoogleVoiceUserAgent(
     SIPTransport sipTransport,
     ISIPCallManager callManager,
     SIPMonitorLogDelegate logDelegate,
     string username,
     string adminMemberId,
     SIPEndPoint outboundProxy)
 {
     Owner = username;
     AdminMemberId = adminMemberId;
     m_googleVoiceCall = new GoogleVoiceCall(sipTransport, callManager, logDelegate, username, adminMemberId, outboundProxy);
     m_googleVoiceCall.CallProgress += new CallProgressDelegate(CallProgress);
 }
 public GoogleVoiceCall(
     SIPTransport sipTransport,
     ISIPCallManager callManager,
     SIPMonitorLogDelegate logDelegate,
     string username,
     string adminMemberId,
     SIPEndPoint outboundProxy)
 {
     m_sipTransport = sipTransport;
     m_callManager = callManager;
     Log_External = logDelegate;
     m_username = username;
     m_adminMemberId = adminMemberId;
     m_outboundProxy = outboundProxy;
 }
 public DialPlanScriptContext(           
     SIPMonitorLogDelegate monitorLogDelegate,
     SIPTransport sipTransport,
     DialogueBridgeCreatedDelegate createBridge,
     SIPEndPoint outboundProxy,
     ISIPServerUserAgent sipServerUserAgent,
     SIPDialPlan dialPlan,
     List<SIPProvider> sipProviders,
     string traceDirectory,
     string callersNetworkId,
     Guid customerId)
     : base(monitorLogDelegate, sipTransport, createBridge, outboundProxy, sipServerUserAgent, dialPlan, sipProviders, traceDirectory, callersNetworkId, customerId)
 {
     ContextType = DialPlanContextsEnum.Script;
 }
        public SIPNonInviteClientUserAgent(
            SIPTransport sipTransport,
            SIPEndPoint outboundProxy,
            SIPCallDescriptor callDescriptor,
            string owner,
            string adminMemberID,
            SIPMonitorLogDelegate logDelegate)
        {
            m_sipTransport = sipTransport;
            m_outboundProxy = outboundProxy;
            m_callDescriptor = callDescriptor;
            m_owner = owner;
            m_adminMemberID = adminMemberID;

            Log_External = logDelegate;
        }
 public CallbackApp(
     SIPTransport sipTransport, 
     ISIPCallManager callManager,
     DialStringParser dialStringParser, 
     SIPMonitorLogDelegate logDelegate, 
     string username,
     string adminMemberId,
     SIPEndPoint outboundProxy)
 {
     m_sipTransport = sipTransport;
     m_callManager = callManager;
     m_dialStringParser = dialStringParser;
     Log_External = logDelegate;
     m_username = username;
     m_adminMemberId = adminMemberId;
     m_outboundProxy = outboundProxy;
 }
Example #17
0
        static void Main(string[] args)
        {
            try
            {
                // Configure the SIP transport layer.
                _sipTransport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine());

                if (_sipSocketsNode != null)
                {
                    // Set up the SIP channels based on the app.config file.
                    List<SIPChannel> sipChannels = SIPTransportConfig.ParseSIPChannelsNode(_sipSocketsNode);
                    _sipTransport.AddSIPChannel(sipChannels);
                }
                else
                {
                    // Use default options to set up a SIP channel.
                    int port = FreePort.FindNextAvailableUDPPort(_defaultSIPUdpPort);
                    var sipChannel = new SIPUDPChannel(new IPEndPoint(_defaultLocalAddress, port));
                    _sipTransport.AddSIPChannel(sipChannel);
                }

                // Wire up the transport layer so SIP requests and responses have somewhere to go.
                _sipTransport.SIPTransportRequestReceived += SIPTransportRequestReceived;
                _sipTransport.SIPTransportResponseReceived += SIPTransportResponseReceived;

                // If you want to see ALL the nitty gritty SIP traffic wire up the events below.
                //_sipTransport.SIPBadRequestInTraceEvent += SIPBadRequestInTraceEvent;
                //_sipTransport.SIPBadResponseInTraceEvent += SIPBadResponseInTraceEvent;
                //_sipTransport.SIPRequestInTraceEvent += SIPRequestInTraceEvent;
                //_sipTransport.SIPRequestOutTraceEvent += SIPRequestOutTraceEvent;
                //_sipTransport.SIPResponseInTraceEvent += SIPResponseInTraceEvent;
                //_sipTransport.SIPResponseOutTraceEvent += SIPResponseOutTraceEvent;

                ManualResetEvent mre = new ManualResetEvent(false);
                mre.WaitOne();
            }
            catch (Exception excp)
            {
                Console.WriteLine("Exception Main. " + excp);
            }
            finally
            {
                Console.WriteLine("Press any key to exit...");
                Console.ReadLine();
            }
        }
 public DialPlanLineContext(
     SIPMonitorLogDelegate monitorLogDelegate,
     SIPTransport sipTransport,
     DialogueBridgeCreatedDelegate createBridge,
     SIPEndPoint outboundProxy,
     ISIPServerUserAgent sipServerUserAgent,
     SIPDialPlan dialPlan,
     List<SIPProvider> sipProviders,
     string traceDirectory,
     string callersNetworkId,
     Customer customer)
     : base(monitorLogDelegate, sipTransport, createBridge, outboundProxy, sipServerUserAgent, dialPlan, sipProviders, traceDirectory, callersNetworkId, customer, null, null)
 {
     ContextType = DialPlanContextsEnum.Line;
      string[] dialPlanEntries = dialPlan.DialPlanScript.Split(new char[] { '\n' });
      ParseDialPlan(dialPlanEntries);
 }
        public SIPNotifyManager(
            SIPTransport sipTransport,
            SIPEndPoint outboundProxy,
            SIPMonitorLogDelegate logDelegate,
            SIPAssetGetDelegate<SIPAccount> getSIPAccount,
            SIPAssetGetListDelegate<SIPRegistrarBinding> getSIPAccountBindings,
            GetCanonicalDomainDelegate getCanonicalDomain)
        {
            m_sipTransport = sipTransport;
            m_outboundProxy = outboundProxy;
            Log_External = logDelegate;
            GetSIPAccount_External = getSIPAccount;
            GetSIPAccountBindings_External = getSIPAccountBindings;
            GetCanonicalDomain_External = getCanonicalDomain;

            ThreadPool.QueueUserWorkItem(delegate { ProcessNewNotifications(PROCESS_NOTIFICATIONS_THREAD_NAME); });
        }
        public IPAddress PublicIPAddress;       // Can be set if there is an object somewhere that knows the public IP. The address wil be available in the proxy runtime script.

        public SIPProxyCore(
            SIPMonitorLogDelegate proxyLogger,
            SIPTransport sipTransport,
            string scriptPath,
            string appServerEndPointsPath)
        {
            try
            {
                m_proxyLogger = proxyLogger ?? m_proxyLogger;
                m_scriptPath = scriptPath;
                m_sipTransport = sipTransport;

                if (!appServerEndPointsPath.IsNullOrBlank() && File.Exists(appServerEndPointsPath))
                {
                    m_sipCallDispatcherFile = new SIPCallDispatcherFile(SendMonitorEvent, appServerEndPointsPath);
                    m_sipCallDispatcherFile.LoadAndWatch();
                }
                else
                {
                    logger.Warn("No call dispatcher file specified for SIP Proxy.");
                }

                m_proxyDispatcher = new SIPProxyDispatcher(new SIPMonitorLogDelegate(SendMonitorEvent));
                GetAppServerDelegate getAppServer = (m_sipCallDispatcherFile != null) ? new GetAppServerDelegate(m_sipCallDispatcherFile.GetAppServer) : null;
                m_proxyScriptFacade = new SIPProxyScriptFacade(
                    new SIPMonitorLogDelegate(SendMonitorEvent),         // Don't use the m_proxyLogger delegate directly here as doing so caused stack overflow exceptions in the IronRuby engine.
                    sipTransport,
                    m_proxyDispatcher,
                    getAppServer);

                m_scriptLoader = new ScriptLoader(SendMonitorEvent, m_scriptPath);
                m_scriptLoader.ScriptFileChanged += (s, e) => { m_compiledScript = m_scriptLoader.GetCompiledScript(); };
                m_compiledScript = m_scriptLoader.GetCompiledScript();

                // Events that pass the SIP requests and responses onto the Stateless Proxy Core.
                m_sipTransport.SIPTransportRequestReceived += GotRequest;
                m_sipTransport.SIPTransportResponseReceived += GotResponse;
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPProxyCore (ctor). " + excp.Message);
                throw excp;
            }
        }
 public SIPDialogueManager(
     SIPTransport sipTransport,
     SIPEndPoint outboundProxy,
     SIPMonitorLogDelegate logDelegate,
     SIPAssetPersistor<SIPDialogueAsset> sipDialoguePersistor,
     SIPAssetPersistor<SIPCDRAsset> sipCDRPersistor,
     SIPAuthenticateRequestDelegate authenticateRequestDelegate,
     SIPAssetGetDelegate<SIPAccount> getSIPAccount,
     GetCanonicalDomainDelegate getCanonicalDomain)
 {
     m_sipTransport = sipTransport;
     m_outboundProxy = outboundProxy;
     Log_External = logDelegate;
     m_sipDialoguePersistor = sipDialoguePersistor;
     m_sipCDRPersistor = sipCDRPersistor;
     SIPAuthenticateRequest_External = authenticateRequestDelegate;
     GetSIPAccount_External = getSIPAccount;
     GetCanonicalDomain_External = getCanonicalDomain;
 }
        private Dictionary<string, SIPEventSubscription> m_subscriptions = new Dictionary<string, SIPEventSubscription>();    // [monitor session ID, subscription].

        public NotifierSubscriptionsManager(
            SIPMonitorLogDelegate logDelegate,
            SIPAssetGetListDelegate<SIPDialogueAsset> getDialogues,
            SIPAssetGetByIdDelegate<SIPDialogueAsset> getDialogue,
            SIPAssetPersistor<SIPAccount> sipAssetPersistor,
            SIPAssetCountDelegate<SIPRegistrarBinding> getBindingsCount,
            SIPTransport sipTransport,
            SIPEndPoint outboundProxy,
            ISIPMonitorPublisher publisher)
        {
            MonitorLogEvent_External = logDelegate;
            GetDialogues_External = getDialogues;
            GetDialogue_External = getDialogue;
            GetSIPRegistrarBindingsCount_External = getBindingsCount;
            m_sipAssetPersistor = sipAssetPersistor;
            m_sipTransport = sipTransport;
            m_outboundProxy = outboundProxy;
            m_publisher = publisher;
            m_publisher.MonitorEventReady += MonitorEventAvailable;
        }
        public Dictionary<string, SIPDispatcherJob> Load(SIPTransport sipTransport)
        {
            try
            {
                Dictionary<string, SIPDispatcherJob> dispatcherJobs = new Dictionary<string, SIPDispatcherJob>();

                if (sipTransport == null)
                {
                    SIPChannel dispatcherChannel = new SIPUDPChannel(new IPEndPoint(IPAddress.Loopback, 0));
                    sipTransport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine(), dispatcherChannel, true);
                }

                foreach (XmlNode dispatcherNode in m_configNode.ChildNodes)
                {
                    string jobType = dispatcherNode.Attributes.GetNamedItem("class").Value;
                    string jobKey = dispatcherNode.Attributes.GetNamedItem("key").Value;

                    if (!jobKey.IsNullOrBlank() && !jobType.IsNullOrBlank())
                    {
                        SIPDispatcherJob job = SIPDispatcherJobFactory.CreateJob(jobType, dispatcherNode, sipTransport);
                        if (job != null && !dispatcherJobs.ContainsKey(jobKey))
                        {
                            ThreadPool.QueueUserWorkItem(delegate { job.Start(); });
                            dispatcherJobs.Add(jobKey, job);
                        }
                    }
                    else
                    {
                        logger.Warn("The job key or class were empty for a SIPDispatcherJob node.\n" + dispatcherNode.OuterXml);
                    }
                }

                return dispatcherJobs;
            }
            catch (Exception dispatcherExcp)
            {
                logger.Error("Exception StatelessProxyCore Starting Dispatcher. " + dispatcherExcp.Message);
                return null;
            }
        }
Example #24
0
 /// <summary>
 /// See overload.
 /// </summary>
 /// <param name="switchCallTransactions">An empty list that will be filled with transactions that the ForkCall creates and that each
 /// represent an outgoing call. The calling object can use the list to check response codes to determine the result of each leg in the
 /// ForkCall.</param>
 public ForkCall(
     SIPTransport sipTransport,
     SIPMonitorLogDelegate statefulProxyLogEvent,
     QueueNewCallDelegate queueNewCall,
     DialStringParser dialStringParser,
     string username,
     string adminMemberId,
     SIPEndPoint outboundProxy,
     ISIPCallManager callManager,
     DialPlanContext dialPlanContext,
     out List<SIPTransaction> switchCallTransactions)
     : this(sipTransport, statefulProxyLogEvent, queueNewCall, dialStringParser, username, adminMemberId, outboundProxy, callManager, dialPlanContext)
 {
     switchCallTransactions = m_switchCallTransactions;
 }
Example #25
0
        private QueueNewCallDelegate QueueNewCall_External; // Function delegate to allow new calls to be placed on the call manager and run through the dialplan logic.

        #endregion Fields

        #region Constructors

        /// <remarks>
        /// The ForkCall allows a SIP call to be forked to multiple destinations. To do this it utilises multiple
        /// simultaneous SIPCallDescriptor objects and consolidates their responses to work out what should and shouldn't
        /// be forwarded onto the client that initiated the call. The ForkCall acts as a classic SIP forking proxy.
        /// 
        /// The ForkCall is capable of both multiple forwards and also of follow on forwarding in the event of a call 
        /// leg of multiple forwards not succeeding. As an example:
        /// 
        ///     Dial(provider1&provider2|provider3&provider4|provider5&provider6)
        ///     
        /// The handling of this call would be:
        /// 1. The call would be simultaneously forwarded to provider1 and provider2,
        /// 2. If the call was not successfully answered in step 1 the  call would be simultaneously forwarded to provider3 and provider4,
        /// 3. If the call was not successfully answered in step 2 the  call would be simultaneously forwarded to provider5 and provider6,
        /// 4. If the call was not successfully answered in step 3 the client call would be sent an error response.
        /// 5. If the client cancels the call at any time during the call all forwarding operations will halt.
        /// </remarks>
        /// <param name="sipTransport">The SIP transport layer that will handle the forked calls.</param>
        /// <param name="statefulProxyLogEvent">A delegate that allows the owning object to receive notifications from the ForkCall.</param>
        /// <param name="queueNewCall">A delegate that can be used to queue a new call with the SIP application server call manager. This
        /// delegate is used when a fork call generates a B2B call that requires the incoming dialplan for a called user to be processed.</param>
        /// <param name="dialStringParser">The dial string parser is used when a redirect response is received on a forked call leg. The
        /// parser can then be applied to the redirect SIP URI to generate new call legs to be added to the ForkCall.</param>
        /// <param name="username">The username of the call owner.</param>
        /// <param name="adminMemberId">The admin ID of the call owner.</param>
        /// <param name="outboundProxy">The outbound proxy to use for all SIP traffic originated. Can be null if an outbound proxy is not 
        /// being used.</param>
        public ForkCall(
            SIPTransport sipTransport,
            SIPMonitorLogDelegate statefulProxyLogEvent,
            QueueNewCallDelegate queueNewCall,
            DialStringParser dialStringParser,
            string username,
            string adminMemberId,
            SIPEndPoint outboundProxy,
            ISIPCallManager callManager,
            DialPlanContext dialPlanContext)
        {
            m_sipTransport = sipTransport;
            m_statefulProxyLogEvent = statefulProxyLogEvent;
            QueueNewCall_External = queueNewCall;
            m_dialStringParser = dialStringParser;
            m_username = username;
            m_adminMemberId = adminMemberId;
            m_outboundProxySocket = outboundProxy;
            m_callManager = callManager;
            m_dialPlanContext = dialPlanContext;
        }
        public SIPServerUserAgent(
            SIPTransport sipTransport,
            SIPEndPoint outboundProxy,
            string sipUsername,
            string sipDomain,
            SIPCallDirection callDirection,
            SIPAssetGetDelegate<SIPAccount> getSIPAccount,
            SIPAuthenticateRequestDelegate sipAuthenticateRequest,
            SIPMonitorLogDelegate logDelegate,
            UASInviteTransaction uasTransaction)
        {
            m_sipTransport = sipTransport;
            m_outboundProxy = outboundProxy;
            m_sipUsername = sipUsername;
            m_sipDomain = sipDomain;
            m_sipCallDirection = callDirection;
            GetSIPAccount_External = getSIPAccount;
            SIPAuthenticateRequest_External = sipAuthenticateRequest;
            Log_External = logDelegate ?? Log_External;
            m_uasTransaction = uasTransaction;

            m_uasTransaction.TransactionTraceMessage += TransactionTraceMessage;
            m_uasTransaction.UASInviteTransactionTimedOut += ClientTimedOut;
            m_uasTransaction.UASInviteTransactionCancelled += UASTransactionCancelled;
            m_uasTransaction.TransactionRemoved += new SIPTransactionRemovedDelegate(UASTransaction_TransactionRemoved);
            //m_uasTransaction.TransactionStateChanged += (t) => { logger.Debug("Transaction state change to " + t.TransactionState + ", uri=" + t.TransactionRequestURI.ToString() + "."); };
        }
        public void Start()
        {
            try
            {
                logger.Debug("pid=" + Process.GetCurrentProcess().Id + ".");
                logger.Debug("os=" + System.Environment.OSVersion + ".");
                logger.Debug("current directory=" + m_currentDirectory + ".");
                logger.Debug("base directory=" + AppDomain.CurrentDomain.BaseDirectory + ".");

                SIPDNSManager.SIPMonitorLogEvent = FireSIPMonitorEvent;
                m_sipSorceryPersistor = new SIPSorceryPersistor(m_storageType, m_connectionString);
                m_customerSessionManager = new CustomerSessionManager(m_storageType, m_connectionString);
                m_cdrDataLayer = new Entities.CDRDataLayer();

                if (m_sipProxyEnabled)
                {
                    m_sipProxyDaemon = new SIPProxyDaemon();
                    m_sipProxyDaemon.Start();

                    if (m_sipProxyDaemon.PublicIPAddress != null)
                    {
                        m_publicIPAddress = m_sipProxyDaemon.PublicIPAddress;
                        DialStringParser.PublicIPAddress = m_sipProxyDaemon.PublicIPAddress;
                        DialPlanScriptFacade.PublicIPAddress = m_sipProxyDaemon.PublicIPAddress;
                        SIPDialogueManager.PublicIPAddress = m_sipProxyDaemon.PublicIPAddress;
                    }
                    else
                    {
                        m_sipProxyDaemon.PublicIPAddressUpdated += (ipAddress) =>
                        {
                            if (ipAddress != null && (m_publicIPAddress == null || ipAddress.ToString() != m_publicIPAddress.ToString()))
                            {
                                m_publicIPAddress = ipAddress;
                                DialStringParser.PublicIPAddress = ipAddress;
                                DialPlanScriptFacade.PublicIPAddress = ipAddress;
                                SIPDialogueManager.PublicIPAddress = ipAddress;
                            }
                        };
                    }
                }

                if (m_sipMonitorEnabled)
                {
                    m_sipMonitorPublisher = new SIPMonitorClientManager(null);
                    m_sipMonitorDaemon = new SIPMonitorDaemon(m_sipMonitorPublisher);
                    m_sipMonitorDaemon.Start();
                }

                if (m_sipRegistrarEnabled)
                {
                    m_sipRegistrarDaemon = new SIPRegistrarDaemon(
                        m_sipSorceryPersistor.SIPDomainManager.GetDomain,
                        m_sipSorceryPersistor.SIPAccountsPersistor.Get,
                        m_sipSorceryPersistor.SIPRegistrarBindingPersistor,
                        SIPRequestAuthenticator.AuthenticateSIPRequest,
                        m_customerSessionManager.CustomerPersistor);
                    m_sipRegistrarDaemon.Start();
                }

                if (m_sipRegAgentEnabled)
                {
                    m_sipRegAgentDaemon = new SIPRegAgentDaemon(
                        m_sipSorceryPersistor.SIPProvidersPersistor,
                        m_sipSorceryPersistor.SIPProviderBindingsPersistor);

                    m_sipRegAgentDaemon.Start();
                }

                if (m_sipNotifierEnabled)
                {
                    m_sipNotifierDaemon = new SIPNotifierDaemon(
                        m_customerSessionManager.CustomerPersistor.Get,
                        m_sipSorceryPersistor.SIPDialoguePersistor.Get,
                        m_sipSorceryPersistor.SIPDialoguePersistor.Get,
                        m_sipSorceryPersistor.SIPDomainManager.GetDomain,
                        m_sipSorceryPersistor.SIPAccountsPersistor,
                        m_sipSorceryPersistor.SIPRegistrarBindingPersistor.Get,
                        m_sipSorceryPersistor.SIPAccountsPersistor.Get,
                        m_sipSorceryPersistor.SIPRegistrarBindingPersistor.Count,
                        SIPRequestAuthenticator.AuthenticateSIPRequest,
                        m_sipMonitorPublisher);
                    //new SIPMonitorUDPSink("127.0.0.1:10003"));
                    m_sipNotifierDaemon.Start();
                }

                if (m_sshServerEnabled)
                {
                    SSHServerDaemon daemon = new SSHServerDaemon(m_customerSessionManager, m_sipMonitorPublisher); // Uses memory to transfer events.
                    //SSHServerDaemon daemon = new SSHServerDaemon(m_customerSessionManager, new SIPMonitorUDPSink("127.0.0.1:10002"));
                    daemon.Start();
                }

                #region Initialise the SIP Application Server and its logging mechanisms including CDRs.

                logger.Debug("Initiating SIP Application Server Agent.");

                // Send events from this process to the monitoring socket.
                if (m_monitorEventLoopbackPort != 0)
                {
                    m_monitorEventWriter = new SIPMonitorEventWriter(m_monitorEventLoopbackPort);
                }

                if (m_cdrDataLayer != null)
                {
                    SIPCDR.CDRCreated += m_cdrDataLayer.Add;
                    SIPCDR.CDRAnswered += m_cdrDataLayer.Update;
                    SIPCDR.CDRHungup += m_cdrDataLayer.Update;
                    SIPCDR.CDRUpdated += m_cdrDataLayer.Update;
                }

                #region Initialise the SIPTransport layers.

                m_sipTransport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine(), true);
                if (m_appServerEndPoint != null)
                {
                    if (m_appServerEndPoint.Protocol == SIPProtocolsEnum.udp)
                    {
                        logger.Debug("Using single SIP transport socket for App Server " + m_appServerEndPoint.ToString() + ".");
                        m_sipTransport.AddSIPChannel(new SIPUDPChannel(m_appServerEndPoint.GetIPEndPoint()));
                    }
                    else if (m_appServerEndPoint.Protocol == SIPProtocolsEnum.tcp)
                    {
                        logger.Debug("Using single SIP transport socket for App Server " + m_appServerEndPoint.ToString() + ".");
                        m_sipTransport.AddSIPChannel(new SIPTCPChannel(m_appServerEndPoint.GetIPEndPoint()));
                    }
                    else
                    {
                        throw new ApplicationException("The SIP End Point of " + m_appServerEndPoint + " cannot be used with the App Server transport layer.");
                    }
                }
                else if (m_sipAppServerSocketsNode != null)
                {
                    m_sipTransport.AddSIPChannel(SIPTransportConfig.ParseSIPChannelsNode(m_sipAppServerSocketsNode));
                }
                else
                {
                    throw new ApplicationException("The SIP App Server could not be started, no SIP sockets have been configured.");
                }

                m_sipTransport.SIPRequestInTraceEvent += LogSIPRequestIn;
                m_sipTransport.SIPRequestOutTraceEvent += LogSIPRequestOut;
                m_sipTransport.SIPResponseInTraceEvent += LogSIPResponseIn;
                m_sipTransport.SIPResponseOutTraceEvent += LogSIPResponseOut;
                m_sipTransport.SIPBadRequestInTraceEvent += LogSIPBadRequestIn;
                m_sipTransport.SIPBadResponseInTraceEvent += LogSIPBadResponseIn;

                #endregion

                m_dialPlanEngine = new DialPlanEngine(
                    m_sipTransport,
                    m_sipSorceryPersistor.SIPDomainManager.GetDomain,
                    FireSIPMonitorEvent,
                    m_sipSorceryPersistor,
                    //m_sipSorceryPersistor.SIPAccountsPersistor,
                    //m_sipSorceryPersistor.SIPRegistrarBindingPersistor.Get,
                    //m_sipSorceryPersistor.SIPDialPlanPersistor,
                    //m_sipSorceryPersistor.SIPDialoguePersistor,
                    m_outboundProxy,
                    m_rubyScriptCommonPath,
                    m_dialplanImpersonationUsername,
                    m_dialplanImpersonationPassword,
                    m_maxDialPlanExecutionLimit);

                m_sipDialogueManager = new SIPDialogueManager(
                    m_sipTransport,
                     m_outboundProxy,
                     FireSIPMonitorEvent,
                     m_sipSorceryPersistor.SIPDialoguePersistor,
                     m_sipSorceryPersistor.SIPCDRPersistor,
                     SIPRequestAuthenticator.AuthenticateSIPRequest,
                     m_sipSorceryPersistor.SIPAccountsPersistor.Get,
                     m_sipSorceryPersistor.SIPDomainManager.GetDomain);

                m_callManager = new SIPCallManager(
                     m_sipTransport,
                     m_outboundProxy,
                     FireSIPMonitorEvent,
                     m_sipDialogueManager,
                     m_sipSorceryPersistor.SIPDialoguePersistor,
                     m_sipSorceryPersistor.SIPCDRPersistor,
                     m_dialPlanEngine,
                     m_sipSorceryPersistor.SIPDialPlanPersistor.Get,
                     m_sipSorceryPersistor.SIPAccountsPersistor.Get,
                     m_sipSorceryPersistor.SIPRegistrarBindingPersistor.Get,
                     m_sipSorceryPersistor.SIPProvidersPersistor.Get,
                     m_sipSorceryPersistor.SIPDomainManager.GetDomain,
                     m_customerSessionManager.CustomerPersistor,
                     m_sipSorceryPersistor.SIPDialPlanPersistor,
                     m_traceDirectory,
                     m_monitorCalls,
                     m_dailyCallLimit);
                m_callManager.Start();

                m_appServerCore = new SIPAppServerCore(
                    m_sipTransport,
                    m_sipSorceryPersistor.SIPDomainManager.GetDomain,
                    m_sipSorceryPersistor.SIPAccountsPersistor.Get,
                    FireSIPMonitorEvent,
                    m_callManager,
                    m_sipDialogueManager,
                    SIPRequestAuthenticator.AuthenticateSIPRequest,
                    m_outboundProxy);

                m_rtccCore = new RTCCCore(
                    FireSIPMonitorEvent,
                    m_sipDialogueManager,
                    m_sipSorceryPersistor.SIPDialoguePersistor);
                m_rtccCore.Start();

                m_rateUpdater = new RateBulkUpdater(FireSIPMonitorEvent);
                m_rateUpdater.Start();

                #endregion

                #region Initialise WCF services.

                try
                {
                    if (WCFUtility.DoesWCFServiceExist(typeof(SIPProvisioningWebService).FullName.ToString()))
                    {
                        if (m_sipSorceryPersistor == null)
                        {
                            logger.Warn("Provisioning hosted service could not be started as Persistor object was null.");
                        }
                        else
                        {
                            SIPProviderBindingSynchroniser sipProviderBindingSynchroniser = new SIPProviderBindingSynchroniser(m_sipSorceryPersistor.SIPProviderBindingsPersistor);
                            m_sipSorceryPersistor.SIPProvidersPersistor.Added += sipProviderBindingSynchroniser.SIPProviderAdded;
                            m_sipSorceryPersistor.SIPProvidersPersistor.Updated += sipProviderBindingSynchroniser.SIPProviderUpdated;
                            m_sipSorceryPersistor.SIPProvidersPersistor.Deleted += sipProviderBindingSynchroniser.SIPProviderDeleted;

                            ProvisioningServiceInstanceProvider instanceProvider = new ProvisioningServiceInstanceProvider(
                                m_sipSorceryPersistor.SIPAccountsPersistor,
                                m_sipSorceryPersistor.SIPDialPlanPersistor,
                                m_sipSorceryPersistor.SIPProvidersPersistor,
                                m_sipSorceryPersistor.SIPProviderBindingsPersistor,
                                m_sipSorceryPersistor.SIPRegistrarBindingPersistor,
                                m_sipSorceryPersistor.SIPDialoguePersistor,
                                m_sipSorceryPersistor.SIPCDRPersistor,
                                m_customerSessionManager,
                                m_sipSorceryPersistor.SIPDomainManager,
                                FireSIPMonitorEvent,
                                0,
                                false);

                            m_sipProvisioningHost = new ServiceHost(typeof(SIPProvisioningWebService));
                            m_sipProvisioningHost.Description.Behaviors.Add(instanceProvider);
                            m_sipProvisioningHost.Open();

                            if (m_sipRegAgentDaemon == null)
                            {
                                m_sipRegAgentDaemon = new SIPRegAgentDaemon(
                                    m_sipSorceryPersistor.SIPProvidersPersistor,
                                    m_sipSorceryPersistor.SIPProviderBindingsPersistor);
                            }

                            logger.Debug("Provisioning hosted service successfully started on " + m_sipProvisioningHost.BaseAddresses[0].AbsoluteUri + ".");
                        }
                    }
                }
                catch (Exception excp)
                {
                    logger.Warn("Exception starting Provisioning hosted service. " + excp.Message);
                }

                try
                {
                    if (WCFUtility.DoesWCFServiceExist(typeof(CrossDomainService).FullName.ToString()))
                    {
                        m_accessPolicyHost = new ServiceHost(typeof(CrossDomainService));
                        m_accessPolicyHost.Open();

                        logger.Debug("CrossDomain hosted service successfully started on " + m_accessPolicyHost.BaseAddresses[0].AbsoluteUri + ".");
                    }
                }
                catch (Exception excp)
                {
                    logger.Warn("Exception starting CrossDomain hosted service. " + excp.Message);
                }

                try
                {
                    if (WCFUtility.DoesWCFServiceExist(typeof(CallManagerServices).FullName.ToString()))
                    {
                        CallManagerServiceInstanceProvider callManagerSvcInstanceProvider = new CallManagerServiceInstanceProvider(m_callManager, m_sipDialogueManager);

                        Uri callManagerBaseAddress = null;
                        if (m_callManagerServiceAddress != null)
                        {
                            logger.Debug("Adding service address to Call Manager Service " + m_callManagerServiceAddress + ".");
                            callManagerBaseAddress = new Uri(m_callManagerServiceAddress);
                        }

                        if (callManagerBaseAddress != null)
                        {
                            m_callManagerSvcHost = new ServiceHost(typeof(CallManagerServices), callManagerBaseAddress);
                        }
                        else
                        {
                            m_callManagerSvcHost = new ServiceHost(typeof(CallManagerServices));
                        }

                        m_callManagerSvcHost.Description.Behaviors.Add(callManagerSvcInstanceProvider);

                        m_callManagerSvcHost.Open();

                        logger.Debug("CallManager hosted service successfully started on " + m_callManagerSvcHost.BaseAddresses[0].AbsoluteUri + ".");
                    }
                }
                catch (Exception excp)
                {
                    logger.Warn("Exception starting CallManager hosted service. " + excp.Message);
                }

                if (WCFUtility.DoesWCFServiceExist(typeof(SIPNotifierService).FullName.ToString()))
                {
                    if (m_sipMonitorPublisher != null)
                    {
                        try
                        {
                            SIPNotifierService notifierService = new SIPNotifierService(m_sipMonitorPublisher, m_customerSessionManager);
                            m_sipNotificationsHost = new ServiceHost(notifierService);

                            m_sipNotificationsHost.Open();

                            logger.Debug("SIPNotificationsService hosted service successfully started on " + m_sipNotificationsHost.BaseAddresses[0].AbsoluteUri + ".");
                        }
                        catch (Exception excp)
                        {
                            logger.Warn("Exception starting SIPNotificationsService hosted service. " + excp.Message);
                        }
                    }
                }

                #endregion
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPAppServerDaemon Start. " + excp.Message);
                throw excp;
            }
        }
        public DialPlanScriptFacade(
            SIPTransport sipTransport,
            DialPlanExecutingScript executingScript,
            SIPMonitorLogDelegate logDelegate,
            DialogueBridgeCreatedDelegate createBridge,
            SIPRequest sipRequest,
            SIPCallDirection callDirection,
            DialPlanContext dialPlanContext,
            GetCanonicalDomainDelegate getCanonicalDomain,
            ISIPCallManager callManager,
            //SIPAssetPersistor<SIPAccount> sipAccountPersistor,
            //SIPAssetPersistor<SIPDialPlan> sipDialPlanPersistor,
            //SIPAssetPersistor<SIPDialogueAsset> sipDialoguePersistor,
            //SIPAssetGetListDelegate<SIPRegistrarBinding> getSIPAccountBindings,
            SIPSorceryPersistor sipSorceryPersistor,
            SIPEndPoint outboundProxySocket,
            DialPlanEngine dialPlanEngine
            )
        {
            m_sipTransport = sipTransport;
            m_executingScript = executingScript;
            m_dialPlanLogDelegate = logDelegate;
            CreateBridge_External = createBridge;
            m_sipRequest = sipRequest;
            m_callDirection = callDirection;
            m_dialPlanContext = dialPlanContext;
            m_getCanonicalDomainDelegate = getCanonicalDomain;
            m_callManager = callManager;
            //m_sipAccountPersistor = sipAccountPersistor;
            //m_sipDialPlanPersistor = sipDialPlanPersistor;
            //m_sipDialoguePersistor = sipDialoguePersistor;
            //GetSIPAccountBindings_External = getSIPAccountBindings;
            m_sipSorceryPersistor = sipSorceryPersistor;
            m_outboundProxySocket = outboundProxySocket;

            m_executingScript.Cleanup = CleanupDialPlanScript;

            if (m_dialPlanContext != null)
            {
                m_username = dialPlanContext.Owner;
                m_adminMemberId = dialPlanContext.AdminMemberId;
                m_sipProviders = dialPlanContext.SIPProviders;

                m_dialPlanContext.TraceLog.AppendLine("DialPlan=> Dialplan trace commenced at " + DateTime.Now.ToString("dd MMM yyyy HH:mm:ss:fff") + ".");
                m_dialPlanContext.CallCancelledByClient += ClientCallTerminated;

                SIPAssetGetDelegate<SIPAccount> getSIPAccount = null;
                if (m_sipSorceryPersistor != null && m_sipSorceryPersistor.SIPAccountsPersistor != null)
                {
                    getSIPAccount = m_sipSorceryPersistor.SIPAccountsPersistor.Get;
                }
                m_dialStringParser = new DialStringParser(m_sipTransport, m_dialPlanContext.Owner, m_dialPlanContext.SIPAccount, m_sipProviders, getSIPAccount, m_sipSorceryPersistor.SIPRegistrarBindingPersistor.Get, m_getCanonicalDomainDelegate, logDelegate, m_dialPlanContext.SIPDialPlan.DialPlanName);
            }
        }
        public void Start()
        {
            try
            {
                logger.Debug("pid=" + Process.GetCurrentProcess().Id + ".");
                logger.Debug("os=" + System.Environment.OSVersion + ".");
                logger.Debug("current directory=" + m_currentDirectory + ".");
                logger.Debug("base directory=" + AppDomain.CurrentDomain.BaseDirectory + ".");

                SIPDNSManager.SIPMonitorLogEvent = FireSIPMonitorEvent;
                m_sipSorceryPersistor = new SIPSorceryPersistor(m_storageType, m_connectionString);
                m_customerSessionManager = new CustomerSessionManager(m_storageType, m_connectionString);
                m_cdrDataLayer = new Entities.CDRDataLayer();

                #region Initialise the SIP Application Server and its logging mechanisms including CDRs.

                logger.Debug("Initiating SIP Application Server Agent.");

                // Send events from this process to the monitoring socket.
                if (m_monitorEventLoopbackPort != 0)
                {
                    m_monitorEventWriter = new SIPMonitorEventWriter(m_monitorEventLoopbackPort);
                }

                if (m_cdrDataLayer != null)
                {
                    SIPCDR.CDRCreated += m_cdrDataLayer.Add;
                    SIPCDR.CDRAnswered += m_cdrDataLayer.Update;
                    SIPCDR.CDRHungup += m_cdrDataLayer.Update;
                    SIPCDR.CDRUpdated += m_cdrDataLayer.Update;
                }

                #region Initialise the SIPTransport layers.

                m_sipTransport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine(), true);
                if (m_appServerEndPoint != null)
                {
                    if (m_appServerEndPoint.Protocol == SIPProtocolsEnum.udp)
                    {
                        logger.Debug("Using single SIP transport socket for App Server " + m_appServerEndPoint.ToString() + ".");
                        m_sipTransport.AddSIPChannel(new SIPUDPChannel(m_appServerEndPoint.GetIPEndPoint()));
                    }
                    else if (m_appServerEndPoint.Protocol == SIPProtocolsEnum.tcp)
                    {
                        logger.Debug("Using single SIP transport socket for App Server " + m_appServerEndPoint.ToString() + ".");
                        m_sipTransport.AddSIPChannel(new SIPTCPChannel(m_appServerEndPoint.GetIPEndPoint()));
                    }
                    else
                    {
                        throw new ApplicationException("The SIP End Point of " + m_appServerEndPoint + " cannot be used with the App Server transport layer.");
                    }
                }
                else if (m_sipAppServerSocketsNode != null)
                {
                    m_sipTransport.AddSIPChannel(SIPTransportConfig.ParseSIPChannelsNode(m_sipAppServerSocketsNode));
                }
                else
                {
                    throw new ApplicationException("The SIP App Server could not be started, no SIP sockets have been configured.");
                }

                m_sipTransport.SIPRequestInTraceEvent += LogSIPRequestIn;
                m_sipTransport.SIPRequestOutTraceEvent += LogSIPRequestOut;
                m_sipTransport.SIPResponseInTraceEvent += LogSIPResponseIn;
                m_sipTransport.SIPResponseOutTraceEvent += LogSIPResponseOut;
                m_sipTransport.SIPBadRequestInTraceEvent += LogSIPBadRequestIn;
                m_sipTransport.SIPBadResponseInTraceEvent += LogSIPBadResponseIn;

                #endregion

                m_dialPlanEngine = new DialPlanEngine(
                    m_sipTransport,
                    m_sipSorceryPersistor.SIPDomainManager.GetDomain,
                    FireSIPMonitorEvent,
                    m_sipSorceryPersistor,
                    m_outboundProxy,
                    m_rubyScriptCommonPath,
                    m_dialplanImpersonationUsername,
                    m_dialplanImpersonationPassword,
                    m_maxDialPlanExecutionLimit);

                m_sipDialogueManager = new SIPDialogueManager(
                    m_sipTransport,
                     m_outboundProxy,
                     FireSIPMonitorEvent,
                     m_sipSorceryPersistor.SIPDialoguePersistor,
                     m_sipSorceryPersistor.SIPCDRPersistor,
                     SIPRequestAuthenticator.AuthenticateSIPRequest,
                     m_sipSorceryPersistor.SIPAccountsPersistor.Get,
                     m_sipSorceryPersistor.SIPDomainManager.GetDomain);

                m_callManager = new SIPCallManager(
                     m_sipTransport,
                     m_outboundProxy,
                     FireSIPMonitorEvent,
                     m_sipDialogueManager,
                     m_sipSorceryPersistor.SIPDialoguePersistor,
                     m_sipSorceryPersistor.SIPCDRPersistor,
                     m_dialPlanEngine,
                     m_sipSorceryPersistor.SIPDialPlanPersistor.Get,
                     m_sipSorceryPersistor.SIPAccountsPersistor.Get,
                     m_sipSorceryPersistor.SIPRegistrarBindingPersistor.Get,
                     m_sipSorceryPersistor.SIPProvidersPersistor.Get,
                     m_sipSorceryPersistor.SIPDomainManager.GetDomain,
                     m_customerSessionManager.CustomerPersistor,
                     m_sipSorceryPersistor.SIPDialPlanPersistor,
                     m_traceDirectory,
                     m_monitorCalls,
                     m_dailyCallLimit);
                m_callManager.Start();

                m_appServerCore = new SIPAppServerCore(
                    m_sipTransport,
                    m_sipSorceryPersistor.SIPDomainManager.GetDomain,
                    m_sipSorceryPersistor.SIPAccountsPersistor.Get,
                    FireSIPMonitorEvent,
                    m_callManager,
                    m_sipDialogueManager,
                    SIPRequestAuthenticator.AuthenticateSIPRequest,
                    m_outboundProxy);

                #endregion

                #region Initialise WCF services.

                try
                {
                    if (WCFUtility.DoesWCFServiceExist(typeof(CallManagerServices).FullName.ToString()))
                    {
                        CallManagerServiceInstanceProvider callManagerSvcInstanceProvider = new CallManagerServiceInstanceProvider(m_callManager, m_sipDialogueManager);

                        Uri callManagerBaseAddress = null;
                        if (m_callManagerServiceAddress != null)
                        {
                            logger.Debug("Adding service address to Call Manager Service " + m_callManagerServiceAddress + ".");
                            callManagerBaseAddress = new Uri(m_callManagerServiceAddress);
                        }

                        if (callManagerBaseAddress != null)
                        {
                            m_callManagerSvcHost = new ServiceHost(typeof(CallManagerServices), callManagerBaseAddress);
                        }
                        else
                        {
                            m_callManagerSvcHost = new ServiceHost(typeof(CallManagerServices));
                        }

                        m_callManagerSvcHost.Description.Behaviors.Add(callManagerSvcInstanceProvider);

                        m_callManagerSvcHost.Open();

                        logger.Debug("CallManager hosted service successfully started on " + m_callManagerSvcHost.BaseAddresses[0].AbsoluteUri + ".");
                    }
                }
                catch (Exception excp)
                {
                    logger.Warn("Exception starting CallManager hosted service. " + excp.Message);
                }

                #endregion
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPAppServerDaemon Start. " + excp.Message);
                throw excp;
            }
        }
        public RegistrarCore(
            SIPTransport sipTransport,
            SIPRegistrarBindingsManager registrarBindingsManager,
            SIPAssetGetDelegate<SIPAccount> getSIPAccount,
            GetCanonicalDomainDelegate getCanonicalDomain,
            bool mangleUACContact,
            bool strictRealmHandling,
            SIPMonitorLogDelegate proxyLogDelegate,
            SIPUserAgentConfigurationManager userAgentConfigs,
            SIPAuthenticateRequestDelegate sipRequestAuthenticator,
            string switchboardCertificateName)
        {
            m_sipTransport = sipTransport;
            m_registrarBindingsManager = registrarBindingsManager;
            GetSIPAccount_External = getSIPAccount;
            GetCanonicalDomain_External = getCanonicalDomain;
            m_mangleUACContact = mangleUACContact;
            m_strictRealmHandling = strictRealmHandling;
            m_registrarLogEvent = proxyLogDelegate;
            m_userAgentConfigs = userAgentConfigs;
            SIPRequestAuthenticator_External = sipRequestAuthenticator;

            try
            {
                if (!switchboardCertificateName.IsNullOrBlank())
                {
                    X509Certificate2 switchboardCertificate = AppState.LoadCertificate(StoreLocation.LocalMachine, switchboardCertificateName, false);
                    m_switchbboardRSAProvider = (RSACryptoServiceProvider)switchboardCertificate.PrivateKey;
                    logger.Debug("Switchboard RSA provider successfully loaded from " + switchboardCertificateName + " certificate.");
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception loading switchboard certificate using " + switchboardCertificateName + ". " + excp.Message);
            }
        }