public static Boolean passHookDataByPipe(HOOKDAT oHookDat) { lock (lockDataOperation) { try { NamedPipeClientStream pipe = new NamedPipeClientStream("localhost", sDataPipe, PipeDirection.InOut); try { // Can we connect to the pipe? pipe.Connect(50); // Unclear if we need a small buffer time here pipe.ReadMode = PipeTransmissionMode.Message; // Turn object into byte array Byte[] bStruct = ObjectToByteArray(oHookDat); // Write data Byte[] ecnHookDat = arrayToAESArray(bStruct); pipe.Write(ecnHookDat, 0, ecnHookDat.Length); pipe.Close(); return(true); } catch { pipe.Close(); return(false); } } catch { return(false); } } }
/// <summary> /// Send a request for connection statistics from the tunnel service via named pipe. /// </summary> /// <returns>Connection status received from the tunnel named pipe.</returns> private Models.ConnectionStatus QueryConnectionStatisticsFromTunnel() { NamedPipeClientStream tunnelPipe = null; try { tunnelPipe = ConnectWGTunnelNamedPipe(); if (tunnelPipe != null) { IPC.WriteToPipe(tunnelPipe, new WireGuard.IPCMessage(WireGuard.IPCCommand.WgGet)); var ret = ParseStatusResponse(IPC.ReadFromPipe(tunnelPipe)); tunnelPipe.Close(); return(ret); } } catch (Exception e) { ErrorHandling.ErrorHandler.Handle(e, ErrorHandling.LogLevel.Debug); } finally { if (tunnelPipe != null && tunnelPipe.IsConnected) { tunnelPipe.Close(); } } return(new Models.ConnectionStatus() { Status = Models.ConnectionState.Protected, ConnectionStability = Models.ConnectionStability.NoSignal }); }
static void EndReadCallBack(IAsyncResult result) { try { var readBytes = RecvStream.EndRead(result); if (readBytes > 0) { string message = Encoding.UTF8.GetString(MsgBuf, 0, readBytes); MsgHandler(message); RecvStream.BeginRead(MsgBuf, 0, BufferSize, EndReadCallBack, null); } else // When no bytes were read, it can mean that the client have been disconnected { log.Info("Named pipe received empty content, close pipe"); RecvStream.Close(); RecvStream.Dispose(); } } catch (Exception ex) { log.Error("Named pipe error, close pipe. ex: " + ex); RecvStream.Close(); RecvStream.Dispose(); } }
internal override void Close() { stopEvent.Set(); if (PipeClientStream != null) { try { PipeClientStream.Close(); PipeClientStream.Dispose(); } catch (Exception e) { System.Diagnostics.Trace.WriteLine(e.Message); } PipeClientStream = null; } if (pipeThread != null) { pipeThread.Join(); pipeThread = null; } }
public static Boolean passControlCodeByPipe() { try { NamedPipeClientStream pipe = new NamedPipeClientStream("localhost", sControlPipe, PipeDirection.InOut); try { // Can we connect to the pipe? pipe.Connect(50); // Unclear if we need a small ms buffer time here pipe.ReadMode = PipeTransmissionMode.Message; // Encrypt magic data Byte[] bMagic = Encoding.UTF8.GetBytes("Dendrobate"); Byte[] bEncrypt = arrayToAESArray(bMagic); // Write data pipe.Write(bEncrypt, 0, bEncrypt.Length); pipe.Close(); return(true); } catch { pipe.Close(); return(false); } } catch { return(false); } }
private static string SendOfData(string input) { string output; using (var pipeClient = new NamedPipeClientStream(".", "UNITY_PIP", PipeDirection.InOut)) { try { pipeClient.Connect(2); } catch (Exception exp) { pipeClient.Close(); return(exp.Message + ": Connection"); } using (var sr = new StreamWriter(pipeClient)) { try { sr.WriteLine(input); output = "Succes"; } catch (Exception exp) { output = exp.Message + ": WriteLine"; } sr.Close(); } pipeClient.Close(); } return(output); }
public void Unsubscribe(string Channel) { if (DataSyncAction.ContainsKey(Channel)) { DataSyncAction.Remove(Channel); using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", string.Format("{0}.{1}.{2}", PipeName, UniqueId, Channel), PipeDirection.Out, PipeOptions.Asynchronous)) { try { pipeClient.Connect(500); pipeClient.Write(new byte[] { 0 }, 0, 1); if (pipeClient.IsConnected) { pipeClient.Close(); } } catch { if (pipeClient.IsConnected) { pipeClient.Close(); } } pipeClient.Dispose(); } } }
public static void SendKillRequest() { NamedPipeClientStream pipeClient = null; try { pipeClient = new NamedPipeClientStream(ServerName, PipeName, PipeDirection.InOut, PipeOptions.None); pipeClient.Connect(1000); pipeClient.ReadMode = PipeTransmissionMode.Message; byte[] bRequest = Encoding.UTF8.GetBytes(KillRequestMessage); int cbRequest = bRequest.Length; pipeClient.Write(bRequest, 0, cbRequest); pipeClient.WaitForPipeDrain(); string msg = ""; var reader = new StreamReader(pipeClient); msg = reader.ReadToEnd(); pipeClient.Close(); } catch { if (pipeClient != null) { pipeClient.Close(); pipeClient = null; } } }
private void RunClient() { try { _clientPipe = new NamedPipeClientStream(".", Constants.PipeName, Constants.PipeDirection, Constants.PipeOptions); _clientPipe.Connect(); _clientPipe.Flush(); _streamString = new StreamString(_clientPipe); Application.Current.Dispatcher.Invoke(() => { _parent.TextArea.Text = ""; }); do { if (_clientPipe != null && _clientPipe.IsConnected) { string line = _streamString.ReadString(); if (!string.IsNullOrWhiteSpace(line)) { if (line == Constants.DisconnectKeyword) { SendMessage(Constants.DisconnectKeyword); } else { Application.Current.Dispatcher.Invoke(() => { _parent.TextArea.Text = line; }); } } else { _serverClose = true; } } } while (!_serverClose); _clientPipe.Close(); Application.Current.Dispatcher.Invoke(() => { OnClientClosed(EventArgs.Empty); }); } catch (IOException) { _serverClose = true; _clientPipe.Flush(); _clientPipe.Close(); } catch (Exception ex) { throw ex; } }
private void tailTransfer() { NamedPipeClientStream stream = null; try { while (threadsRunning) { while (threadsRunning) { try { stream = Tunnel.Service.GetPipe(configFile); stream.Connect(); break; } catch { } Thread.Sleep(1000); } var reader = new StreamReader(stream); stream.Write(Encoding.UTF8.GetBytes("get=1\n\n")); ulong rx = 0, tx = 0; while (threadsRunning) { var line = reader.ReadLine(); if (line == null) { break; } line = line.Trim(); if (line.Length == 0) { break; } if (line.StartsWith("rx_bytes=")) { rx += ulong.Parse(line.Substring(9)); } else if (line.StartsWith("tx_bytes=")) { tx += ulong.Parse(line.Substring(9)); } } Invoke(new Action <ulong, ulong>(updateTransferTitle), new object[] { rx, tx }); stream.Close(); Thread.Sleep(1000); } } catch { } finally { if (stream != null && stream.IsConnected) { stream.Close(); } } }
/// <summary> /// Disconnects input client from the EmuController device. /// Will also disconnect FFBPipeClient if it is connected. /// </summary> public void CloseInputClient() { if (InputPipeClient.IsConnected) { InputPipeClient.Close(); if (FFBPipeClient.IsConnected) { FFBPipeClient.Close(); } } }
public void Stop() { if (pipeThread.IsAlive) { client.Close(); pipeThread.Abort(); } if (IsProcessRunning(playbackServerProcess)) { playbackServerProcess.Kill(); } }
private void OnApplicationQuit() { if (clientStream != null) { try { clientStream.Close(); clientStream.Dispose(); } catch (Exception) { } } }
/// <summary> /// DoCheckForReplay method implementation /// </summary> public bool DoCheckForReplay(NamedPipeReplayRecord requestor) { try { if (OnDecrypt == null) { OnDecrypt += PipeClientOnDecrypt; } if (OnEncrypt == null) { OnEncrypt += PipeClientOnEncrypt; } Task <bool> task = null; NamedPipeClientStream ClientStream = new NamedPipeClientStream(_servers[0], "adfsmfaconfig", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation); task = Task <bool> .Factory.StartNew(() => { try { ClientStream.Connect(); PipeStreamData ss = new PipeStreamData(ClientStream); ss.WriteString(OnEncrypt(Proofkey)); if (OnDecrypt(ss.ReadString()) == Proofkey) { NamedPipeNotificationReplayRecord xdata = new NamedPipeNotificationReplayRecord(requestor); ss.WriteData(ObjectToByteArray(xdata)); return(ByteArrayToObject <bool>(ss.ReadData())); } } catch (IOException e) { LogForSlots.WriteEntry("PipeClient Error : " + e.Message, EventLogEntryType.Error, 8888); ClientStream.Close(); } finally { ClientStream.Close(); } return(false); }); task.Wait(); return(task.Result); } catch (Exception e) { LogForSlots.WriteEntry("PipeClient Error : " + e.Message, EventLogEntryType.Error, 8888); return(false); } }
public void Close() { if (ioStream != null) { ioStream.Close(); } bClientConn = false; /* Wake up the write thread so it can die */ newWriteData.Set(); /* Close connection streams */ if (waitThread != null) { if (sStream != null) { sStream.Close(); } else if (cStream != null) { cStream.Close(); } } }
public override void ReadMessages(string host) { while (true) { NamedPipeClientStream clientStream = null; IPCMessages.IPCMessage msg; try { clientStream = new NamedPipeClientStream( host, PipeName, PipeDirection.InOut, PipeOptions.Asynchronous); clientStream.Connect(3000); msg = (IPCMessages.IPCMessage)bf.Deserialize(clientStream); string broadcastMessage = FormatMessage(host, msg.Message); mtx.WaitOne(); Console.Write(broadcastMessage); mtx.ReleaseMutex(); } catch (Exception ex) { Console.WriteLine($"[-] Error in SMB Client when communicating with {host}: {ex.Message}"); } finally { if (clientStream != null) { clientStream.Close(); } } Thread.Sleep(30000); } }
public void Disconnect() { if (_client.IsConnected) { _client.Close(); } }
private static void RunCore(string ip, string pipeName) { NamedPipeClientStream pipeClient = new NamedPipeClientStream(ip, pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation); Console.WriteLine("Connecting to server...\n"); pipeClient.Connect(); StreamString ss = new StreamString(pipeClient); // Validate the server's signature string if (ss.ReadString() == "I am the one true server!") { // The client security token is sent with the first write. // Send the name of the file whose contents are returned // by the server. ss.WriteString("Message from client " + DateTime.Now.ToString()); // Print the file to the screen. Console.Write(ss.ReadString()); } else { Console.WriteLine("Server could not be verified."); } pipeClient.Close(); }
static int QuickLookServerAvailable() { string PipeName = $"QuickLook.App.Pipe.{WindowsIdentity.GetCurrent().User?.Value}"; string Switch = "QuickLook.App.PipeMessages.Switch"; using var client = new NamedPipeClientStream(".", PipeName, PipeDirection.Out); try { client.Connect(500); var serverInstances = client.NumberOfServerInstances; using (var writer = new StreamWriter(client)) { writer.WriteLine($"{Switch}|"); writer.Flush(); } return(serverInstances); } catch (TimeoutException) { client.Close(); return(0); } }
private bool TryConnect() { // We need to delay creation and connect until its used, so we guarantee // that the server side is active and ready. // Because we have a timeout in connect this can happen more than once // concurrently if the user is quick. I had this issue several times during // testing. To avoid this, we block with a lock. lock (this) { if (mPipe == null || !mPipe.IsConnected) { var xPipe = new NamedPipeClientStream(".", mPipeName, PipeDirection.Out); try { // For now we assume its there or not from the first call. // If we don't find the server, we disable it to avoid causing lag. // TODO: In future - try this instead: // String[] listOfPipes = System.IO.Directory.GetFiles(@"\.\pipe\"); // or maybe not - what we have seems to work just fine... xPipe.Connect(500); } catch (Exception) { xPipe.Close(); return(false); } mWriter = new StreamWriter(xPipe); // Only set mPipe if we are truly ready. Other code can check it. mPipe = xPipe; } } return(true); }
// receive event notifications from MusicBee // you need to set about.ReceiveNotificationFlags = PlayerEvents to receive all notifications, and not just the startup event public void ReceiveNotification(string sourceFileUrl, NotificationType type) { // perform some action depending on the notification type switch (type) { case NotificationType.TrackChanged: var sendmap = new Dictionary <string, string>(); sendmap.Add("title", mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle)); sendmap.Add("albumartist", mbApiInterface.NowPlaying_GetFileTag(MetaDataType.AlbumArtist)); sendmap.Add("artist", mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist)); sendmap.Add("trackcount", mbApiInterface.NowPlaying_GetFileProperty(FilePropertyType.PlayCount)); sendmap.Add("album", mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album)); sendmap.Add("albumart", mbApiInterface.NowPlaying_GetArtwork()); sendmap.Add("composer", mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Composer)); var json = new JavaScriptSerializer().Serialize(sendmap.ToDictionary(item => item.Key.ToString(), item => item.Value.ToString())); Task.Run(() => { try { var bary = Encoding.UTF8.GetBytes(json); var pipe = new NamedPipeClientStream("NowPlayingTunesV2PIPE"); pipe.Connect(1000); //set timeout 1000msec. pipe.Write(bary, 0, bary.Count()); pipe.Close(); } catch { } }); break; } }
private void SendCommands(string[] commands, bool launch = false) { for (int i = 0; i < MaxInstancesNumber; i++) { try { var pipeClient = new NamedPipeClientStream(".", PipeBaseName + i, PipeDirection.Out); pipeClient.Connect(launch ? 10 : 100); var writer = new StreamWriter(pipeClient); foreach (var command in commands) { writer.WriteLine(command); } writer.Close(); pipeClient.Close(); return; } catch (TimeoutException) { } catch (IOException) { } } if (launch == true) { Process p = new Process(); p.StartInfo.FileName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; p.Start(); p.WaitForInputIdle(); SendCommands(commands); } }
/// <summary> /// Connect to our named-pipe server, send arguements and close current process /// </summary> /// <param name="args"></param> /// <param name="param"></param> private static void RunClient(string[] args, string param) { if (!IsServerRunning) { MessageBox.Show("FTPbox must be running to use the context menus!", "FTPbox", MessageBoxButtons.OK, MessageBoxIcon.Information); RemoveFTPboxMenu(); Process.GetCurrentProcess().Kill(); } var pipeClient = new NamedPipeClientStream(".", "FTPbox Server", PipeDirection.InOut, PipeOptions.None, System.Security.Principal.TokenImpersonationLevel.Impersonation); Log.Write(l.Client, "Connecting client..."); pipeClient.Connect(); var ss = new StreamString(pipeClient); if (ss.ReadString() == "ftpbox") { var p = CombineParameters(args, param); ss.WriteString(p); Log.Write(l.Client, ss.ReadString()); } else { Log.Write(l.Client, "Server couldnt be verified."); } pipeClient.Close(); Thread.Sleep(4000); Process.GetCurrentProcess().Kill(); }
private void mainForm_FormClosed(object sender, FormClosedEventArgs e) { SendMessage("exit"); server.Disconnect(); server.Close(); client.Close(); }
/// <summary> /// Connect to our named-pipe server, send arguements and exit /// </summary> public static void RunClient(string file, string param) { if (!IsServerRunning) { MessageBox.Show("FTPbox must be running to use the context menus!", "FTPbox", MessageBoxButtons.OK, MessageBoxIcon.Information); RemoveContextMenu(); Process.GetCurrentProcess().Kill(); } var pipeClient = new NamedPipeClientStream(".", "FTPboxServer", PipeDirection.Out, PipeOptions.None, System.Security.Principal.TokenImpersonationLevel.Impersonation); pipeClient.Connect(); Log.Write(l.Info, "[PipeClient] Connected"); using (var writer = new StreamWriter(pipeClient)) { var message = $"{param} {file}"; writer.WriteAsync(message).ContinueWith(s => { Log.Write(l.Info, "[PipeClient] Message sent"); pipeClient.Close(); Process.GetCurrentProcess().Kill(); }); } }
static void Main(string[] args) { try { Log("START"); //args = $@"bdf0d464-5bcc-4a4f-aaa3-0d2d1bafe5e4, I:\ConsoleApp1\ConsoleApp1.Tests\bin\Debug\ConsoleApp1.Tests.dll".Split(',').Select(s => s.Trim()).ToArray(); if (args.Length > 1) { Log(string.Join(", ", args)); Log("Creating client"); NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", args[0], PipeDirection.InOut); Log("Client connecting"); pipeClient.Connect(); Log("Starting discovery"); Discover(args, pipeClient); Log("Waiting for pipedrain"); pipeClient.WaitForPipeDrain(); Log("Closing connection"); pipeClient.Close(); Log("Connection closed"); } } catch (Exception ex) { Log("EXCEPTION"); Log(ex.Message); Console.WriteLine(ex.Message); } }
public void CheckUnenrolledHostShouldRemoved() { IXenConnection connection = DatabaseManager.ConnectionFor(dbName); Session _session = DatabaseManager.ConnectionFor(dbName).Session; Dictionary <string, string> config = cleanStack(); ServerListHelper.instance.ClearServerList(); int conSize = ServerListHelper.instance.GetServerList().Count; NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.Out); pipeClient.Connect(); string credential = EncryptionUtils.ProtectForLocalMachine(String.Join(SEPARATOR.ToString(), new[] { connection.Hostname, connection.Username, nonEmptyPassword })); pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length); pipeClient.Close(); System.Threading.Thread.Sleep(1000); List <ServerInfo> con = ServerListHelper.instance.GetServerList(); Assert.IsTrue(con.Count == conSize + 1); //1. If XenServer has not enroll, lock will not been set. config = cleanStack(); config[HealthCheckSettings.STATUS] = "false"; Pool.set_health_check_config(_session, connection.Cache.Pools[0].opaque_ref, config); Assert.IsFalse(RequestUploadTask.Request(connection, _session)); con = ServerListHelper.instance.GetServerList(); Assert.IsTrue(con.Count == conSize); }
private void ClosePipe(string pipeName, ref NamedPipeClientStream pipe) { if (pipe != null) { try { // CAUTION! closing a pipe in use can make .NET to crash! disconnect it first... if (pipe.IsConnected) { pipe.WaitForPipeDrain(); } pipe.Close(); } catch (Exception exc) { Trace.TraceError("Failed to close pipe {0}, remote session {1} ({2})", pipeName, _remotesessionID, exc); } finally { pipe.Dispose(); pipe = null; } } }
public CClashResponse Transact(CClashRequest req) { Connect(); CClashResponse resp = null; req.pid = System.Diagnostics.Process.GetCurrentProcess().Id; var txbuf = req.Serialize(); ncs.Write(txbuf, 0, txbuf.Length); ncs.Flush(); var rx = new List <byte>(); var rxbuf = new byte[8192]; do { var rbytes = ncs.Read(rxbuf, 0, rxbuf.Length); rx.AddRange(rxbuf.Take(rbytes)); } while (!ncs.IsMessageComplete); if (rx.Count > 0) { resp = CClashMessage.Deserialize <CClashResponse>(rx.ToArray()); ncs.Close(); } return(resp); }
private void SecondInstance(string[] args) { NamedPipeClientStream stream = new NamedPipeClientStream(".", m_guid, PipeDirection.Out); try { stream.Connect(1000); using (MemoryStream mem = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(mem, Encoding.UTF8)) { writer.Write(args.Length); foreach (string argument in args) { writer.Write(argument); } } byte[] data = mem.ToArray(); stream.Write(data, 0, data.Length); } stream.Close(); } catch (IOException) { } }