Exemple #1
0
        public void CanInvokeDelegate_WithArgs_ReturnValue()
        {
            Response <object> reply = default;

            var fakePipe = new StreamDuplexPipe(PipeOptions.Default, new MemoryStream());
            var server   = new JsonRpcServer();

            var clientMock = new Mock <JsonRpcServer.ClientConnection>(1, "localhost", fakePipe, _process, Encoding.UTF8);

            clientMock.Setup(x => x.WriteAsJson(It.IsAny <object>())).Callback <object>(o => reply = (Response <object>)o);

            bool called = false;

            server.Bind("DelegateFunction", (Func <int, string, string>)((a, b) =>
            {
                called = b == "TestString";
                return(b);
            }));
            server.ExecuteHandler(clientMock.Object, 21, "DelegateFunction", new object[] { 176, "TestString" });

            called.Should().BeTrue();
            reply.Should().NotBeNull();
            reply.Error.Should().BeNull();
            reply.Id.Should().Be(21);
            reply.Result.Should().NotBeNull();
            reply.Result.Should().Be("TestString");
        }
Exemple #2
0
 private static async Task ProcessConnection <TContext>(IHttpApplication <TContext> application, MemoryPool <byte> memoryPool, Socket socket)
 {
     using (var ns = new NetworkStream(socket))
     {
         using (var connection = new StreamDuplexPipe(new PipeOptions(memoryPool), ns))
         {
             await ProcessClient(application, connection);
         }
     }
 }
        protected override Task <IDuplexPipe> GetConnection()
        {
            Socket s = new Socket(SocketType.Stream, ProtocolType.Tcp);

            s.Connect(new IPEndPoint(IPAddress.Loopback, 5000));

            var pipeConnection = new StreamDuplexPipe(new PipeOptions(pool), new NetworkStream(s));

            return(Task.FromResult((IDuplexPipe)pipeConnection));
        }
Exemple #4
0
        public void Call_StaticFunction()
        {
            Response reply = default;

            var fakePipe = new StreamDuplexPipe(PipeOptions.Default, new MemoryStream());
            var server   = new JsonRpcServer();

            var clientMock = new Mock <JsonRpcServer.ClientConnection>(1, "localhost", fakePipe, _process, Encoding.UTF8);

            clientMock.Setup(x => x.WriteAsJson(It.IsAny <object>())).Callback <object>(o => reply = (Response)o);

            server.Bind(typeof(StaticHandler));
            server.ExecuteHandler(clientMock.Object, 43, "Function1", null);

            reply.Should().NotBeNull();
            reply.Error.Should().BeNull();
        }
        protected override async Task <IDuplexPipe> ConnectPipelineAsync(int sendMaxMessageSize, int receiveMaxMessageSize, CancellationToken cancellationToken)
        {
            // TODO: The URL should be parsed in RpConnectionInfo constructor .
            // If invalid an ArgumentException should be thrown there.

            if (this.ConnectionInfo.HostUrl is Uri url)
            {
#pragma warning disable CA2000 // Dispose objects before losing scope
                string pipeName = PipeUri.LookupPipeName(url);
                if (string.IsNullOrEmpty(pipeName))
                {
                    throw new RpcCommunicationException(RpcCommunicationStatus.Unavailable, $"Failed to connect to named pipe at '{url}'");
                }

                NamedPipeClientStream?pipeClientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, System.IO.Pipes.PipeOptions.Asynchronous);

                try
                {
                    await pipeClientStream.ConnectAsync(cancellationToken).ContextFree();

                    var sendOptions = new System.IO.Pipelines.PipeOptions(
                        pauseWriterThreshold: sendMaxMessageSize * 2, resumeWriterThreshold: sendMaxMessageSize,
                        readerScheduler: System.IO.Pipelines.PipeScheduler.Inline,
                        useSynchronizationContext: false);
                    var receiveOptions = new System.IO.Pipelines.PipeOptions(
                        pauseWriterThreshold: receiveMaxMessageSize * 2, resumeWriterThreshold: receiveMaxMessageSize,
                        readerScheduler: System.IO.Pipelines.PipeScheduler.Inline,
                        useSynchronizationContext: false);

                    var connection = new StreamDuplexPipe(pipeClientStream); //, sendOptions, receiveOptions);

                    pipeClientStream = null;                                 // Prevent disposal

                    return(connection);
                }
                finally
                {
                    pipeClientStream?.Dispose();
                }
#pragma warning restore CA2000 // Dispose objects before losing scope
            }
            else
            {
                throw new InvalidOperationException("Missing connection URL.");
            }
        }
Exemple #6
0
        public void CanInvokeDelegate()
        {
            Response reply = default;

            var fakePipe = new StreamDuplexPipe(PipeOptions.Default, new MemoryStream());
            var server   = new JsonRpcServer();

            var clientMock = new Mock <JsonRpcServer.ClientConnection>(1, "localhost", fakePipe, _process, Encoding.UTF8);

            clientMock.Setup(x => x.WriteAsJson(It.IsAny <object>())).Callback <object>(o => reply = (Response)o);

            bool called = false;

            server.Bind("DelegateFunction", (Action)(() => { called = true; }));
            server.ExecuteHandler(clientMock.Object, 43, "DelegateFunction", null);

            called.Should().BeTrue();
            reply.Should().NotBeNull();
            reply.Error.Should().BeNull();
            reply.Id.Should().Be(43);
        }
        public async Task Run()
        {
            var pipeOptions = new PipeOptions(GetBufferPool());

            var consoleOutput = StreamDuplexPipe.CreateWriter(pipeOptions, Console.OpenStandardOutput());
            var connection    = await GetConnection();

            while (true)
            {
                var buffer = connection.Output;
                var output = buffer;

                output.Append("GET / HTTP/1.1", SymbolTable.InvariantUtf8);
                output.Append("\r\n\r\n", SymbolTable.InvariantUtf8);
                await buffer.FlushAsync();

                // Write the client output to the console
                await CopyCompletedAsync(connection.Input, consoleOutput);

                await Task.Delay(1000);
            }
        }
        protected override async Task <IDuplexPipe> ConnectPipelineAsync(int sendMaxMessageSize, int receiveMaxMessageSize, CancellationToken cancellationToken)
        {
            // TODO: Implement cancellationToken somehow, but how?. ConnectAsync and AuthenticateAsClientAsync don't accept a CancellationToken.
            IDuplexPipe?connection;

            var    endPoint            = this.CreateNetEndPoint();
            Stream?authenticatedStream = null;
            Stream?workStream          = null;

            var sendOptions = new PipeOptions(
                pauseWriterThreshold: sendMaxMessageSize * 2, resumeWriterThreshold: sendMaxMessageSize,
                readerScheduler: PipeScheduler.ThreadPool,
                useSynchronizationContext: false);
            var receiveOptions = new PipeOptions(
                pauseWriterThreshold: receiveMaxMessageSize * 2, resumeWriterThreshold: receiveMaxMessageSize,
                readerScheduler: PipeScheduler.Inline,
                useSynchronizationContext: false);

            try
            {
                Socket?socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    SetRecommendedClientOptions(socket);

                    string sslHost;
                    switch (endPoint)
                    {
                    case IPEndPoint ipEndPoint:
#if PLAT_CONNECT_CANCELLATION
                        await socket.ConnectAsync(ipEndPoint.Address, ipEndPoint.Port, cancellationToken).ContextFree();
#else
                        await socket.ConnectAsync(ipEndPoint.Address, ipEndPoint.Port).ContextFree();
#endif
                        sslHost = ipEndPoint.Address.ToString();
                        break;

                    case DnsEndPoint dnsEndPoint:
#if PLAT_CONNECT_CANCELLATION
                        await socket.ConnectAsync(dnsEndPoint.Host, dnsEndPoint.Port, cancellationToken).ContextFree();
#else
                        await socket.ConnectAsync(dnsEndPoint.Host, dnsEndPoint.Port).ContextFree();
#endif

                        sslHost = dnsEndPoint.Host;
                        break;

                    default:
                        throw new NotSupportedException($"Unsupported end point '{endPoint}',");
                    }

                    workStream = new NetworkStream(socket, true);
                    socket     = null; // Prevent closing, NetworkStream has taken ownership

                    var selectedAuthentication = await this.GetAuthenticationOptionsAsync(workStream, cancellationToken).ContextFree();

                    if (selectedAuthentication is SslClientOptions sslOptions)
                    {
                        var sslStream = new SslStream(workStream, false,
                                                      sslOptions.RemoteCertificateValidationCallback,
                                                      sslOptions.LocalCertificateSelectionCallback,
                                                      sslOptions.EncryptionPolicy);

                        workStream = authenticatedStream = sslStream;

#if PLAT_CONNECT_CANCELLATION
                        var authOptions = new SslClientAuthenticationOptions()
                        {
                            TargetHost                     = sslHost,
                            ClientCertificates             = sslOptions.ClientCertificates,
                            EnabledSslProtocols            = sslOptions.EnabledSslProtocols,
                            CertificateRevocationCheckMode = sslOptions.CertificateRevocationCheckMode
                        };

                        await sslStream.AuthenticateAsClientAsync(authOptions, cancellationToken).ContextFree();
#else
                        await sslStream.AuthenticateAsClientAsync(sslHost, sslOptions.ClientCertificates, sslOptions.EnabledSslProtocols,
                                                                  sslOptions.CertificateRevocationCheckMode != X509RevocationMode.NoCheck).ContextFree();
#endif
                    }
                    else if (selectedAuthentication is NegotiateClientOptions negotiateOptions)
                    {
                        var negotiateStream = new NegotiateStream(workStream, false);
                        workStream = authenticatedStream = negotiateStream;

                        await negotiateStream.AuthenticateAsClientAsync(
                            negotiateOptions !.Credential ?? CredentialCache.DefaultNetworkCredentials,
                            negotiateOptions.TargetName ?? "").ContextFree();
                    }
                    else if (selectedAuthentication is AnonymousAuthenticationClientOptions)
                    {
                        authenticatedStream = workStream;
                    }
                    else
                    {
                        throw new NotSupportedException("Authentication options not supported.");
                    }

                    connection = new StreamDuplexPipe(authenticatedStream);//, sendOptions, receiveOptions);
                }
                finally
                {
                    socket?.Dispose();
                }

                this.authenticatedStream = authenticatedStream as AuthenticatedStream;
                workStream = null;

                return(connection);
            }
            finally
            {
                workStream?.Dispose();
            }
        }