public void Run() { while (true) { var security = new PipeSecurity(); security.SetAccessRule(new PipeAccessRule("Administrators", PipeAccessRights.FullControl, AccessControlType.Allow)); using (pipeServer = new NamedPipeServerStream( Config.PipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.None, Config.BufferSize, Config.BufferSize, security, HandleInheritability.None )) { try { Console.Write("Waiting..."); pipeServer.WaitForConnection(); Console.WriteLine("...Connected!"); if (THROTTLE_TIMER) { timer = new Timer { Interval = THROTTLE_DELAY, }; timer.Elapsed += (sender, args) => SendMessage(); timer.Start(); while(pipeServer.IsConnected)Thread.Sleep(1); timer.Stop(); } else { while (true) SendMessage(); } } catch(Exception ex) { Console.WriteLine("Error: " + ex.Message); } finally { if (pipeServer != null) { Console.WriteLine("Cleaning up pipe server..."); pipeServer.Disconnect(); pipeServer.Close(); pipeServer = null; } } } } }
public ServerWorker() { connected = false; disconnected = false; PipeSecurity ps = new PipeSecurity(); ps.SetAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow)); ps.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().User, PipeAccessRights.FullControl, AccessControlType.Allow)); pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, MAXCLIENTS, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 5000, 5000, ps); thread = new Thread(ThreadRun); thread.Start(); }
public Server() { var security = new PipeSecurity(); security.SetAccessRule(new PipeAccessRule("Administrators", PipeAccessRights.FullControl, AccessControlType.Allow)); // TODO: other options? pipeServer = new NamedPipeServerStream( Config.PipeName, PipeDirection.InOut, // TODO: single direction, benefits? NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, // TODO: investigate other options PipeOptions.None, // TODO: Async and writethrough, benefits? Config.BufferSize, Config.BufferSize, security, HandleInheritability.None ); }
internal void Start() { // setting up pipeServer PipeSecurity pipeSec = new PipeSecurity(); pipeSec.SetAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow)); pipeServer = new NamedPipeServerStream( "HKHRATP2\\" + System.Diagnostics.Process.GetCurrentProcess().ProcessName + System.Diagnostics.Process.GetCurrentProcess().Id, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 4096, 4096, pipeSec, System.IO.HandleInheritability.None ); StartListening(); }
public void Start(Boolean isClient) { if (isClient) { NamedPipeClientStream client = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); client.Connect(10000); // 10 second timeout. pipe = client; isReady = true; } else { // Grant read/write access to everyone, so the pipe can be written to from impersonated processes PipeSecurity pipeSecurity = new PipeSecurity(); pipeSecurity.SetAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow)); NamedPipeServerStream server = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 4096, 4096, pipeSecurity); server.BeginWaitForConnection(new AsyncCallback(WaitForConnection), server); } }
/// <summary> /// Listen from service for commands from core or configurator /// </summary> public static void StartListening() { if (connected) return; //only one connection... Async.Queue("MB Connection", () => { System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.BuiltinUsersSid, null); PipeSecurity pipeSa = new PipeSecurity(); pipeSa.SetAccessRule(new PipeAccessRule(sid, PipeAccessRights.ReadWrite, AccessControlType.Allow)); using (NamedPipeServerStream pipe = new NamedPipeServerStream(MBServiceController.MBSERVICE_IN_PIPE, PipeDirection.In,1,PipeTransmissionMode.Message,PipeOptions.None,1024,1024,pipeSa)) { connected = true; bool process = true; while (process) { pipe.WaitForConnection(); //wait for the core to tell us something try { // Read the request from the sender. StreamReader sr = new StreamReader(pipe); string command = sr.ReadLine(); switch (command.ToLower()) { case IPCCommands.ReloadKernel: //don't use this yet - need to figure out how to unload first do a shutdown and restart //something changed, we need to re-load everything Logger.ReportInfo("Re-loading kernel due to request from client."); Kernel.Init(KernelLoadDirective.ShadowPlugins); break; case IPCCommands.ReloadConfig: //re-load the main config file Kernel.Instance.ReLoadConfig(); break; case IPCCommands.Shutdown: //close Service Logger.ReportInfo("Shutting down due to request from client."); MainWindow.Instance.Shutdown(); break; case IPCCommands.Restart: //restart Service Logger.ReportInfo("Restarting due to request from client."); MainWindow.Instance.Restart(); break; case IPCCommands.CancelRefresh: //cancel any running refresh MainWindow.Instance.CancelRefresh(); break; case IPCCommands.ForceRebuild: //force a re-build of the library - used with new version that requires it Logger.ReportInfo("Forcing re-build of library due to request from client."); MainWindow.Instance.ForceRebuild(); break; case IPCCommands.Refresh: Logger.ReportInfo("Refreshing now due to request from client."); MainWindow.Instance.RefreshNow(); break; case IPCCommands.CloseConnection: //exit this connection Logger.ReportInfo("Client requested we stop listening."); process = false; break; } pipe.Disconnect(); } catch (IOException e) { Logger.ReportException("Error in MB connection", e); } } pipe.Close(); connected = false; } }); }
public void Listen(string pipeName) { try { _security = new PipeSecurity(); // Allow Everyone read and write access to the pipe. _security.SetAccessRule(new PipeAccessRule("Authenticated Users", PipeAccessRights.ReadWrite, AccessControlType.Allow)); // Allow the Administrators group full access to the pipe. _security.SetAccessRule(new PipeAccessRule("Administrators", PipeAccessRights.FullControl, AccessControlType.Allow)); // Set to class level var so we can re-use in the async callback method _pipeName = pipeName; // Create the new async pipe var pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1024, 1024, _security); // Wait for a connection pipeServer.BeginWaitForConnection(WaitForConnectionCallBack, pipeServer); _started.Set(); } catch (Exception oEx) { Debug.WriteLine(oEx.Message); } }
/// <summary> /// The CreateSystemIOPipeSecurity function creates a new PipeSecurity /// object to allow Authenticated Users read and write access to a pipe, /// and to allow the Administrators group full access to the pipe. /// </summary> /// <returns> /// A PipeSecurity object that allows Authenticated Users read and write /// access to a pipe, and allows the Administrators group full access to /// the pipe. /// </returns> /// <see cref="http://msdn.microsoft.com/en-us/library/aa365600(VS.85).aspx"/> static PipeSecurity CreateSystemIOPipeSecurity() { PipeSecurity pipeSecurity = new PipeSecurity(); // Allow Everyone read and write access to the pipe. pipeSecurity.SetAccessRule(new PipeAccessRule("Authenticated Users", PipeAccessRights.ReadWrite, AccessControlType.Allow)); // Allow the Administrators group full access to the pipe. pipeSecurity.SetAccessRule(new PipeAccessRule("Administrators", PipeAccessRights.FullControl, AccessControlType.Allow)); return pipeSecurity; }
PipeSecurity CreatePipeSecurity() { PipeSecurity ps = new PipeSecurity(); ps.SetAccessRule( new PipeAccessRule( "Authenticated Users", PipeAccessRights.ReadWrite, AccessControlType.Allow ) ); ps.SetAccessRule( new PipeAccessRule( "Administrators", PipeAccessRights.FullControl, AccessControlType.Allow ) ); return ps; }
const int BUFFER_SIZE = 4096; // 4 KB #endregion Fields #region Methods /// <summary> /// Named pipe server through BCL System.IO.Pipes /// </summary> static void BCLSystemIOPipeServer() { NamedPipeServerStream pipeServer = null; try { ///////////////////////////////////////////////////////////////// // Create a named pipe. // // Prepare the pipe name String strPipeName = "HelloWorld"; // Prepare the security attributes // Granting everyone the full control of the pipe is just for // demo purpose, though it creates a security hole. PipeSecurity pipeSa = new PipeSecurity(); pipeSa.SetAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow)); // Create the named pipe pipeServer = new NamedPipeServerStream( strPipeName, // The unique pipe name. PipeDirection.InOut, // The pipe is bi-directional NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, // Message type pipe PipeOptions.None, // No additional parameters BUFFER_SIZE, // Input buffer size BUFFER_SIZE, // Output buffer size pipeSa, // Pipe security attributes HandleInheritability.None // Not inheritable ); Console.WriteLine("The named pipe, {0}, is created", strPipeName); ///////////////////////////////////////////////////////////////// // Wait for the client to connect. // Console.WriteLine("Waiting for the client's connection..."); pipeServer.WaitForConnection(); ///////////////////////////////////////////////////////////////// // Read client requests from the pipe and write the response. // // A byte buffer of BUFFER_SIZE bytes. The buffer should be big // enough for ONE request from a client. string strMessage; byte[] bRequest = new byte[BUFFER_SIZE];// Client -> Server int cbBytesRead, cbRequestBytes; byte[] bReply; // Server -> Client int cbBytesWritten, cbReplyBytes; do { // Receive one message from the pipe. cbRequestBytes = BUFFER_SIZE; cbBytesRead = pipeServer.Read(bRequest, 0, cbRequestBytes); // Unicode-encode the byte array and trim all the '\0' chars // at the end. strMessage = Encoding.Unicode.GetString(bRequest).TrimEnd('\0'); Console.WriteLine("Receives {0} bytes; Message: \"{1}\"", cbBytesRead, strMessage); // Prepare the response. // '\0' is appended in the end because the client may be a // native C++ program. strMessage = "Default response from server\0"; bReply = Encoding.Unicode.GetBytes(strMessage); cbReplyBytes = bReply.Length; // Write the response to the pipe. pipeServer.Write(bReply, 0, cbReplyBytes); // If no IO exception is thrown from Write, number of bytes // written (cbBytesWritten) != -1. cbBytesWritten = cbReplyBytes; Console.WriteLine("Replies {0} bytes; Message: \"{1}\"", cbBytesWritten, strMessage.TrimEnd('\0')); } while (!pipeServer.IsMessageComplete); ///////////////////////////////////////////////////////////////// // Flush the pipe to allow the client to read the pipe's contents // before disconnecting. Then disconnect the pipe. // pipeServer.Flush(); pipeServer.Disconnect(); } catch (Exception ex) { Console.WriteLine("The server throws the error: {0}", ex.Message); } finally { if (pipeServer != null) { // Close the stream. pipeServer.Close(); } } }
public void CreatePipe2() { string ss; if (strPipeName2 == "") { ss = "Cannot create pipe " + strPipeName2; LogMessage(ss);//DataPipeInfoTxt, ss); return; } if (DataSrvHandle != null) return; try { PipeSecurity pipeSa = new PipeSecurity(); pipeSa.SetAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow)); DataSrvHandle = new NamedPipeServerStream( strPipeName2, // The unique pipe name. PipeDirection.In, // The pipe is read only NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, // Message type pipe PipeOptions.Asynchronous, // No additional parameters MAX_DATA_SIZE, // Input buffer size MAX_DATA_SIZE, // Output buffer size pipeSa, // Pipe security attributes HandleInheritability.None // Not inheritable ); ss = "The server named pipe " + strPipeName2 + " is created"; LogMessage(ss);//DataPipeInfoTxt, ss); if (EmulatorEnabled == false) { DataSrvHandle.WaitForConnection(); } ss = "The named pipe " + strPipeName2 + " is connected"; LogMessage(ss);//DataPipeInfoTxt, ss); DataPipeConnected = true; } catch (Exception ex) { ss = "Cannot create pipe " + strPipeName2; LogMessage(ss);//DataPipeInfoTxt, ss); LogMessage(ex.Message);//DataPipeInfoTxt, ex.Message); DataPipeConnected = false; } }
public void CreatePipe1() { string ss; if (strPipeName1 == "") { ss = "Cannot create pipe " + strPipeName1; LogMessage(ss); return; } if (MsgSrvHandle != null) return; try { PipeSecurity pipeSa = new PipeSecurity(); pipeSa.SetAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow)); MsgSrvHandle = new NamedPipeServerStream( strPipeName1, // The unique pipe name. PipeDirection.InOut, // The pipe is bi-directional NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, // Message type pipe PipeOptions.Asynchronous, // set to asynk mode MSG_BUFFER_SIZE, // Input buffer size MSG_BUFFER_SIZE, // Output buffer size pipeSa, // Pipe security attributes HandleInheritability.None // Not inheritable ); ss = "The server named pipe " + strPipeName1 + " is created"; LogMessage(ss); if (EmulatorEnabled == false) { MsgSrvHandle.WaitForConnection(); } if (MsgSrvHandle.IsConnected) { byte[] res = new byte[16]; byte[] bReply = new byte[16]; res = SendClientMessage1(); if (res.Length == 16) { //old style //OneMore: res = PrepareMessage(res); // if (res[4] != CX_MSG_ERROR) // { // SendPackage(res); // bReply = GetPackage(); // } // if (bReply[5] == CX_MSG_ACK) // { // Buffer.BlockCopy(bReply, 0, res, 0, 16); // goto OneMore; // } //================================================= while (res[4] != CX_MSG_ERROR) { res = PrepareMessage(res); if (res[4] != CX_MSG_ERROR) { SendPackage(res); bReply = GetPackage(); } if (bReply[5] == CX_MSG_ACK) { Buffer.BlockCopy(bReply, 0, res, 0, 16); } } //=================================================== }// } } catch (Exception ex) { ss = "Cannot create pipe " + strPipeName1; LogMessage(ss); LogMessage(ex.Message); } }