public void SetUp() { Logger.Debug("Setting up test..."); _barrier.Reset(); _server = new NamedPipeServer<byte[]>(PipeName); _client = new NamedPipeClient<byte[]>(PipeName); _expectedData = null; _expectedHash = null; _actualData = null; _actualHash = null; _clientDisconnected = false; _server.ClientDisconnected += ServerOnClientDisconnected; _server.ClientMessage += ServerOnClientMessage; _server.Error += ServerOnError; _client.Error += ClientOnError; _server.Start(); _client.Start(); // Give the client and server a few seconds to connect before sending data Thread.Sleep(TimeSpan.FromSeconds(1)); Logger.Debug("Client and server started"); Logger.Debug("---"); _startTime = DateTime.Now; }
public MyServer(string pipeName) { var server = new NamedPipeServer<MyMessage>(pipeName); server.ClientConnected += OnClientConnected; server.ClientDisconnected += OnClientDisconnected; server.ClientMessage += OnClientMessage; server.Error += OnError; server.Start(); while (KeepRunning) { // Do nothing - wait for user to press 'q' key } server.Stop(); }
private static void InitServer(string pipeName) { server = new NamedPipeServer <string>(pipeName); server.ClientConnected += delegate(NamedPipeConnection <string, string> conn) { Console.WriteLine("Client {0} is now connected!", conn.Id); clients += 1; }; server.ClientDisconnected += delegate(NamedPipeConnection <string, string> conn) { Console.WriteLine("Client {0} disconnected!", conn.Id); clients -= 1; }; server.ClientMessage += delegate(NamedPipeConnection <string, string> conn, string message) { Console.WriteLine("Client {0} says: {1}", conn.Id, message); PipeCommandReceived(message); }; server.Start(); int prevClients = 0; Console.WriteLine("Waiting for client..."); while (clients == 0) { Thread.Sleep(1000); } prevClients = clients; Thread.Sleep(1000); while (clients != prevClients) { Thread.Sleep(1000); } if (clients != 1) { throw new Exception("More than 1 client instance has connected!"); } }
public void Run() { try { EventMetadata metadata = new EventMetadata(); metadata.Add("Version", ProcessHelper.GetCurrentProcessVersion()); this.tracer.RelatedEvent(EventLevel.Informational, $"ScalarService_{nameof(this.Run)}", metadata); PhysicalFileSystem fileSystem = new PhysicalFileSystem(); this.repoRegistry = new ScalarRepoRegistry( this.tracer, fileSystem, this.repoRegistryLocation); this.maintenanceTaskScheduler = new MaintenanceTaskScheduler(this.tracer, fileSystem, new WindowsScalarVerbRunner(this.tracer), this.repoRegistry); this.AssignCurrentLoggedOnUser(); this.maintenanceTaskScheduler.ScheduleRecurringTasks(); this.requestHandler = new RequestHandler(this.tracer, EtwArea); string pipeName = ScalarPlatform.Instance.GetScalarServiceNamedPipeName(this.serviceName); this.tracer.RelatedInfo("Starting pipe server with name: " + pipeName); using (NamedPipeServer pipeServer = NamedPipeServer.StartNewServer( pipeName, this.tracer, this.requestHandler.HandleRequest)) { this.productUpgradeTimer.Start(); this.serviceStopped.WaitOne(); } } catch (Exception e) { this.LogExceptionAndExit(e, nameof(this.Run)); } }
/// <summary> /// Constructs a new named pipe server for IPC, with a channel name derived from the class /// namespace and the current machine's digital fingerprint. /// </summary> public IPCServer() { m_logger = LoggerUtil.GetAppWideLogger(); var channel = string.Format("{0}.{1}", nameof(Citadel.IPC), FingerPrint.Value).ToLower(); var security = GetSecurityForChannel(); m_server = new NamedPipeServer <BaseMessage>(channel, security); m_server.ClientConnected += OnClientConnected; m_server.ClientDisconnected += OnClientDisconnected; m_server.ClientMessage += OnClientMessage; m_server.Error += M_server_Error; m_server.Start(); m_ipcQueue = new IPCMessageTracker(); m_logger.Info("IPC Server started."); }
public void Run() { try { EventMetadata metadata = new EventMetadata(); metadata.Add("Version", ProcessHelper.GetCurrentProcessVersion()); this.tracer.RelatedEvent(EventLevel.Informational, $"{nameof(GVFSService)}_{nameof(this.Run)}", metadata); this.repoRegistry = new RepoRegistry(this.tracer, new PhysicalFileSystem(), this.serviceDataLocation); this.repoRegistry.Upgrade(); string pipeName = this.serviceName + ".Pipe"; this.tracer.RelatedInfo("Starting pipe server with name: " + pipeName); using (NamedPipeServer pipeServer = NamedPipeServer.StartNewServer(pipeName, this.tracer, this.HandleRequest)) { this.CheckEnableGitStatusCacheTokenFile(); using (ITracer activity = this.tracer.StartActivity("EnsurePrjFltHealthy", EventLevel.Informational)) { // Make a best-effort to enable PrjFlt. Continue even if it fails. // This will be tried again when user attempts to mount an enlistment. string error; EnableAndAttachProjFSHandler.TryEnablePrjFlt(activity, out error); } // Start product upgrade timer only after attempting to enable prjflt. // On Windows server (where PrjFlt is not inboxed) this helps avoid // a race between TryEnablePrjFlt() and installer pre-check which is // performed by UpgradeTimer in parallel. this.productUpgradeTimer.Start(); this.serviceStopped.WaitOne(); } } catch (Exception e) { this.LogExceptionAndExit(e, nameof(this.Run)); } }
public void NamedPipeTest() { string a = "abc"; string b = "123"; // serwer wysyla do klienta "abc" // klient weryfikuje, ze otrzymal "abc" // klient odsyla do serwera "123" // serwer weryfikuje, ze otrzymal "123" var pipeServer = new NamedPipeServer <PipeMessage>("testtesttest"); pipeServer.ClientMessage += delegate(NamedPipeConnection <PipeMessage, PipeMessage> conn, PipeMessage message) { Assert.AreEqual(b, message.content); }; pipeServer.Start(); var pipeClient = new NamedPipeClient <PipeMessage>("testtesttest"); pipeClient.ServerMessage += delegate(NamedPipeConnection <PipeMessage, PipeMessage> conn, PipeMessage message) { Assert.AreEqual(a, message.content); pipeClient.PushMessage(new PipeMessage() { messageType = 0, content = b }); }; pipeClient.Start(); pipeServer.PushMessage(new PipeMessage() { messageType = 0, content = a }); }
private static void onMessage(NativeMessagingMessage msg) { lock (_lock) { if (pipe == null && !string.IsNullOrEmpty(msg.browser)) { pipe = new NamedPipeServer <NativeMessagingMessage>(PIPE_NAME + "_" + msg.browser); pipe.ClientMessage += Server_OnReceivedMessage; //pipe.OnReceivedMessage += Server_OnReceivedMessage; pipe.Start(); } } if (msg.functionName == "ping") { return; } //if (ignore.Contains(msg.functionName)) return; string json = JsonConvert.SerializeObject(msg, Formatting.Indented); if (!ignore.Contains(msg.functionName)) { System.Diagnostics.Trace.WriteLine("[send]" + msg.functionName + " for tab " + msg.tabid + " - " + msg.messageid); } try { if (pipe != null) { pipe.PushMessage(msg); //System.Diagnostics.Trace.WriteLine(result); //var result = pipe.PushMessage(msg); //System.Diagnostics.Trace.WriteLine(result); } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.ToString()); } }
public static void Main() { Enumerable.Range(0, 2).ToList().ForEach(i => Task.Run(async() => { bool disconnected = false; var pipeServer = new NamedPipeServer("testpipe", 10, i); pipeServer.OnDisconnect = (() => { Console.WriteLine($"client {i} disconnected"); disconnected = true; }); Console.WriteLine($"{i}: Server initialized"); await pipeServer.WaitForConnectionAsync(); Console.WriteLine($"{i}: Client connected"); while (true) { string s = Console.ReadLine(); if (disconnected) { break; } var l = new List <int> { 1, 2, 3 }; /*int id = await pipeServer.SendAsync(new { s, l }); * Console.WriteLine("message sent"); * var result = await pipeServer.ReadAsync<object>(id);//*/ var result = await pipeServer.CallAsync <object, object>(new { s, l }); Console.WriteLine($"{i}: recieved {JsonConvert.SerializeObject(result)}"); } })); while (true) { ; } }
public void Run() { try { this.repoRegistry = new RepoRegistry(this.tracer, this.serviceDataLocation); using (ITracer activity = this.tracer.StartActivity("StartUp", EventLevel.Informational)) { this.repoRegistry.AutoMountRepos(); this.repoRegistry.TraceStatus(); } string pipeName = this.serviceName + ".Pipe"; this.tracer.RelatedInfo("Starting pipe server with name: " + pipeName); using (NamedPipeServer pipeServer = NamedPipeServer.StartNewServer(pipeName, this.tracer, this.HandleRequest)) { this.serviceStopped.WaitOne(); } } catch (Exception e) { this.LogExceptionAndExit(e, nameof(this.Run)); } }
public Events() { _server = new NamedPipeServer<string>("io-jaywick-labs-pastr-messaging"); _server.ClientMessage += server_ClientMessage; _server.Start(); _ahkEngine = new AutoHotkey.Interop.AutoHotkeyEngine(); _shortcutCallbackMap = new Dictionary<string, Action>(); ReserveHotKey("^+z", () => OnInvokeDrop.SafeInvoke()); ReserveHotKey("^+x", () => OnInvokeShunt.SafeInvoke()); ReserveHotKey("^+c", () => OnInvokePush.SafeInvoke()); ReserveHotKey("^+v", () => OnInvokePeek.SafeInvoke()); ReserveHotKey("^+b", () => OnInvokePop.SafeInvoke()); ReserveHotKey("^+a", () => OnInvokeExpire.SafeInvoke()); ReserveHotKey("^+s", () => OnInvokePinch.SafeInvoke()); ReserveHotKey("^+d", () => OnInvokeWipe.SafeInvoke()); ReserveHotKey("^+w", () => OnInvokeSwap.SafeInvoke()); ReserveHotKey("^+f", () => OnInvokePoke.SafeInvoke()); ReserveHotKey("^+q", () => OnInvokeRotateLeft.SafeInvoke()); ReserveHotKey("^+e", () => OnInvokeRotateRight.SafeInvoke()); ReserveHotKey("^+r", () => OnInvokeReverse.SafeInvoke()); RegisterHotKeys(); }
private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { if (m_server != null) { #if CLIFTON m_server.Close(); #else m_server.Stop(); #endif m_server = null; } } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } }
public Events() { _server = new NamedPipeServer <string>("jaywick.labs.pastr.messaging"); _server.ClientMessage += server_ClientMessage; _server.Start(); _ahkEngine = AutoHotkey.Interop.AutoHotkeyEngine.Instance; _shortcutCallbackMap = new Dictionary <string, Action>(); ReserveHotKey("^+z", () => OnInvokeDrop?.Invoke()); ReserveHotKey("^+x", () => OnInvokeShunt?.Invoke()); ReserveHotKey("^+c", () => OnInvokePush?.Invoke()); ReserveHotKey("^+v", () => OnInvokePeek?.Invoke()); ReserveHotKey("^+b", () => OnInvokePop?.Invoke()); ReserveHotKey("^+a", () => OnInvokeExpire?.Invoke()); ReserveHotKey("^+s", () => OnInvokePinch?.Invoke()); ReserveHotKey("^+d", () => OnInvokeWipe?.Invoke()); ReserveHotKey("^+w", () => OnInvokeSwap?.Invoke()); ReserveHotKey("^+f", () => OnInvokePoke?.Invoke()); ReserveHotKey("^+q", () => OnInvokeRotateLeft?.Invoke()); ReserveHotKey("^+e", () => OnInvokeRotateRight?.Invoke()); ReserveHotKey("^+r", () => OnInvokeReverse?.Invoke()); RegisterHotKeys(); }
private ControllerResult ProcessNamedPipes() { _logger.Info("Entering NamedPipes Mode"); NamedPipeServer Server = new NamedPipeServer("InProc"); Server.OnReceivedMessage += new EventHandler <ReceivedMessageEventArgs>(Server_OnReceivedMessage); Server.Start(); bool waitForCommand = true; while (waitForCommand) { waitForCommand = _waitForCommand; } ApplicationContext.Args = _clientArgs.ToArray(); ControllerResult result = ProcessStandardMode(); if (result is StringResult) { Server.Write(((StringResult)result).Model); } return(result); }
public void Mount(EventLevel verbosity, Keywords keywords) { this.currentState = MountState.Mounting; if (Environment.CurrentDirectory != this.enlistment.EnlistmentRoot) { Environment.CurrentDirectory = this.enlistment.EnlistmentRoot; } using (NamedPipeServer pipeServer = this.StartNamedPipe()) { this.AcquireRepoMutex(); GVFSContext context = this.CreateContext(); this.ValidateMountPoints(); this.UpdateHooks(); this.SetVisualStudioRegistryKey(); this.gvfsLock = context.Repository.GVFSLock; this.MountAndStartWorkingDirectoryCallbacks(context); Console.Title = "GVFS " + ProcessHelper.GetCurrentProcessVersion() + " - " + this.enlistment.EnlistmentRoot; this.tracer.RelatedEvent( EventLevel.Critical, "Mount", new EventMetadata { { "Message", "Virtual repo is ready" }, }); this.currentState = MountState.Ready; this.unmountEvent.WaitOne(); } }
/// <summary> /// Gets the Named Pipe Server. /// </summary> /// <param name="script">The script to push.</param> /// <param name="channelId">The named pipe channel identifier to use.</param> /// <returns>The named pipe server.</returns> private NamedPipeServer <String> GetNamePipeServer(string script, int channelId) { NamedPipeServer <String> server = new NamedPipeServer <String>(NAMEDPIPES_NAME + channelId); server.ClientConnected += (connection) => { connection.PushMessage(NAMEDPIPES_PASSKEY); }; server.ClientDisconnected += (connection) => { HasExited = true; }; server.ClientMessage += (connection, message) => { Log("RECV MSG : " + message); if (message.StartsWith(NAMEDPIPES_EXITCODE)) { ExitCode = Convert.ToInt32(message.Remove(0, NAMEDPIPES_EXITCODE.Length)); HasExited = true; } else if (message == GETSCRIPT_CMD) { connection.PushMessage(script); } else { Console.WriteLine(message); } }; server.Error += (exception) => { throw exception; }; return(server); }
public static INamedPipeServer CreateServer(string namedPipeName, IPipePlatform pipePlatform) { return(NamedPipeServer.StartNewServer(namedPipeName, pipePlatform, HandleRequest)); }
/// <summary>終了</summary> /// <remarks>スレッド セーフ</remarks> public static void Final() { lock (AsyncEventFx._lock) // staticなのでロックする。 { // NPCS // GC + デストラクタで問題ない。 AsyncEventFx.NPCS = null; // NPS if (AsyncEventFx.NPS != null) { // リスナーを停止させる必要がある(ping)。 // NPS.Finalは本メソッドとは別のメソッド AsyncEventFx.NPS.Final(); // ping後は、GC + デストラクタで問題ない。 AsyncEventFx.NPS = null; } } }
/// <summary>初期化</summary> /// <param name="serverPipeName">名前付きパイプ サーバの名前</param> /// <param name="clientPipeNames">名前付きパイプ クライアントの名前の配列</param> /// <param name="waitTime_msec">接続待ちの待機時間(ミリ秒)</param> /// <remarks>スレッド セーフ</remarks> public static void Init(string serverPipeName, string[] clientPipeNames, int waitTime_msec) { // 初期化前にクリーンナップ AsyncEventFx.Final(); // デッドロックに注意 lock (AsyncEventFx._lock) // staticなのでロックする。 { // 接続待ちの待機時間(ミリ秒)を初期化 AsyncEventFx.WaitTime_msec = waitTime_msec; // 名前付きパイプ(クラ・サバ)を初期化 // ・初めに名前付きパイプ(サーバ)を初期化(new) AsyncEventFx.NPS = new NamedPipeServer(serverPipeName); // ・次に名前付きパイプ(クライアント)を初期化(new) AsyncEventFx.NPCS = new Dictionary<string, NamedPipeClient>(); foreach (string cpn in clientPipeNames) { // ディクショナリへ追加 AsyncEventFx.NPCS.Add(cpn, new NamedPipeClient(cpn)); } } }
public MessageBusNamedPipeServer() { Server = new NamedPipeServer(new NamedPipeServerOptions("godhsarp.bus.message.transmitter.namedpipe", OnReadCompleted, OnConnectionCompleted, OnInteractionCompleted, OnStopCompleted, OnException, OnOutputLogging, 1024, 254)); Server.Start(); }
private INamedPipeServer CreateServer(string namedPipeName, IPipePlatform pipePlatform) { _pipeName = namedPipeName; return(NamedPipeServer.StartNewServer(namedPipeName, pipePlatform, HandleConnection)); }
public static NamedPipeServer Create(GVFSEnlistment enlistment) { return(NamedPipeServer.StartNewServer(enlistment.NamedPipeName, AllowAllLocksNamedPipeServer.HandleRequest)); }
private void StartServer() { Server = new NamedPipeServer(NAME_OF_PIPE); Server.OnReceivedMessage += new EventHandler<ReceivedMessageEventArgs>(Server_OnReceivedMessage); Server.Start(); }
private Result TryClone(JsonEtwTracer tracer, GVFSEnlistment enlistment) { this.CheckVolumeSupportsDeleteNotifications(tracer, enlistment); this.CheckGitVersion(enlistment); Result pipeResult; using (NamedPipeServer pipeServer = this.StartNamedPipe(tracer, enlistment, out pipeResult)) { if (!pipeResult.Success) { return(pipeResult); } using (ConfigHttpRequestor configRequestor = new ConfigHttpRequestor(tracer, enlistment)) { GVFSConfig config = configRequestor.QueryGVFSConfig(); this.ValidateGVFSVersion(enlistment, config, tracer); } using (GitObjectsHttpRequestor objectRequestor = new GitObjectsHttpRequestor(tracer, enlistment)) { GitRefs refs = objectRequestor.QueryInfoRefs(this.SingleBranch ? this.Branch : null); if (refs == null) { return(new Result("Could not query info/refs from: " + Uri.EscapeUriString(enlistment.RepoUrl))); } if (this.Branch == null) { this.Branch = refs.GetDefaultBranch(); EventMetadata metadata = new EventMetadata(); metadata.Add("Branch", this.Branch); tracer.RelatedEvent(EventLevel.Informational, "CloneDefaultRemoteBranch", metadata); } else { if (!refs.HasBranch(this.Branch)) { EventMetadata metadata = new EventMetadata(); metadata.Add("Branch", this.Branch); tracer.RelatedEvent(EventLevel.Warning, "CloneBranchDoesNotExist", metadata); string errorMessage = string.Format("Remote branch {0} not found in upstream origin", this.Branch); return(new Result(errorMessage)); } } if (!enlistment.TryCreateEnlistmentFolders()) { string error = "Could not create enlistment directory"; tracer.RelatedError(error); return(new Result(error)); } CloneHelper cloneHelper = new CloneHelper(tracer, enlistment, objectRequestor); return(cloneHelper.CreateClone(refs, this.Branch)); } } }
public IDisposable Listen() { _server = SetupServer(); return new ServerManager(this); }
public void ListenForArgs(Action <string[]> listener) { namedPipeServer = new NamedPipeServer <string[]>("WinDynamicDesktop"); namedPipeServer.ClientMessage += (conn, args) => listener(args); namedPipeServer.Start(); }
/// <summary> /// Runs the Powershell Script Engine. /// </summary> /// <param name="options">The options parameters.</param> /// <returns>Exit code</returns> public int Run(string[] options) { Console.OutputEncoding = Encoding.ASCII; FileVersionInfo fvi = GetFileVersionInfo(); try { NetworkCredential credential = null; int version = 2; string domain = null; string userName = null; SecureString password = null; string script = null; bool isElevated = false; int schedule = -1; bool passthrough = false; bool hash = false; bool nologo = false; StageType stage = StageType.None; // Gets CLI arguments. for (int i = 0; i < options.Length; i++) { string arg = options[i]; if (arg.StartsWith("-")) { switch (arg.ToLowerInvariant()) { case "-hash": password = GetArgumentValue(options, ref i).ConvertToSecureString(); hash = true; break; case "-script": script = GetArgumentValue(options, ref i); break; case "-version": version = Convert.ToInt32(GetArgumentValue(options, ref i)); break; case "-domain": domain = StringCipher.Decrypt(GetArgumentValue(options, ref i), GetUniqueIdentifier()); break; case "-username": userName = StringCipher.Decrypt(GetArgumentValue(options, ref i), GetUniqueIdentifier()); break; case "-password": password = StringCipher.Decrypt(GetArgumentValue(options, ref i), GetUniqueIdentifier()).ConvertToSecureString(); break; case "-elevated": isElevated = true; break; case "-schedule": double s = Convert.ToDouble(GetArgumentValue(options, ref i), CultureInfo.InvariantCulture) * 60 * 1000; if (s > Int32.MaxValue) { schedule = Int32.MaxValue; } else if (s == 0) { schedule = 500; } else { schedule = (int)s; } break; case "-pid": _processId = Convert.ToInt32(GetArgumentValue(options, ref i)); passthrough = true; break; case "-stage": stage = (StageType)Enum.Parse(typeof(StageType), GetArgumentValue(options, ref i)); break; case "-silent": _silent = true; break; case "-debug": _debug = true; break; case "-nologo": nologo = true; break; case "-help": PrintHeader(); PrintNotice(); return(0); default: PrintHeader(); Console.WriteLine("Wrong argument: {0}", arg); PrintWarning(); return(EXITCODE_KO); } } } Log("START " + fvi.ProductName.ToUpperInvariant() + " v" + fvi.FileVersion + " WITH PID #" + Process.GetCurrentProcess().Id); Log("ARGS : " + string.Join(" ", options)); // Script parameters is requiered ! if (string.IsNullOrEmpty(script) && !passthrough && !hash) { PrintHeader(); Console.WriteLine("Script parameter is required !"); PrintWarning(); return(EXITCODE_KO); } // Show Copyright banner. if (!nologo) { PrintHeader(); } // Hash password. if (hash) { // Get system UID string k = StringCipher.Encrypt(password.ConvertToUnsecureString(), GetUniqueIdentifier()); Console.WriteLine(k); return(EXITCODE_OK); } // Gets user credentials if (!string.IsNullOrEmpty(userName)) { // WTF! .Net 3.5 does not implements the creation of ICredentials with a SecureString. MS are you serious ? if (!string.IsNullOrEmpty(domain)) { credential = new NetworkCredential(userName, password.ConvertToUnsecureString(), domain); } else { credential = new NetworkCredential(userName, password.ConvertToUnsecureString()); } } // Check if the current process already runs with elevated privileges WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); if (isElevated) { if (UAC.IsProcessElevated) { // removes elevated mode options = GetFilteredParameters(options, new[] { "-elevated" }, null).ToArray(); isElevated = false; Log("UAC : Elevation not needed"); } else { Log("UAC : Need elevation"); } } // Encode pipeline for use in PS if any. if (IsPipedInput() && !passthrough) { string pipe = Console.In.ReadToEnd(); if (!string.IsNullOrEmpty(pipe)) { Log("READ PIPE :\n" + pipe); StringBuilder s = new StringBuilder(); s.AppendFormat("\"{0}\"", Convert.ToBase64String(Encoding.Unicode.GetBytes(pipe))); s.Append("|%{[System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($_))}|" + script); script = s.ToString(); } } // Stage Logic if (stage == StageType.None) { if (!string.IsNullOrEmpty(userName)) { stage = StageType.Credential; } else if (isElevated) { stage = StageType.Elevated; } else { stage = StageType.PowerShell; } } // Starts named pipes server for communication with the child process NamedPipeServer <String> server = null; if (stage != StageType.PowerShell) { if (!passthrough) { server = GetNamePipeServer(script, _processId); server.Start(); } } // Starts the child processes loop. do { try { Log("STAGE : " + ((int)stage).ToString() + " - " + stage.ToString()); Log("PASSTHRU : " + passthrough.ToString()); switch (stage) { case StageType.Credential: { // Construct child process arguments string[] switchParamToRemoves = { "-help" }; string[] keyPairParamToRemoves = { "-domain", "-username", "-password", "-script", "-schedule", "-stage" }; List <string> param = GetFilteredParameters(options, switchParamToRemoves, keyPairParamToRemoves); // Add PID identifier for named pipe communication if (!passthrough) { param.Add("-pid"); param.Add(_processId.ToString()); } Log("ARGS CHILD : " + string.Join(" ", param.ToArray())); // Starts child process of myself with credentials: .Net Process class failed to start a process with custom credentials when running under LocalSystem account. if (WindowsIdentity.GetCurrent().Name.ToLowerInvariant() == "nt authority\\system") { RunSelfProcessInLocalSystem(param, credential); } else { RunSelfProcess(param, false, credential); } Thread.Sleep(1000); break; } case StageType.Elevated: { // Construct child process arguments string[] switchParamToRemoves = { "-elevated", "-help" }; string[] keyPairParamToRemoves = { "-script", "-schedule", "-stage" }; List <string> param = GetFilteredParameters(options, switchParamToRemoves, keyPairParamToRemoves); // Add PID identifier if (!passthrough) { param.Add("-pid"); param.Add(_processId.ToString()); } Log("ARGS CHILD : " + string.Join(" ", param.ToArray())); // Starts child process of myself with elevated privileges RunSelfProcess(param, isElevated, credential); Thread.Sleep(1000); break; } case StageType.PowerShell: { // Starts named pipes client for communication with the parent process. NamedPipeClient <String> client = null; if (passthrough) { client = GetNamedPipeClientAndWaitForConnection(_processId, out script); } // Runs the PS process //WindowsStationAndDesktop.GrantAccess(credential.UserName); using (new PrivilegeEnabler(Process.GetCurrentProcess(), Privilege.AssignPrimaryToken, Privilege.IncreaseQuota, Privilege.TrustedComputerBase)) using (ScriptRunner ps = new ScriptRunner(ScriptEngine.Language.PowerShell, credential, isElevated, script)) { ps.OutputReceived += (o, e) => { if (passthrough) { client.PushMessage(e.Data); } else { Console.WriteLine(e.Data); } Log("PS : " + e.Data); }; ps.ProcessExited += (o, e) => { ExitCode = e.ExitCode; if (passthrough) { client.PushMessage(NAMEDPIPES_EXITCODE + e.ExitCode); } }; ps.Run(new[] { "-V", version.ToString() }); } Thread.Sleep(1000); if (passthrough) { client.Stop(); } break; } } } catch (Exception ex) { if (!_silent) { Console.WriteLine("ERROR: {0}", ex.ToString().Replace(Environment.NewLine, " ")); } Log("ERROR : " + ex.ToString()); } // Wait the schedule time if (schedule != -1) { Thread.Sleep(schedule); } } while (schedule != -1); // Stops the pipe server if (server != null && !passthrough) { server.Stop(); } } catch (Exception ex) { if (!_silent) { Console.WriteLine("ERROR: {0}", ex.ToString().Replace(Environment.NewLine, " ")); } Log("ERROR : " + ex.ToString()); } Log("EXIT CODE : " + ExitCode); Log("STOP " + fvi.ProductName.ToUpperInvariant() + " v" + fvi.FileVersion + " WITH PID #" + Process.GetCurrentProcess().Id); return(ExitCode); }
private static void Main(string[] args) { Directory.SetCurrentDirectory(Application.StartupPath); // todo: initialize the NLog configuartion Model.NLogConfig.TouchAndApplyNLogConfig(); // .NET Framework 4.7.2 on Win7 compatibility ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; // store args for further use Args = args; // Check OS since we are using dual-mode socket if (!Utils.IsWinVistaOrHigher()) { MessageBox.Show(I18N.GetString("Unsupported operating system, use Windows Vista at least."), "Shadowsocks Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Check .NET Framework version if (!Utils.IsSupportedRuntimeVersion()) { if (DialogResult.OK == MessageBox.Show(I18N.GetString("Unsupported .NET Framework, please update to {0} or later.", "4.7.2"), "Shadowsocks Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error)) { Process.Start("https://dotnet.microsoft.com/download/dotnet-framework/net472"); } return; } string pipename = $"Shadowsocks\\{Application.StartupPath.GetHashCode()}"; string addedUrl = null; using (NamedPipeClientStream pipe = new NamedPipeClientStream(pipename)) { bool pipeExist = false; try { pipe.Connect(10); pipeExist = true; } catch (TimeoutException) { pipeExist = false; } // TODO: switch to better argv parser when it's getting complicate List <string> alist = Args.ToList(); // check --open-url param int urlidx = alist.IndexOf("--open-url") + 1; if (urlidx > 0) { if (Args.Length <= urlidx) { return; } // --open-url exist, and no other instance, add it later if (!pipeExist) { addedUrl = Args[urlidx]; } // has other instance, send url via pipe then exit else { byte[] b = Encoding.UTF8.GetBytes(Args[urlidx]); byte[] opAddUrl = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(1)); byte[] blen = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(b.Length)); pipe.Write(opAddUrl, 0, 4); // opcode addurl pipe.Write(blen, 0, 4); pipe.Write(b, 0, b.Length); pipe.Close(); return; } } // has another instance, and no need to communicate with it return else if (pipeExist) { Process[] oldProcesses = Process.GetProcessesByName("Shadowsocks"); if (oldProcesses.Length > 0) { Process oldProcess = oldProcesses[0]; } MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.") + Environment.NewLine + I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."), I18N.GetString("Shadowsocks is already running.")); return; } } Utils.ReleaseMemory(true); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); // handle UI exceptions Application.ThreadException += Application_ThreadException; // handle non-UI exceptions AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.ApplicationExit += Application_ApplicationExit; SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); AutoStartup.RegisterForRestart(true); Directory.SetCurrentDirectory(Application.StartupPath); #if DEBUG // truncate privoxy log file while debugging string privoxyLogFilename = Utils.GetTempPath("privoxy.log"); if (File.Exists(privoxyLogFilename)) { using (new FileStream(privoxyLogFilename, FileMode.Truncate)) { } } #endif MainController = new ShadowsocksController(); MenuController = new MenuViewController(MainController); HotKeys.Init(MainController); MainController.Start(); NamedPipeServer namedPipeServer = new NamedPipeServer(); Task.Run(() => namedPipeServer.Run(pipename)); namedPipeServer.AddUrlRequested += (_1, e) => MainController.AskAddServerBySSURL(e.Url); if (!addedUrl.IsNullOrEmpty()) { MainController.AskAddServerBySSURL(addedUrl); } Application.Run(); }
public void InitServer() { server = new NamedPipeServer(); server.ReceivedEvent += Server_Received; server.Start("SamplePipeName"); }
public void TestNotEmptyAddress(string address) { var server = new NamedPipeServer(Mock.Of <INamedPipeStreamFactory>(), address); Assert.Equal(address, server.Address); }
private NamedPipeServer<PipeMessage> SetupServer() { var server = new NamedPipeServer<PipeMessage>(PipeName); server.Error += Server_Error; ; server.ClientConnected += Server_ClientConnected; server.ClientMessage += Server_ClientMessage; return server; }
private void StartServer() { server = new NamedPipeServer <object>(appKey); server.ClientConnected += Server_ClientConnected; server.Start(); }
public PipeServer(string pipeName) { stopwatchLastCommand.Start(); string databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "PhotoTagsSynchronizer"); string destinationFile = Path.Combine(databasePath, "Pictures.pd6"); string sourceFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft\\Windows Live Photo Gallery\\Pictures.pd6"); #region Create folder try { if (!Directory.Exists(databasePath)) { Directory.CreateDirectory(databasePath); } } catch (Exception e) { WriteError("Failed create folder for storing copy of the database: " + e.Message); databaseWindowsLivePhotGallery = null; return; } #endregion #region Copy Windows Live Photo Gallery database try { if (!File.Exists(destinationFile) || (File.GetLastWriteTime(sourceFile) >= File.GetLastWriteTime(destinationFile).AddSeconds(3600))) { //Copy new only every hour File.Copy(sourceFile, destinationFile, true); WriteResponseLine("Copy the databasebase file"); //Write message back to client WriteResponseLine("Copy from: " + sourceFile); //Write message back to client WriteResponseLine("Copy to: " + destinationFile); //Write message back to client } } catch (IOException iox) { WriteError("Copy the database failed: " + iox.Message); return; } #endregion #region Connect to database try { databaseWindowsLivePhotGallery = new WindowsLivePhotoGalleryDatabaseReader(); databaseWindowsLivePhotGallery.Connect(destinationFile); WriteResponseLine("Windows Live Photo Gallery connected: " + destinationFile); //Write message back to client } catch (Exception e) { WriteError("Windows Live Photo Gallery connect to database failed: " + e.Message); databaseWindowsLivePhotGallery = null; return; } WriteResponseLine("Cache Database connected...");//Write message back to client #endregion #region Server Start var server = new NamedPipeServer <PipeMessageCommand>(pipeName); server.ClientConnected += OnClientConnected; server.ClientDisconnected += OnClientDisconnected; server.ClientMessage += OnClientMessage; server.Error += OnError; server.Start(); WriteResponseLine("Server up and running..."); WriteResponseLine("Waiting client connection..."); #endregion #region Server loop stopwatchLastCommand.Start(); while (KeepRunning) { Task.Delay(10).Wait(); if (stopwatchLastCommand.ElapsedMilliseconds > 3600000) { WriteResponseLine("Server didn't get any request, quiting..."); WriteResponseLine("Server disconnecting..."); KeepRunning = false; } } #endregion server.Stop(); }
static void Main(string[] args) { ServerArgs serverArgs = new ServerArgs().Parse(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "config.json")).Parse(args).Validate(); EventLogOutputPipe eventLogOutputPipe = new EventLogOutputPipe(); CompositeLogger logger = new CompositeLogger(); if (serverArgs.EnableEventLog) { logger.AddLogger(new Logger(eventLogOutputPipe, eventLogOutputPipe)); } if (serverArgs.EnablePipeLog) { try { NamedPipeServer namedPipe = new NamedPipeServer(serverArgs.LogPipeName); Logger namedPipeLogger = new Logger(namedPipe, namedPipe); logger.AddLogger(namedPipeLogger); } catch (Exception e) { logger.LogError("Failed to initialize named pipe logger: " + e.Message); } } if (serverArgs.Errors.Count > 0) { logger.LogError("Server arguments had errors."); foreach (string error in serverArgs.Errors) { logger.LogError(error); } return; } // Load external modules PowerShellRunspace runspace = new PowerShellRunspace(logger); foreach (string externalModule in serverArgs.ExternalModules) { GeneratedModule module = new GeneratedModule(runspace); module.ModulePath = externalModule; CommandExecutionResult result = module.Load(); if (result != null && result.HadErrors) { logger.LogError(String.Format(CultureInfo.CurrentCulture, "Failed to load extra module: {0}", externalModule)); result.LogErrors(logger); return; } } // Start test server JsonRpcPipe jsonRpcPipe = new JsonRpcPipe(new StandardInputPipe(), new StandardOutputPipe()); LiveTestServer server = new LiveTestServer(new LiveTestServerStartParams() { Logger = logger, Input = jsonRpcPipe, Output = jsonRpcPipe, CredentialFactory = new LiveTestCredentialFactory(), RunspaceManager = runspace, ModulePath = serverArgs.ModulePath, TracingManager = new ServiceTracingManager(), SpecificationPaths = serverArgs.SpecificationPaths, ObjectTransforms = serverArgs.GetTransforms() }); try { server.RunAsync().Wait(); } catch (Exception ex) { logger.LogError("Failed to start server: " + ex.ToString()); } // Wait until server exits (usually means the server ran into an internal error) while (server.IsRunning) { Thread.Sleep(2); } }
private Result TryClone( JsonTracer tracer, GVFSEnlistment enlistment, CacheServerInfo cacheServer, RetryConfig retryConfig, ServerGVFSConfig serverGVFSConfig, string resolvedLocalCacheRoot) { Result pipeResult; using (NamedPipeServer pipeServer = this.StartNamedPipe(tracer, enlistment, out pipeResult)) { if (!pipeResult.Success) { return(pipeResult); } using (GitObjectsHttpRequestor objectRequestor = new GitObjectsHttpRequestor(tracer, enlistment, cacheServer, retryConfig)) { GitRefs refs = objectRequestor.QueryInfoRefs(this.SingleBranch ? this.Branch : null); if (refs == null) { return(new Result("Could not query info/refs from: " + Uri.EscapeUriString(enlistment.RepoUrl))); } if (this.Branch == null) { this.Branch = refs.GetDefaultBranch(); EventMetadata metadata = new EventMetadata(); metadata.Add("Branch", this.Branch); tracer.RelatedEvent(EventLevel.Informational, "CloneDefaultRemoteBranch", metadata); } else { if (!refs.HasBranch(this.Branch)) { EventMetadata metadata = new EventMetadata(); metadata.Add("Branch", this.Branch); tracer.RelatedEvent(EventLevel.Warning, "CloneBranchDoesNotExist", metadata); string errorMessage = string.Format("Remote branch {0} not found in upstream origin", this.Branch); return(new Result(errorMessage)); } } if (!enlistment.TryCreateEnlistmentFolders()) { string error = "Could not create enlistment directory"; tracer.RelatedError(error); return(new Result(error)); } string localCacheError; if (!this.TryDetermineLocalCacheAndInitializePaths(tracer, enlistment, serverGVFSConfig, cacheServer, resolvedLocalCacheRoot, out localCacheError)) { tracer.RelatedError(localCacheError); return(new Result(localCacheError)); } Directory.CreateDirectory(enlistment.GitObjectsRoot); Directory.CreateDirectory(enlistment.GitPackRoot); Directory.CreateDirectory(enlistment.BlobSizesRoot); return(this.CreateClone(tracer, enlistment, objectRequestor, refs, this.Branch)); } } }
private static INamedPipe CreateServer(string namedPipeName, IPipePlatform pipePlatform, Action <IMessage, ITransportChannel> handleRequest) { return(NamedPipeServer.StartNewServer(namedPipeName, pipePlatform, handleRequest)); }
public void Mount(EventLevel verbosity, Keywords keywords) { this.currentState = MountState.Mounting; // We must initialize repo metadata before starting the pipe server so it // can immediately handle status requests string error; if (!RepoMetadata.TryInitialize(this.tracer, this.enlistment.DotGVFSRoot, out error)) { this.FailMountAndExit("Failed to load repo metadata: " + error); } string gitObjectsRoot; if (!RepoMetadata.Instance.TryGetGitObjectsRoot(out gitObjectsRoot, out error)) { this.FailMountAndExit("Failed to determine git objects root from repo metadata: " + error); } string localCacheRoot; if (!RepoMetadata.Instance.TryGetLocalCacheRoot(out localCacheRoot, out error)) { this.FailMountAndExit("Failed to determine local cache path from repo metadata: " + error); } string blobSizesRoot; if (!RepoMetadata.Instance.TryGetBlobSizesRoot(out blobSizesRoot, out error)) { this.FailMountAndExit("Failed to determine blob sizes root from repo metadata: " + error); } this.tracer.RelatedEvent( EventLevel.Informational, "CachePathsLoaded", new EventMetadata { { "gitObjectsRoot", gitObjectsRoot }, { "localCacheRoot", localCacheRoot }, { "blobSizesRoot", blobSizesRoot }, }); this.enlistment.InitializeCachePaths(localCacheRoot, gitObjectsRoot, blobSizesRoot); using (NamedPipeServer pipeServer = this.StartNamedPipe()) { this.tracer.RelatedEvent( EventLevel.Informational, $"{nameof(this.Mount)}_StartedNamedPipe", new EventMetadata { { "NamedPipeName", this.enlistment.NamedPipeName } }); this.context = this.CreateContext(); if (this.context.Unattended) { this.tracer.RelatedEvent(EventLevel.Critical, GVFSConstants.UnattendedEnvironmentVariable, null); } this.ValidateMountPoints(); string errorMessage; if (!HooksInstaller.TryUpdateHooks(this.context, out errorMessage)) { this.FailMountAndExit(errorMessage); } GVFSPlatform.Instance.ConfigureVisualStudio(this.enlistment.GitBinPath, this.tracer); this.MountAndStartWorkingDirectoryCallbacks(this.cacheServer); Console.Title = "GVFS " + ProcessHelper.GetCurrentProcessVersion() + " - " + this.enlistment.EnlistmentRoot; this.tracer.RelatedEvent( EventLevel.Informational, "Mount", new EventMetadata { // Use TracingConstants.MessageKey.InfoMessage rather than TracingConstants.MessageKey.CriticalMessage // as this message should not appear as an error { TracingConstants.MessageKey.InfoMessage, "Virtual repo is ready" }, }, Keywords.Telemetry); this.currentState = MountState.Ready; this.unmountEvent.WaitOne(); } }
private static INamedPipeServer CreateServer(string namedPipeName, IPipePlatform pipePlatform, Action <string, IPC.IConnection> handleRequest) { return(NamedPipeServer.StartNewServer(namedPipeName, pipePlatform, handleRequest)); }