public async Task PingPong_Async()
        {
            // Create names for two pipes
            string outName = Path.GetRandomFileName();
            string inName = Path.GetRandomFileName();

            // Create the two named pipes, one for each direction, then create
            // another process with which to communicate
            using (var outbound = new NamedPipeServerStream(outName, PipeDirection.Out))
            using (var inbound = new NamedPipeClientStream(".", inName, PipeDirection.In))
            using (RemoteInvoke(PingPong_OtherProcess, outName, inName))
            {
                // Wait for both pipes to be connected
                await Task.WhenAll(outbound.WaitForConnectionAsync(), inbound.ConnectAsync());

                // Repeatedly write then read a byte to and from the other process
                var data = new byte[1];
                for (byte i = 0; i < 10; i++)
                {
                    data[0] = i;
                    await outbound.WriteAsync(data, 0, data.Length);
                    data[0] = 0;
                    int received = await inbound.ReadAsync(data, 0, data.Length);
                    Assert.Equal(1, received);
                    Assert.Equal(i, data[0]);
                }
            }
        }
Пример #2
0
 public void InvalidConnectTimeout_Throws_ArgumentOutOfRangeException()
 {
     using (NamedPipeClientStream client = new NamedPipeClientStream("client1"))
     {
         Assert.Throws<ArgumentOutOfRangeException>("timeout", () => client.Connect(-111));
         Assert.Throws<ArgumentOutOfRangeException>("timeout", () => { client.ConnectAsync(-111); });
     }
 }
Пример #3
0
 public async Task ConnectToNonExistentServer_Throws_TimeoutException()
 {
     using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere"))
     {
         var ctx = new CancellationTokenSource();
         Assert.Throws<TimeoutException>(() => client.Connect(60));  // 60 to be over internal 50 interval
         await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(50));
         await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(60, ctx.Token)); // testing Token overload; ctx is not canceled in this test
     }
 }
Пример #4
0
 private static int ClientConnectAsID(string pipeName, string pairIDString)
 {
     uint pairID = uint.Parse(pairIDString);
     using (var inbound = new NamedPipeClientStream(".", pipeName, PipeDirection.In))
     {
         Assert.NotEqual(-1, seteuid(pairID));
         inbound.Connect();
     }
     return SuccessExitCode;
 }
        public void GetAccessControl_NamedPipe_BeforeWaitingToConnect()
        {
            string pipeName = GetUniquePipeName();
            var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
            var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In, PipeOptions.Asynchronous);

            Assert.NotNull(server.GetAccessControl());
            server.SetAccessControl(new PipeSecurity());
            Assert.Throws<InvalidOperationException>(() => client.GetAccessControl());
            Assert.Throws<InvalidOperationException>(() => client.SetAccessControl(new PipeSecurity()));
        }
Пример #6
0
        public async Task CancelConnectToNonExistentServer_Throws_OperationCanceledException()
        {
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere"))
            {
                var ctx = new CancellationTokenSource();

                Task clientConnectToken = client.ConnectAsync(ctx.Token);
                ctx.Cancel();
                await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientConnectToken);

                ctx.Cancel();
                await Assert.ThrowsAnyAsync<OperationCanceledException>(() => client.ConnectAsync(ctx.Token));
            }
        }
        protected override ServerClientPair CreateServerClientPair()
        {
            ServerClientPair ret = new ServerClientPair();
            string pipeName = GetUniquePipeName();
            var readablePipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
            var writeablePipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);

            Task serverConnect = Task.Factory.FromAsync(readablePipe.BeginWaitForConnection, readablePipe.EndWaitForConnection, null);
            writeablePipe.Connect();
            serverConnect.Wait();

            ret.readablePipe = readablePipe;
            ret.writeablePipe = writeablePipe;
            return ret;
        }
        protected override ServerClientPair CreateServerClientPair()
        {
            ServerClientPair ret = new ServerClientPair();
            string pipeName = GetUniquePipeName();
            var writeablePipe = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
            var readablePipe = new NamedPipeClientStream(".", pipeName, PipeDirection.In, PipeOptions.Asynchronous);

            Task clientConnect = readablePipe.ConnectAsync();
            writeablePipe.WaitForConnection();
            clientConnect.Wait();

            ret.readablePipe = readablePipe;
            ret.writeablePipe = writeablePipe;
            return ret;
        }
Пример #9
0
 public async Task CancelConnectToNonExistentServer_Throws_OperationCanceledException()
 {
     using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere"))
     {
         var ctx = new CancellationTokenSource();
         if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(812, PlatformID.AnyUnix)] - Unix implementation currently ignores timeout and cancellation token once the operation has been initiated
         {
             Task clientConnectToken = client.ConnectAsync(ctx.Token);
             ctx.Cancel();
             await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientConnectToken);
         }
         ctx.Cancel();
         await Assert.ThrowsAnyAsync<OperationCanceledException>(() => client.ConnectAsync(ctx.Token));
     }
 }
Пример #10
0
        public async Task RunAsClient_Windows()
        {
            string pipeName = Path.GetRandomFileName();
            using (var server = new NamedPipeServerStream(pipeName))
            using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
            {
                Task serverTask = server.WaitForConnectionAsync();

                client.Connect();
                await serverTask;

                bool ran = false;
                server.RunAsClient(() => ran = true);
                Assert.True(ran, "Expected delegate to have been invoked");
            }
        }
Пример #11
0
        [PlatformSpecific(PlatformID.Windows)] // Unix implementation uses bidirectional sockets
        public void ConnectWithConflictingDirections_Throws_UnauthorizedAccessException()
        {
            string serverName1 = GetUniquePipeName();
            using (NamedPipeServerStream server = new NamedPipeServerStream(serverName1, PipeDirection.Out))
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", serverName1, PipeDirection.Out))
            {
                Assert.Throws<UnauthorizedAccessException>(() => client.Connect());
                Assert.False(client.IsConnected);
            }

            string serverName2 = GetUniquePipeName();
            using (NamedPipeServerStream server = new NamedPipeServerStream(serverName2, PipeDirection.In))
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", serverName2, PipeDirection.In))
            {
                Assert.Throws<UnauthorizedAccessException>(() => client.Connect());
                Assert.False(client.IsConnected);
            }
        }
        private static int PingPong_OtherProcess(string inName, string outName)
        {
            // Create pipes with the supplied names
            using (var inbound = new NamedPipeClientStream(".", inName, PipeDirection.In))
            using (var outbound = new NamedPipeServerStream(outName, PipeDirection.Out))
            {
                // Wait for the connections to be established
                Task.WaitAll(inbound.ConnectAsync(), outbound.WaitForConnectionAsync());

                // Repeatedly read then write bytes from and to the other process
                for (int i = 0; i < 10; i++)
                {
                    int b = inbound.ReadByte();
                    outbound.WriteByte((byte)b);
                }
            }
            return SuccessExitCode;
        }
        public void GetAccessControl_NamedPipeServerStream_Broken()
        {
            string pipeName = GetUniquePipeName();
            var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
            var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In, PipeOptions.Asynchronous);

            Task clientConnect = client.ConnectAsync();
            server.WaitForConnection();
            clientConnect.Wait();

            Assert.NotNull(server.GetAccessControl());
            server.SetAccessControl(new PipeSecurity());
            Assert.NotNull(client.GetAccessControl());
            client.SetAccessControl(new PipeSecurity());

            client.Dispose();
            Assert.Throws<IOException>(() => server.Write(new byte[] { 0 }, 0, 1)); // Sets the servers PipeState to Broken
            server.SetAccessControl(new PipeSecurity());
        }
        public void PingPong_Sync()
        {
            // Create names for two pipes
            string outName = Path.GetRandomFileName();
            string inName = Path.GetRandomFileName();

            // Create the two named pipes, one for each direction, then create
            // another process with which to communicate
            using (var outbound = new NamedPipeServerStream(outName, PipeDirection.Out))
            using (var inbound = new NamedPipeClientStream(".", inName, PipeDirection.In))
            using (RemoteInvoke(PingPong_OtherProcess, outName, inName))
            {
                // Wait for both pipes to be connected
                Task.WaitAll(outbound.WaitForConnectionAsync(), inbound.ConnectAsync());

                // Repeatedly write then read a byte to and from the other process
                for (byte i = 0; i < 10; i++)
                {
                    outbound.WriteByte(i);
                    int received = inbound.ReadByte();
                    Assert.Equal(i, received);
                }
            }
        }
Пример #15
0
        //[MTAThread]
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.ProcessExit += (s, e) =>
            {
                int code = Environment.ExitCode;
                if (code == 0)
                {
                    Console.Out.WriteLine("The launcher tool exited with code: 0");
                }
                else
                {
                    Console.Error.WriteLine("The launcher tool exited with error code: {0}", code);
                }
            };

            ConsoleQuickEdit.Disable();
            ConsoleWriter.Initialize();
            if (!args.Any() || args.Contains("/?"))
            {
                ShowHelp();
                return;
            }
            // show version?
            if (args[0] == "-v" || args[0] == "-version" || args[0] == "/v")
            {
                Console.WriteLine(Assembly.GetEntryAssembly().GetName().Version.ToString());
                Environment.Exit(0);
                return;
            }

            for (int i = 0; i < args.Length; i += 2)
            {
                string arg = args[i].Trim();
                if (arg.StartsWith("--"))
                {
                    // --<flag> means it is a flag without value
                    string key = arg.Substring(2);
                    argsDictionary[key] = string.Empty;
                    i -= 1;
                }
                else
                {
                    string key = arg.StartsWith("-") ? arg.Substring(1) : arg;
                    string val = i + 1 < args.Length ? args[i + 1].Trim() : string.Empty;
                    argsDictionary[key] = val;
                }
            }

            // verbose output mode?
            if (argsDictionary.ContainsKey("verbose"))
            {
                ConsoleWriter.EnableVerboseOutput = true;
            }

            // redirect output if required
            string redirectOutPipeName;

            if (argsDictionary.TryGetValue("redirect-out-pipe", out redirectOutPipeName))
            {
                // need to redirect stdout to the specified pipe
                var outPipe = new NamedPipeClientStream(".", redirectOutPipeName, PipeDirection.Out);
                outPipe.Connect();
                // create stream write for stdout
                var sw = new StreamWriter(outPipe)
                {
                    AutoFlush = true
                };
                Console.SetOut(sw);

                ConsoleWriter.WriteVerboseLine("The stdout is redirected via the named pipe: " + redirectOutPipeName);
            }

            // redirect error if required
            string redirectErrPipeName;

            if (argsDictionary.TryGetValue("redirect-err-pipe", out redirectErrPipeName))
            {
                // need to redirect stderr to the specified pipe
                var errPipe = new NamedPipeClientStream(".", redirectErrPipeName, PipeDirection.Out);
                errPipe.Connect();
                // create stream write for stderr
                var sw = new StreamWriter(errPipe)
                {
                    AutoFlush = true
                };
                Console.SetError(sw);

                ConsoleWriter.WriteVerboseLine("The stderr is redirected via the named pipe: " + redirectErrPipeName);
            }

            string paramFileName, runtype;
            string failOnTestFailed = "N";

            argsDictionary.TryGetValue("runtype", out runtype);
            argsDictionary.TryGetValue("paramfile", out paramFileName);
            TestStorageType enmRuntype = TestStorageType.Unknown;

            if (!Enum.TryParse <TestStorageType>(runtype, true, out enmRuntype))
            {
                enmRuntype = TestStorageType.Unknown;
            }

            if (string.IsNullOrEmpty(paramFileName))
            {
                ShowHelp();
                return;
            }

            ShowTitle();
            ConsoleWriter.WriteLine(Resources.GeneralStarted);

            try
            {
                if (StartNewLauncherProcess(args))
                {
                    // the new launcher process is launched and everthing shall already be handled in the StartNewLauncherProcess
                    // so here returns, that is, this process shall exit
                    return;
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Warning: Error occurred when creating the new process in the user session:");
                Console.Error.WriteLine("-------------------------------");
                Console.Error.WriteLine(ex.Message);
                ConsoleWriter.WriteVerboseLine(ex.ToString());
                Console.Error.WriteLine("-------------------------------");
                Console.Error.WriteLine("Warning: Test(s) will be run in non-user session, however, the test(s) might fail.");
            }

            var launcher = new Launcher(failOnTestFailed, paramFileName, enmRuntype);

            if (launcher.IsParamFileEncodingNotSupported)
            {
                Console.WriteLine(Properties.Resources.JavaPropertyFileBOMNotSupported);
                Environment.Exit((int)Launcher.ExitCodeEnum.Failed);
                return;
            }

            launcher.Run();
        }
Пример #16
0
        public void TestMetadata()
        {
            // Empty server list
            ServerListHelper.instance.ClearServerList();
            int conSize           = 0;
            List <ServerInfo> con = ServerListHelper.instance.GetServerList();

            Assert.IsTrue(con.Count == conSize);

            // Send metadata, then check that it has been received and processed and that the server list remained unchanged
            NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.Out);

            pipeClient.Connect();
            byte[] metadataBytes = Encoding.UTF8.GetBytes(String.Join(ServerListHelper.SEPARATOR.ToString(), HealthCheckSettings.XENCENTER_METADATA, EncryptionUtils.ProtectForLocalMachine(metadata)));
            pipeClient.Write(metadataBytes, 0, metadataBytes.Length);
            pipeClient.Close();
            System.Threading.Thread.Sleep(1000);
            con = ServerListHelper.instance.GetServerList();
            Assert.IsTrue(con.Count == conSize);
            Assert.IsTrue(ServerListHelper.instance.XenCenterMetadata == metadata, "\"Send metadata\" test failed");

            // Send metadata containing the separator
            pipeClient = new NamedPipeClientStream(".", HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.Out);
            pipeClient.Connect();
            int separatorPosition = new Random().Next(0, metadata.Length);

            metadata      = metadata.Insert(separatorPosition, ServerListHelper.SEPARATOR.ToString());
            metadataBytes = Encoding.UTF8.GetBytes(String.Join(ServerListHelper.SEPARATOR.ToString(), HealthCheckSettings.XENCENTER_METADATA, EncryptionUtils.ProtectForLocalMachine(metadata)));
            pipeClient.Write(metadataBytes, 0, metadataBytes.Length);
            pipeClient.Close();
            System.Threading.Thread.Sleep(1000);
            con = ServerListHelper.instance.GetServerList();
            Assert.IsTrue(con.Count == conSize);
            Assert.IsTrue(ServerListHelper.instance.XenCenterMetadata == metadata, "\"Send metadata containing the separator\" test failed (separator at position {0})", separatorPosition);

            // Send empty metadata
            pipeClient = new NamedPipeClientStream(".", HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.Out);
            pipeClient.Connect();
            metadataBytes = Encoding.UTF8.GetBytes(String.Join(ServerListHelper.SEPARATOR.ToString(), HealthCheckSettings.XENCENTER_METADATA, EncryptionUtils.ProtectForLocalMachine("")));
            pipeClient.Write(metadataBytes, 0, metadataBytes.Length);
            pipeClient.Close();
            System.Threading.Thread.Sleep(1000);
            con = ServerListHelper.instance.GetServerList();
            Assert.IsTrue(con.Count == conSize);
            Assert.IsTrue(ServerListHelper.instance.XenCenterMetadata.Length == 0, "\"Send empty metadata\" test failed");

            // Send metadata unencrypted
            pipeClient = new NamedPipeClientStream(".", HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.Out);
            pipeClient.Connect();
            metadataBytes = Encoding.UTF8.GetBytes(String.Join(ServerListHelper.SEPARATOR.ToString(), HealthCheckSettings.XENCENTER_METADATA, metadata));
            pipeClient.Write(metadataBytes, 0, metadataBytes.Length);
            pipeClient.Close();
            System.Threading.Thread.Sleep(1000);
            con = ServerListHelper.instance.GetServerList();
            Assert.IsTrue(con.Count == conSize);
            Assert.IsTrue(ServerListHelper.instance.XenCenterMetadata.Length == 0, "\"Send metadata unencrypted\" test failed");

            // Send something else
            pipeClient = new NamedPipeClientStream(".", HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.Out);
            pipeClient.Connect();
            var someText = "Some random text";

            metadataBytes = Encoding.UTF8.GetBytes(String.Join(ServerListHelper.SEPARATOR.ToString(), "SomethingElse", EncryptionUtils.ProtectForLocalMachine(someText)));
            pipeClient.Write(metadataBytes, 0, metadataBytes.Length);
            pipeClient.Close();
            System.Threading.Thread.Sleep(1000);
            con = ServerListHelper.instance.GetServerList();
            Assert.IsTrue(con.Count == conSize);
            Assert.IsTrue(ServerListHelper.instance.XenCenterMetadata.Length == 0, "\"Send something else\" test failed");
        }
Пример #17
0
        private void setPipeName(Process p)
        {
            var pn = ((int)(new Random().NextDouble() * 10000)).ToString();

            //form.addLogText(pn);
            p.StandardInput.WriteLine(pn);
            p.StandardInput.Flush();

            //a

            /*
             * for (var i = 0; i < 10; i++) {
             *      Thread.Sleep(1000);
             *      try {
             *              var server = new NamedPipeClientStream(pn);
             *              server.Connect(3000);
             *              pipeWriter = new StreamWriter(server);
             *      } catch (Exception e) {
             *              util.debugWriteLine("named pipe sleep i " + i + " " + e.Message + e.Source + e.StackTrace + e.TargetSite);
             *              continue;
             *      }
             *  break;
             * }
             */
            //b

            /*
             * Thread.Sleep(7000);
             * try {
             *      var server = new NamedPipeClientStream(pn);
             *      server.Connect(5000);
             *      pipeWriter = new StreamWriter(server);
             * } catch (Exception e) {
             *      util.debugWriteLine("named pipe sleep  " + " " + e.Message + e.Source + e.StackTrace + e.TargetSite);
             * }
             */
            /*
             * //c
             * Thread.Sleep(1000);
             * try {
             *      var server = new NamedPipeClientStream(pn);
             *      server.Connect(5000);
             *      pipeWriter = new StreamWriter(server);
             * } catch (Exception e) {
             *      util.debugWriteLine("named pipe sleep  " + " " + e.Message + e.Source + e.StackTrace + e.TargetSite);
             * }
             */
            //moto
            Thread.Sleep(1000);
            try {
                var server = new NamedPipeClientStream(pn);
                server.Connect(5000);
                pipeWriter = new StreamWriter(server);
            } catch (Exception e) {
                util.debugWriteLine("named pipe sleep  " + " " + e.Message + e.Source + e.StackTrace + e.TargetSite);
                form.addLogText("デフォルトのプレイヤーの起動設定中に問題が発生しました" + e.Message + e.Source + e.StackTrace + e.TargetSite);
            }

            //                while (server.IsConnected) {
//          pipeWriter.WriteLine();
//          pipeWriter.Flush();
        }
Пример #18
0
 public FepClient()
 {
     pipeName  = "PipeLis";
     fepClient = new NamedPipeClientStream("PipeLis");
 }
Пример #19
0
        static int Main(string[] argv)
        {
            bool        help        = false;
            bool        version     = false;
            bool        once        = false;
            StartClient startClient = StartClient.No;
            var         config      = new TypeCobolConfiguration();

            config.CommandLine = string.Join(" ", argv);
            var pipename = "TypeCobol.Server";


            var p = TypeCobolOptionSet.GetCommonTypeCobolOptions(config);

            //Add custom options for CLI
            p.Add(string.Format("USAGE\n {0} [OPTIONS]... [PIPENAME]\n VERSION:\n {1} \n DESCRIPTION: \n Run the TypeCObol parser server", PROGNAME, PROGVERSION));
            p.Add("p|pipename", "Pipename used if running as server. Default: \"TypeCobol.Server\"", v => pipename = v);
            p.Add("k|startServer:",
                  "Start the server if not already started, and executes commandline.\n" + "By default the server is started in window mode\n" + "'{hidden}' hide the window.",
                  v =>
            {
                if ("hidden".Equals(v, StringComparison.InvariantCultureIgnoreCase))
                {
                    startClient = StartClient.HiddenWindow;
                }
                else
                {
                    startClient = StartClient.NormalWindow;
                }
            });
            p.Add("1|once", "Parse one set of files and exit. If present, this option does NOT launch the server.", v => once = (v != null));
            p.Add("h|help", "Output a usage message and exit.", v => help = (v != null));
            p.Add("V|version", "Output the version number of " + PROGNAME + " and exit.", v => version = (v != null));


            //Add DefaultCopies to running session
            var folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);

            config.CopyFolders.Add(folder + @"\DefaultCopies\");

            try
            {
                var errors = TypeCobolOptionSet.InitializeCobolOptions(config, argv, p);

                if (!errors.IsNullOrEmpty())
                {
                    return(exit(errors));
                }

                if (help)
                {
                    p.WriteOptionDescriptions(Console.Out);
                    return(0);
                }

                if (version)
                {
                    Console.WriteLine(PROGVERSION);
                    return(0);
                }

                if (config.Telemetry)
                {
                    AnalyticsWrapper.Telemetry.TelemetryVerboseLevel = TelemetryVerboseLevel.CodeGeneration; //If telemetry arg is passed enable telemetry
                }

                if (config.OutputFiles.Count == 0 && config.ExecToStep >= ExecutionStep.Generate)
                {
                    config.ExecToStep = ExecutionStep.CrossCheck; //If there is no given output file, we can't run generation, fallback to CrossCheck
                }
                //"startClient" will be true when "-K" is passed as an argument in command line.
                if (startClient != StartClient.No && once)
                {
                    pipename = "TypeCobol.Server";
                    using (NamedPipeClientStream namedPipeClient = new NamedPipeClientStream(pipename))
                    {
                        try {
                            namedPipeClient.Connect(100);
                        } catch
                        {
                            System.Diagnostics.Process          process   = new System.Diagnostics.Process();
                            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                            if (startClient == StartClient.NormalWindow)
                            {
                                startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                            }
                            else
                            {
                                startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                            }
                            startInfo.FileName  = "cmd.exe";
                            startInfo.Arguments = @"/c " + folder + Path.DirectorySeparatorChar + "TypeCobol.CLI.exe";
                            process.StartInfo   = startInfo;
                            process.Start();

                            namedPipeClient.Connect(1000);
                        }

                        namedPipeClient.WriteByte(68);

                        ConfigSerializer configSerializer = new ConfigSerializer();
                        var configBytes = configSerializer.Serialize(config);

                        namedPipeClient.Write(configBytes, 0, configBytes.Length);
                        //Wait for the response "job is done"
                        var returnCode = namedPipeClient.ReadByte(); //Get running server ReturnCode
                        return(exit((ReturnCode)returnCode, ""));
                    }
                }

                //option -1
                else if (once)
                {
                    var returnCode = CLI.runOnce(config);
                    if (returnCode != ReturnCode.Success)
                    {
                        return(exit(returnCode, "Operation failled"));
                    }
                }
                else
                {
                    runServer(pipename);
                }
            }
            catch (Exception e) {
                AnalyticsWrapper.Telemetry.TrackException(e, null);
                return(exit(ReturnCode.FatalError, e.Message));
            }

            return(exit((int)ReturnCode.Success, "Success"));
        }
Пример #20
0
        [PlatformSpecific(PlatformID.Windows)] // Win32 P/Invokes to verify the user name
        public async Task Windows_GetImpersonationUserName_Succeed()
        {
            string pipeName = GetUniquePipeName();

            using (var server = new NamedPipeServerStream(pipeName))
            {
                using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
                {
                    string expectedUserName;
                    Task serverTask = server.WaitForConnectionAsync();

                    client.Connect();
                    await serverTask;

                    Assert.True(Interop.TryGetImpersonationUserName(server.SafePipeHandle, out expectedUserName), "GetNamedPipeHandleState failed");
                    Assert.Equal(expectedUserName, server.GetImpersonationUserName());
                }
            }
        }
Пример #21
0
 // Validation is handled by CurrentUserOnly
 internal static bool CheckPipeConnectionOwnership(NamedPipeClientStream pipeStream) => true;
Пример #22
0
        public void Unix_SetReadModeTo__PipeTransmissionModeByte()
        {
            string pipeName = GetUniquePipeName();
            using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
            using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out))
            {
                Task clientConnect = client.ConnectAsync();
                server.WaitForConnection();
                clientConnect.Wait();

                server.ReadMode = PipeTransmissionMode.Byte;
                client.ReadMode = PipeTransmissionMode.Byte;
            }

            using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
            using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In))
            {
                Task clientConnect = client.ConnectAsync();
                server.WaitForConnection();
                clientConnect.Wait();

                client.ReadMode = PipeTransmissionMode.Byte;
                server.ReadMode = PipeTransmissionMode.Byte;
            }

            using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
            using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous))
            {
                Task clientConnect = client.ConnectAsync();
                server.WaitForConnection();
                clientConnect.Wait();

                server.ReadMode = PipeTransmissionMode.Byte;
                client.ReadMode = PipeTransmissionMode.Byte;
            }
        }
Пример #23
0
        [PlatformSpecific(PlatformID.Windows)] // Unix doesn't currently support message mode
        public void Windows_SetReadModeTo__PipeTransmissionModeByte()
        {
            string pipeName = GetUniquePipeName();
            using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
            using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out))
            {
                Task clientConnect = client.ConnectAsync();
                server.WaitForConnection();
                clientConnect.Wait();

                // Throws regardless of connection status for the pipe that is set to PipeDirection.In
                Assert.Throws<UnauthorizedAccessException>(() => server.ReadMode = PipeTransmissionMode.Byte);
                client.ReadMode = PipeTransmissionMode.Byte;
            }

            using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
            using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In))
            {
                Task clientConnect = client.ConnectAsync();
                server.WaitForConnection();
                clientConnect.Wait();

                // Throws regardless of connection status for the pipe that is set to PipeDirection.In
                Assert.Throws<UnauthorizedAccessException>(() => client.ReadMode = PipeTransmissionMode.Byte);
                server.ReadMode = PipeTransmissionMode.Byte;
            }

            using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
            using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous))
            {
                Task clientConnect = client.ConnectAsync();
                server.WaitForConnection();
                clientConnect.Wait();

                server.ReadMode = PipeTransmissionMode.Byte;
                client.ReadMode = PipeTransmissionMode.Byte;
            }
        }
Пример #24
0
        public static void Windows_BufferSizeRoundtripping()
        {
            int desiredBufferSize = 10;
            string pipeName = GetUniquePipeName();
            using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize))
            using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In))
            {
                Task clientConnect = client.ConnectAsync();
                server.WaitForConnection();
                clientConnect.Wait();

                Assert.Equal(desiredBufferSize, server.OutBufferSize);
                Assert.Equal(desiredBufferSize, client.InBufferSize);
            }

            using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize))
            using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out))
            {
                Task clientConnect = client.ConnectAsync();
                server.WaitForConnection();
                clientConnect.Wait();

                Assert.Equal(desiredBufferSize, server.InBufferSize);
                Assert.Equal(0, client.OutBufferSize);
            }
        }
Пример #25
0
        public static void Unix_BufferSizeRoundtripping(PipeDirection direction)
        {
            int desiredBufferSize = 0;
            string pipeName = GetUniquePipeName();
            using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize))
            using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut))
            {
                Task clientConnect = client.ConnectAsync();
                server.WaitForConnection();
                clientConnect.Wait();

                desiredBufferSize = server.OutBufferSize * 2;
            }

            using (var server = new NamedPipeServerStream(pipeName, direction, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize))
            using (var client = new NamedPipeClientStream(".", pipeName, direction == PipeDirection.In ? PipeDirection.Out : PipeDirection.In))
            {
                Task clientConnect = client.ConnectAsync();
                server.WaitForConnection();
                clientConnect.Wait();

                if ((direction & PipeDirection.Out) != 0)
                {
                    Assert.InRange(server.OutBufferSize, desiredBufferSize, int.MaxValue);
                }

                if ((direction & PipeDirection.In) != 0)
                {
                    Assert.InRange(server.InBufferSize, desiredBufferSize, int.MaxValue);
                }
            }
        }
Пример #26
0
        public async Task Unix_GetImpersonationUserName_Succeed()
        {
            string pipeName = GetUniquePipeName();

            using (var server = new NamedPipeServerStream(pipeName))
            using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
            {
                Task serverTask = server.WaitForConnectionAsync();

                client.Connect();
                await serverTask;

                string name = server.GetImpersonationUserName();
                Assert.NotNull(name);
                Assert.False(string.IsNullOrWhiteSpace(name));
            }
        }
Пример #27
0
 public PipeClient(string serverId)
 {
     _pipeClient = new NamedPipeClientStream(".", serverId, PipeDirection.InOut, PipeOptions.Asynchronous);
 }
Пример #28
0
        public void InvalidReadMode_Throws_ArgumentOutOfRangeException(PipeDirection serverDirection, PipeDirection clientDirection)
        {
            string pipeName = GetUniquePipeName();
            using (var server = new NamedPipeServerStream(pipeName, serverDirection, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
            using (var client = new NamedPipeClientStream(".", pipeName, clientDirection))
            {
                Task clientConnect = client.ConnectAsync();
                server.WaitForConnection();
                clientConnect.Wait();

                Assert.Throws<ArgumentOutOfRangeException>(() => server.ReadMode = (PipeTransmissionMode)999);
                Assert.Throws<ArgumentOutOfRangeException>(() => client.ReadMode = (PipeTransmissionMode)999);
            }
        }
Пример #29
0
        private async void Application_Startup(object sender, StartupEventArgs e)
        {
            App.Reload(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ConvertZZ.json"));
            ShutdownMode = ShutdownMode.OnMainWindowClose;
            if (e.Args.Length > 0)
            {
                if (e.Args[0] == "/file" || e.Args[0] == "/audio")
                {
                    var    ps       = Process.GetProcessesByName("ConvertZZ");
                    IntPtr hwndTest = IntPtr.Zero;
                    if (ps.Length > 1)
                    {
                        long mini = ps.ToList().Min(x => x.StartTime.Ticks);
                        hwndTest = ps.Where(x => x.StartTime.Ticks == mini).First().Handle;
                    }
                    else
                    {
                        ShowUI();
                        Window_DialogHost window_DialogHost = new Window_DialogHost(e.Args[0] == "/file" ? Enums.Enum_Mode.Mode.File_FileName : Enums.Enum_Mode.Mode.AutioTag, e.Args.Skip(1).ToArray());
                        window_DialogHost.Show();
                        return;
                    }
                    try
                    {
                        using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "ConvertZZ_Pipe", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
                        {
                            Console.WriteLine("Connecting to server...\n");
                            await pipeClient.ConnectAsync(1000);

                            StreamString ss = new StreamString(pipeClient);
                            // The client security token is sent with the first write.
                            // Send the name of the file whose contents are returned
                            // by the server.
                            await ss.WriteStringAsync(string.Join("|", e.Args));

                            pipeClient.WaitForPipeDrain();
                            string returns = await ss.ReadStringAsync();

                            pipeClient.Close();
                        };
                    }
                    catch { }
                    Shutdown(1);
                    return;
                }
                Encoding[] encoding = new Encoding[2];
                bool       EncodingSetted = false;
                int        ToChinese = 0;
                string     path1 = null, path2 = null;
                Regex      Regex_path1          = null;
                int        VocabularyCorrection = -1;
                for (int i = 0; i < e.Args.Length; i++)
                {
                    switch (e.Args[i])
                    {
                    case "/i:ule":
                        encoding[0]    = Encoding.Unicode;
                        EncodingSetted = true;
                        break;

                    case "/i:ube":
                        encoding[0]    = Encoding.BigEndianUnicode;
                        EncodingSetted = true;
                        break;

                    case "/i:utf8":
                        encoding[0]    = Encoding.UTF8;
                        EncodingSetted = true;
                        break;

                    case "/i:gbk":
                        encoding[0]    = Encoding.GetEncoding("GBK");
                        EncodingSetted = true;
                        break;

                    case "/i:big5":
                        encoding[0]    = Encoding.GetEncoding("Big5");
                        EncodingSetted = true;
                        break;

                    case "/o:ule":
                        encoding[1] = Encoding.Unicode;
                        break;

                    case "/o:ube":
                        encoding[1] = Encoding.BigEndianUnicode;
                        break;

                    case "/o:utf8":
                        encoding[1] = Encoding.UTF8;
                        break;

                    case "/o:gbk":
                        encoding[1] = Encoding.GetEncoding("GBK");
                        break;

                    case "/o:big5":
                        encoding[1] = Encoding.GetEncoding("Big5");
                        break;

                    case "/f:t":
                        ToChinese = 1;
                        break;

                    case "/f:s":
                        ToChinese = 2;
                        break;

                    case "/f:d":
                        ToChinese = 0;
                        break;

                    case "/d:t":
                        VocabularyCorrection = 1;
                        break;

                    case "/d:f":
                        VocabularyCorrection = 0;
                        break;

                    case "/d:s":
                        VocabularyCorrection = -1;
                        break;

                    default:
                        if (path1 == null)
                        {
                            path1       = e.Args[i];
                            Regex_path1 = new Regex(Regex.Replace(path1.Replace("*", "(.*?)"), "[\\/]", "[\\\\/]") + "$");
                        }
                        else
                        {
                            path2 = e.Args[i];
                        }
                        break;
                    }
                }
                if (VocabularyCorrection == 1 || (VocabularyCorrection == -1 && App.Settings.VocabularyCorrection))
                {
                    new Thread(new ThreadStart(async() =>
                    {
                        await ChineseConverter.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Dictionary.csv"));
                        DicLoaded = true;
                    })).Start();
                }
                string        s             = "";
                List <string> file          = new List <string>();
                bool          ModeIsOneFile = true;
                if (path1.Contains("*"))
                {
                    ModeIsOneFile = false;
                    Directory.GetFiles(Path.GetDirectoryName(path1), Path.GetFileName(path1)).ToList().ForEach(x =>
                                                                                                               file.Add(x)
                                                                                                               );
                }
                else
                {
                    if (File.Exists(path1))
                    {
                        file.Add(path1);
                    }
                    else
                    {
                        Console.WriteLine($"檔案\"{path1}\" 不存在");
                        Console.Read();
                        Shutdown(1);
                        return;
                    }
                }
                if (encoding[1] == null || string.IsNullOrWhiteSpace(path1))
                {
                    Console.WriteLine("參數錯誤(目標編碼為空或來源檔案路徑未填寫)");
                    Console.Read();
                    Shutdown(1);
                    return;
                }
                if (string.IsNullOrWhiteSpace(path2))
                {
                    path2 = path1;
                }
                if (path1.Count(x => x == '*') != path2.Count(x => x == '*') && path2.Contains("*"))
                {
                    Console.WriteLine("參數錯誤(輸出路徑的萬用字元術與輸入路徑不同)");
                    Console.Read();
                    Shutdown(1);
                    return;
                }
                if (path1.Contains("*") && !path2.Contains("*") && File.Exists(path2))
                {
                    Console.WriteLine("參數錯誤(輸入路徑具有萬用字元,但輸出路徑卻指向一個檔案)");
                    Console.Read();
                    Shutdown(1);
                    return;
                }
                foreach (var f in file)
                {
                    using (Stream stream = new FileStream(f, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        using (StreamReader streamReader = new StreamReader(stream, encoding[0], false))
                        {
                            s = streamReader.ReadToEnd();
                        }
                    }
                    if (!EncodingSetted)
                    {
                        switch (EncodingAnalyzer.Analyze(s))
                        {
                        case -1:
                            encoding[0] = Encoding.Default;
                            break;

                        case 0:
                        case 1:
                            encoding[0] = Encoding.GetEncoding("BIG5");
                            break;

                        case 2:
                        case 3:
                            encoding[0] = Encoding.GetEncoding("GBK");
                            break;
                        }
                    }
                    s = ConvertHelper.FileConvert(s, encoding, ToChinese, VocabularyCorrection);
                    if (ModeIsOneFile)
                    {
                        using (StreamWriter streamWriter = new StreamWriter(path2, false, encoding[1] == Encoding.UTF8 ? new UTF8Encoding(App.Settings.FileConvert.UnicodeAddBom) : encoding[1]))
                        {
                            streamWriter.Write(s);
                            streamWriter.Flush();
                        }
                    }
                    else
                    {
                        var m1 = Regex_path1.Match(f);
                        if (m1.Success)
                        {
                            if (path2.Contains("*"))
                            {
                                var    array   = path2.Split('*');
                                string @string = "";
                                for (int i = 0; i < array.Length; i++)
                                {
                                    @string += array[i];
                                    if (i + 1 <= m1.Groups.Count - 1)
                                    {
                                        @string += m1.Groups[i + 1].Value;
                                    }
                                }

                                Directory.CreateDirectory(Path.GetDirectoryName(@string));
                                using (StreamWriter streamWriter = new StreamWriter(@string, false, encoding[1] == Encoding.UTF8 ? new UTF8Encoding(App.Settings.FileConvert.UnicodeAddBom) : encoding[1]))
                                {
                                    streamWriter.Write(s);
                                    streamWriter.Flush();
                                }
                            }
                            else
                            {
                                Directory.CreateDirectory(Path.GetDirectoryName(path2));
                                using (StreamWriter streamWriter = new StreamWriter(Path.Combine(Path.GetDirectoryName(path2), Path.GetFileName(f)), false, encoding[1] == Encoding.UTF8 ? new UTF8Encoding(App.Settings.FileConvert.UnicodeAddBom) : encoding[1]))
                                {
                                    streamWriter.Write(s);
                                    streamWriter.Flush();
                                }
                            }
                        }
                    }
                }
                Shutdown(1);
                return;
            }
            else
            {
                if ((Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1))
                {
                    MessageBox.Show("應用程式 " + Process.GetCurrentProcess().ProcessName + " 己在執行中,請先關閉舊視窗。", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                    Shutdown(1);
                    return;
                }
                ShowUI();
            }
        }
Пример #30
0
        public static void ClientConnectWrongConflictingDirection()
        {
            const string serverName1 = "testServer4";

            using (NamedPipeServerStream server = new NamedPipeServerStream(serverName1, PipeDirection.Out))
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", serverName1, PipeDirection.Out))
            {
                Assert.Throws<UnauthorizedAccessException>(() => client.Connect());

                Assert.False(client.IsConnected);
            }

            const string serverName2 = "testServer5";

            using (NamedPipeServerStream server = new NamedPipeServerStream(serverName2, PipeDirection.In))
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", serverName2, PipeDirection.In))
            {
                Assert.Throws<UnauthorizedAccessException>(() => client.Connect());

                Assert.False(client.IsConnected);
            }
        }
Пример #31
0
 public NamedPipeClientStreamWrapper(string v, string token, PipeDirection inOut)
 {
     _pipeClientStream = new NamedPipeClientStream(v, token, inOut);
 }
Пример #32
0
        public void NameTooLong_MaxLengthPerPlatform()
        {
            // Increase a name's length until it fails
            ArgumentOutOfRangeException e = null;
            string name = Path.GetRandomFileName();
            for (int i = 0; ; i++)
            {
                try
                {
                    name += 'c';
                    using (var s = new NamedPipeServerStream(name))
                    using (var c = new NamedPipeClientStream(name))
                    {
                        Task t = s.WaitForConnectionAsync();
                        c.Connect();
                        t.GetAwaiter().GetResult();
                    }
                }
                catch (ArgumentOutOfRangeException exc)
                {
                    e = exc;
                    break;
                }
            }
            Assert.NotNull(e);
            Assert.NotNull(e.ActualValue);

            // Validate the length was expected
            string path = (string)e.ActualValue;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                Assert.Equal(108, path.Length);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                Assert.Equal(104, path.Length);
            }
            else
            {
                Assert.InRange(path.Length, 92, int.MaxValue);
            }
        }
Пример #33
0
        static void Main(string[] args)
        {
            var client = new NamedPipeClientStream("SharpBrain");

            Console.Write("Connecting...");
            client.Connect();
            Console.WriteLine("DONE");

            var reader = new StreamReader(client);
            var writer = new StreamWriter(client)
            {
                AutoFlush = true
            };

            var train = new List <string>();

            train.Add("n0=0 n1=0 n2=0 -e"); //   0   0   = 0
            train.Add("n0=0 n1=1 n2=1 -e"); //   0   1   = 1
            train.Add("n0=1 n1=0 n2=1 -e"); //   1   0   = 1
            train.Add("n0=1 n1=1 n2=0 -e"); //   1   1   = 0

            for (int i = 0; i < 1e5; i++)
            {
                double error = 0;
                for (int j = 0; j < train.Count; j++)
                {
                    writer.WriteLine(train[j]);
                    var str = reader.ReadLine();
                    error += double.Parse(str);
                }
                error /= train.Count;
                Console.WriteLine(string.Format("#iteration-{0}: {1}", i, error));
            }


            var test = new List <string>();

            test.Add("n0=0 n1=0");
            test.Add("n0=0 n1=1");
            test.Add("n0=1 n1=0");
            test.Add("n0=1 n1=1");

            Console.WriteLine("Testing...");
            for (int i = 0; i < test.Count; i++)
            {
                writer.WriteLine(test[i]);
                Console.Write(test[i] + "\t");
                Console.WriteLine(reader.ReadLine());
            }

            while (true)
            {
                try
                {
                    writer.WriteLine(Console.ReadLine());
                    Console.WriteLine(reader.ReadLine());
                }
                catch (Exception e)
                { Console.WriteLine("Error => " + e.Message); }
            }
        }
Пример #34
0
 public Context(Session session, int id, bool isMainThread)
 {
     mIsMainThread = isMainThread;
     mSession = session;
     mKey = mSession.mKey + "\\" + id.ToString("x8");
     mPipe = new NamedPipeClientStream(".", mKey, PipeDirection.InOut);
     mPipe.Connect();
     mReader = new BinaryReader(mPipe);
     mWriter = new BinaryWriter(mPipe);
 }
Пример #35
0
        /// <summary>
        /// Attempts to connect to the specified process.
        /// </summary>
        private Stream TryConnectToProcess(int nodeProcessId, int timeout, long hostHandshake, long clientHandshake)
        {
            // Try and connect to the process.
            string pipeName = "MSBuild" + nodeProcessId;

            NamedPipeClientStream nodeStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);

            CommunicationsUtilities.Trace("Attempting connect to PID {0} with pipe {1} with timeout {2} ms", nodeProcessId, pipeName, timeout);

            try
            {
                nodeStream.Connect(timeout);

#if !MONO
                if (NativeMethodsShared.IsWindows)
                {
                    // Verify that the owner of the pipe is us.  This prevents a security hole where a remote node has
                    // been faked up with ACLs that would let us attach to it.  It could then issue fake build requests back to
                    // us, potentially causing us to execute builds that do harmful or unexpected things.  The pipe owner can
                    // only be set to the user's own SID by a normal, unprivileged process.  The conditions where a faked up
                    // remote node could set the owner to something else would also let it change owners on other objects, so
                    // this would be a security flaw upstream of us.
                    ValidateRemotePipeSecurityOnWindows(nodeStream);
                }
#endif

                CommunicationsUtilities.Trace("Writing handshake to pipe {0}", pipeName);
                nodeStream.WriteLongForHandshake(hostHandshake);

                CommunicationsUtilities.Trace("Reading handshake from pipe {0}", pipeName);
                long handshake = nodeStream.ReadLongForHandshake();

                if (handshake != clientHandshake)
                {
                    CommunicationsUtilities.Trace("Handshake failed. Received {0} from client not {1}. Probably the client is a different MSBuild build.", handshake, clientHandshake);
                    throw new InvalidOperationException();
                }

                // We got a connection.
                CommunicationsUtilities.Trace("Successfully connected to pipe {0}...!", pipeName);
                return(nodeStream);
            }
            catch (Exception e)
            {
                if (ExceptionHandling.IsCriticalException(e))
                {
                    throw;
                }

                // Can be:
                // UnauthorizedAccessException -- Couldn't connect, might not be a node.
                // IOException -- Couldn't connect, already in use.
                // TimeoutException -- Couldn't connect, might not be a node.
                // InvalidOperationException – Couldn’t connect, probably a different build
                CommunicationsUtilities.Trace("Failed to connect to pipe {0}. {1}", pipeName, e.Message.TrimEnd());

                // If we don't close any stream, we might hang up the child
                if (nodeStream != null)
                {
                    nodeStream.Dispose();
                }
            }

            return(null);
        }
Пример #36
0
        [PlatformSpecific(PlatformID.Windows)] // Unix currently doesn't support message mode
        public async Task Windows_MessagePipeTransissionMode(PipeOptions serverOptions)
        {
            byte[] msg1 = new byte[] { 5, 7, 9, 10 };
            byte[] msg2 = new byte[] { 2, 4 };
            byte[] received1 = new byte[] { 0, 0, 0, 0 };
            byte[] received2 = new byte[] { 0, 0 };
            byte[] received3 = new byte[] { 0, 0, 0, 0 };
            byte[] received4 = new byte[] { 0, 0, 0, 0 };
            byte[] received5 = new byte[] { 0, 0 };
            byte[] received6 = new byte[] { 0, 0, 0, 0 };
            string pipeName = GetUniquePipeName();

            using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, serverOptions))
            {
                using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
                {
                    server.ReadMode = PipeTransmissionMode.Message;
                    Assert.Equal(PipeTransmissionMode.Message, server.ReadMode);

                    Task clientTask = Task.Run(() =>
                    {
                        client.Connect();

                        client.Write(msg1, 0, msg1.Length);
                        client.Write(msg2, 0, msg2.Length);
                        client.Write(msg1, 0, msg1.Length);

                        client.Write(msg1, 0, msg1.Length);
                        client.Write(msg2, 0, msg2.Length);
                        client.Write(msg1, 0, msg1.Length);

                        int serverCount = client.NumberOfServerInstances;
                        Assert.Equal(1, serverCount);
                    });

                    server.WaitForConnection();

                    int len1 = server.Read(received1, 0, msg1.Length);
                    Assert.True(server.IsMessageComplete);
                    Assert.Equal(msg1.Length, len1);
                    Assert.Equal(msg1, received1);

                    int len2 = server.Read(received2, 0, msg2.Length);
                    Assert.True(server.IsMessageComplete);
                    Assert.Equal(msg2.Length, len2);
                    Assert.Equal(msg2, received2);

                    int expectedRead = msg1.Length - 1;
                    int len3 = server.Read(received3, 0, expectedRead);  // read one less than message
                    Assert.False(server.IsMessageComplete);
                    Assert.Equal(expectedRead, len3);
                    for (int i = 0; i < expectedRead; ++i)
                    {
                        Assert.Equal(msg1[i], received3[i]);
                    }

                    expectedRead = msg1.Length - expectedRead;
                    Assert.Equal(expectedRead, server.Read(received3, len3, expectedRead));
                    Assert.True(server.IsMessageComplete);
                    Assert.Equal(msg1, received3);

                    Assert.Equal(msg1.Length, await server.ReadAsync(received4, 0, msg1.Length));
                    Assert.True(server.IsMessageComplete);
                    Assert.Equal(msg1, received4);

                    Assert.Equal(msg2.Length, await server.ReadAsync(received5, 0, msg2.Length));
                    Assert.True(server.IsMessageComplete);
                    Assert.Equal(msg2, received5);

                    expectedRead = msg1.Length - 1;
                    Assert.Equal(expectedRead, await server.ReadAsync(received6, 0, expectedRead));  // read one less than message
                    Assert.False(server.IsMessageComplete);
                    for (int i = 0; i < expectedRead; ++i)
                    {
                        Assert.Equal(msg1[i], received6[i]);
                    }

                    expectedRead = msg1.Length - expectedRead;
                    Assert.Equal(expectedRead, await server.ReadAsync(received6, msg1.Length - expectedRead, expectedRead));
                    Assert.True(server.IsMessageComplete);
                    Assert.Equal(msg1, received6);

                    await clientTask;
                }
            }
        }
Пример #37
0
        void ContextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Name)
            {
            case "C":
                Process.Start("Explorer.exe", "/select," + AgentHubConfig.AppConfigPath);
                break;

            case "L":
                Process.Start("Explorer.exe", App.CombinePath(@"logs\"));
                break;

            case "D":
                using (var pipeClient = new NamedPipeClientStream(SecurityPolicy.PipeName))
                {
                    pipeClient.Connect();
                    pipeClient.WriteByte(0);
                    pipeClient.WaitForPipeDrain();
                }
                break;

            case "P":
                using (var pipeClient = new NamedPipeClientStream(SecurityPolicy.PipeName))
                {
                    pipeClient.Connect();
                    pipeClient.WriteByte(1);
                    pipeClient.WaitForPipeDrain();
                }
                break;

            case "PS":
                using (var pipeClient = new NamedPipeClientStream(SecurityPolicy.PipeName))
                {
                    pipeClient.Connect();
                    pipeClient.WriteByte(2);
                    pipeClient.WaitForPipeDrain();
                }
                break;

            case "H":
                Process.Start("http://www.cnblogs.com/Googler/archive/2013/05/30/3109402.html");
                break;

            case "S":
                var reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                if (reg.GetValue(_notify.Text) == null)
                {
                    reg.SetValue(_notify.Text, GetExecPath());
                    Console.Out.WriteTip("开机启动 Ok.");
                }
                else
                {
                    reg.DeleteValue(_notify.Text, false);
                    Console.Out.WriteTip("开机禁止 Ok.");
                }
                break;

            case "V":
                Visible = !Visible;
                break;

            case "R":
                Application.Restart();
                this.Exit();
                break;

            default:
                this.Exit();
                break;
            }
        }
Пример #38
0
        /// <summary>
        /// Main function
        ///
        /// </summary>
        /// <param name="args">
        ///		(Optional)
        ///		Callsign (args[0]) and verification code (args[1]).
        ///		If not provided, the user is prompted to enter them via the commandline interface.
        /// </param>
        static void Main(string[] args)
        {
            // Callsign + verification code provided via arguments
            bool isStartedWithArgs = (args.Length == 2);

            try {
                logger.Log("Starting FcomClient...");

                bool  isInputValid   = false;
                Regex callsignFormat = new Regex(@"^(\d|\w|_|-)+$");

                // Callsign + verification code provided via arguments
                if (isStartedWithArgs)
                {
                    // Connect to GUI via named pipe
                    namedPipeClient = new NamedPipeClientStream(FCOM_GUI_PIPE);
                    namedPipeClient.Connect();

                    if (callsignFormat.IsMatch(args[0]))
                    {
                        isInputValid = true;
                        callsign     = args[0];

                        logger.Log(String.Format("Client was started with the following arguments: {0} {1}", args[0], args[1]));

                        am = new ApiManager(args[1], callsign);

                        if (!am.IsRegistered)
                        {
                            logger.Log("[FCOM_API_ERROR] Couldn't register with API");
                            SendPipeMessage(namedPipeClient, "FCOM_API_ERROR");
                        }
                    }
                    else
                    {
                        // if invalid callsign format, ask the user via the command-line interface
                        isInputValid = false;
                        SendPipeMessage(namedPipeClient, "FCOM_CLIENT_BAD_CALLSIGN");
                    }
                }

                // ask user for callsign + verification code,
                // if not provided via args, or if args were invalid
                if (!isInputValid)
                {
                    bool isRegistered = false;
                    while (!isRegistered)
                    {
                        while (!isInputValid)
                        {
                            Console.Write("\nPlease enter your exact callsign, then press Enter: ");
                            callsign = Console.ReadLine();

                            if (callsignFormat.IsMatch(callsign))
                            {
                                isInputValid = true;
                            }
                            else
                            {
                                Console.WriteLine("Invalid callsign!");
                            }
                        }

                        Console.Write("\nPlease enter the verification code from Discord, then press Enter:\n");
                        string token = Console.ReadLine();

                        logger.Log(String.Format("Callsign: \"{0}\", Token: \"{1}\"", callsign, token));

                        Console.WriteLine("\nRegistering token with Discord bot...");
                        am = new ApiManager(token, callsign);
                        logger.Log(String.Format("Register at {0}{1}", am.SERVER_ADDRESS, am.REGISTRATION_ENDPOINT));

                        isRegistered = am.IsRegistered;
                        if (isRegistered)
                        {
                            Console.WriteLine("Registered {0} to Discord user {1} ({2})", callsign, am.DiscordName, am.DiscordId);
                        }
                        else
                        {
                            Console.WriteLine("Couldn't register! You've either entered the incorrect code," +
                                              " or the server isn't responding.");
                        }
                    }
                }

                Console.Write("\nDetecting connections...\n\n");
                ConnectionManager     cm          = new ConnectionManager();
                List <HardwareDevice> connections = cm.Connections;

                // TODO: completely decouple SharpPcap from the UI

                // Provide GUI with list of detected connections and wait for user response
                //ExternalGuiManager ext = new ExternalGuiManager();
                //ICaptureDevice device = ext.GetHardwareDevice(connections).Device;       // BLOCKING CALL

                ICaptureDevice device;

                // Auto-select the only connection available
                if (connections.Count == 1)
                {
                    device = connections[0].Device;

                    // No additional user input needed - close the console window if opened via GUI
                    if (isStartedWithArgs)
                    {
                        ShowWindow(GetConsoleWindow(), 0);
                        logger.Log("Hiding console window");
                    }
                }
                // Otherwise, prompt the user for the correct one
                else
                {
                    int i = 0;
                    foreach (HardwareDevice h in connections)
                    {
                        Console.WriteLine("({0})", i);
                        Console.WriteLine("------");
                        Console.WriteLine("Name: {0}\nDescription: {1}", h.FriendlyName, h.Description);
                        Console.WriteLine("IP addresses:");
                        foreach (string s in h.IpAddresses)
                        {
                            // print detected IPs
                            Console.WriteLine("\t" + s);
                        }
                        i++;
                    }

                    bool parseSuccess = false;
                    int  deviceNumber = -1;
                    Console.WriteLine("\nWhich of the above is your internet connection?");

                    // Ignore invalid inputs
                    while (deviceNumber < 0 || deviceNumber >= connections.Count || !parseSuccess)
                    {
                        Console.Write("Enter the corresponding number: ");
                        parseSuccess = Int32.TryParse(Console.ReadLine(), out deviceNumber);
                    }

                    device = connections[deviceNumber].Device;
                }

                // force a wait so that the user can see what's happening
                System.Threading.Thread.Sleep(700);

                // register event handler
                device.OnPacketArrival +=
                    new SharpPcap.PacketArrivalEventHandler(OnIncomingFsdPacket);

                // open device for capturing
                int readTimeoutMilliseconds = 2000;
                device.Open(DeviceMode.Normal, readTimeoutMilliseconds);

                // set filter to tcp port 6809
                device.Filter = "tcp port 6809";

                // Hide console window
                if (isStartedWithArgs)
                {
                    logger.Log("Hiding console window");
                    ShowWindow(GetConsoleWindow(), 0);
                }

                Console.WriteLine("\nYou may now minimize this window. To quit, simply close it.");
                Console.WriteLine("When you're done, close this window and send \"remove\" to the Discord bot!\n\n");

                logger.Log("Starting FSD capture...");

                // Start capturing packets indefinitely
                device.Capture();

                // note: this line is uncreachable, since we're capturing indefinitely
                device.Close();
            }
            catch (Exception ex)
            {
                // Dump stack trace to logfile
                logger.Log("[CRASH] " + ex.ToString());

                Console.WriteLine("\nFcomClient has crashed! Please see log.txt for error details.\n");

                if (args.Length == 0)
                {
                    Console.WriteLine("Press any key to exit...");
                    Console.ReadKey();
                }
                else if (isStartedWithArgs)
                {
                    // Notify GUI of crash
                    byte[] messageBytes = System.Text.Encoding.UTF8.GetBytes("FCOM_CLIENT_CRASH");
                    namedPipeClient.Write(messageBytes, 0, messageBytes.Length);
                }
            }
        }
Пример #39
0
        static void Main()
        {
            bool main;

            using (var appMutex = new Mutex(true, "catlock", out main)) {
                if (main)
                {
                    var isAdmin = new WindowsPrincipal(WindowsIdentity.GetCurrent())
                                  .IsInRole(WindowsBuiltInRole.Administrator);

                    if (!isAdmin)
                    {
                        try {
                            appMutex.Dispose();

                            Process.Start(new ProcessStartInfo {
                                FileName = Assembly.GetExecutingAssembly().CodeBase,
                                Verb     = "runas"
                            });
                        }
                        catch (Win32Exception) { }

                        return;
                    }

                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);

                    var form = new MainForm();
                    var cts  = new CancellationTokenSource();
                    var task = Task.Factory.StartNew(() => {
                        while (!cts.Token.IsCancellationRequested)
                        {
                            var ps = new PipeSecurity();
                            ps.SetAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow));
                            var server = new NamedPipeServerStream("catlock", PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 512, 512, ps);

                            using (var commandProcessed = new ManualResetEvent(false)) {
                                server.BeginWaitForConnection(ar => {
                                    if (!server.CanRead)
                                    {
                                        return;
                                    }
                                    server.EndWaitForConnection(ar);

                                    using (var sr = new StreamReader(server)) {
                                        var cmd = sr.ReadLine();

                                        if (cmd == "block")
                                        {
                                            form.Invoke((Action)(() => form.Block()));
                                        }
                                    }

                                    commandProcessed.Set();
                                }, null);

                                WaitHandle.WaitAny(new WaitHandle[] { commandProcessed, cts.Token.WaitHandle });
                            }
                        }
                    });

                    Application.Run(form);

                    cts.Cancel();
                    task.Wait();
                }
                else
                {
                    using (var client = new NamedPipeClientStream(".", "catlock", PipeDirection.Out, PipeOptions.Asynchronous)) {
                        client.Connect();

                        using (var sw = new StreamWriter(client)) {
                            sw.WriteLine("block");
                            sw.Flush();
                            client.WaitForPipeDrain();
                        }
                    }
                }
            }
        }
Пример #40
0
 public PipeClient()
 {
     client = new NamedPipeClientStream("catpost_update");
     sr     = new StreamReader(client);
     sw     = new StreamWriter(client);
 }
Пример #41
0
        public void CredentialOp()
        {
            string HostName = "Host1";
            string UserName = "******";
            string Password = "******";

            // Empty list
            ServerListHelper.instance.ClearServerList();
            int conSize           = 0;
            List <ServerInfo> con = ServerListHelper.instance.GetServerList();

            Assert.IsTrue(con.Count == conSize);

            //1. Empty credential
            NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.Out);

            pipeClient.Connect();
            string credential = EncryptionUtils.ProtectForLocalMachine(String.Join(ServerListHelper.SEPARATOR.ToString(), new[] { HostName, null, null }));

            pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length);
            pipeClient.Close();
            System.Threading.Thread.Sleep(1000);
            con = ServerListHelper.instance.GetServerList();
            Assert.IsTrue(con.Count == conSize);

            //2. Send credential and check result
            pipeClient = new NamedPipeClientStream(".", HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.Out);
            pipeClient.Connect();
            credential = EncryptionUtils.ProtectForLocalMachine(String.Join(ServerListHelper.SEPARATOR.ToString(), new[] { HostName, UserName, Password }));
            pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length);
            pipeClient.Close();
            System.Threading.Thread.Sleep(1000);
            con = ServerListHelper.instance.GetServerList();
            Assert.IsTrue(con.Count == conSize + 1);

            //3. Send credential twice and check result
            pipeClient = new NamedPipeClientStream(".", HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.Out);
            pipeClient.Connect();
            credential = EncryptionUtils.ProtectForLocalMachine(String.Join(ServerListHelper.SEPARATOR.ToString(), new[] { HostName, UserName, Password }));
            pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length);
            pipeClient.Close();
            System.Threading.Thread.Sleep(1000);
            con = ServerListHelper.instance.GetServerList();
            Assert.IsTrue(con.Count == conSize + 1);

            //4. remove credential and check result
            pipeClient = new NamedPipeClientStream(".", HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.Out);
            pipeClient.Connect();
            credential = EncryptionUtils.ProtectForLocalMachine(String.Join(ServerListHelper.SEPARATOR.ToString(), new[] { HostName }));
            pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length);
            pipeClient.Close();
            System.Threading.Thread.Sleep(1000);
            con = ServerListHelper.instance.GetServerList();
            Assert.IsTrue(con.Count == conSize);

            //5. add long credential size
            pipeClient = new NamedPipeClientStream(".", HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.Out);
            pipeClient.Connect();
            HostName   = "Host01234546789012345467890123454678901234546789012345467890123454678901234546789012345467890123454678901234546789";
            UserName   = "******";
            Password   = "******";
            credential = EncryptionUtils.ProtectForLocalMachine(String.Join(ServerListHelper.SEPARATOR.ToString(), new[] { HostName, UserName, Password }));
            pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length);
            pipeClient.Close();
            System.Threading.Thread.Sleep(1000);
            con = ServerListHelper.instance.GetServerList();
            Assert.IsTrue(con.Count == conSize + 1);

            //6. remove long credential size
            pipeClient = new NamedPipeClientStream(".", HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.Out);
            pipeClient.Connect();
            credential = EncryptionUtils.ProtectForLocalMachine(String.Join(ServerListHelper.SEPARATOR.ToString(), new[] { HostName }));
            pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length);
            pipeClient.Close();
            System.Threading.Thread.Sleep(1000);
            con = ServerListHelper.instance.GetServerList();
            Assert.IsTrue(con.Count == conSize);


            //7. send 2 credentials
            pipeClient = new NamedPipeClientStream(".", HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.Out);
            pipeClient.Connect();
            HostName   = "host3";
            credential = EncryptionUtils.ProtectForLocalMachine(String.Join(ServerListHelper.SEPARATOR.ToString(), new[] { HostName, UserName, Password }));
            pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length);
            HostName   = "host4";
            credential = EncryptionUtils.ProtectForLocalMachine(String.Join(ServerListHelper.SEPARATOR.ToString(), new[] { HostName, UserName, Password }));
            pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length);
            pipeClient.Close();
            System.Threading.Thread.Sleep(1000);
            con = ServerListHelper.instance.GetServerList();
            Assert.IsTrue(con.Count == conSize + 2);

            //8. remove 2 credentials
            pipeClient = new NamedPipeClientStream(".", HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.Out);
            pipeClient.Connect();
            HostName   = "host3";
            credential = EncryptionUtils.ProtectForLocalMachine(String.Join(ServerListHelper.SEPARATOR.ToString(), new[] { HostName }));
            pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length);
            HostName   = "host4";
            credential = EncryptionUtils.ProtectForLocalMachine(String.Join(ServerListHelper.SEPARATOR.ToString(), new[] { HostName }));
            pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length);
            pipeClient.Close();
            System.Threading.Thread.Sleep(1000);
            con = ServerListHelper.instance.GetServerList();
            Assert.IsTrue(con.Count == conSize);
        }
Пример #42
0
 public override void Dispose()
 {
     base.Dispose();
     _clientStream?.Dispose();
     _clientStream = null;
 }
Пример #43
0
        private NamedPipeClientStream StartHostService()
        {
            var isWindows = true;

#if NETCOREAPP
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                isWindows = false;
            }
#endif
            string folder      = Path.GetDirectoryName(ExeFile);
            string exeFullPath = ExeFile;
            if (folder.IsNullOrEmpty())
            {
                if (isWindows)
                {
                    folder      = Path.GetDirectoryName(Assembly.GetAssembly(typeof(T)).Location).Replace("\\lib\\", "\\bin\\");
                    exeFullPath = Path.Combine(folder, ExeFile);
                }
                else
                {
                    folder      = Path.GetDirectoryName(Assembly.GetAssembly(typeof(T)).Location).Replace("/lib/", "/bin/");
                    Arguments   = string.Concat(Path.Combine(folder, ExeFile.Replace(".exe", ".dll")), " ", Arguments);
                    exeFullPath = "dotnet";
                }
            }

            if (!File.Exists(exeFullPath) && isWindows ||
                !isWindows && string.IsNullOrEmpty(Arguments))
            {
                throw new Exception($"Process path not found: {exeFullPath}");
            }

            // start the host process
            ProcessStartInfo psi = new ProcessStartInfo()
            {
                UseShellExecute  = true,
                FileName         = exeFullPath,
                WorkingDirectory = folder,
                Arguments        = Arguments,
                WindowStyle      = Visible ? ProcessWindowStyle.Normal : ProcessWindowStyle.Hidden
            };
            Process process = Process.Start(psi);

            // wait for service to become available
            bool ServiceReady()
            {
                pipeClient =
                    new NamedPipeClientStream(".", process.Id.ToString(), PipeDirection.InOut,
                                              PipeOptions.Asynchronous);

                pipeClient.Connect();
                if (pipeClient.IsConnected)
                {
                    return(true);
                }
                return(false);
            }

            Retry(ServiceReady, StartTimeout, RetryInterval);
            return(pipeClient);
        }
Пример #44
0
 /// <summary>
 /// Test handle for killing underlying connection
 /// </summary>
 public override void KillConnection()
 {
     _pipeStream.Dispose();
     _pipeStream = null;
 }
Пример #45
0
 /// <summary>
 /// Check to ensure that the named pipe server we connected to is owned by the same
 /// user.
 /// </summary>
 /// <remarks>
 /// The type is embedded in assemblies that need to run cross platform.  While this particular
 /// code will never be hit when running on non-Windows platforms it does need to work when
 /// on Windows.  To facilitate that we use reflection to make the check here to enable it to
 /// compile into our cross plat assemblies.
 /// </remarks>
 private static bool CheckPipeConnectionOwnership(NamedPipeClientStream pipeStream)
 {
     return(true);
 }
Пример #46
0
        internal DockerClient(DockerClientConfiguration configuration, Version requestedApiVersion)
        {
            Configuration        = configuration;
            _requestedApiVersion = requestedApiVersion;
            JsonSerializer       = new JsonSerializer();

            Images        = new ImageOperations(this);
            Containers    = new ContainerOperations(this);
            Miscellaneous = new MiscellaneousOperations(this);
            Networks      = new NetworkOperations(this);
            Swarm         = new SwarmOperations(this);

            ManagedHandler handler;
            var            uri = Configuration.EndpointBaseUri;

            switch (uri.Scheme.ToLowerInvariant())
            {
            case "npipe":
                if (Configuration.Credentials.IsTlsCredentials())
                {
                    throw new Exception("TLS not supported over npipe");
                }

                var segments = uri.Segments;
                if (segments.Length != 3 || !segments[1].Equals("pipe/", StringComparison.OrdinalIgnoreCase))
                {
                    throw new ArgumentException($"{Configuration.EndpointBaseUri} is not a valid npipe URI");
                }

                var serverName = uri.Host;
                if (string.Equals(serverName, "localhost", StringComparison.OrdinalIgnoreCase))
                {
                    // npipe schemes dont work with npipe://localhost/... and need npipe://./... so fix that for a client here.
                    serverName = ".";
                }

                var pipeName = uri.Segments[2];

                uri     = new UriBuilder("http", pipeName).Uri;
                handler = new ManagedHandler(async(host, port, cancellationToken) =>
                {
                    // NamedPipeClientStream handles file not found by polling until the server arrives. Use a short
                    // timeout so that the user doesn't get stuck waiting for a dockerd instance that is not running.
                    var timeout      = 100; // 100ms
                    var stream       = new NamedPipeClientStream(serverName, pipeName);
                    var dockerStream = new DockerPipeStream(stream);

#if NET45
                    await Task.Run(() => stream.Connect(timeout), cancellationToken);
#else
                    await stream.ConnectAsync(timeout, cancellationToken);
#endif
                    return(dockerStream);
                });

                break;

            case "tcp":
            case "http":
                var builder = new UriBuilder(uri)
                {
                    Scheme = configuration.Credentials.IsTlsCredentials() ? "https" : "http"
                };
                uri     = builder.Uri;
                handler = new ManagedHandler();
                break;

            case "https":
                handler = new ManagedHandler();
                break;

#if NETSTANDARD1_6
            case "unix":
                var pipeString = uri.LocalPath;
                handler = new ManagedHandler(async(string host, int port, CancellationToken cancellationToken) =>
                {
                    var sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
                    await sock.ConnectAsync(new UnixDomainSocketEndPoint(pipeString));
                    return(sock);
                });
                uri = new UriBuilder("http", uri.Segments.Last()).Uri;
                break;
#endif

            default:
                throw new Exception($"Unknown URL scheme {configuration.EndpointBaseUri.Scheme}");
            }

            _endpointBaseUri = uri;

            _client         = new HttpClient(Configuration.Credentials.GetHandler(handler), true);
            DefaultTimeout  = Configuration.DefaultTimeout;
            _client.Timeout = s_InfiniteTimeout;
        }
 /// <summary>
 /// Creates a new instance of a Managed NamedPipe client. Doesn't connect to anything yet, just setups the values.
 /// </summary>
 public ManagedNamedPipeClient()
 {
     _buffer = new byte[PipeFrame.MAX_SIZE];
     Logger  = new NullLogger();
     _stream = null;
 }
Пример #48
0
            private void PipeThread(object id)
            {
                try
                {
                    using (var pipe = new NamedPipeClientStream(".", (string)id + "\\root", PipeDirection.In))
                    {
                        pipe.Connect();

                        BinaryReader rd = new BinaryReader(pipe);

                        for (;;)
                        {
                            lock (mSync)
                                if (mShutdown)
                                    return;

                            int op = pipe.ReadByte();
                            if (op < 0)
                                return;

                            ProcessPipeThreadEvent(rd, op);
                        }
                    }
                }
                catch (Exception ex)
                {
                    lock (mSync)
                        mError.Add(ex);
                }
            }
Пример #49
0
 public void Open()
 {
     pipeClient = new NamedPipeClientStream(".", Program.PROCESS_PIPE_NAME, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation);
     Debug.WriteLine("Connecting to server via named pipe (" + Program.PROCESS_PIPE_NAME + ")...\n");
     pipeClient.Connect(3000);
 }
Пример #50
0
        public void Unix_MultipleServerDisposal_DoesntDeletePipe()
        {
            // Test for when multiple servers are created and linked to the same FIFO. The original ServerStream
            // that created the FIFO is disposed. The other servers should still be valid and useable.
            string serverName = GetUniquePipeName();

            var server1 = new NamedPipeServerStream(serverName, PipeDirection.In); // Creates the FIFO
            var server2 = new NamedPipeServerStream(serverName, PipeDirection.In);
            var client1 = new NamedPipeClientStream(".", serverName, PipeDirection.Out);
            var client2 = new NamedPipeClientStream(".", serverName, PipeDirection.Out);

            Task server1Task = server1.WaitForConnectionAsync(); // Opens a handle to the FIFO
            Task server2Task = server2.WaitForConnectionAsync(); // Opens a handle to the same FIFO as server1

            Task client1Task = client1.ConnectAsync();
            Task.WaitAll(server1Task, server2Task, client1Task); // client1 connects to server1 AND server2

            Assert.True(server1.IsConnected);
            Assert.True(server2.IsConnected);

            // Get rid of client1/server1 and make sure server2 isn't connected (so that it can connect to client2)
            server1.Dispose();
            client1.Dispose();
            server2.Disconnect();
            Assert.False(server2.IsConnected);

            server2Task = server2.WaitForConnectionAsync(); // Opens a handle to the same FIFO
            Task client2Task = client2.ConnectAsync(); 
            Task.WaitAll(server2Task, client2Task); // Should not block!
            Assert.True(server2.IsConnected);
        }
Пример #51
0
        public SNINpHandle(string serverName, string pipeName, long timerExpire, object callbackObject)
        {
            long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent("<sc.SNI.SNINpHandle.SNINpHandle |SNI|INFO|SCOPE> Constructor");

            SqlClientEventSource.Log.SNITraceEvent("<sc.SNI.SNINpHandle.SNINpHandle |SNI|INFO> Constructor. server name = {0}, pipe name = {1}", serverName, pipeName);
            try
            {
                _sendSync       = new object();
                _targetServer   = serverName;
                _callbackObject = callbackObject;

                try
                {
                    _pipeStream = new NamedPipeClientStream(
                        serverName,
                        pipeName,
                        PipeDirection.InOut,
                        PipeOptions.Asynchronous | PipeOptions.WriteThrough);

                    bool isInfiniteTimeOut = long.MaxValue == timerExpire;
                    if (isInfiniteTimeOut)
                    {
                        _pipeStream.Connect(System.Threading.Timeout.Infinite);
                    }
                    else
                    {
                        TimeSpan ts = DateTime.FromFileTime(timerExpire) - DateTime.Now;
                        ts = ts.Ticks < 0 ? TimeSpan.FromTicks(0) : ts;

                        _pipeStream.Connect((int)ts.TotalMilliseconds);
                    }
                }
                catch (TimeoutException te)
                {
                    SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnOpenFailedError, te);
                    _status = TdsEnums.SNI_ERROR;
                    SqlClientEventSource.Log.SNITraceEvent("<sc.SNI.SNINpHandle.SNINpHandle |SNI|ERR> Timed out. Exception = {0}", te.Message);
                    return;
                }
                catch (IOException ioe)
                {
                    SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnOpenFailedError, ioe);
                    _status = TdsEnums.SNI_ERROR;
                    SqlClientEventSource.Log.SNITraceEvent("<sc.SNI.SNINpHandle.SNINpHandle |SNI|ERR> IOException = {0}", ioe.Message);
                    return;
                }

                if (!_pipeStream.IsConnected || !_pipeStream.CanWrite || !_pipeStream.CanRead)
                {
                    SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.ConnOpenFailedError, string.Empty);
                    _status = TdsEnums.SNI_ERROR;
                    SqlClientEventSource.Log.SNITraceEvent("<sc.SNI.SNINpHandle.SNINpHandle |SNI|ERR> Pipe stream is not connected or cannot write or read to/from it.");
                    return;
                }

                _sslOverTdsStream = new SslOverTdsStream(_pipeStream);
                _sslStream        = new SslStream(_sslOverTdsStream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);

                _stream = _pipeStream;
                _status = TdsEnums.SNI_SUCCESS;
            }
            finally
            {
                SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID);
            }
        }
Пример #52
0
 public void Dispose()
 {
     if (mPipe != null)
     {
         mPipe.Close();
         mPipe = null;
     }
 }
Пример #53
0
 public ClientPipeStreamFacade(string name)
 {
     _clientStream = new NamedPipeClientStream(".", name, PipeDirection.InOut);
 }
Пример #54
0
 public void Dispose()
 {
     _connectionStopped = true;
     _pipeStream?.Dispose();
     _pipeStream = null;
 }
        /// <summary>
        /// Establish connection and log into the SQL Server
        /// </summary>
        public void Connect()
        {
            // Initialize context
            TDSClient.OnPreConnect();

            // Loop while we reach logged-in state. This accounts for connection failures and routing.
            while (TDSClient.State != TDSClientState.LoggedIn)
            {
                Log("Connecting to the server {0} port {1}...", TDSClient.Context.ServerHost, TDSClient.Context.ServerPort);

                // Check if server pipe is specified
                if (string.IsNullOrEmpty(TDSClient.Context.ServerPipe))
                {
                    try
                    {
                        // Establish transport to the TDS Server
                        ClientSocket = new TcpClient(AddressFamily.InterNetwork);
                        ClientSocket.Connect(TDSClient.Context.ServerHost, (int)TDSClient.Context.ServerPort);
                    }
                    catch (SocketException e)
                    {
                        // Check error code
                        if (e.ErrorCode != 10057)
                        {
                            // We don't recognize it
                            throw;
                        }

                        // We are going to retry with IPv6 now because of won't fix bug
                        // http://bugcheck/bugs/VSWhidbey/285220
                        ClientSocket = new TcpClient(AddressFamily.InterNetworkV6);
                        ClientSocket.Connect(TDSClient.Context.ServerHost, (int)TDSClient.Context.ServerPort);
                    }

                    // Callback of PostConnect
                    if (_funcPostConnect != null)
                    {
                        _funcPostConnect(ClientSocket);
                    }
                }
                else
                {
                    // Use named pipes transport
                    ClientPipe = new NamedPipeClientStream(TDSClient.Context.ServerHost, TDSClient.Context.ServerPipe, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation);
                    ClientPipe.Connect();
                }

                Log("Connected");

                try
                {
                    // Check if we have a client socket
                    if (ClientSocket != null)
                    {
                        // Create a client TDS parser with TCP transport
                        ClientParser = new TDSClientParser(TDSClient, ClientSocket.GetStream());
                    }
                    else
                    {
                        // Create a client TDS parser through named pipes transort
                        ClientParser = new TDSClientParser(TDSClient, ClientPipe);
                    }

                    if (_funcTDSStreamPreWriteCallBack != null)
                    {
                        ClientParser.SetTDSStreamPreWriteCallback(_funcTDSStreamPreWriteCallBack);
                    }

                    // Assign event log
                    ClientParser.EventLog = EventLog;

                    // Run login sequence
                    ClientParser.Login();

                    // Check if connection is being re-routed
                    if (TDSClient.State == TDSClientState.ReConnect)
                    {
                        Log("Client is being routed");

                        // Close established connection
                        Disconnect();
                    }
                }
                catch (Exception)
                {
                    // Disconnect client
                    Disconnect();

                    // Bubble up the exception
                    throw;
                }
            }
        }
Пример #56
0
        private static Task <BuildResponse> RunServerCompilationCore(
            RequestLanguage language,
            List <string> arguments,
            BuildPaths buildPaths,
            string pipeName,
            string keepAlive,
            string libEnvVariable,
            Func <string, string, bool> tryCreateServerFunc,
            CancellationToken cancellationToken)
        {
            var clientDir = buildPaths.ClientDirectory;

            var  clientMutexName = BuildProtocolConstants.GetClientMutexName(pipeName);
            bool holdsMutex;

            using (var clientMutex = new Mutex(initiallyOwned: true,
                                               name: clientMutexName,
                                               createdNew: out holdsMutex))
            {
                try
                {
                    if (!holdsMutex)
                    {
                        try
                        {
                            holdsMutex = clientMutex.WaitOne(TimeOutMsNewProcess);

                            if (!holdsMutex)
                            {
                                return(Task.FromResult <BuildResponse>(null));
                            }
                        }
                        catch (AbandonedMutexException)
                        {
                            holdsMutex = true;
                        }
                    }

                    // Check for an already running server
                    var   serverMutexName = BuildProtocolConstants.GetServerMutexName(pipeName);
                    Mutex mutexIgnore;
                    bool  wasServerRunning = Mutex.TryOpenExisting(serverMutexName, out mutexIgnore);
                    var   timeout          = wasServerRunning ? TimeOutMsExistingProcess : TimeOutMsNewProcess;

                    NamedPipeClientStream pipe = null;

                    if (wasServerRunning || tryCreateServerFunc(clientDir, pipeName))
                    {
                        pipe = TryConnectToServer(pipeName,
                                                  timeout,
                                                  cancellationToken);
                    }

                    if (pipe != null)
                    {
                        var request = BuildRequest.Create(language,
                                                          buildPaths.WorkingDirectory,
                                                          arguments,
                                                          keepAlive,
                                                          libEnvVariable);

                        return(TryCompile(pipe, request, cancellationToken));
                    }
                }
                finally
                {
                    if (holdsMutex)
                    {
                        clientMutex.ReleaseMutex();
                    }
                }
            }

            return(null);
        }
Пример #57
0
        public async Task OneWayReadWrites(PipeOptions serverOptions, PipeOptions clientOptions, bool asyncServerOps, bool asyncClientOps)
        {
            using (NamedPipePair pair = CreateNamedPipePair(serverOptions, clientOptions))
            {
                NamedPipeClientStream client = pair.clientStream;
                NamedPipeServerStream server = pair.serverStream;
                byte[] received   = new byte[] { 0 };
                Task   clientTask = Task.Run(async() =>
                {
                    if (asyncClientOps)
                    {
                        await client.ConnectAsync();

                        if (pair.writeToServer)
                        {
                            received = await ReadBytesAsync(client, sendBytes.Length);
                        }
                        else
                        {
                            await WriteBytesAsync(client, sendBytes);
                        }
                    }
                    else
                    {
                        client.Connect();
                        if (pair.writeToServer)
                        {
                            received = ReadBytes(client, sendBytes.Length);
                        }
                        else
                        {
                            WriteBytes(client, sendBytes);
                        }
                    }
                });
                if (asyncServerOps)
                {
                    await server.WaitForConnectionAsync();

                    if (pair.writeToServer)
                    {
                        await WriteBytesAsync(server, sendBytes);
                    }
                    else
                    {
                        received = await ReadBytesAsync(server, sendBytes.Length);
                    }
                }
                else
                {
                    server.WaitForConnection();
                    if (pair.writeToServer)
                    {
                        WriteBytes(server, sendBytes);
                    }
                    else
                    {
                        received = ReadBytes(server, sendBytes.Length);
                    }
                }

                await clientTask;
                Assert.Equal(sendBytes, received);

                server.Disconnect();
                Assert.False(server.IsConnected);
            }
        }
Пример #58
0
        public static void OSX_BufferSizeNotSupported()
        {
            int desiredBufferSize = 10;
            string pipeName = GetUniquePipeName();
            using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize))
            using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out))
            {
                Task clientConnect = client.ConnectAsync();
                server.WaitForConnection();
                clientConnect.Wait();

                Assert.Throws<PlatformNotSupportedException>(() => server.InBufferSize);
                Assert.Throws<PlatformNotSupportedException>(() => client.OutBufferSize);
            }
        }
Пример #59
0
        public async Task ClonedClient_ActsAsOriginalClient()
        {
            byte[] msg1 = new byte[] { 5, 7, 9, 10 };
            byte[] received1 = new byte[] { 0, 0, 0, 0 };

            using (NamedPipePair pair = CreateNamedPipePair())
            {
                pair.Connect();
                NamedPipeServerStream server = pair.serverStream;
                if (pair.writeToServer)
                {
                    using (NamedPipeClientStream client = new NamedPipeClientStream(PipeDirection.In, false, true, pair.clientStream.SafePipeHandle))
                    {
                        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                        {
                            Assert.Equal(1, client.NumberOfServerInstances);
                        }
                        Task<int> clientTask = client.ReadAsync(received1, 0, received1.Length);
                        server.Write(msg1, 0, msg1.Length);
                        int receivedLength = await clientTask;
                        Assert.Equal(msg1.Length, receivedLength);
                        Assert.Equal(msg1, received1);
                    }
                }
                else
                {
                    using (NamedPipeClientStream client = new NamedPipeClientStream(PipeDirection.Out, false, true, pair.clientStream.SafePipeHandle))
                    {
                        Task clientTask = client.WriteAsync(msg1, 0, msg1.Length);
                        int receivedLength = server.Read(received1, 0, msg1.Length);
                        Assert.Equal(msg1.Length, receivedLength);
                        Assert.Equal(msg1, received1);
                        await clientTask;
                    }
                }
            }
        }
Пример #60
0
        private static void Main(string[] args)
        {
            try
            {
                // Upgrade the user settings if necessary.
                if (Settings.Default.SettingsUpgradeRequired)
                {
                    Settings.Default.Upgrade();
                    Settings.Default.SettingsUpgradeRequired = false;
                    Settings.Default.SaveSettings();
                }
            }
            catch (Exception ex)
            {
                Logger.Error(
                    "Error while upgrading the user settings: {0}"
                    , ex);
            }

            if (Settings.Default.FrmMainAllowOnlyOneInstance && !MainForm.CreateNamedPipe(NAMED_PIPED_NAME))
            {
                Logger.Info("Another instance of Logbert is already running.");

                // Bring the window of the other instance to front.
                NamedPipeClientStream anotherLogbertInstance = new NamedPipeClientStream(
                    "."
                    , NAMED_PIPED_NAME
                    , PipeDirection.Out);

                try
                {
                    if (!anotherLogbertInstance.ConnectAndWrite(Encoding.Default.GetBytes(BRING_TO_FRONT_MSG)))
                    {
                        Logger.Error("Unable to passing arguments to it.");
                        return;
                    }

                    Logger.Info("Passing arguments to it and exiting.");

                    if (args.Length > 0)
                    {
                        // Send the command line arguments to the other instance and exit.
                        anotherLogbertInstance = new NamedPipeClientStream(
                            "."
                            , NAMED_PIPED_NAME
                            , PipeDirection.Out);

                        anotherLogbertInstance.ConnectAndWrite(
                            Encoding.Default.GetBytes(args[0]));

                        return;
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.Message);
                    return;
                }

                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Application.Run(new MainForm(args.Length == 0
        ? string.Empty
        : args[0]));
        }