コード例 #1
0
        //[Fact]
        public async void LookupAnyRecordAsyncCacheTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            //1.queue dns lookup for async resolution
            //DNSResponse result = DNSManager.Lookup("dns.google", QType.ANY, 1, null, false, true);

            var nonCacheResult = SIPDns.LookupClient.QueryAsync("dns.google", QueryType.ANY);

            Assert.False(nonCacheResult.IsCompleted);

            System.Threading.Thread.Sleep(500);

            //2.check lookup / resolution cache for result
            //result = DNSManager.Lookup("dns.google", QType.ANY, 150, null, true, false);
            var result = await SIPDns.LookupClient.QueryAsync("dns.google", QueryType.ANY);

            Assert.NotNull(result);

            Assert.NotEmpty(result.Answers?.AddressRecords());
            var ipv4Addresses = from a in result.Answers?.AddressRecords() select a.Address;

            Assert.NotEmpty(ipv4Addresses);
            Assert.Contains(IPSocket.ParseSocketString("8.8.8.8").Address, ipv4Addresses);
            Assert.Contains(IPSocket.ParseSocketString("8.8.4.4").Address, ipv4Addresses);

            Assert.NotEmpty(result.Answers?.AaaaRecords());
            var ipv6Addresses = from a in result.Answers?.AaaaRecords() select a.Address;

            Assert.NotEmpty(ipv6Addresses);
            Assert.Contains(IPSocket.ParseSocketString("2001:4860:4860::8888").Address, ipv6Addresses);
            Assert.Contains(IPSocket.ParseSocketString("2001:4860:4860::8844").Address, ipv6Addresses);
        }
コード例 #2
0
        public static List <IPEndPoint> ParseIPSockets(XmlNode socketNodes)
        {
            List <IPEndPoint> endPoints      = new List <IPEndPoint>();
            List <IPAddress>  localAddresses = GetLocalIPv4Addresses();

            foreach (XmlNode socketNode in socketNodes.ChildNodes)
            {
                string socketString = socketNode.InnerText;
                Logger.Logger.Debug("Parsing end point from socket string " + socketString + ".");

                int port = IPSocket.ParsePortFromSocket(socketString);
                if (socketString.StartsWith(ALL_LOCAL_IPADDRESSES_KEY))
                {
                    foreach (IPAddress ipAddress in localAddresses)
                    {
                        endPoints.Add(new IPEndPoint(ipAddress, port));
                    }
                }
                else
                {
                    endPoints.Add(IPSocket.ParseSocketString(socketString));
                }
            }

            return(endPoints);
        }
コード例 #3
0
        public void LookupAnyRecordAsyncCacheTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            //1.queue dns lookup for async resolution
            DNSResponse result = DNSManager.Lookup("dns.google", QType.ANY, 1, null, false, true);

            Assert.Null(result);

            System.Threading.Thread.Sleep(500);

            //2.check lookup / resolution cache for result
            result = DNSManager.Lookup("dns.google", QType.ANY, 150, null, true, false);

            Assert.NotNull(result);

            Assert.NotEmpty(result.RecordsA);
            var ipv4Addresses = from a in result.RecordsA select a.Address;

            Assert.NotEmpty(ipv4Addresses);
            Assert.Contains(IPSocket.ParseSocketString("8.8.8.8").Address, ipv4Addresses);
            Assert.Contains(IPSocket.ParseSocketString("8.8.4.4").Address, ipv4Addresses);

            Assert.NotEmpty(result.RecordsAAAA);
            var ipv6Addresses = from a in result.RecordsAAAA select a.Address;

            Assert.NotEmpty(ipv6Addresses);
            Assert.Contains(IPSocket.ParseSocketString("2001:4860:4860::8888").Address, ipv6Addresses);
            Assert.Contains(IPSocket.ParseSocketString("2001:4860:4860::8844").Address, ipv6Addresses);
        }
コード例 #4
0
        //[Fact]
        public async void LookupAnyRecordTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            //DNSResponse result = DNSManager.Lookup("dns.google", QType.ANY, 100, null, false, false);
            var result = await SIPDns.LookupClient.QueryAsync("dns.google", QueryType.ANY);

            Assert.NotNull(result);

            //Assert.NotEmpty(result.RecordsA);
            Assert.NotEmpty(result.Answers?.AddressRecords());
            var ipv4Addresses = from a in result.Answers.AddressRecords() select a.Address;

            Assert.NotEmpty(ipv4Addresses);
            Assert.Contains(IPSocket.ParseSocketString("8.8.8.8").Address, ipv4Addresses);
            Assert.Contains(IPSocket.ParseSocketString("8.8.4.4").Address, ipv4Addresses);

            Assert.NotEmpty(result.Answers?.AaaaRecords());
            var ipv6Addresses = from a in result.Answers.AaaaRecords() select a.Address;

            Assert.NotEmpty(ipv6Addresses);
            Assert.Contains(IPSocket.ParseSocketString("2001:4860:4860::8888").Address, ipv6Addresses);
            Assert.Contains(IPSocket.ParseSocketString("2001:4860:4860::8844").Address, ipv6Addresses);
        }
コード例 #5
0
        public static NetTestDescriptor ParseNetTestDescriptor(string description)
        {
            try
            {
                if (description == null || description.Trim().Length == 0)
                {
                    Logger.Logger.Error("Cannot parse NetTestDescriptor from an empty string.");
                    return(null);
                }
                else
                {
                    int numberChannels = Convert.ToInt32(Regex.Match(description, @"channels=(?<channels>\d+)",
                                                                     RegexOptions.IgnoreCase | RegexOptions.Singleline).Result("${channels}"));
                    int frameSize = Convert.ToInt32(Regex.Match(description, @"frame=(?<frame>\d+)",
                                                                RegexOptions.IgnoreCase | RegexOptions.Singleline).Result("${frame}"));
                    int payloadSize = Convert.ToInt32(Regex.Match(description, @"payload=(?<payload>\d+)",
                                                                  RegexOptions.IgnoreCase | RegexOptions.Singleline).Result("${payload}"));
                    string socketStr = Regex.Match(description, @"socket=(?<socket>.+?)(\s|$)",
                                                   RegexOptions.IgnoreCase | RegexOptions.Singleline).Result("${socket}");

                    NetTestDescriptor descriptor = new NetTestDescriptor(numberChannels, frameSize, payloadSize,
                                                                         IPSocket.ParseSocketString(socketStr));
                    return(descriptor);
                }
            }
            catch (Exception excp)
            {
                Logger.Logger.Error("Exception ParseNetTestDescriptor. ->" + excp.Message);
                throw excp;
            }
        }
コード例 #6
0
        public SIPEndPoint(SIPURI sipURI)
        {
            Protocol = sipURI.Protocol;
            IPEndPoint endPoint = IPSocket.ParseSocketString(sipURI.Host);

            Address = endPoint.Address;
            Port    = (endPoint.Port == 0) ? (Protocol == SIPProtocolsEnum.tls) ? m_defaultSIPTLSPort : m_defaultSIPPort : endPoint.Port;
        }
コード例 #7
0
        static SIPRegistrarState()
        {
            try
            {
                #region Configure logging.

                try
                {
                    log4net.Config.XmlConfigurator.Configure();
                    logger = log4net.LogManager.GetLogger(LOGGER_NAME);
                }
                catch (Exception logExcp)
                {
                    Console.WriteLine("Exception SIPRegistrarState Configure Logging. " + logExcp.Message);
                }

                #endregion

                if (AppState.GetSection(SIPREGISTRAR_CONFIGNODE_NAME) != null)
                {
                    m_sipRegistrarNode = (XmlNode)AppState.GetSection(SIPREGISTRAR_CONFIGNODE_NAME);
                }

                if (m_sipRegistrarNode == null)
                {
                    //throw new ApplicationException("The SIP Registrar could not be started, no " + SIPREGISTRAR_CONFIGNODE_NAME + " config node available.");
                    logger.Warn("The SIP Registrar " + SIPREGISTRAR_CONFIGNODE_NAME + " config node was not available, the agent will not be able to start.");
                }
                else
                {
                    SIPRegistrarSocketsNode = m_sipRegistrarNode.SelectSingleNode(SIPSOCKETS_CONFIGNODE_NAME);
                    if (SIPRegistrarSocketsNode == null)
                    {
                        throw new ApplicationException("The SIP Registrar could not be started, no " + SIPSOCKETS_CONFIGNODE_NAME + " node could be found.");
                    }

                    UserAgentsConfigNode = m_sipRegistrarNode.SelectSingleNode(USERAGENTS_CONFIGNODE_NAME);
                    Int32.TryParse(AppState.GetConfigNodeValue(m_sipRegistrarNode, MONITOR_LOOPBACK_PORT_KEY), out MonitorLoopbackPort);
                    Int32.TryParse(AppState.GetConfigNodeValue(m_sipRegistrarNode, MAXIMUM_ACCOUNT_BINDINGS_KEY), out MaximumAccountBindings);
                    if (!AppState.GetConfigNodeValue(m_sipRegistrarNode, NATKEEPALIVE_RELAY_SOCKET).IsNullOrBlank())
                    {
                        NATKeepAliveRelaySocket = IPSocket.ParseSocketString(AppState.GetConfigNodeValue(m_sipRegistrarNode, NATKEEPALIVE_RELAY_SOCKET));
                    }
                    //SwitchboardCertificateName = AppState.GetConfigNodeValue(m_sipRegistrarNode, SWITCHBOARD_CERTIFICATE_NAME_KEY);
                    SwitchboardUserAgentPrefix = AppState.GetConfigNodeValue(m_sipRegistrarNode, SWITCHBOARD_USERAGNET_PREFIX_KEY);
                    if (!AppState.GetConfigNodeValue(m_sipRegistrarNode, THREAD_COUNT_KEY).IsNullOrBlank())
                    {
                        Int32.TryParse(AppState.GetConfigNodeValue(m_sipRegistrarNode, THREAD_COUNT_KEY), out ThreadCount);
                    }
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPRegistrarState. " + excp.Message);
                throw;
            }
        }
コード例 #8
0
        public SIPMonitorUDPSink(string udpSocket)
        {
            logger.Debug("Request to create SIPMonitorUDPSink on " + udpSocket + ".");

            m_monitorProxyManager   = new MonitorProxyManager();
            m_eventReceiverEndPoint = IPSocket.ParseSocketString(udpSocket);

            ThreadPool.QueueUserWorkItem(delegate { Listen(); });
        }
コード例 #9
0
 private void SendMonitorEventViaUDP(SIPMonitorEvent monitorEvent, string destinationSocket)
 {
     try
     {
         byte[] monitorEventBytes = Encoding.UTF8.GetBytes(monitorEvent.ToCSV());
         m_udpEventSender.Send(monitorEventBytes, monitorEventBytes.Length, IPSocket.ParseSocketString(destinationSocket));
     }
     catch (Exception excp)
     {
         logger.Error("Exception SendMonitorEventViaUDP. " + excp.Message);
     }
 }
コード例 #10
0
        /// <summary>
        /// Initialises the SIP transport layer.
        /// </summary>
        public async Task InitialiseSIP()
        {
            if (_isIntialised == false)
            {
                await Task.Run(() =>
                {
                    _isIntialised = true;

                    if (String.IsNullOrEmpty(m_DnsServer) == false)
                    {
                        // Use a custom DNS server.
                        m_DnsServer = m_DnsServer.Contains(":") ? m_DnsServer : m_DnsServer + ":53";
                        DNSManager.SetDNSServers(new List <IPEndPoint> {
                            IPSocket.ParseSocketString(m_DnsServer)
                        });
                    }

                    // Configure the SIP transport layer.
                    m_sipTransport       = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine());
                    bool sipChannelAdded = false;

                    if (m_sipSocketsNode != null)
                    {
                        // Set up the SIP channels based on the app.config file.
                        List <SIPChannel> sipChannels = SIPTransportConfig.ParseSIPChannelsNode(m_sipSocketsNode);
                        if (sipChannels?.Count > 0)
                        {
                            m_sipTransport.AddSIPChannel(sipChannels);
                            sipChannelAdded = true;
                        }
                    }

                    if (sipChannelAdded == false)
                    {
                        // Use default options to set up a SIP channel.
                        int port       = FreePort.FindNextAvailableUDPPort(_defaultSIPUdpPort);
                        var sipChannel = new SIPUDPChannel(new IPEndPoint(_defaultLocalAddress, port));
                        m_sipTransport.AddSIPChannel(sipChannel);
                    }
                });

                // Wire up the transport layer so incoming SIP requests have somewhere to go.
                m_sipTransport.SIPTransportRequestReceived += SIPTransportRequestReceived;

                // Log all SIP packets received to a log file.
                m_sipTransport.SIPRequestInTraceEvent   += (localSIPEndPoint, endPoint, sipRequest) => { _sipTraceLogger.Debug("Request Received : " + localSIPEndPoint + "<-" + endPoint + "\r\n" + sipRequest.ToString()); };
                m_sipTransport.SIPRequestOutTraceEvent  += (localSIPEndPoint, endPoint, sipRequest) => { _sipTraceLogger.Debug("Request Sent: " + localSIPEndPoint + "->" + endPoint + "\r\n" + sipRequest.ToString()); };
                m_sipTransport.SIPResponseInTraceEvent  += (localSIPEndPoint, endPoint, sipResponse) => { _sipTraceLogger.Debug("Response Received: " + localSIPEndPoint + "<-" + endPoint + "\r\n" + sipResponse.ToString()); };
                m_sipTransport.SIPResponseOutTraceEvent += (localSIPEndPoint, endPoint, sipResponse) => { _sipTraceLogger.Debug("Response Sent: " + localSIPEndPoint + "->" + endPoint + "\r\n" + sipResponse.ToString()); };
            }
        }
コード例 #11
0
        private IPEndPoint ResolveSIPSocketInternal(string socket)
        {
            logger.Debug("Attempting to resolve SIP socket " + socket + ".");

            if (socket == null || socket.Trim().Length == 0)
            {
                logger.Warn("An empty socket string was passed to the DNSResolver.");
                return(null);
            }

            int    port     = DEFAULT_SIP_PORT;
            string hostname = socket;

            int colonIndex = socket.LastIndexOf(":");

            if (colonIndex != -1)
            {
                port     = Convert.ToInt32(socket.Substring(colonIndex + 1));
                hostname = socket.Substring(0, colonIndex);
            }

            DateTime    startTime   = DateTime.Now;
            IPHostEntry serverEntry = Dns.GetHostEntry(hostname);
            TimeSpan    resolveTime = DateTime.Now.Subtract(startTime);

            if (serverEntry != null)
            {
                IPAddress address = ((IPAddress[])serverEntry.AddressList)[0];

                if (resolveTime.TotalMilliseconds > 20)
                {
                    logger.Debug("Hostname " + hostname + " resolved to " + address.ToString() + " in " + resolveTime.TotalMilliseconds + "ms.");
                }

                return(IPSocket.ParseSocketString(address.ToString() + ":" + port));
            }
            else
            {
                //throw new ApplicationException("Could not resolve " + socket + ".");
                return(null);
            }
        }
コード例 #12
0
        public void LookupAnyRecordTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            DNSResponse result = DNSManager.Lookup("dns.google", QType.ANY, 100, null, false, false);

            Assert.NotNull(result);

            Assert.NotEmpty(result.RecordsA);
            var ipv4Addresses = from a in result.RecordsA select a.Address;

            Assert.NotEmpty(ipv4Addresses);
            Assert.Contains(IPSocket.ParseSocketString("8.8.8.8").Address, ipv4Addresses);
            Assert.Contains(IPSocket.ParseSocketString("8.8.4.4").Address, ipv4Addresses);

            Assert.NotEmpty(result.RecordsAAAA);
            var ipv6Addresses = from a in result.RecordsAAAA select a.Address;

            Assert.NotEmpty(ipv6Addresses);
            Assert.Contains(IPSocket.ParseSocketString("2001:4860:4860::8888").Address, ipv6Addresses);
            Assert.Contains(IPSocket.ParseSocketString("2001:4860:4860::8844").Address, ipv6Addresses);
        }
コード例 #13
0
        public static readonly string PublicIPAddress;          // Should only be set if operating on a static public IP otherwise use the STUN client.

        static SIPProxyState()
        {
            try
            {
                logger = AppState.GetLogger(LOGGER_NAME);

                if (AppState.GetSection(SIPPROXY_CONFIGNODE_NAME) != null)
                {
                    m_sipProxyNode = (XmlNode)AppState.GetSection(SIPPROXY_CONFIGNODE_NAME);
                }
                else
                {
                    throw new ApplicationException("The SIP Proxy could not be started, no " + SIPPROXY_CONFIGNODE_NAME + " config node available.");
                }

                SIPProxySocketsNode = m_sipProxyNode.SelectSingleNode(SIPSOCKETS_CONFIGNODE_NAME);
                if (SIPProxySocketsNode == null)
                {
                    throw new ApplicationException("The SIP Proxy could not be started, no " + SIPSOCKETS_CONFIGNODE_NAME + " node could be found.");
                }

                ProxyScriptPath        = AppState.ToAbsoluteFilePath(AppState.GetConfigNodeValue(m_sipProxyNode, PROXY_SCRIPTPATH_KEY));
                AppServerEndPointsPath = AppState.ToAbsoluteFilePath(AppState.GetConfigNodeValue(m_sipProxyNode, PROXY_APPSERVER_ENDPOINTS_PATH_KEY));
                if (!AppState.GetConfigNodeValue(m_sipProxyNode, PROXY_NATKEEPALIVESOCKET_KEY).IsNullOrBlank())
                {
                    NATKeepAliveSocket = IPSocket.ParseSocketString(AppState.GetConfigNodeValue(m_sipProxyNode, PROXY_NATKEEPALIVESOCKET_KEY));
                }
                Int32.TryParse(AppState.GetConfigNodeValue(m_sipProxyNode, PROXY_LOOPBACK_PORT_KEY), out MonitorLoopbackPort);
                STUNServerHostname = AppState.GetConfigNodeValue(m_sipProxyNode, PROXY_STUNSERVERHOSTNAME_KEY);
                PublicIPAddress    = AppState.GetConfigNodeValue(m_sipProxyNode, PROXY_PUBLICIPADDRESS_KEY);
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPProxyState. " + excp.Message);
                throw;
            }
        }
コード例 #14
0
 public static SIPDNSLookupResult Resolve(SIPURI sipURI, bool async)
 {
     // This assumes the input SIP URI has an IP address as the host!
     return(new SIPDNSLookupResult(sipURI, new SIPEndPoint(IPSocket.ParseSocketString(sipURI.Host))));
 }
コード例 #15
0
        /// <summary>
        /// Initialises the SIP transport layer.
        /// </summary>
        public async Task InitialiseSIP()
        {
            if (_isInitialised == false)
            {
                await Task.Run(() =>
                {
                    _isInitialised = true;

                    if (String.IsNullOrEmpty(m_DnsServer) == false)
                    {
                        // Use a custom DNS server.
                        m_DnsServer = m_DnsServer.Contains(":") ? m_DnsServer : m_DnsServer + ":53";
                        DNSManager.SetDNSServers(new List <IPEndPoint> {
                            IPSocket.ParseSocketString(m_DnsServer)
                        });
                    }

                    // Configure the SIP transport layer.
                    SIPTransport         = new SIPTransport();
                    bool sipChannelAdded = false;

                    if (m_sipSocketsNode != null)
                    {
                        // Set up the SIP channels based on the app.config file.
                        List <SIPChannel> sipChannels = SIPTransportConfig.ParseSIPChannelsNode(m_sipSocketsNode);
                        if (sipChannels?.Count > 0)
                        {
                            SIPTransport.AddSIPChannel(sipChannels);
                            sipChannelAdded = true;
                        }
                    }

                    if (sipChannelAdded == false)
                    {
                        // Use default options to set up a SIP channel.
                        SIPUDPChannel udpChannel = null;
                        try
                        {
                            udpChannel = new SIPUDPChannel(new IPEndPoint(IPAddress.Any, SIP_DEFAULT_PORT));
                        }
                        catch (SocketException bindExcp)
                        {
                            logger.Warn($"Socket exception attempting to bind UDP channel to port {SIP_DEFAULT_PORT}, will use random port. {bindExcp.Message}.");
                            udpChannel = new SIPUDPChannel(new IPEndPoint(IPAddress.Any, 0));
                        }
                        var tcpChannel = new SIPTCPChannel(new IPEndPoint(IPAddress.Any, udpChannel.Port));
                        SIPTransport.AddSIPChannel(new List <SIPChannel> {
                            udpChannel, tcpChannel
                        });
                    }
                });

                // Wire up the transport layer so incoming SIP requests have somewhere to go.
                SIPTransport.SIPTransportRequestReceived += SIPTransportRequestReceived;

                // Log all SIP packets received to a log file.
                SIPTransport.SIPRequestInTraceEvent   += SIPRequestInTraceEvent;
                SIPTransport.SIPRequestOutTraceEvent  += SIPRequestOutTraceEvent;
                SIPTransport.SIPResponseInTraceEvent  += SIPResponseInTraceEvent;
                SIPTransport.SIPResponseOutTraceEvent += SIPResponseOutTraceEvent;
            }
        }
コード例 #16
0
 /// <summary>
 /// Reverses ToString().
 /// </summary>
 /// <param name="serialisedSIPEndPoint">The serialised SIP end point MUST be in the form protocol:socket and protocol must
 /// be exactly 3 characters. Valid examples are udp:10.0.0.1:5060, invalid example is 10.0.0.1:5060.</param>
 private static SIPEndPoint ParseSerialisedSIPEndPoint(string serialisedSIPEndPoint)
 {
     return(new SIPEndPoint(SIPProtocolsType.GetProtocolType(serialisedSIPEndPoint.Substring(0, 3)), IPSocket.ParseSocketString(serialisedSIPEndPoint.Substring(4))));
 }