Exemplo n.º 1
0
        public ClientServerTester(RequestHandler servercallback, RequestHandler clientcallback)
        {
            S1 = new BlockingPipeStream("serverInput/clientOutput");
            S2 = new BlockingPipeStream("clientInput/serverOutput");

            Server = new InterProcessConnection(S1, S2);
            Client = new InterProcessConnection(S2, S1);

            ServerTask = Task.Run(() => Server.RunMainLoopAsync(servercallback, false));
            ClientTask = Task.Run(() => Client.RunMainLoopAsync(clientcallback, true));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:LeanIPC.RPCPeer"/> class.
        /// </summary>
        /// <param name="connection">The connection to use for invoking methods.</param>
        /// <param name="allowedTypes">The types on which remote execution is allowed</param>
        /// <param name="filterPredicate">A predicate function used to filter which methods can be invoked</param>
        public RPCPeer(InterProcessConnection connection, Type[] allowedTypes, Func <System.Reflection.MemberInfo, object[], bool> filterPredicate)
        {
            m_connection = connection ?? throw new ArgumentNullException(nameof(connection));
            m_connection.AddMessageHandler(HandleMessage);
            if (allowedTypes != null)
            {
                if (allowedTypes.Length != 0 && filterPredicate == null)
                {
                    filterPredicate = (a, b) => true;
                }

                foreach (var at in allowedTypes)
                {
                    m_allowedTypes.Add(at, filterPredicate);
                }
            }

            m_typeSerializer = m_connection.TypeSerializer ?? throw new ArgumentNullException(nameof(m_connection.TypeSerializer));
            m_remoteObjects  = m_connection.RemoteHandler ?? throw new ArgumentNullException(nameof(m_connection.RemoteHandler));
        }
Exemplo n.º 3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:LeanIPC.IPCPeer"/> class.
 /// </summary>
 /// <param name="reader">The stream to read from.</param>
 /// <param name="reader">The stream to write to.</param>
 /// <param name="authenticationHandler">The authentication code to use</param>
 public IPCPeer(BinaryConverterStream reader, BinaryConverterStream writer, IAuthenticationHandler authenticationHandler = null)
 {
     m_connection = new InterProcessConnection(reader, writer, authenticationHandler);
 }
Exemplo n.º 4
0
 public static async Task <RequestHandlerResponse> GenericInvokeHelper2 <T1, T2>(ClientServerTester setup, InterProcessConnection con, T1 v1, T2 v2)
 {
     return(await setup.GuardedOperationAsync(() => con.SendAndWaitAsync(new Type[] { typeof(T1), typeof(T2) }, new object[] { v1, v2 })));
 }
Exemplo n.º 5
0
 public static async Task <object> GenericInvokeHelper <T>(ClientServerTester setup, InterProcessConnection con, T value)
 {
     return((object)await setup.GuardedOperationAsync(() => con.SendAndWaitAsync <T, T>(value)));
 }
Exemplo n.º 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Ceen.Httpd.Cli.SubProcess.SpawnRemoteInstance"/> class.
        /// </summary>
        /// <param name="path">The path to the config file</param>
        /// <param name="usessl">If set to <c>true</c> use ssl.</param>
        public SpawnRemoteInstance(string path, bool usessl, IStorageCreator storage, CancellationToken token)
        {
            m_path    = path;
            m_useSSL  = usessl;
            m_storage = storage;

            var prefix = m_hiddenSocketPath ? "\0" : string.Empty;
            var sockid = string.Format("ceen-socket-{0}", new Random().Next().ToString("x8"));

            if (m_hiddenSocketPath)
            {
                m_socketpath = sockid;
            }
            else
            {
                var pathPrefix = Environment.GetEnvironmentVariable("CEEN_SOCKET_FOLDER");
                if (string.IsNullOrWhiteSpace(pathPrefix))
                {
                    pathPrefix = System.IO.Path.GetTempPath();
                }

                m_socketpath = System.IO.Path.GetFullPath(System.IO.Path.Combine(pathPrefix, sockid));
            }

            // Setup a socket server, start the child, and stop the server
            using ((SystemHelper.IsCurrentOSPosix && !m_hiddenSocketPath) ? new DeleteFilesHelper(m_socketpath, m_socketpath + "_fd") : null)
                using (var serveripcsocket = SystemHelper.IsCurrentOSPosix ? new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP) : null)
                    using (var serverfdsocket = SystemHelper.IsCurrentOSPosix ? new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP) : null)
                    {
                        if (SystemHelper.IsCurrentOSPosix)
                        {
                            serveripcsocket.Bind(new SockRock.UnixEndPoint(prefix + m_socketpath));
                            serveripcsocket.Listen(1);

                            serverfdsocket.Bind(new SockRock.UnixEndPoint(prefix + m_socketpath + "_fd"));
                            serverfdsocket.Listen(1);
                        }

                        // Launch the child process
                        m_proc = StartRemoteProcess();

                        // TODO: Consider some multiplexer to allow multiple outputs without mixing the contents
                        var tasks = Task.WhenAll(
                            m_proc.StandardOutput.BaseStream.CopyToAsync(Console.OpenStandardOutput()),
                            m_proc.StandardError.BaseStream.CopyToAsync(Console.OpenStandardError()),
                            Console.OpenStandardInput().CopyToAsync(m_proc.StandardInput.BaseStream)
                            );

                        if (SystemHelper.IsCurrentOSPosix)
                        {
                            var ct = new CancellationTokenSource();

                            // Prepare cancellation after 5 seconds
                            Task.Delay(5000, ct.Token).ContinueWith(_ =>
                            {
                                serveripcsocket.Dispose();
                                serverfdsocket.Dispose();
                            });

                            // Get the first connection
                            m_ipcSocket = serveripcsocket.Accept();
                            m_fdSocket  = serverfdsocket.Accept();

                            // Stop the timer
                            ct.Cancel();
                        }

                        //and then don't listen anymore
                    }


            var ipc = new InterProcessConnection(new NetworkStream(m_ipcSocket, true));

            m_peer = new RPCPeer(
                ipc,
                typeof(IStorageEntry),
                typeof(IStorageCreator)
                );

            // We pass these by reference
            m_peer.TypeSerializer.RegisterSerializationAction(typeof(IStorageEntry), SerializationAction.Reference);
            m_peer.TypeSerializer.RegisterSerializationAction(typeof(IStorageCreator), SerializationAction.Reference);

            // Set up special handling for serializing an endpoint instance
            m_peer.TypeSerializer.RegisterEndPointSerializers();
            m_peer.TypeSerializer.RegisterIPEndPointSerializers();

            m_main = Task.Run(async() => {
                try
                {
                    using (m_fdSocket)
                        using (m_ipcSocket)
                            await ipc.RunMainLoopAsync(false);
                }
                finally
                {
                    Program.DebugConsoleOutput("{0}: Finished main loop, no longer connected to: {1}", System.Diagnostics.Process.GetCurrentProcess().Id, m_proc.Id);
                    m_proc.WaitForExit((int)TimeSpan.FromMinutes(1).TotalMilliseconds);
                    if (!m_proc.HasExited)
                    {
                        m_proc.Kill();
                    }
                    Program.DebugConsoleOutput("{0}: Target now stopped: {1}", System.Diagnostics.Process.GetCurrentProcess().Id, m_proc.Id);
                }
            });

            if (token.CanBeCanceled)
            {
                token.Register(() => this.Stop());
            }

            // Register the storage item, since it is a different concrete class (i.e. not the interface)
            if (storage != null)
            {
                m_peer.TypeSerializer.RegisterSerializationAction(storage.GetType(), SerializationAction.Reference);
                m_peer.RegisterLocalObjectOnRemote(storage, typeof(IStorageCreator)).Wait();
            }

            m_peer.AddAutomaticProxy(typeof(SpawnedServer), typeof(ISpawnedServerProxy));
            m_proxy = m_peer.CreateAsync <ISpawnedServerProxy>(typeof(SpawnedServer), usessl, path, storage).Result;

            if (SystemHelper.IsCurrentOSPosix)
            {
                // Prepare the file descriptor socket
                m_fdSocketTypeSerializer = new TypeSerializer(false, false);
                SetupDescriptorSocket().Wait();
            }
        }
Exemplo n.º 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:LeanIPC.RPCPeer"/> class.
 /// </summary>
 /// <param name="connection">The connection to use for invoking methods.</param>
 /// <param name="allowedTypes">The types on which remote execution is allowed</param>
 public RPCPeer(InterProcessConnection connection, params Type[] allowedTypes)
     : this(connection, allowedTypes, null)
 {
 }
Exemplo n.º 8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:LeanIPC.RPCPeer"/> class.
 /// </summary>
 /// <param name="connection">The connection to use for invoking methods.</param>
 /// <param name="filterPredicate">A predicate function used to filter which methods can be invoked</param>
 public RPCPeer(InterProcessConnection connection, Func <System.Reflection.MemberInfo, object[], bool> filterPredicate)
     : this(connection, null, filterPredicate)
 {
 }