public void ResolveSIPServiceFromCacheTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            CancellationTokenSource cts = new CancellationTokenSource();

            SIPURI lookupURI = SIPURI.ParseSIPURIRelaxed("sip:tel.t-online.de");
            //var result = SIPDNSManager.ResolveSIPService(lookupURI, false);
            var result = SIPDns.ResolveAsync(lookupURI, false, cts.Token).Result;

            Assert.NotNull(result);

            //SIPEndPoint resultEP = result.GetSIPEndPoint();
            Assert.NotNull(result);
            Assert.NotEqual(SIPEndPoint.Empty, result);
            logger.LogDebug($"resolved to SIP end point {result}.");
            //Assert.NotEmpty(result.SIPSRVResults);
            //Assert.NotEmpty(result.EndPointResults);

            // Do the same look up again immediately to check the result when it comes from the in-memory cache.
            var resultCache = SIPDns.ResolveFromCache(lookupURI, false);

            Assert.NotNull(resultCache);
            Assert.NotEqual(SIPEndPoint.Empty, resultCache);
            logger.LogDebug($"cache resolved to SIP end point {resultCache}.");
        }
        private SIPRequest GetRequest(SIPMethodsEnum method)
        {
            try
            {
                SIPURI uri = SIPURI.ParseSIPURIRelaxed(m_callDescriptor.Uri);

                SIPRequest    request    = new SIPRequest(method, uri);
                SIPFromHeader fromHeader = m_callDescriptor.GetFromHeader();
                fromHeader.FromTag = CallProperties.CreateNewTag();
                SIPToHeader toHeader = new SIPToHeader(null, uri, null);
                int         cseq     = Crypto.GetRandomInt(10000, 20000);

                SIPHeader header = new SIPHeader(fromHeader, toHeader, cseq, CallProperties.CreateNewCallId());
                header.CSeqMethod = method;
                header.UserAgent  = m_userAgent;
                request.Header    = header;

                header.Vias.PushViaHeader(SIPViaHeader.GetDefaultSIPViaHeader());

                try
                {
                    if (m_callDescriptor.CustomHeaders != null && m_callDescriptor.CustomHeaders.Count > 0)
                    {
                        foreach (string customHeader in m_callDescriptor.CustomHeaders)
                        {
                            if (customHeader.IsNullOrBlank())
                            {
                                continue;
                            }
                            else if (customHeader.Trim().StartsWith(SIPHeaders.SIP_HEADER_USERAGENT))
                            {
                                request.Header.UserAgent = customHeader.Substring(customHeader.IndexOf(":") + 1).Trim();
                            }
                            else
                            {
                                request.Header.UnknownHeaders.Add(customHeader);
                            }
                        }
                    }
                }
                catch (Exception excp)
                {
                    logger.LogError("Exception Parsing CustomHeader for SIPNonInviteClientUserAgent GetRequest. " + excp.Message + m_callDescriptor.CustomHeaders);
                }

                if (!m_callDescriptor.Content.IsNullOrBlank())
                {
                    request.Body = m_callDescriptor.Content;
                    request.Header.ContentType   = m_callDescriptor.ContentType;
                    request.Header.ContentLength = request.Body.Length;
                }

                return(request);
            }
            catch (Exception excp)
            {
                logger.LogError("Exception SIPNonInviteClientUserAgent GetRequest. " + excp.Message);
                throw;
            }
        }
示例#3
0
        static void Main()
        {
            Console.WriteLine("SIPSorcery Notification Client Demo");

            // Use verbose to get display the full SIP messages.
            AddConsoleLogger(LogEventLevel.Verbose);

            var sipTransport = new SIPTransport();

            sipTransport.EnableTraceLogs();

            var mwiURI = SIPURI.ParseSIPURIRelaxed($"{USERNAME}@{SERVER}");
            int expiry = 180;

            SIPNotifierClient mwiSubscriber = new SIPNotifierClient(sipTransport, null, SIPEventPackagesEnum.MessageSummary, mwiURI, USERNAME, null, PASSWORD, expiry, null);

            mwiSubscriber.SubscriptionFailed     += (uri, failureStatus, errorMessage) => Console.WriteLine($"MWI failed for {uri}, {errorMessage}");
            mwiSubscriber.SubscriptionSuccessful += (uri) => Console.WriteLine($"MWI subscription successful for {uri}");
            mwiSubscriber.NotificationReceived   += (evt, msg) => Console.WriteLine($"MWI notification, type {evt}, message {msg}.");

            mwiSubscriber.Start();

            Console.WriteLine("press any key to exit...");
            Console.ReadLine();

            Console.WriteLine("Exiting...");

            // Clean up.
            mwiSubscriber.Stop();
            Thread.Sleep(1000);
            sipTransport.Shutdown();
        }
示例#4
0
        /// <summary>
        /// Places an outgoing SIP call.
        /// </summary>
        /// <param name="destination">The SIP URI to place a call to. The destination can be a full SIP URI in which case the all will
        /// be placed anonymously directly to that URI. Alternatively it can be just the user portion of a URI in which case it will
        /// be sent to the configured SIP server.</param>
        public async Task Call(string destination)
        {
            // Determine if this is a direct anonymous call or whether it should be placed using the pre-configured SIP server account.
            SIPURI callURI     = null;
            string sipUsername = null;
            string sipPassword = null;
            string fromHeader  = null;

            if (destination.Contains("@") || m_sipServer == null)
            {
                // Anonymous call direct to SIP server specified in the URI.
                callURI    = SIPURI.ParseSIPURIRelaxed(destination);
                fromHeader = (new SIPFromHeader(m_sipFromName, SIPURI.ParseSIPURI(SIPFromHeader.DEFAULT_FROM_URI), null)).ToString();
            }
            else
            {
                // This call will use the pre-configured SIP account.
                callURI     = SIPURI.ParseSIPURIRelaxed(destination + "@" + m_sipServer);
                sipUsername = m_sipUsername;
                sipPassword = m_sipPassword;
                fromHeader  = (new SIPFromHeader(m_sipFromName, new SIPURI(m_sipUsername, m_sipServer, null), null)).ToString();
            }

            StatusMessage(this, $"Starting call to {callURI}.");

            var lookupResult = await Task.Run(() =>
            {
                return(SIPDNSManager.ResolveSIPService(callURI, false));
            });

            if (lookupResult == null || lookupResult.LookupError != null)
            {
                StatusMessage(this, $"Call failed, could not resolve {callURI}.");
            }
            else
            {
                var dstEndpoint = lookupResult.GetSIPEndPoint();
                StatusMessage(this, $"Call progressing, resolved {callURI} to {dstEndpoint}.");
                System.Diagnostics.Debug.WriteLine($"DNS lookup result for {callURI}: {dstEndpoint}.");
                SIPCallDescriptor callDescriptor = new SIPCallDescriptor(sipUsername, sipPassword, callURI.ToString(), fromHeader, null, null, null, null, SIPCallDirection.Out, _sdpMimeContentType, null, null);

                var audioSrcOpts = new AudioOptions
                {
                    AudioSource       = AudioSourcesEnum.Microphone,
                    OutputDeviceIndex = m_audioOutDeviceIndex
                };
                var videoSrcOpts = new VideoOptions
                {
                    VideoSource           = VideoSourcesEnum.TestPattern,
                    SourceFile            = RtpAVSession.VIDEO_TESTPATTERN,
                    SourceFramesPerSecond = VIDEO_LIVE_FRAMES_PER_SECOND
                };
                MediaSession = new RtpAVSession(audioSrcOpts, videoSrcOpts);

                m_userAgent.RemotePutOnHold   += OnRemotePutOnHold;
                m_userAgent.RemoteTookOffHold += OnRemoteTookOffHold;

                await m_userAgent.InitiateCallAsync(callDescriptor, MediaSession);
            }
        }
示例#5
0
        /// <summary>
        /// Parses the destination command line option into:
        ///  - A SIPEndPoint, which is an IP end point and transport (udp, tcp or tls),
        ///  - A SIP URI.
        ///  The SIPEndPoint determines the remote network destination to send the request to.
        ///  The SIP URI is whe URI that will be set on the request.
        /// </summary>
        /// <param name="dstn">The destination string to parse.</param>
        /// <returns>The SIPEndPoint and SIPURI parsed from the destination string.</returns>
        private static (SIPEndPoint, SIPURI) ParseDestination(string dst)
        {
            var dstEp = SIPEndPoint.ParseSIPEndPoint(dst);

            SIPURI dstUri = null;

            // Don't attempt a SIP URI parse for serialised SIPEndPoints.
            if (Regex.IsMatch(dst, "^(udp|tcp|tls|ws|wss)") == false && SIPURI.TryParse(dst))
            {
                dstUri = SIPURI.ParseSIPURIRelaxed(dst);
            }
            else
            {
                dstUri = new SIPURI(dstEp.Scheme, dstEp);
            }

            if (dstEp == null)
            {
                logger.LogDebug($"Could not extract IP end point from destination host of {dstUri.Host}.");
                var result = SIPDNSManager.ResolveSIPService(dstUri, false);
                if (result != null)
                {
                    logger.LogDebug($"Resolved SIP URI {dstUri} to {result.GetSIPEndPoint()}.");
                    dstEp = result.GetSIPEndPoint();
                }
            }

            return(dstEp, dstUri);
        }
 public void CallFailed(SIPResponseStatusCodesEnum failureStatus, string reasonPhrase, string[] customHeaders)
 {
     try
     {
         if (m_sipServerUserAgent != null && !m_isAnswered)
         {
             Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Call failed with a failure status of " + failureStatus + " and " + reasonPhrase + ".", Owner));
             m_isAnswered = true;
             if ((int)failureStatus >= 300 && (int)failureStatus <= 399)
             {
                 SIPURI redirectURI = SIPURI.ParseSIPURIRelaxed(customHeaders[0]);
                 m_sipServerUserAgent.Redirect(failureStatus, redirectURI);
             }
             else
             {
                 m_sipServerUserAgent.Reject(failureStatus, reasonPhrase, customHeaders);
             }
         }
     }
     catch (Exception excp)
     {
         logger.Error("Exception DialPlanContext CallFailed. " + excp.Message);
     }
     finally
     {
         DialPlanExecutionFinished();
     }
 }
        public void ResolveSIPServiceTest()
        {
            try
            {
                logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
                logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

                //SIPDNSManager.UseNAPTRLookups = true;

                CancellationTokenSource cts = new CancellationTokenSource();

                //var result = SIPDNSManager.ResolveSIPService(SIPURI.ParseSIPURIRelaxed("sip:reg.sip-trunk.telekom.de;transport=tcp"), false);
                var result = SIPDns.ResolveAsync(SIPURI.ParseSIPURIRelaxed("sip:reg.sip-trunk.telekom.de;transport=tcp"), false, cts.Token).Result;

                Assert.NotNull(result);
                logger.LogDebug($"resolved to SIP end point {result}.");
                //Assert.NotEmpty(result.SIPNAPTRResults);
                //Assert.NotEmpty(result.SIPSRVResults);
                //Assert.NotEmpty(result.EndPointResults);

                //result = SIPDNSManager.ResolveSIPService(SIPURI.ParseSIPURIRelaxed("sip:tel.t-online.de"), false);
                //Assert.NotNull(resultEP);
                //result = SIPDNSManager.ResolveSIPService(SIPURI.ParseSIPURIRelaxed("sips:hpbxsec.deutschland-lan.de:5061;transport=tls"), false);
                //Assert.NotNull(resultEP);
            }
            finally
            {
                //SIPDNSManager.UseNAPTRLookups = false;
            }
        }
 public void CallFailed(SIPResponseStatusCodesEnum failureStatus, string reasonPhrase, string[] customHeaders)
 {
     try
     {
         if (!m_isAnswered)
         {
             m_isAnswered = true;
             if ((int)failureStatus >= 300 && (int)failureStatus <= 399)
             {
                 SIPURI redirectURI = SIPURI.ParseSIPURIRelaxed(customHeaders[0]);
                 m_sipServerUserAgent.Redirect(failureStatus, redirectURI);
             }
             else
             {
                 m_sipServerUserAgent.Reject(failureStatus, reasonPhrase, customHeaders);
             }
         }
     }
     catch (Exception excp)
     {
         logger.Error("Exception DialPlanContext CallFailed. " + excp.Message);
     }
     finally
     {
         DialPlanExecutionFinished();
     }
 }
        public void ResolveSIPServiceTest()
        {
            try
            {
                logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
                logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

                SIPDNSManager.UseNAPTRLookups = true;

                var result = SIPDNSManager.ResolveSIPService(SIPURI.ParseSIPURIRelaxed("sip:reg.sip-trunk.telekom.de;transport=tcp"), false);

                SIPEndPoint resultEP = result.GetSIPEndPoint();
                Assert.NotNull(resultEP);
                logger.LogDebug($"resolved to SIP end point {resultEP}");
                Assert.NotEmpty(result.SIPNAPTRResults);
                Assert.NotEmpty(result.SIPSRVResults);
                Assert.NotEmpty(result.EndPointResults);

                result = SIPDNSManager.ResolveSIPService(SIPURI.ParseSIPURIRelaxed("sip:tel.t-online.de"), false);
                Assert.NotNull(resultEP);
                result = SIPDNSManager.ResolveSIPService(SIPURI.ParseSIPURIRelaxed("sips:hpbxsec.deutschland-lan.de:5061;transport=tls"), false);
                Assert.NotNull(resultEP);
            }
            finally
            {
                SIPDNSManager.UseNAPTRLookups = false;
            }
        }
示例#10
0
        public void NonRespondingDNSServerTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            var originalClient = SIPDns.LookupClient;

            try
            {
                LookupClientOptions clientOptions = new LookupClientOptions(IPAddress.Loopback)
                {
                    Retries        = 3,
                    Timeout        = TimeSpan.FromSeconds(1),
                    UseCache       = true,
                    UseTcpFallback = false
                };

                SIPDns.LookupClient = new LookupClient(clientOptions);

                CancellationTokenSource cts = new CancellationTokenSource();
                var result = SIPDns.ResolveAsync(SIPURI.ParseSIPURIRelaxed("sipsorcery.com"), false, cts.Token).Result;

                Assert.Equal(SIPEndPoint.Empty, result);
            }
            finally
            {
                SIPDns.LookupClient = originalClient;
            }
        }
示例#11
0
        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;
            }
        }
示例#12
0
        public void NonRespondingDNSServerTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            var originalClient = SIPDns.LookupClient;

            try
            {
                LookupClientOptions clientOptions = new LookupClientOptions(IPAddress.Loopback)
                {
                    Retries        = 3,
                    Timeout        = TimeSpan.FromSeconds(1),
                    UseCache       = true,
                    UseTcpFallback = false
                };

                SIPDns.PreferIPv6NameResolution = true;
                SIPDns.LookupClient             = new LookupClient(clientOptions);

                var result = SIPDns.Resolve(SIPURI.ParseSIPURIRelaxed("sipsorcery.com"), false).Result;

                Assert.Null(result);
            }
            finally
            {
                SIPDns.LookupClient             = originalClient;
                SIPDns.PreferIPv6NameResolution = false;
            }
        }
        public override void GetFullState()
        {
            try
            {
                List <SIPAccount> sipAccounts = null;

                if (ResourceURI.User == m_wildcardUser)
                {
                    if (m_switchboardSIPAccountsOnly)
                    {
                        //sipAccounts = m_sipAccountPersistor.Get(s => s.Owner == SubscriptionDialogue.Owner && s.IsSwitchboardEnabled, "SIPUsername", 0, MAX_SIPACCOUNTS_TO_RETRIEVE);
                        sipAccounts = GetSIPAccounts_External(s => s.Owner == SubscriptionDialogue.Owner && s.IsSwitchboardEnabled, "SIPUsername", 0, MAX_SIPACCOUNTS_TO_RETRIEVE);
                    }
                    else
                    {
                        //sipAccounts = m_sipAccountPersistor.Get(s => s.Owner == SubscriptionDialogue.Owner, "SIPUsername", 0, MAX_SIPACCOUNTS_TO_RETRIEVE);
                        sipAccounts = GetSIPAccounts_External(s => s.Owner == SubscriptionDialogue.Owner, "SIPUsername", 0, MAX_SIPACCOUNTS_TO_RETRIEVE);
                    }
                }
                else
                {
                    if (m_switchboardSIPAccountsOnly)
                    {
                        //sipAccounts = m_sipAccountPersistor.Get(s => s.SIPUsername == CanonicalResourceURI.User && s.SIPDomain == CanonicalResourceURI.Host && s.IsSwitchboardEnabled, "SIPUsername", 0, MAX_SIPACCOUNTS_TO_RETRIEVE);
                        sipAccounts = GetSIPAccounts_External(s => s.SIPUsername == CanonicalResourceURI.User && s.SIPDomain == CanonicalResourceURI.Host && s.IsSwitchboardEnabled, "SIPUsername", 0, MAX_SIPACCOUNTS_TO_RETRIEVE);
                    }
                    else
                    {
                        //sipAccounts = m_sipAccountPersistor.Get(s => s.SIPUsername == CanonicalResourceURI.User && s.SIPDomain == CanonicalResourceURI.Host, "SIPUsername", 0, MAX_SIPACCOUNTS_TO_RETRIEVE);
                        sipAccounts = GetSIPAccounts_External(s => s.SIPUsername == CanonicalResourceURI.User && s.SIPDomain == CanonicalResourceURI.Host, "SIPUsername", 0, MAX_SIPACCOUNTS_TO_RETRIEVE);
                    }
                }

                foreach (SIPAccount sipAccount in sipAccounts)
                {
                    SIPURI aor = SIPURI.ParseSIPURIRelaxed(sipAccount.SIPUsername + "@" + sipAccount.SIPDomain);

                    int bindingsCount = GetSIPRegistrarBindingsCount_External(b => b.SIPAccountId == sipAccount.Id);
                    if (bindingsCount > 0)
                    {
                        string safeSIPAccountID = sipAccount.Id.ToString();
                        Presence.Tuples.Add(new SIPEventPresenceTuple(safeSIPAccountID, SIPEventPresenceStateEnum.open, aor, Decimal.Zero, sipAccount.AvatarURL));
                        //logger.Debug(" full presence " + aor.ToString() + " open.");
                    }
                    else
                    {
                        string safeSIPAccountID = sipAccount.Id.ToString();
                        Presence.Tuples.Add(new SIPEventPresenceTuple(safeSIPAccountID, SIPEventPresenceStateEnum.closed, null, Decimal.Zero, sipAccount.AvatarURL));
                        //logger.Debug(" full presence " + aor.ToString() + " closed.");
                    }
                }

                MonitorLogEvent_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Notifier, SIPMonitorEventTypesEnum.NotifySent, "Full state notification for presence and " + ResourceURI.ToString() + ".", SubscriptionDialogue.Owner));
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPPresenceEventSubscription GetFullState. " + excp.Message);
            }
        }
示例#14
0
        public void ParseMalformedContactUnitTest()
        {
            Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

            Assert.Throws <SIPValidationException>(() => SIPURI.ParseSIPURIRelaxed("sip:[email protected], sip:5060"));

            Console.WriteLine("-----------------------------------------");
        }
示例#15
0
        public void ParseMalformedContactUnitTest()
        {
            Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

            SIPURI sipURI = SIPURI.ParseSIPURIRelaxed("sip:[email protected], sip:5060");

            Console.WriteLine(sipURI.ToString());
            Console.WriteLine("-----------------------------------------");
        }
示例#16
0
        private void SendInitialRegister()
        {
            try
            {
                if (m_attempts >= m_maxRegisterAttempts)
                {
                    logger.LogWarning("Registration to " + m_sipAccountAOR.ToString() + " reached the maximum number of allowed attempts without a failure condition.");
                    m_isRegistered = false;
                    RegistrationTemporaryFailure?.Invoke(m_sipAccountAOR, "Registration reached the maximum number of allowed attempts.");
                    m_waitForRegistrationMRE.Set();
                }
                else
                {
                    m_attempts++;

                    SIPEndPoint registrarSIPEndPoint = m_outboundProxy;
                    if (registrarSIPEndPoint == null)
                    {
                        //SIPDNSLookupResult lookupResult = m_sipTransport.GetHostEndPoint(m_registrarHost, false);
                        SIPURI uri          = SIPURI.ParseSIPURIRelaxed(m_registrarHost);
                        var    lookupResult = m_sipTransport.ResolveSIPUriAsync(uri).ConfigureAwait(false).GetAwaiter().GetResult();
                        if (lookupResult == null)
                        {
                            logger.LogWarning("Could not resolve " + m_registrarHost + ".");
                        }
                        else
                        {
                            registrarSIPEndPoint = lookupResult;
                        }
                    }

                    if (registrarSIPEndPoint == null)
                    {
                        logger.LogWarning("SIPRegistrationAgent could not resolve " + m_registrarHost + ".");

                        RegistrationFailed?.Invoke(m_sipAccountAOR, "Could not resolve " + m_registrarHost + ".");
                    }
                    else
                    {
                        logger.LogDebug("Initiating registration to " + m_registrarHost + " at " + registrarSIPEndPoint.ToString() + " for " + m_sipAccountAOR.ToString() + ".");
                        SIPRequest regRequest = GetRegistrationRequest();

                        SIPNonInviteTransaction regTransaction = new SIPNonInviteTransaction(m_sipTransport, regRequest, registrarSIPEndPoint);
                        // These handlers need to be on their own threads to take the processing off the SIP transport layer.
                        regTransaction.NonInviteTransactionFinalResponseReceived += (lep, rep, tn, rsp) => { ThreadPool.QueueUserWorkItem(delegate { ServerResponseReceived(lep, rep, tn, rsp); }); return(Task.FromResult(SocketError.Success)); };
                        regTransaction.NonInviteTransactionTimedOut += (tn) => { ThreadPool.QueueUserWorkItem(delegate { RegistrationTimedOut(tn); }); };

                        m_sipTransport.SendTransaction(regTransaction);
                    }
                }
            }
            catch (Exception excp)
            {
                logger.LogError("Exception SendInitialRegister to " + m_registrarHost + ". " + excp.Message);
                RegistrationFailed?.Invoke(m_sipAccountAOR, "Exception SendInitialRegister to " + m_registrarHost + ". " + excp.Message);
            }
        }
示例#17
0
        public void ParseMalformedContactUnitTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            Assert.Throws <SIPValidationException>(() => SIPURI.ParseSIPURIRelaxed("sip:[email protected], sip:5060"));

            logger.LogDebug("-----------------------------------------");
        }
示例#18
0
        public void ResolveNonExistentServiceTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            var result = SIPDns.Resolve(SIPURI.ParseSIPURIRelaxed("sipsorceryx.com"), false).Result;

            Assert.Null(result);
        }
示例#19
0
        public void ParseUDPProtocolToStringTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            SIPURI sipURI = SIPURI.ParseSIPURIRelaxed("127.0.0.1");
            logger.LogDebug(sipURI.ToString());
            Assert.True(sipURI.ToString() == "sip:127.0.0.1", "The SIP URI was not ToString'ed correctly.");
            logger.LogDebug("-----------------------------------------");
        }
示例#20
0
        public void ResolveNonExistentServiceTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            CancellationTokenSource cts = new CancellationTokenSource();
            var result = SIPDns.ResolveAsync(SIPURI.ParseSIPURIRelaxed("sipsorceryx.com"), false, cts.Token).Result;

            Assert.Equal(SIPEndPoint.Empty, result);
        }
示例#21
0
        public void ParseBigURIUnitTest()
        {
            Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

            SIPURI sipURI = SIPURI.ParseSIPURIRelaxed("[email protected]:5069");

            Console.WriteLine(sipURI.ToString());
            Assert.True(sipURI.ToString() == "sip:[email protected]:5069", "The SIP URI was not ToString'ed correctly.");
            Console.WriteLine("-----------------------------------------");
        }
示例#22
0
        public void ParseUDPProtocolToStringTest()
        {
            Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

            SIPURI sipURI = SIPURI.ParseSIPURIRelaxed("127.0.0.1");

            Console.WriteLine(sipURI.ToString());
            Assert.True(sipURI.ToString() == "sip:127.0.0.1", "The SIP URI was not ToString'ed correctly.");
            Console.WriteLine("-----------------------------------------");
        }
        public async Task BlindTransferCancelUnitTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            SIPTransport transport = new SIPTransport();

            transport.AddSIPChannel(new MockSIPChannel(new System.Net.IPEndPoint(IPAddress.Any, 0)));

            SIPUserAgent userAgent = new SIPUserAgent(transport, null);

            string inviteReqStr = "INVITE sip:192.168.11.50:5060 SIP/2.0" + m_CRLF +
                                  "Via: SIP/2.0/UDP 192.168.11.50:60163;rport;branch=z9hG4bKPj869f70960bdd4204b1352eaf242a3691" + m_CRLF +
                                  "To: <sip:[email protected]>;tag=ZUJSXRRGXQ" + m_CRLF +
                                  "From: <sip:[email protected]>;tag=4a60ce364b774258873ff199e5e39938" + m_CRLF +
                                  "Call-ID: 17324d6df8744d978008c8997bfd208d" + m_CRLF +
                                  "CSeq: 3532 INVITE" + m_CRLF +
                                  "Contact: <sip:[email protected]:60163;ob>" + m_CRLF +
                                  "Max-Forwards: 70" + m_CRLF +
                                  "User-Agent: MicroSIP/3.19.22" + m_CRLF +
                                  "Allow: PRACK, INVITE, ACK, BYE, CANCEL, UPDATE, INFO, SUBSCRIBE, NOTIFY, REFER, MESSAGE, OPTIONS" + m_CRLF +
                                  "Supported: replaces, 100rel, timer, norefersub" + m_CRLF +
                                  "Content-Length: 343" + m_CRLF +
                                  "Content-Type: application/sdp" + m_CRLF +
                                  "Session-Expires: 1800" + m_CRLF +
                                  "Min-SE: 90" + m_CRLF +
                                  "" + m_CRLF +
                                  "v=0" + m_CRLF +
                                  "o=- 3785527268 3785527269 IN IP4 192.168.11.50" + m_CRLF +
                                  "s=pjmedia" + m_CRLF +
                                  "t=0 0" + m_CRLF +
                                  "m=audio 4032 RTP/AVP 0 101" + m_CRLF +
                                  "c=IN IP4 192.168.11.50" + m_CRLF +
                                  "a=rtpmap:0 PCMU/8000" + m_CRLF +
                                  "a=rtpmap:101 telephone-event/8000" + m_CRLF +
                                  "a=fmtp:101 0-16" + m_CRLF +
                                  "a=sendrecv";

            SIPEndPoint      dummySipEndPoint = new SIPEndPoint(new IPEndPoint(IPAddress.Any, 0));
            SIPMessageBuffer sipMessageBuffer = SIPMessageBuffer.ParseSIPMessage(inviteReqStr, dummySipEndPoint, dummySipEndPoint);
            SIPRequest       inviteReq        = SIPRequest.ParseSIPRequest(sipMessageBuffer);

            UASInviteTransaction uasTx   = new UASInviteTransaction(transport, inviteReq, null);
            SIPServerUserAgent   mockUas = new SIPServerUserAgent(transport, null, null, null, SIPCallDirection.In, null, null, null, uasTx);
            await userAgent.Answer(mockUas, CreateMediaSession());

            CancellationTokenSource cts = new CancellationTokenSource();
            var blindTransferTask       = userAgent.BlindTransfer(SIPURI.ParseSIPURIRelaxed("127.0.0.1"), TimeSpan.FromSeconds(2), cts.Token);

            cts.Cancel();

            Assert.False(await blindTransferTask);

            //await Assert.ThrowsAnyAsync<TaskCanceledException>(async () => { bool result = ; });
        }
示例#24
0
        private void SendInitialRegister()
        {
            try
            {
                if (m_attempts >= m_maxRegisterAttempts)
                {
                    logger.LogWarning($"Registration to {m_sipAccountAOR} reached the maximum number of allowed attempts without a failure condition.");
                    m_isRegistered = false;
                    RegistrationTemporaryFailure?.Invoke(m_sipAccountAOR, "Registration reached the maximum number of allowed attempts.");
                    m_waitForRegistrationMRE.Set();
                }
                else
                {
                    m_attempts++;

                    SIPEndPoint registrarSIPEndPoint = m_outboundProxy;
                    if (registrarSIPEndPoint == null)
                    {
                        SIPURI uri          = SIPURI.ParseSIPURIRelaxed(m_registrarHost);
                        var    lookupResult = m_sipTransport.ResolveSIPUriAsync(uri).Result;
                        if (lookupResult == null || lookupResult == SIPEndPoint.Empty)
                        {
                            logger.LogWarning("Could not resolve " + m_registrarHost + " when sending initial registration request.");
                        }
                        else
                        {
                            registrarSIPEndPoint = lookupResult;
                        }
                    }

                    if (registrarSIPEndPoint == null)
                    {
                        logger.LogWarning("SIPRegistrationAgent could not resolve " + m_registrarHost + ".");

                        RegistrationFailed?.Invoke(m_sipAccountAOR, "Could not resolve " + m_registrarHost + ".");
                    }
                    else
                    {
                        logger.LogDebug("Initiating registration to " + m_registrarHost + " at " + registrarSIPEndPoint.ToString() + " for " + m_sipAccountAOR.ToString() + ".");
                        SIPRequest regRequest = GetRegistrationRequest();

                        SIPNonInviteTransaction regTransaction = new SIPNonInviteTransaction(m_sipTransport, regRequest, registrarSIPEndPoint);
                        regTransaction.NonInviteTransactionFinalResponseReceived += (lep, rep, tn, rsp) => { ServerResponseReceived(lep, rep, tn, rsp); return(Task.FromResult(SocketError.Success)); };
                        regTransaction.NonInviteTransactionTimedOut += RegistrationTimedOut;

                        m_sipTransport.SendTransaction(regTransaction);
                    }
                }
            }
            catch (Exception excp)
            {
                logger.LogError("Exception SendInitialRegister to " + m_registrarHost + ". " + excp.Message);
                RegistrationFailed?.Invoke(m_sipAccountAOR, "Exception SendInitialRegister to " + m_registrarHost + ". " + excp.Message);
            }
        }
示例#25
0
        public void Start(string endpoint)
        {
            this.endpoint = endpoint;

            var caller   = "1003";
            var password = passwords[0];
            var port     = FreePort.FindNextAvailableUDPPort(15090);

            rtpChannel = new RTPChannel
            {
                DontTimeout    = true,
                RemoteEndPoint = new IPEndPoint(IPAddress.Parse(asterisk), port)
            };

            rtpChannel.SetFrameType(FrameTypesEnum.Audio);
            rtpChannel.ReservePorts(15000, 15090);
            rtpChannel.OnFrameReady += RtpChannel_OnFrameReady;

            uac = new SIPClientUserAgent(transport, null, null, null, null);

            var uri    = SIPURI.ParseSIPURIRelaxed($"{ endpoint }@{ asterisk }");
            var from   = (new SIPFromHeader(caller, new SIPURI(caller, asterisk, null), null)).ToString();
            var random = Crypto.GetRandomInt(5).ToString();
            var sdp    = new SDP
            {
                Version     = 2,
                Username    = "******",
                SessionId   = random,
                Address     = localIPEndPoint.Address.ToString(),
                SessionName = "redfox_" + random,
                Timing      = "0 0",
                Connection  = new SDPConnectionInformation(publicIPAddress.ToString())
            };

            var announcement = new SDPMediaAnnouncement
            {
                Media        = SDPMediaTypesEnum.audio,
                MediaFormats = new List <SDPMediaFormat>()
                {
                    new SDPMediaFormat((int)SDPMediaFormatsEnum.PCMU, "PCMU", 8000)
                },
                Port = rtpChannel.RTPPort
            };

            sdp.Media.Add(announcement);

            var descriptor = new SIPCallDescriptor(caller, password, uri.ToString(), from, null, null, null, null, SIPCallDirection.Out, SDP.SDP_MIME_CONTENTTYPE, sdp.ToString(), null);

            uac.CallTrying   += Uac_CallTrying;
            uac.CallRinging  += Uac_CallRinging;
            uac.CallAnswered += Uac_CallAnswered;
            uac.CallFailed   += Uac_CallFailed;

            uac.Call(descriptor);
        }
        public void SetProviderFields(SIPProvider sipProvider)
        {
            ProviderID            = sipProvider.ID;
            Owner                 = sipProvider.Owner;
            AdminMemberID         = sipProvider.AdminMemberID;
            ProviderName          = sipProvider.ProviderName;
            ProviderAuthUsername  = (!sipProvider.ProviderAuthUsername.IsNullOrBlank()) ? sipProvider.ProviderAuthUsername : sipProvider.ProviderUsername;
            ProviderPassword      = sipProvider.ProviderPassword;
            RegistrarServer       = sipProvider.GetRegistrar();
            RegistrarRealm        = (!sipProvider.RegisterRealm.IsNullOrBlank()) ? sipProvider.RegisterRealm : RegistrarServer.Host;
            ProviderOutboundProxy = sipProvider.ProviderOutboundProxy;

            if (sipProvider.RegisterEnabled)
            {
                BindingExpiry = (sipProvider.RegisterExpiry.HasValue) ? sipProvider.RegisterExpiry.Value : 0;
            }
            else
            {
                BindingExpiry = 0;
            }

            string bindingId = null;
            SIPURI binding   = (!BindingURI.IsNullOrBlank()) ? SIPURI.ParseSIPURIRelaxed(BindingURI) : null;

            if (binding != null && binding.Parameters.Has(REGAGENT_CONTACT_ID_KEY))
            {
                bindingId = binding.Parameters.Get(REGAGENT_CONTACT_ID_KEY);
            }

            if (!sipProvider.RegisterContact.IsNullOrBlank())
            {
                binding = SIPURI.ParseSIPURI(sipProvider.RegisterContact);
                if (!bindingId.IsNullOrBlank())
                {
                    binding.Parameters.Set(REGAGENT_CONTACT_ID_KEY, bindingId);
                }

                if (binding != null)
                {
                    BindingURI = binding.ToString();
                }
                else
                {
                    BindingURI    = null;
                    BindingExpiry = 0;
                }
            }
            else
            {
                // The register contact field on the SIP Provider is empty.
                // This condition needs to be trearted as the binding being disabled and it needs to be removed.
                BindingExpiry = 0;
            }
        }
示例#27
0
        public void ResolveHostFromServiceTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            var result = SIPDns.Resolve(SIPURI.ParseSIPURIRelaxed("sipsorcery.com"), false).Result;

            Assert.NotNull(result);

            logger.LogDebug($"resolved to SIP end point {result}.");
        }
示例#28
0
        public void ResolveHostFromServiceTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

            var result = SIPDNSManager.ResolveSIPService(SIPURI.ParseSIPURIRelaxed("sipsorcery.com"), false);

            SIPEndPoint resultEP = result.GetSIPEndPoint();

            Assert.NotNull(resultEP);

            logger.LogDebug($"resolved to SIP end point {resultEP}");
        }
 public static SIPDNSLookupResult ResolveSIPService(string host)
 {
     try
     {
         return(ResolveSIPService(SIPURI.ParseSIPURIRelaxed(host), true));
     }
     catch (Exception excp)
     {
         logger.Error("Exception SIPDNSManager ResolveSIPService (" + host + "). " + excp.Message);
         throw;
     }
 }
示例#30
0
        public void ParsePartialURISIPSSchemeUnitTest()
        {
            Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

            SIPURI sipURI = SIPURI.ParseSIPURIRelaxed("sips:sip.domain.com:1234");

            Assert.True(sipURI.Scheme == SIPSchemesEnum.sips, "The SIP URI scheme was not parsed correctly.");
            Assert.True(sipURI.User == null, "The SIP URI User was not parsed correctly.");
            Assert.True(sipURI.Host == "sip.domain.com:1234", "The SIP URI Host was not parsed correctly.");

            Console.WriteLine("-----------------------------------------");
        }