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

            var serverChannel = new SIPWebSocketChannel(IPAddress.Loopback, 9001);
            var clientChannel = new SIPClientWebSocketChannel();
            var sipTransport  = new SIPTransport();

            sipTransport.AddSIPChannel(new List <SIPChannel> {
                serverChannel, clientChannel
            });

            ManualResetEvent gotResponseMre = new ManualResetEvent(false);

            SIPRequest  receivedRequest  = null;
            SIPResponse receivedResponse = null;

            sipTransport.SIPTransportRequestReceived += (localSIPEndPoint, remoteEndPoint, sipRequest) =>
            {
                receivedRequest = sipRequest;

                SIPResponse optionsResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                optionsResponse.Header.UnknownHeaders.Add($"X-Response-Random:{Crypto.GetRandomString(1000)}");
                optionsResponse.Header.UnknownHeaders.Add("X-Response-Final: TheEnd");

                return(sipTransport.SendResponseAsync(optionsResponse));
            };

            sipTransport.SIPTransportResponseReceived += (localSIPEndPoint, remoteEndPoint, sipResponse) =>
            {
                receivedResponse = sipResponse;
                gotResponseMre.Set();
                return(Task.CompletedTask);
            };

            var serverUri      = serverChannel.GetContactURI(SIPSchemesEnum.sip, clientChannel.ListeningSIPEndPoint);
            var optionsRequest = SIPRequest.GetRequest(SIPMethodsEnum.OPTIONS, serverUri);

            optionsRequest.Header.UnknownHeaders.Add($"X-Request-Random:{Crypto.GetRandomString(1000)}");
            optionsRequest.Header.UnknownHeaders.Add("X-Request-Final: TheEnd");
            await sipTransport.SendRequestAsync(optionsRequest);

            gotResponseMre.WaitOne(TRANSPORT_TEST_TIMEOUT, false);

            Assert.NotNull(receivedRequest);
            Assert.NotNull(receivedResponse);
            //rj2: confirm that we have received the whole SIP-Message by checking for the last x-header (issue #175, websocket fragmented send/receive)
            Assert.Contains("X-Request-Final: TheEnd", receivedRequest.Header.UnknownHeaders);
            Assert.Contains("X-Response-Final: TheEnd", receivedResponse.Header.UnknownHeaders);

            sipTransport.Shutdown();

            logger.LogDebug("Test complete.");
        }
        public async void WebSocketLoopbackSendReceiveTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            var serverChannel = new SIPWebSocketChannel(IPAddress.Loopback, 9000);
            var clientChannel = new SIPClientWebSocketChannel();
            var sipTransport  = new SIPTransport();

            sipTransport.AddSIPChannel(new List <SIPChannel> {
                serverChannel, clientChannel
            });

            ManualResetEvent gotResponseMre = new ManualResetEvent(false);

            sipTransport.SIPTransportRequestReceived += (localSIPEndPoint, remoteEndPoint, sipRequest) =>
            {
                SIPResponse optionsResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                return(sipTransport.SendResponseAsync(optionsResponse));
            };

            SIPResponse rtnResponse = null;

            sipTransport.SIPTransportResponseReceived += (localSIPEndPoint, remoteEndPoint, sipResponse) =>
            {
                rtnResponse = sipResponse;
                gotResponseMre.Set();
                return(Task.CompletedTask);
            };

            var serverUri      = serverChannel.GetContactURI(SIPSchemesEnum.sip, clientChannel.ListeningSIPEndPoint);
            var optionsRequest = SIPRequest.GetRequest(SIPMethodsEnum.OPTIONS, serverUri);
            await sipTransport.SendRequestAsync(optionsRequest);

            gotResponseMre.WaitOne(TRANSPORT_TEST_TIMEOUT, false);

            Assert.NotNull(rtnResponse);

            sipTransport.Shutdown();

            logger.LogDebug("Test complete.");
        }
Example #3
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();
            }
        }
Example #4
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}");
            }
        }