示例#1
0
        public override void Close()
        {
            CancelIfBlocking();

            // It's important that we abort the thread before we
            // grab the lock here and close the underlying
            // UnixClient, or else we'd deadlock between here and
            // the Read() in HandleConnection()

            // Do this in a lock since Close() should be thread-safe (can be called from AsyncCallback handler)
            lock (this.client_lock) {
                if (closed)
                {
                    return;
                }

                if (this.client != null)
                {
                    this.client.Close();
                    this.client = null;
                }

                if (this.executor != null)
                {
                    this.executor.Cleanup();
                    this.executor.AsyncResponseEvent -= OnAsyncResponse;
                    this.executor = null;
                }

                closed = true;
            }

            Server.RunGC();
        }
示例#2
0
        /////////////////////////////////////////////////////////

        static bool CheckHelper()
        {
            string storage_dir = PathFinder.GetRemoteStorageDir(false);

            if (storage_dir == null)
            {
                return(false);
            }

            // FIXME: We shouldn't need to know the path to the helper socket.
            string socket_name = Path.Combine(storage_dir, "socket-helper");

            if (!File.Exists(socket_name))
            {
                return(false);
            }

            // Open, and then immediately close, a connection to the helper's socket.
            try {
                UnixClient test_client;
                test_client = new UnixClient(socket_name);
                test_client.Close();
                return(true);
            } catch (Exception ex) {
                return(false);
            }
        }
示例#3
0
                #pragma warning restore CS0067

        public async Task <Connection> ActivateAsync(CancellationToken token)
        {
            await Task.Yield();

            var vscodeDirectory = Path.Combine(
                Environment.GetFolderPath(
                    Environment.SpecialFolder.UserProfile),
                ".vscode",
                "extensions");

            if (!Directory.Exists(vscodeDirectory))
            {
                throw new Exception("PowerShell VS Code extension required.");
            }

            var extensionDirectory = Directory.GetDirectories(vscodeDirectory)
                                     .FirstOrDefault(m => m.Contains("ms-vscode.powershell"));

            var script = Path.Combine(extensionDirectory, "modules", "PowerShellEditorServices", "Start-EditorServices.ps1");

            var info = new ProcessStartInfo {
                FileName               = @"/usr/local/bin/pwsh",
                Arguments              = $@"-NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "" & '{script}' -HostName 'Visual Studio Code Host' -HostProfileId 'Microsoft.VSCode' -HostVersion '1.5.1' -AdditionalModules @('PowerShellEditorServices.VSCode') -BundledModulesPath '{extensionDirectory}/modules' -EnableConsoleRepl -LogLevel 'Diagnostic' -LogPath '{extensionDirectory}/logs/VSEditorServices.log' -SessionDetailsPath '{extensionDirectory}/logs/PSES-VS' -FeatureFlags @()""",
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                UseShellExecute        = false,
                CreateNoWindow         = true
            };

            var process = new Process();

            process.StartInfo = info;

            if (process.Start())
            {
                //Wait for startup....
                string sessionFile = $@"{extensionDirectory}/logs/PSES-VS";
                var    sessionInfo = await WaitForSessionFileAsync(sessionFile);

                File.Delete(sessionFile);

                var sessionInfoJObject = JsonConvert.DeserializeObject <JObject> (sessionInfo);

                var status = (string)sessionInfoJObject ["status"];
                if (status != "started")
                {
                    LanguageClientLoggingService.Log(sessionInfoJObject.ToString());
                    var reason = (string)sessionInfoJObject ["reason"];
                    throw new ApplicationException($"Failed to start PowerShell console. {reason}");
                }

                var languageServicePipeName = (string)sessionInfoJObject ["languageServicePipeName"];
                var client = new UnixClient(languageServicePipeName);
                var stream = client.GetStream();
                return(new Connection(stream, stream));
            }

            return(null);
        }
示例#4
0
        protected override void SendRequest(RequestMessage request)
        {
            client = new UnixClient(this.socket_name);
            client.SendBufferSize    = 4096;
            client.ReceiveBufferSize = 4096;
            NetworkStream stream = client.GetStream();

            base.SendRequest(request, stream);
        }
示例#5
0
文件: Socket.cs 项目: zofuthan/xsp
        static IDisposable ListenUnix(string path, AsyncCallback accept)
        {
            var socket = new UnixClient();
            var client = socket.Client;

            client.Bind(new UnixEndPoint(path));
            client.Listen(1);
            client.BeginAccept(accept, client);
            return(socket);
        }
示例#6
0
        public Connection OnAccept(Socket socket)
        {
            if (socket == null)
            {
                throw new ArgumentNullException("socket");
            }
            Logger.Write(LogLevel.Debug, "ChildInfo.OnAccept");
            if (Process == null || Process.HasExited)
            {
                if (TrySpawn())
                {
                    var process = Process;
                    int id      = process.Id;
                    Logger.Write(LogLevel.Notice, "Started fastcgi daemon [dynamic] with pid {0} and config file {1}", id, Path.GetFileName(Name));
                    process.EnableRaisingEvents = true;
                    process.Exited += (sender, e) => Logger.Write(LogLevel.Notice, "Fastcgi daemon [dynamic] with pid {0} exited [it is {1}ly dead]", id, process.HasExited.ToString().ToLowerInvariant());
                    // Let the daemon start
                    Thread.Sleep(300);
                }
                else
                {
                    throw new Exception("Couldn't spawn child!");
                }
            }
            else
            {
                Logger.Write(LogLevel.Debug, "Recycling child with pid {0}", Process.Id);
            }

            Logger.Write(LogLevel.Debug, "Will connect to backend");
            var onDemandSocket = new UnixClient();

            Logger.Write(LogLevel.Debug, "Connecting to backend on {0}", OnDemandSock);
            if (OnDemandSock.StartsWith("\\0", StringComparison.Ordinal))
            {
                onDemandSocket.Connect('\0' + OnDemandSock.Substring(2));
            }
            else
            {
                Uri uri;
                if (Uri.TryCreate(OnDemandSock, UriKind.Absolute, out uri))
                {
                    onDemandSocket.Connect(uri.PathAndQuery);
                }
                else
                {
                    onDemandSocket.Connect(OnDemandSock);
                }
            }
            SocketPassing.SendTo(onDemandSocket.Client.Handle, socket.Handle);
            Logger.Write(LogLevel.Debug, "Sent fd {0} via fd {1}", socket.Handle, onDemandSocket.Client.Handle);
            onDemandSocket.Close();

            return(new Connection(socket));
        }
示例#7
0
文件: Socket.cs 项目: zofuthan/xsp
 public void TestPassUnixFd()
 {
     using (ListenUnix(FASTCGI_SOCKET_PATH, FastCgiAccept))
         using (ListenUnix(FPM_SOCKET_PATH, FpmUnixAccept)) {
             var    webserver = new UnixClient(FPM_SOCKET_PATH);
             string read;
             using (var stream = webserver.GetStream())
                 using (var reader = new StreamReader(stream))
                     read = reader.ReadLine();
             Assert.AreEqual(MESSAGE, read);
         }
 }
示例#8
0
文件: Spawner.cs 项目: zofuthan/xsp
        public static Process SpawnOndemandChild(string socketFile)
        {
            CompatArraySegment <byte>?torelease = null;

            try {
                Logger.Write(LogLevel.Debug, "Spawning via the shim {0}", socketFile);
                var client = new UnixClient();
                client.Connect(socketFile);
                CompatArraySegment <byte> buffer = buffers.ClaimBuffer();
                torelease = buffer;
                int receivedCount;
                using (NetworkStream socket = client.GetStream()) {
                    socket.Write(spawnString, 0, spawnString.Length);
                    receivedCount = socket.Read(buffer.Array, buffer.Offset, buffer.Count);
                    if (receivedCount < 0)
                    {
                        throw new Exception("Didn't receive the child pid");
                    }
                }
                string received = Encoding.UTF8.GetString(buffer.Array, buffer.Offset, receivedCount);
                string clean    = received.Trim();
                int    pid;
                if (!Int32.TryParse(clean, out pid))
                {
                    throw new Exception("Couldn't parse the pid \"" + clean + "\"");
                }

                if (pid < 0)
                {
                    throw new Exception("Invalid pid: " + pid);
                }

                return(Process.GetProcessById(pid));
            } catch (Exception e) {
                Logger.Write(LogLevel.Error, "Error while talking to the shim for socket file {0}", socketFile);
                Logger.Write(e);
                return(null);
            } finally {
                if (torelease != null)
                {
                    buffers.ReturnBuffer(torelease.Value);
                }
            }
        }
示例#9
0
文件: Socket.cs 项目: zofuthan/xsp
        static void FpmTcpAccept(IAsyncResult res)
        {
            if (!res.IsCompleted)
            {
                throw new ArgumentException("res");
            }

            var socket = res.AsyncState as TcpListener;

            if (socket == null)
            {
                throw new ArgumentNullException("state");
            }

            using (var connection = socket.EndAcceptSocket(res)) {
                var back = new UnixClient(FASTCGI_SOCKET_PATH);
                SocketPassing.SendTo(back.Client, connection.Handle);
            }
        }
示例#10
0
        public override void Close()
        {
            bool previously_closed = this.IsClosed;

            // Important to set this before we close the
            // UnixClient, since that will trigger the
            // ReadCallback() method, reading 0 bytes off the
            // wire, and we check this.closed in there.
            this.IsClosed = true;

            if (client != null)
            {
                client.Close();
                client = null;
            }

            if (!previously_closed)
            {
                InvokeClosedEvent();
            }
        }
示例#11
0
        /*
         * Loads the specific agent assembly into this vm.
         */
        public void Attach(string agent, string args)
        {
            string user = UnixUserInfo.GetRealUser().UserName;

            // Check whenever the attach socket exists
            string socket_file = "/tmp/mono-" + user + "/.mono-" + pid;

            if (!File.Exists(socket_file))
            {
                string     trigger_file = "/tmp/.mono_attach_pid" + pid;
                FileStream trigger      = null;

                try {
                    trigger = File.Create(trigger_file);
                    trigger.Close();

                    // Ask the vm to start the attach mechanism
                    Syscall.kill((int)pid, Signum.SIGQUIT);

                    // Wait for the socket file to materialize
                    int i;
                    for (i = 0; i < 10; ++i)
                    {
                        if (File.Exists(socket_file))
                        {
                            break;
                        }
                        Thread.Sleep(100);
                    }

                    if (i == 10)
                    {
                        throw new Exception(String.Format("Runtime failed to create attach socket '{0}'.", socket_file));
                    }
                } finally {
                    File.Delete(trigger_file);
                }
            }

            /*
             * We communicate with the agent inside the runtime using a simlified
             * version of the .net remoting protocol.
             */

            string path = "/tmp/mono-" + user + "/.mono-" + pid;

            UnixClient client = new UnixClient(path);

            NetworkStream stream = client.GetStream();

            // Compose payload
            MemoryStream ms     = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(ms);

            write_string(writer, "attach");
            write_string(writer, agent);
            write_string(writer, args);

            // Write header
            byte[] magic = new byte [] { (byte)'M', (byte)'O', (byte)'N', (byte)'O', 1, 0 };
            stream.Write(magic, 0, magic.Length);

            // Write payload length
            new BinaryWriter(stream).Write((int)ms.Length);

            // Write payload
            stream.Write(ms.GetBuffer(), 0, (int)ms.Length);
        }
 public async Task Unix_Client_Ping()
 {
     await UnixClient.Ping();
 }
示例#13
0
        protected override Stream RequestStream()
        {
            string filename = Environment.GetEnvironmentVariable("OPTIMIZATION_UNIX_SOCKET");

            if (filename == null)
            {
                return(null);
            }

            if (d_client != null)
            {
                return(null);
            }

            // Open unix socket...
            d_client = new UnixClient();

            try
            {
                d_client.Connect(filename);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Could not open unix socket: " + e.Message);
                return(null);
            }

            int ctx = 0;

            while (!d_client.GetStream().DataAvailable&& ctx < 10)
            {
                System.Threading.Thread.Sleep(100);
                ++ctx;
            }

            byte[] all = new byte[] {};

            while (d_client.GetStream().DataAvailable)
            {
                byte[] buffer = new byte[1024];
                int    ret;

                try
                {
                    ret = d_client.GetStream().Read(buffer, 0, buffer.Length);
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("Failed to read: " + e.Message);
                    return(null);
                }

                if (ret == 0)
                {
                    break;
                }

                int prev = all.Length;
                Array.Resize(ref all, all.Length + ret);
                Array.Copy(buffer, 0, all, prev, ret);
            }

            return(new MemoryStream(all));
        }
示例#14
0
 public UnixConnectionHandler(UnixClient client)
 {
     this.client = client;
     this.client.SendBufferSize    = 4096;
     this.client.ReceiveBufferSize = 4096;
 }