public void IPv4TlsLoopbackSendReceiveTest()
        {
            CancellationTokenSource     cancelServer = new CancellationTokenSource();
            TaskCompletionSource <bool> testComplete = new TaskCompletionSource <bool>();

            Assert.IsTrue(File.Exists(@"certs\localhost.pfx"), "The TLS transport channel test was missing the localhost.pfx certificate file.");

            var serverCertificate = new X509Certificate2(@"certs\localhost.pfx", "");
            var verifyCert        = serverCertificate.Verify();

            logger.LogDebug("Server Certificate loaded from file, Subject=" + serverCertificate.Subject + ", valid=" + verifyCert + ".");

            var serverChannel = new SIPTLSChannel(serverCertificate, IPAddress.Loopback, 8060);

            serverChannel.DisableLocalTCPSocketsCheck = true;
            var clientChannel = new SIPTLSChannel(serverCertificate, IPAddress.Loopback, 8061);

            clientChannel.DisableLocalTCPSocketsCheck = true;

            var serverTask = Task.Run(() => { RunServer(serverChannel, cancelServer); });
            var clientTask = Task.Run(async() => { await RunClient(clientChannel, new SIPURI(SIPSchemesEnum.sips, serverChannel.SIPChannelEndPoint), testComplete); });

            Task.WhenAny(new Task[] { serverTask, clientTask, Task.Delay(3000) }).Wait();

            if (testComplete.Task.IsCompleted == false)
            {
                // The client did not set the completed signal. This means the delay task must have completed and hence the test failed.
                testComplete.SetResult(false);
            }

            Assert.IsTrue(testComplete.Task.Result);

            cancelServer.Cancel();
        }
Exemplo n.º 2
0
        public void IPv6TlsLoopbackSendReceiveTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            if (!Socket.OSSupportsIPv6)
            {
                logger.LogDebug("Test skipped as OS does not support IPv6.");
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                logger.LogDebug("Test skipped as MacOS is not able to load certificates from a .pfx file pre .NET Core 5.0.");
            }
            else
            {
                ManualResetEventSlim        serverReadyEvent = new ManualResetEventSlim(false);
                CancellationTokenSource     cancelServer     = new CancellationTokenSource();
                TaskCompletionSource <bool> testComplete     = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously);

                Assert.True(File.Exists(@"certs/localhost.pfx"), "The TLS transport channel test was missing the localhost.pfx certificate file.");

                var serverCertificate = new X509Certificate2(@"certs/localhost.pfx", "");
                var verifyCert        = serverCertificate.Verify();
                logger.LogDebug("Server Certificate loaded from file, Subject=" + serverCertificate.Subject + ", valid=" + verifyCert + ".");

                var serverChannel = new SIPTLSChannel(serverCertificate, IPAddress.IPv6Loopback, 0);
                serverChannel.DisableLocalTCPSocketsCheck = true;
                var clientChannel = new SIPTLSChannel(new IPEndPoint(IPAddress.IPv6Loopback, 0));
                clientChannel.DisableLocalTCPSocketsCheck = true;

                var serverTask = Task.Run(() => { RunServer(serverChannel, cancelServer, serverReadyEvent); });
                var clientTask = Task.Run(async() =>
                {
#pragma warning disable RCS1090 // Add call to 'ConfigureAwait' (or vice versa).
                    await RunClient(
                        clientChannel,
                        serverChannel.GetContactURI(SIPSchemesEnum.sips, new SIPEndPoint(SIPProtocolsEnum.tls, new IPEndPoint(IPAddress.IPv6Loopback, 0))),
                        testComplete,
                        cancelServer,
                        serverReadyEvent);
#pragma warning restore RCS1090 // Add call to 'ConfigureAwait' (or vice versa).
                });

                if (!Task.WhenAny(new Task[] { serverTask, clientTask }).Wait(TRANSPORT_TEST_TIMEOUT))
                {
                    logger.LogWarning($"Tasks timed out");
                }

                if (testComplete.Task.IsCompleted == false)
                {
                    // The client did not set the completed signal. This means the delay task must have completed and hence the test failed.
                    testComplete.SetResult(false);
                }

                Assert.True(testComplete.Task.Result);

                cancelServer.Cancel();
            }
        }
Exemplo n.º 3
0
        public void IPv4TlsLoopbackSendReceiveTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            ManualResetEventSlim        serverReadyEvent = new ManualResetEventSlim(false);
            CancellationTokenSource     cancelServer     = new CancellationTokenSource();
            TaskCompletionSource <bool> testComplete     = new TaskCompletionSource <bool>();

            Assert.True(File.Exists(@"certs/localhost.pfx"), "The TLS transport channel test was missing the localhost.pfx certificate file.");

            var serverCertificate = new X509Certificate2(@"certs/localhost.pfx", "");
            var verifyCert        = serverCertificate.Verify();

            logger.LogDebug("Server Certificate loaded from file, Subject=" + serverCertificate.Subject + ", valid=" + verifyCert + ".");

            var serverChannel = new SIPTLSChannel(serverCertificate, IPAddress.Loopback, 0);

            serverChannel.DisableLocalTCPSocketsCheck = true;
            var clientChannel = new SIPTLSChannel(serverCertificate, IPAddress.Loopback, 0);

            clientChannel.DisableLocalTCPSocketsCheck = true;

            var serverTask = Task.Run(() => { RunServer(serverChannel, cancelServer, serverReadyEvent); });
            var clientTask = Task.Run(async() => { await RunClient(
                                                       clientChannel,
                                                       serverChannel.GetContactURI(SIPSchemesEnum.sips, new SIPEndPoint(SIPProtocolsEnum.tls, new IPEndPoint(IPAddress.Loopback, 0))),
                                                       testComplete,
                                                       cancelServer,
                                                       serverReadyEvent); });

            serverReadyEvent.Wait();
            if (!Task.WhenAny(new Task[] { serverTask, clientTask }).Wait(TRANSPORT_TEST_TIMEOUT))
            {
                logger.LogWarning($"Tasks timed out");
            }

            if (testComplete.Task.IsCompleted == false)
            {
                // The client did not set the completed signal. This means the delay task must have completed and hence the test failed.
                testComplete.SetResult(false);
            }

            Assert.True(testComplete.Task.Result);

            cancelServer.Cancel();
        }
 static void Main(string[] args)
 {
     try
     {
         var sipTransport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine());
         sipTransport.SIPTransportRequestReceived  += SIPRequestReceived;
         sipTransport.SIPTransportResponseReceived += SIPResponseReceived;
         X509Certificate2 cert       = new X509Certificate2("test-cert.cer");
         SIPTLSChannel    tlsChannel = new SIPTLSChannel(cert, new IPEndPoint(IPAddress.Any, 5061));
         sipTransport.AddSIPChannel(tlsChannel);
         var optionsReq = sipTransport.GetRequest(SIPMethodsEnum.OPTIONS, SIPURI.ParseSIPURI("sips:67.222.131.147:5061"));
         sipTransport.SendRequest(optionsReq);
     }
     catch (Exception excp)
     {
         Console.WriteLine("Exception Main. " + excp);
     }
     finally
     {
         Console.WriteLine("Press any key to exit...");
         Console.Read();
     }
 }
Exemplo n.º 5
0
        /// <summary>
        /// Runs a single task as part of the overall job.
        /// </summary>
        /// <param name="options">The options that dictate the type of task to run.</param>
        /// <param name="taskNumber">The number assigned to this task.</param>
        /// <returns>A boolean indicating whether this single task succeeded or not.</returns>
        private static async Task <bool> RunTask(Options options, int taskNumber)
        {
            SIPTransport sipTransport = new SIPTransport();

            try
            {
                DateTime startTime = DateTime.Now;

                (var dstEp, var dstUri) = ParseDestination(options.Destination);

                logger.LogDebug($"Destination IP end point {dstEp} and SIP URI {dstUri}");

                IPAddress  localAddress = (dstEp.Address.AddressFamily == AddressFamily.InterNetworkV6) ? IPAddress.IPv6Any : IPAddress.Any;
                SIPChannel sipChannel   = null;

                switch (dstEp.Protocol)
                {
                case SIPProtocolsEnum.tcp:
                    sipChannel = new SIPTCPChannel(new IPEndPoint(localAddress, DEFAULT_SIP_CLIENT_PORT));
                    (sipChannel as SIPTCPChannel).DisableLocalTCPSocketsCheck = true;     // Allow sends to listeners on this host.
                    break;

                case SIPProtocolsEnum.tls:
                    var certificate = new X509Certificate2(@"localhost.pfx", "");
                    sipChannel = new SIPTLSChannel(certificate, new IPEndPoint(localAddress, DEFAULT_SIPS_CLIENT_PORT));
                    break;

                case SIPProtocolsEnum.udp:
                    sipChannel = new SIPUDPChannel(new IPEndPoint(localAddress, DEFAULT_SIP_CLIENT_PORT));
                    break;

                case SIPProtocolsEnum.ws:
                    sipChannel = new SIPClientWebSocketChannel();
                    break;

                case SIPProtocolsEnum.wss:
                    sipChannel = new SIPClientWebSocketChannel();
                    break;

                default:
                    throw new ApplicationException($"Don't know how to create SIP channel for transport {dstEp.Protocol}.");
                }

                sipTransport.AddSIPChannel(sipChannel);

                Task <bool> task = null;

                switch (options.Scenario)
                {
                case Scenarios.uac:
                    task = InitiateCallTaskAsync(sipTransport, dstUri);
                    break;

                case Scenarios.opt:
                default:
                    task = SendOptionsTaskAsync(sipTransport, dstUri);
                    break;
                }

                var result = await Task.WhenAny(task, Task.Delay(options.Timeout * 1000));

                TimeSpan duration = DateTime.Now.Subtract(startTime);
                bool     failed   = false;

                if (!task.IsCompleted)
                {
                    logger.LogWarning($"=> Request to {dstEp} did not get a response on task {taskNumber} after {duration.TotalMilliseconds.ToString("0")}ms.");
                    failed = true;
                }
                else if (!task.Result)
                {
                    logger.LogWarning($"=> Request to {dstEp} did not get the expected response on task {taskNumber} after {duration.TotalMilliseconds.ToString("0")}ms.");
                    failed = true;
                }
                else
                {
                    logger.LogInformation($"=> Got correct response on send {taskNumber} in {duration.TotalMilliseconds.ToString("0")}ms.");
                }

                return(!failed);
            }
            finally
            {
                logger.LogDebug("Shutting down the SIP transport...");
                sipTransport.Shutdown();
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Executes the command set by the program's command line arguments.
        /// </summary>
        /// <param name="options">The options that dictate the SIP command to execute.</param>
        static async Task RunCommand(Options options)
        {
            try
            {
                logger.LogDebug($"RunCommand {options.Destination}");

                (var dstEp, var dstUri) = ParseDestination(options.Destination);

                logger.LogDebug($"Destination IP end point {dstEp} and SIP URI {dstUri}");

                int  sendCount = 0;
                bool success   = true;

                do
                {
                    IPAddress  localAddress = (dstEp.Address.AddressFamily == AddressFamily.InterNetworkV6) ? IPAddress.IPv6Any : IPAddress.Any;
                    SIPChannel sipChannel   = null;

                    switch (dstEp.Protocol)
                    {
                    case SIPProtocolsEnum.tcp:
                        sipChannel = new SIPTCPChannel(new IPEndPoint(localAddress, DEFAULT_SIP_CLIENT_PORT));
                        (sipChannel as SIPTCPChannel).DisableLocalTCPSocketsCheck = true;     // Allow sends to listeners on this host.
                        break;

                    case SIPProtocolsEnum.tls:
                        var certificate = new X509Certificate2(@"localhost.pfx", "");
                        sipChannel = new SIPTLSChannel(certificate, new IPEndPoint(localAddress, DEFAULT_SIPS_CLIENT_PORT));
                        break;

                    case SIPProtocolsEnum.udp:
                        sipChannel = new SIPUDPChannel(new IPEndPoint(localAddress, DEFAULT_SIP_CLIENT_PORT));
                        break;

                    case SIPProtocolsEnum.ws:
                        sipChannel = new SIPClientWebSocketChannel();
                        break;

                    case SIPProtocolsEnum.wss:
                        sipChannel = new SIPClientWebSocketChannel();
                        break;

                    default:
                        throw new ApplicationException($"Don't know how to create SIP channel for transport {dstEp.Protocol}.");
                    }

                    SIPTransport sipTransport = new SIPTransport();
                    sipTransport.AddSIPChannel(sipChannel);

                    if (sendCount > 0 && options.Period > 0)
                    {
                        await Task.Delay(options.Period * 1000);
                    }

                    sendCount++;

                    DateTime sendTime = DateTime.Now;
                    var      sendTask = SendOptionsTaskAsync(sipTransport, dstUri);
                    var      result   = await Task.WhenAny(sendTask, Task.Delay(options.Timeout * 1000));

                    TimeSpan duration = DateTime.Now.Subtract(sendTime);

                    if (!sendTask.IsCompleted)
                    {
                        logger.LogWarning($"=> Request to {dstEp} did not get a response on send {sendCount} of {options.Count} after {duration.TotalMilliseconds.ToString("0")}ms.");
                        success = false;
                    }
                    else if (!sendTask.Result)
                    {
                        logger.LogWarning($"=> Request to {dstEp} did not get the expected response on request {sendCount} of {options.Count} after {duration.TotalMilliseconds.ToString("0")}ms.");
                        success = false;
                    }
                    else
                    {
                        logger.LogInformation($"=> Got correct response on send {sendCount} of {options.Count} in {duration.TotalMilliseconds.ToString("0")}ms.");
                    }

                    logger.LogDebug("Shutting down the SIP transport...");
                    sipTransport.Shutdown();

                    if (success == false)
                    {
                        break;
                    }
                }while (sendCount < options.Count);

                DNSManager.Stop();

                // Give the transport half a second to shutdown (puts the log messages in a better sequence).
                await Task.Delay(500);

                logger.LogInformation($"=> Command completed {((success) ? "successfully" : "with failure")}.");
            }
            catch (Exception excp)
            {
                logger.LogError($"Exception RunCommand. {excp.Message}");
            }
        }