AddAccessRule() public méthode

public AddAccessRule ( PipeAccessRule rule ) : void
rule PipeAccessRule
Résultat void
Exemple #1
2
        static NamedPipeServerStream CreateServerStream()
        {
            var user = WindowsIdentity.GetCurrent().User;
            var security = new PipeSecurity();
            security.AddAccessRule( new PipeAccessRule( user, PipeAccessRights.FullControl, AccessControlType.Allow ) );
            security.SetOwner( user );
            security.SetGroup( user );

            IncrementServers();
            try
            {
                return new NamedPipeServerStream(
                    ProtocolConstants.PipeName,
                    PipeDirection.InOut,
                    20,
                    PipeTransmissionMode.Byte,
                    PipeOptions.Asynchronous,
                    CommandLineLength,
                    CommandLineLength,
                    security );
            }
            catch ( Exception )
            {
                DecrementServers();
                throw;
            }
        }
Exemple #2
0
        public MyServiceTasks()
        {
            SetupEventLog();

            PipeSecurity ps = new PipeSecurity();
            ps.AddAccessRule(new PipeAccessRule("Users", PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow));
            ps.AddAccessRule(new PipeAccessRule("CREATOR OWNER", PipeAccessRights.FullControl, AccessControlType.Allow));
            ps.AddAccessRule(new PipeAccessRule("SYSTEM", PipeAccessRights.FullControl, AccessControlType.Allow));

            pipe = new NamedPipeServerStream("MyServicePipe", PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1024, 1024, ps);
            InterProcessSecurity.SetLowIntegrityLevel(pipe.SafePipeHandle);
        }
 public NpListener(string pipeName, int maxConnections = 254, ILog log = null, IStats stats = null)
 {
     _log = log ?? _log;
     _stats = stats ?? _stats;
     if (maxConnections > 254) maxConnections = 254;
     _maxConnections = maxConnections;
     this.PipeName = pipeName;
     _pipeSecurity = new PipeSecurity();
     _pipeSecurity.AddAccessRule(new PipeAccessRule(@"Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow));
     _pipeSecurity.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().User, PipeAccessRights.FullControl, AccessControlType.Allow));
     _pipeSecurity.AddAccessRule(new PipeAccessRule(@"SYSTEM", PipeAccessRights.FullControl, AccessControlType.Allow));
 }
 PipeSecurity createPipeSecurity()
 {
     var pipeSecurity = new PipeSecurity();
     pipeSecurity.AddAccessRule(new PipeAccessRule(
         new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null),
         PipeAccessRights.ReadWrite,
         AccessControlType.Allow));
     pipeSecurity.AddAccessRule(new PipeAccessRule(
         WindowsIdentity.GetCurrent().Owner,
         PipeAccessRights.FullControl,
         AccessControlType.Allow));
     return pipeSecurity;
 }
 public static NamedPipeServerStream Create(string name, int maxInstances = NamedPipeServerStream.MaxAllowedServerInstances) {
     PipeSecurity ps = new PipeSecurity();
     SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
     PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
     ps.AddAccessRule(par);
     return new NamedPipeServerStream(name, PipeDirection.InOut, maxInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024, ps);
 }
 public NamedPipesReadQueue()
 {
     var ps = new PipeSecurity();
     ps.AddAccessRule(new PipeAccessRule("Users", PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow));
     _serverStream = new NamedPipeServerStream(Whitebox.Connector.Constants.PipeName, PipeDirection.In, MaxInstances,
                                               PipeTransmissionMode.Message, PipeOptions.None, MaxMessage * MaxMessagesInBuffer,
                                               MaxMessage, ps);
 }
        private void PipeThreadStart()
        {
            PipeSecurity pSec = new PipeSecurity();
            PipeAccessRule pAccRule = new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null)
            , PipeAccessRights.ReadWrite | PipeAccessRights.Synchronize, System.Security.AccessControl.AccessControlType.Allow);
            pSec.AddAccessRule(pAccRule);

            using (_pipeServer = new NamedPipeServerStream("NKT_SQLINTERCEPT_PIPE",
                PipeDirection.InOut,
                NamedPipeServerStream.MaxAllowedServerInstances,
                PipeTransmissionMode.Byte,
                PipeOptions.None,
                MAX_STRING_CCH * 2,
                MAX_STRING_CCH * 2,
                pSec,
                HandleInheritability.Inheritable))
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("(pipe thread) Waiting for connection...");
                Console.ForegroundColor = ConsoleColor.Gray;

                try
                {
                    _pipeServer.WaitForConnection();

                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("(pipe thread) Client connected.");
                    Console.ForegroundColor = ConsoleColor.Gray;

                    while (true)
                    {
                        byte[] readBuf = new byte[MAX_STRING_CCH * 2];

                        int cbRead = _pipeServer.Read(readBuf, 0, MAX_STRING_CCH * 2);

                        string str = Encoding.Unicode.GetString(readBuf, 0, cbRead);

                        Console.WriteLine(str);
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine("--------------------------------------------------------");
                        Console.ForegroundColor = ConsoleColor.Gray;

                        if (_blockQuery)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("(pipe thread) QUERY ABORTED");
                            Console.ForegroundColor = ConsoleColor.Gray;
                        }

                    }
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine("(pipethread) Pipe or data marshaling operation exception! ({0})", ex.Message);
                }
            }
        }
Exemple #8
0
        private static NamedPipeServerStream CreateNamedPipeServerStream(string pipeName) {
            var pipeSecurity = new PipeSecurity();
            pipeSecurity.AddAccessRule(
                new PipeAccessRule(
                    new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null),
                    PipeAccessRights.ReadWrite, AccessControlType.Allow));

            return new NamedPipeServerStream(pipeName,
                PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.None,
                4096, 4096, pipeSecurity);
        }
 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();
 }
Exemple #10
0
        public void Start(string pipeName)
        {
            _pipeName = pipeName;

            var security = new PipeSecurity();
            var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            security.AddAccessRule(new PipeAccessRule(sid, PipeAccessRights.FullControl, AccessControlType.Allow));
            _pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.In, 254,
                PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 4096, 4096, security);
            _pipeServer.BeginWaitForConnection(WaitForConnectionCallBack, _pipeServer);
            _logger.Info("Opened named pipe '{0}'", _pipeName);
            _closed = false;
        }
        /*
        *METHOD		    :	QuestionWindow
        *
        *DESCRIPTION	:	Constructor for the QuestionWindow class. takes in users name, the computers name to connect to and name of the pipe to use.
         *                  Opens connestion to the service and starts the first qestion
        *
        *PARAMETERS		:	string userName     The name of the user
         *                  string serverName   The name of the computer running the server
         *                  string pipeName     The name of the por to connect to
        *
        *RETURNS		:
        *
        */
        public QuestionWindow(string userName, string serverName, string pipeName)
        {
            InitializeComponent();
            this.userName = userName;
            this.serverName = serverName;
            this.pipeName = pipeName;

            answers = new string[4];

            PipeSecurity ps = new PipeSecurity();
            System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
            PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
            ps.AddAccessRule(par);

            questionNumber = 1;
            answers[0] = "";
            answers[1] = "";
            answers[2] = "";
            answers[3] = "";

            //start timer for counting down users score (1 per second)
            timer = new System.Timers.Timer();
            timer.Elapsed += on_Timer_Event;
            timer.Interval = 1000;

            //connect to service
            client = new NamedPipeClientStream(serverName, pipeName + "service");//naming convention for pipe is given name(pipeName) and who has the server (service or user)
            client.Connect(30);
            output = new StreamWriter(client);

            //tell service the name of the computer to connect back to
            output.WriteLine(Environment.MachineName);
            output.Flush();

            server = new NamedPipeServerStream(pipeName + "User", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 5000, 5000, ps);//naming convention for pipe is given name(pipeName) and who has the server (service or user)
            server.WaitForConnection();
            input = new StreamReader(server);

            Thread.Sleep(100);//allow server time complete actions
            //tell service name of new user
            newUser();
            Thread.Sleep(200);//allow server time complete actions
            //get the first question
            getGameQuestion();
            //start score counter
            timer.Start();
        }
Exemple #12
0
 public void Init()
 {
     lock (pipeServerLock)
     {
         if (pipeServer != null)
         {
             return;
         }
         var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
         var rule = new PipeAccessRule(sid, PipeAccessRights.ReadWrite,
         System.Security.AccessControl.AccessControlType.Allow);
         var sec = new PipeSecurity();
         sec.AddAccessRule(rule);
         pipeServer = new NamedPipeServerStream(HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 0, 0, sec);
         pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer);
     }
 }
Exemple #13
0
        static void Main(string[] args)
        {
            argCallbacks = new Dictionary<string, ArgCallback>();
            argCallbacks.Add("--list-mods", Command.ListMods);
            argCallbacks.Add("-l", Command.ListMods);
            argCallbacks.Add("--mod-info", Command.ListModInfo);
            argCallbacks.Add("-i", Command.ListModInfo);
            argCallbacks.Add("--download-url", Command.DownloadUrl);
            argCallbacks.Add("--extract-zip", Command.ExtractZip);
            argCallbacks.Add("--install-ra-packages", Command.InstallRAPackages);
            argCallbacks.Add("--install-cnc-packages", Command.InstallCncPackages);
            argCallbacks.Add("--settings-value", Command.Settings);

            if (args.Length == 0) { PrintUsage(); return; }
            var arg = SplitArgs(args[0]);

            bool piping = false;
            if (args.Length > 1 && SplitArgs(args[1]).Key == "--pipe")
            {
                piping = true;
                string pipename = SplitArgs(args[1]).Value;
                NamedPipeServerStream pipe;
                var id = WindowsIdentity.GetCurrent();
                var principal = new WindowsPrincipal(id);
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    var ps = new PipeSecurity();
                    ps.AddAccessRule(new PipeAccessRule("EVERYONE", (PipeAccessRights)2032031, AccessControlType.Allow));
                    pipe = new NamedPipeServerStream(pipename, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.None, 1024*1024, 1024*1024, ps);
                }
                else
                    pipe = new NamedPipeServerStream(pipename, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.None, 1024*1024,1024*1024,null);

                pipe.WaitForConnection();
                Console.SetOut(new StreamWriter(pipe) { AutoFlush = true });
            }

            ArgCallback callback;
            if (argCallbacks.TryGetValue(arg.Key, out callback))
                callback(arg.Value);
            else
                PrintUsage();

            if (piping)
                Console.Out.Close();
        }
        public RpcPipeServerChannel(string pipeName, int instanceCount)
        {
            _pipeName = pipeName;
            _pipeServers = new NamedPipeServerStream[instanceCount];
            for (int i = 0; i < instanceCount; i++) {
                //
                // TODO: Add PipeSecurity
                PipeSecurity security = new PipeSecurity();
                // new PipeAccessRule(.

                security.AddAccessRule(new PipeAccessRule(new NTAccount("Everyone"), PipeAccessRights.FullControl, AccessControlType.Allow));

                _pipeServers[i] = new NamedPipeServerStream(pipeName, PipeDirection.InOut,
                    instanceCount, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, 0,
                    security);

            }
        }
Exemple #15
0
 public void StartServer(SelectCounter selectCountersDelegate, ReceivedValues receivedValuesDelegate)
 {
     selectCounters = selectCountersDelegate;
     receivedValues = receivedValuesDelegate;
     System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
     PipeAccessRule pac = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
     PipeSecurity ps = new PipeSecurity();
     ps.AddAccessRule(pac);
     sid = null;
     pipeServer = new NamedPipeServerStream(serverPipeName,
             PipeDirection.InOut,
             serverInstances,
             PipeTransmissionMode.Message,
             PipeOptions.Asynchronous,
             1024,
             1024,
             ps);
     AsyncCallback myCallback = new AsyncCallback(AsyncPipeCallback);
     pipeServer.BeginWaitForConnection(myCallback, null);
 }
Exemple #16
0
		void NamedPipePermissionsActuallyWorkSync (string name, bool addDenyEveryone)
		{
			if (PlatformID.Win32NT != Environment.OSVersion.Platform) {
				Assert.Ignore (); return;
			}

			PipeSecurity security = new PipeSecurity ();
			SecurityIdentifier worldSid = new SecurityIdentifier ("WD");
			PipeAccessRule rule = new PipeAccessRule (worldSid,
			                                          PipeAccessRights.FullControl,
			                                          AccessControlType.Allow);
			security.AddAccessRule (rule);

			using (NamedPipeServerStream server = CreateNamedServer (false, name, security,
										 PipeAccessRights.ChangePermissions)) {
				security = server.GetAccessControl ();

				AuthorizationRuleCollection rules;
				rules = security.GetAccessRules (true, true, typeof (SecurityIdentifier));
				Assert.AreEqual (1, rules.Count);

				rule = (PipeAccessRule)rules [0];
				Assert.AreEqual (AccessControlType.Allow, rule.AccessControlType);
				Assert.AreEqual (worldSid, rule.IdentityReference);
				Assert.AreEqual (PipeAccessRights.FullControl, rule.PipeAccessRights);

				if (addDenyEveryone)
					AddDenyEveryone (server);

				bool unauthorized = false;
				using (NamedPipeClientStream client = CreateNamedClient (false, name)) {
					try {
						client.Connect (1000);
					} catch (UnauthorizedAccessException) {
						unauthorized = true;
					}
				}

				Assert.AreEqual (addDenyEveryone, unauthorized);
			}
		}
Exemple #17
0
        private void ServerThreadRoutine(object data)
        {
            string defaultTimeOutValuestring = TimeOutValuestring;
            TvBusinessLayer layer = new TvBusinessLayer();
            Setting setting = null;

            while (PipeServerActive)
            {
                try
                {
                    var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                    var rule = new PipeAccessRule(sid, PipeAccessRights.ReadWrite,System.Security.AccessControl.AccessControlType.Allow);
                    var sec = new PipeSecurity();
                    sec.AddAccessRule(rule);

#if (MPTV2)
                    string pipeName = "MP2TvWishListPipe";
#else
                    string pipeName = "TvWishListPipe";
#endif

                    pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, sec);  //only 1 thread for pipe

                    int threadId = Thread.CurrentThread.ManagedThreadId;

                    // Wait for a client to connect
                    Logdebug("TvServer: Waiting for client to connect");
                    PipeServerBusy = false;

                    pipeServer.WaitForConnection();
                    ServerMessage = string.Empty;
                    Logdebug("Client connected on pipe server thread.");
                    PipeServerBusy = true; ;
                    // Read the request from the client. Once the client has
                    // written to the pipe its security token will be available.

                    //pipeServer.ReadTimeout = 5000; //timeout not supported for async streams

                    StreamString ss = new StreamString(pipeServer);

                    // Verify our identity to the connected client using a
                    // string that the client anticipates.


                    MessageFromClient = ss.ReadString();            //receive message from client first
                    //labelreceivedTextServer.Text = messagefromclient;
                    Logdebug("***** CLIENTMESSAGE=" + MessageFromClient);

                    //*******************************
                    //commandinterpretation 
                    //*******************************
                    if (MessageFromClient == PipeCommands.RequestTvVersion.ToString())
                    {
                        string response = PipeCommands.RequestTvVersion.ToString() + "=" + this.Version;
                        Logdebug("sending response " + response);
                        ss.WriteString(response);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.StartEpg.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;
                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }
                        Logdebug("Starting EPG Search from pipe command");
                        Thread StartEPGsearchThread = new Thread(StartEPGsearchCommand);
                        StartEPGsearchThread.Start();
                        

                        while ((ServerMessage.StartsWith(PipeCommands.Ready.ToString())==false) && (ServerMessage.StartsWith(PipeCommands.Error.ToString()) == false))
                        {
                            ServerTimeOutCounter = new Thread(ServerTimeOutError);
                            ServerTimeOutCounter.Start();
                            while ((NewServerMessage == false) || (ServerMessage==string.Empty))
                            {
                                Thread.Sleep(500);
                                Logdebug("waiting for new servermessage (ServerMessage="+ServerMessage);
                            }
                            Logdebug("Sending Servermessage=" + ServerMessage);
                            ss.WriteString(ServerMessage);                   //send response messages until done
                            ServerTimeOutCounter.Abort();
                            NewServerMessage = false;
                        }
                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.Error_TimeOut.ToString()) == true)
                    {
                        TimeOutValuestring = MessageFromClient.Replace(PipeCommands.Error_TimeOut.ToString(), string.Empty);
                        Logdebug("new TimeOutValuestring="+TimeOutValuestring);
                        ss.WriteString(TimeOutValuestring);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ExportTvWishes.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Log.Debug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        if (MessageFromClient.Contains("VIEWONLY=TRUE") == true)
                        {
                            ServerMessage = ExportTvWishes(true);
                        }
                        else //Email & Record Mode
                        {
                            ServerMessage = ExportTvWishes(false);
                        }

                        ss.WriteString(ServerMessage);

                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ImportTvWishes.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        if (MessageFromClient.Contains("VIEWONLY=TRUE") == true)
                        {
                            ServerMessage = ImportTvWishes(true);
                        }
                        else //Email & Record Mode
                        {
                            ServerMessage = ImportTvWishes(false);
                        }

                        ss.WriteString(ServerMessage);

                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.RemoveSetting.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        string tag = tokens[0].Replace(PipeCommands.RemoveSetting.ToString(), string.Empty);

                        
                        setting = layer.GetSetting(tag, string.Empty);
                        if (setting != null)
                        {
                            setting.Remove();
                            ServerMessage = "Setting " + tag + " removed";
                            Logdebug("Setting " + tag + " removed");
                        }
                        else
                        {
                            ServerMessage = "Setting " + tag + " could not be removed";
                            Logdebug("Eror: Setting " + tag + " could not be removed");
                 
                        }

                        ss.WriteString(ServerMessage);
                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.RemoveRecording.ToString()) == true)
                    {//string command = Main_GUI.PipeCommands.RemoveRecording.ToString() + this.IdRecording.ToString() + ":10";
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        string idRecordingString = tokens[0].Replace(PipeCommands.RemoveRecording.ToString(), string.Empty);
                        try
                        {
                            int idRecording = -1;
                            int.TryParse(idRecordingString, out idRecording);
                            Logdebug("idRecording=" + idRecording.ToString());
                            Recording myrecording = Recording.Retrieve(idRecording);
                            Logdebug("idRecording=" + myrecording.Title.ToString());
                            myrecording.Delete();
                            Logdebug("Recording deleted");
                            ServerMessage = "Recording deleted"; 
                        }
                        catch (Exception exc)
                        {
                            Logdebug("no recording found for idRecordingString = " + idRecordingString);
                            Logdebug("exception is " + exc.Message);
                            ServerMessage = "Error: Recording could not be deleted check the tvserver log file"; 
                        }

                        ss.WriteString(ServerMessage);
                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    
                    else if (MessageFromClient.StartsWith(PipeCommands.RemoveLongSetting.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        //processing
                        string mysetting = string.Empty;
                        try
                        {
                            //cleanup work
                            mysetting = tokens[0].Replace(PipeCommands.RemoveLongSetting.ToString(), string.Empty);
                            Log.Debug("mysetting=" + mysetting);
                            for (int i = 1; i < 1000; i++)
                            {
                                setting = layer.GetSetting(mysetting + "_" + i.ToString("D3"), "_DOES_NOT_EXIST_");
                                Log.Debug("save_longsetting setting=" + setting.Value);
                                if (setting.Value == "_DOES_NOT_EXIST_")
                                {
                                    setting.Remove();
                                    break;
                                }
                                else
                                {
                                    string value = setting.Value;
                                    setting.Remove();

                                }
                            }
                            ServerMessage = "Long setting could be removed";
                        }
                        catch (Exception exc)
                        {
                            Logdebug("Longsetting could not be removed for mysetting= " + mysetting);
                            Logdebug("exception is " + exc.Message);
                            ServerMessage = "Error: Long setting could not be removed - check the tvserver log file";
                        }

                        ss.WriteString(ServerMessage);
                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
#if (MPTV2)
                    else if (MessageFromClient.StartsWith(PipeCommands.WriteSetting.ToString()) == true)
                    {
                        string tag = MessageFromClient.Replace(PipeCommands.WriteSetting.ToString(), string.Empty);
                        string[] tags = tag.Split('\n');
                        ServiceAgents.Instance.SettingServiceAgent.SaveValue(tags[0], tags[1]);

                        ServerMessage = "SUCCESS";
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadSetting.ToString()) == true)
                    {
                        string tag = MessageFromClient.Replace(PipeCommands.ReadSetting.ToString(), string.Empty);
                        Log.Debug("tag="+tag);
                        string value = ServiceAgents.Instance.SettingServiceAgent.GetValue(tag, string.Empty);
                        Log.Debug("value=" + value);
                        ServerMessage = value;
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllCards.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        ServerMessage = string.Empty;
                        foreach (Card mycard in Card.ListAll())
                        {
                            ServerMessage += mycard.IdCard.ToString() + "\n" + mycard.Name + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }                  
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllChannelsByGroup.ToString()) == true)
                    {
                        string groupIdString = MessageFromClient.Replace(PipeCommands.ReadAllChannelsByGroup.ToString(), string.Empty);
                        Log.Debug("groupIdString="+groupIdString);
                        int groupId = -1;
                        int.TryParse(groupIdString, out groupId);
                        Log.Debug("groupId=" + groupId.ToString());

                        ServerMessage = string.Empty;
                        foreach (Channel mychannel in Channel.ListAllByGroup(groupId))
                        {
                            ServerMessage += mychannel.IdChannel.ToString() + "\n" + mychannel.DisplayName + "\n";
                        }
                        Log.Debug("Groupchannels=" + ServerMessage);
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllChannels.ToString()) == true)//must be after ReadAllChannelsByGroup
                    {
                        ServerMessage = string.Empty;
                        foreach (Channel mychannel in Channel.ListAll())
                        {
                            ServerMessage += mychannel.IdChannel.ToString() + "\n" + mychannel.DisplayName + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRadioChannelsByGroup.ToString()) == true)
                    {
                        string groupIdString = MessageFromClient.Replace(PipeCommands.ReadAllRadioChannelsByGroup.ToString(), string.Empty);
                        Log.Debug("radiogroupIdString=" + groupIdString);
                        int groupId = -1;
                        int.TryParse(groupIdString, out groupId);
                        Log.Debug("radiogroupId=" + groupId.ToString());

                        ServerMessage = string.Empty;
                        foreach (RadioChannel myradiochannel in RadioChannel.ListAllByGroup(groupId))
                        {
                            ServerMessage += myradiochannel.Id.ToString() + "\n" + myradiochannel.Name + "\n";
                        }
                        Log.Debug("radioGroupchannels=" + ServerMessage);
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRadioChannels.ToString()) == true)//must be after ReadAllRadioChannelsByGroup
                    {
                        ServerMessage = string.Empty;
                        foreach (RadioChannel myradiochannel in RadioChannel.ListAll())
                        {
                            ServerMessage += myradiochannel.Id.ToString() + "\n" + myradiochannel.Name + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllChannelGroups.ToString()) == true)
                    {
                        ServerMessage = string.Empty;
                        foreach (ChannelGroup mygroup in ChannelGroup.ListAll())
                        {
                            ServerMessage += mygroup.Id.ToString() + "\n" + mygroup.GroupName + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRadioChannelGroups.ToString()) == true)
                    {
                        ServerMessage = string.Empty;
                        foreach (RadioChannelGroup myradiogroup in RadioChannelGroup.ListAll())
                        {
                            ServerMessage += myradiogroup.Id.ToString() + "\n" + myradiogroup.GroupName + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRecordings.ToString()) == true)
                    {
                        ServerMessage = string.Empty;
                        foreach (Recording myrecording in Recording.ListAll())
                        {
                            ServerMessage += myrecording.IdRecording.ToString() + "\n" + myrecording.Title + "\n"+myrecording.FileName + "\n" +
                                             myrecording.IdChannel.ToString() + "\n" + myrecording.StartTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) +
                                             "\n" + myrecording.EndTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllSchedules.ToString()) == true)
                    {
                        ServerMessage = string.Empty;
                        foreach (Schedule myschedule in Schedule.ListAll())
                        {
                            ServerMessage += myschedule.IdSchedule.ToString() + "\n" + myschedule.ProgramName + "\n" + 
                                             myschedule.IdChannel.ToString() + "\n" + myschedule.StartTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) +
                                             "\n" + myschedule.EndTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n" +
                                             myschedule.ScheduleType.ToString() + "\n" + myschedule.PreRecordInterval.ToString() + "\n" +
                                             myschedule.PostRecordInterval.ToString() + "\n" + myschedule.MaxAirings.ToString() + "\n" +
                                             myschedule.KeepDate.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n" +
                                             myschedule.KeepMethod.ToString() + "\n" + myschedule.Priority.ToString() + "\n" +
                                             myschedule.PreRecordInterval.ToString() + "\n" + myschedule.Series.ToString() + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ScheduleDelete.ToString()) == true)
                    {
                        string scheduleIdString = MessageFromClient.Replace(PipeCommands.ScheduleDelete.ToString(), string.Empty);
                        Log.Debug("scheduleIdString=" + scheduleIdString);
                        int scheduleId = -1;
                        int.TryParse(scheduleIdString, out scheduleId);
                        Log.Debug("scheduleId=" + scheduleId.ToString());
                        Schedule.Delete(scheduleId);
                        
                        //65000 max chars                        
                        ss.WriteString("Deleted");
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ScheduleNew.ToString()) == true)
                    {
                        string schedule = MessageFromClient.Replace(PipeCommands.ScheduleNew.ToString(), string.Empty);
                        string[] scheduletags = schedule.Split('\n');

                        int idChannel = -1;
                        int.TryParse(scheduletags[1], out idChannel);
                        DateTime start = DateTime.ParseExact(scheduletags[2], "yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture);
                        DateTime end = DateTime.ParseExact(scheduletags[3], "yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture);

                        Schedule myschedule = new Schedule(idChannel, scheduletags[0], start, end);
                        myschedule.Persist();
                        

                        ServerMessage = "SUCCESS";
                        ss.WriteString(ServerMessage);
                    }

#endif

                    else //Unknown command
                    {
                        Logdebug("sending response " + PipeCommands.UnknownCommand.ToString());
                        ss.WriteString(PipeCommands.UnknownCommand.ToString());
                    }
                    
                }
                // Catch the IOException that is raised if the pipe is broken
                // or disconnected.
                catch (IOException e)
                {
                    Log.Error("ServerThread ERROR: " + e.Message);
                }
                catch (Exception e)
                {
                    Log.Error("ServerThread ERROR: " + e.Message);
                }

                if (pipeServer != null)
                {
                    if (pipeServer.IsConnected)
                        pipeServer.Disconnect();

                    pipeServer.Close();
                    pipeServer.Dispose();
                    pipeServer = null;
                }
                Logdebug("Connection closed");

            }

            Logdebug("Pipe Server Thread Completed");
        }
        /// <summary>
        /// Instantiates an endpoint to act as a client
        /// </summary>
        /// <param name="pipeName">The name of the pipe to which we should connect.</param>
        internal void InternalConstruct(string pipeName)
        {
            ErrorUtilities.VerifyThrowArgumentLength(pipeName, "pipeName");

            _debugCommunications = (Environment.GetEnvironmentVariable("MSBUILDDEBUGCOMM") == "1");

            _status = LinkStatus.Inactive;
            _asyncDataMonitor = new object();
            _sharedReadBuffer = InterningBinaryReader.CreateSharedBuffer();

            SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner;
            PipeSecurity security = new PipeSecurity();

            // Restrict access to just this account.  We set the owner specifically here, and on the
            // pipe client side they will check the owner against this one - they must have identical
            // SIDs or the client will reject this server.  This is used to avoid attacks where a
            // hacked server creates a less restricted pipe in an attempt to lure us into using it and 
            // then sending build requests to the real pipe client (which is the MSBuild Build Manager.)
            PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.ReadWrite, AccessControlType.Allow);
            security.AddAccessRule(rule);
            security.SetOwner(identifier);

            _pipeServer = new NamedPipeServerStream
                (
                pipeName,
                PipeDirection.InOut,
                1, // Only allow one connection at a time.
                PipeTransmissionMode.Byte,
                PipeOptions.Asynchronous | PipeOptions.WriteThrough,
                PipeBufferSize, // Default input buffer
                PipeBufferSize, // Default output buffer
                security,
                HandleInheritability.None
                );
        }
        /// <summary>
        /// Mains this instance.
        /// </summary>
        /// <remarks></remarks>
        private Task Main()
        {
            if (_isRunning) {
                return _engineService;
            }
            var npmi = NewPackageManager.Instance;

            _cancellationTokenSource = new CancellationTokenSource();
            _isRunning = true;

            // make sure coapp is properly set up.
            Task.Factory.StartNew(() => {
                try {
                    Logger.Warning("Gonna make sure stuff is setup right.");
                    // this ensures that composition rules are run for toolkit.
                    Package.EnsureCanonicalFoldersArePresent();

                    Logger.Warning("Getting Version of CoApp.");
                    var v = Package.GetCurrentPackageVersion("coapp.toolkit", "820d50196d4e8857");
                    Logger.Warning("CoApp Version : " + v);
                } catch (Exception e ) {
                    Logger.Error(e);
                }
            });

            _engineService = Task.Factory.StartNew(() => {
                _pipeSecurity = new PipeSecurity();
                _pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid,null ), PipeAccessRights.ReadWrite, AccessControlType.Allow));
                _pipeSecurity.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().Owner, PipeAccessRights.FullControl, AccessControlType.Allow));

                // start a few listeners by default--each listener will also spawn a new empty one.
                StartListener();
                StartListener();
                StartListener();
                StartListener();
                StartListener();
                StartListener();

            }, _cancellationTokenSource.Token).AutoManage();

            _engineService = _engineService.ContinueWith(antecedent => {
                _isRunning = false;
                // ensure the sessions are all getting closed.
                Session.CancelAll();
                _engineService = null;
            }, TaskContinuationOptions.AttachedToParent).AutoManage();
            return _engineService;
        }
        /*
        *METHOD		    :	btn_submit_Click
        *
        *DESCRIPTION	:	used to send the new question to the service when submit clicked
        *
        *PARAMETERS		:	object sender:  Object relaying information on where the event call came from
        *                   EventArgs e:    Object that contains data about the event
        *
        *RETURNS		:	void
        *
        */
        private void btn_submit_Click(object sender, EventArgs e)
        {
            if (txtbx_server.Text.Length > 0 && txtbx_name.Text.Length > 0)
            {
                try
                {
                    userName = txtbx_name.Text;
                    serverName = txtbx_server.Text;
                    //set up the named pipe security
                    PipeSecurity ps = new PipeSecurity();
                    System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
                    PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
                    ps.AddAccessRule(par);

                    //connect to service
                    client = new NamedPipeClientStream(serverName, "ServiceOutgoing");//add server name
                    client.Connect(30);
                    output = new StreamWriter(client);

                    //tell ther service this computers name
                    output.WriteLine(Environment.MachineName);
                    output.Flush();

                    server = new NamedPipeServerStream("UserOutgoing", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 5000, 5000, ps);
                    server.WaitForConnection();
                    input = new StreamReader(server);

                    //get namedPipe Name
                    pipeName = input.ReadLine();

                    server.Disconnect();
                    server.Dispose();
                    Close();
                }
                catch (Exception)
                {
                    MessageBox.Show("Failed to connect to Server", "Error");
                }
            }
        }
Exemple #21
0
        /// <summary>
        /// Checks to see if memory is available, and if it is creates a new
        /// Connection object, awaits the completion of the connection, then
        /// runs <see cref="ConnectionCompleted"/> for cleanup.
        /// </summary>
        private async Task DispatchConnection(NamedPipeServerStream pipeStream)
        {
            try
            {
                // There is always a race between timeout and connections because
                // there is no way to cancel listening on the pipe without
                // closing the pipe. We immediately increment the connection
                // semaphore while processing connections in order to narrow
                // the race window as much as possible.
                Interlocked.Increment(ref this.activeConnectionCount);

                if (Environment.Is64BitProcess || MemoryHelper.IsMemoryAvailable())
                {
                    CompilerServerLogger.Log("Memory available - accepting connection");

                    Connection connection = new Connection(pipeStream, handler);

                    await connection.ServeConnection().ConfigureAwait(false);

                    // The connection should be finished
                    ConnectionCompleted(connection);
                }
                else
                {
                    CompilerServerLogger.Log("Memory tight - rejecting connection.");
                    // As long as we haven't written a response, the client has not 
                    // committed to this server instance and can look elsewhere.
                    pipeStream.Close();

                    // We didn't create a connection -- decrement the semaphore
                    Interlocked.Decrement(ref this.activeConnectionCount);

                    // Start a terminate server timer if there are no active
                    // connections
                    StartTimeoutTimerIfNecessary();
                }
            }
            catch (Exception e) if (CompilerFatalError.Report(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

        /// <summary>
        /// Create an instance of the pipe. This might be the first instance, or a subsequent instance.
        /// There always needs to be an instance of the pipe created to listen for a new client connection.
        /// </summary>
        /// <returns>The pipe instance, or NULL if the pipe couldn't be created..</returns>
        private NamedPipeServerStream ConstructPipe()
        {
            // Add the process ID onto the pipe name so each process gets a unique pipe name.
            // The client must user this algorithm too to connect.
            string pipeName = basePipeName + Process.GetCurrentProcess().Id.ToString();

            try
            {
                CompilerServerLogger.Log("Constructing pipe '{0}'.", pipeName);

                SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner;
                PipeSecurity security = new PipeSecurity();

                // Restrict access to just this account.  
                PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow);
                security.AddAccessRule(rule);
                security.SetOwner(identifier);

                NamedPipeServerStream pipeStream = new NamedPipeServerStream(
                    pipeName,
                    PipeDirection.InOut,
                    NamedPipeServerStream.MaxAllowedServerInstances, // Maximum connections.
                    PipeTransmissionMode.Byte,
                    PipeOptions.Asynchronous | PipeOptions.WriteThrough,
                    PipeBufferSize, // Default input buffer
                    PipeBufferSize, // Default output buffer
                    security,
                    HandleInheritability.None);

                CompilerServerLogger.Log("Successfully constructed pipe '{0}'.", pipeName);

                return pipeStream;
            }
            catch (Exception e)
            {
                // Windows may not create the pipe for a number of reasons.
                CompilerServerLogger.LogException(e, string.Format("Construction of pipe '{0}' failed", pipeName));
                return null;
            }
        }
        public CommServer(ICommServerImpl callbacks)
            : base(callbacks)
        {
            int numsecretbytes=16;
            byte[] secretbytes = new byte[numsecretbytes];
            RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();
            int i;
            rnd.GetBytes(secretbytes);
            secret="";
            for (i = 0; i < numsecretbytes; i++)
            {
                secret = secret + String.Format("{0:x2}", secretbytes[i]);
            }
            PipeSecurity sec = new PipeSecurity();
            sec.AddAccessRule(
                    new PipeAccessRule(
                        new System.Security.Principal.SecurityIdentifier(
                            System.Security.Principal.WellKnownSidType.WorldSid,
                            null),
                        PipeAccessRights.ReadWrite,
                        System.Security.AccessControl.AccessControlType.Allow));
            sec.AddAccessRule(new PipeAccessRule(System.Security.Principal.WindowsIdentity.GetCurrent().Name, PipeAccessRights.FullControl,
                System.Security.AccessControl.AccessControlType.Allow));

            Pipe = new NamedPipeServerStream(PIPENAME,
                PipeDirection.InOut, 1, PipeTransmissionMode.Byte,
                PipeOptions.Asynchronous, 1024*1024, 1024*1024, sec);
            SetPipe(Pipe);
            this.callbacks = callbacks;
            Pipe.BeginWaitForConnection(HandleConnected, this);
        }
Exemple #23
0
        static void HandleQueueThread(Object stateInfo)
        {
            // the pipe here will be handled synchronously
            NewQueueToken token = (NewQueueToken)stateInfo;
            string pipename = token.queueName;
            System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
            PipeAccessRule pac = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
            PipeSecurity ps = new PipeSecurity();
            ps.AddAccessRule(pac);
            sid = null;

            using (NamedPipeServerStream queuePipe = new NamedPipeServerStream(pipename,
                    PipeDirection.InOut,
                    serverInstances,
                    PipeTransmissionMode.Message,
                    PipeOptions.None,
                    1024,
                    1024,
                    ps))
            {                Console.WriteLine("pipe {0} created, waiting..", token.queueName);
                // inform the main thread that the queue is on
                token.semaphore.Set();
                if (token.abort)
                    return;
                queuePipe.WaitForConnection();
                Console.WriteLine("pipe {0} connected", token.queueName);
                StreamReader reader = new StreamReader(queuePipe);
                StreamWriter writer = new StreamWriter(queuePipe);
                try
                {
                    MonitorMessage messageIn;
                    // step 1: enable counters
                    char[] data = new char[1024];
                    for (int i = 0; i < data.Length; i++)
                        data[i] = (char)0;
                    reader.ReadBlock(data, 0, data.Length);
                    messageIn = MonitorMessage.ParseFromString(new String(data));
                    Console.WriteLine("pipe {0} received {1}", token.queueName, messageIn.ToString());

                    if (messageIn.OpCode != OpCodes.ENABLE_COUNTERS_MESSAGE)
                        throw new InvalidOperationException("I was expeting an Enumerate Counters message and received " + messageIn.OpCode.ToString());
                    // counters
                    List<string> countersList = new List<string>(messageIn.Body);
                    // list of counters to enable
                    // TODO: how to get selectedCounters?
                    if (token.selectCounter != null)
                    {
                        string[] selectedCounters = token.selectCounter(token.DeviceId, countersList.ToArray());
                        writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 0, 0, selectedCounters.Select(x => countersList.IndexOf(x)).ToArray()).ToString());
                        writer.Flush();
                    }
                    else
                    {
                        // delegate not set!
                        writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 0, 0, new int[] { }).ToString());
                        writer.Flush();
                    }
                    // step 2:perf init
                    for (int i = 0; i < data.Length; i++)
                        data[i] = (char)0;
                    reader.ReadBlock(data, 0, data.Length);
                    messageIn = MonitorMessage.ParseFromString(new String(data));
                    Console.WriteLine("pipe {0} received {1}", token.queueName, messageIn.ToString());
                    if (messageIn.OpCode != OpCodes.GPU_PERF_INIT_MESSAGE)
                        throw new InvalidOperationException("I was expeting an Perf init message and received " + messageIn.OpCode.ToString());
                    writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 0, 0).ToString());
                    writer.Flush();

                    // step 3: release
                    for (int i = 0; i < data.Length; i++)
                        data[i] = (char)0;
                    reader.ReadBlock(data, 0, data.Length);
                    messageIn = MonitorMessage.ParseFromString(new String(data));
                    if (messageIn.OpCode != OpCodes.RELEASE_QUEUE_MESSAGE)
                        throw new InvalidOperationException("I was expeting a release message and received " + messageIn.OpCode.ToString());
                    writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 0, 0).ToString());
                    writer.Flush();

                    // step 5: end
                    for (int i = 0; i < data.Length; i++)
                        data[i] = (char)0;
                    reader.ReadBlock(data, 0, data.Length);
                    messageIn = MonitorMessage.ParseFromString(new String(data));
                    Console.WriteLine("pipe {0} received {1}", token.queueName, messageIn.ToString());
                    if (messageIn.OpCode != OpCodes.GPU_PERF_RELEASE_MESSAGE)
                        throw new InvalidOperationException("I was expeting an End message and received " + messageIn.OpCode.ToString());
                    writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 0, 0).ToString());
                    writer.Flush();

                    // step 4: get counters
                    for (int i = 0; i < data.Length; i++)
                        data[i] = (char)0;
                    reader.ReadBlock(data, 0, data.Length);
                    messageIn = MonitorMessage.ParseFromString(new String(data));
                    Console.WriteLine("pipe {0} received {1}", token.queueName, messageIn.ToString());
                    if (messageIn.OpCode != OpCodes.GET_COUNTERS_MESSAGE)
                        throw new InvalidOperationException("I was expeting a Get Counters message and received " + messageIn.OpCode.ToString());
                    float[] values = messageIn.BodyAsFloatArray;
                    // TODO: send values
                    if (token.receivedValues != null)
                    {
                        token.receivedValues(token.DeviceId, values);
                    }

                    writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 0, 0).ToString());
                    writer.Flush();

                }
                // Catch the IOException that is raised if the pipe is broken
                // or disconnected.
                catch (IOException e)
                {
                    Console.WriteLine("ERROR: {0}", e.Message);
                }
                catch (InvalidOperationException e)
                {
                    // TODO: what is the code for invalid operation?
                    writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 1, 1).ToString());
                    writer.Flush();
                }
                finally
                {
                    queuePipe.Close();
                }
            }
        }
        /// <summary>
        /// Create an instance of the pipe. This might be the first instance, or a subsequent instance.
        /// There always needs to be an instance of the pipe created to listen for a new client connection.
        /// </summary>
        /// <returns>The pipe instance or throws an exception.</returns>
        private NamedPipeServerStream ConstructPipe(string pipeName)
        {
            CompilerServerLogger.Log("Constructing pipe '{0}'.", pipeName);

            SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner;
            PipeSecurity security = new PipeSecurity();

            // Restrict access to just this account.  
            PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow);
            security.AddAccessRule(rule);
            security.SetOwner(identifier);

            NamedPipeServerStream pipeStream = new NamedPipeServerStream(
                pipeName,
                PipeDirection.InOut,
                NamedPipeServerStream.MaxAllowedServerInstances, // Maximum connections.
                PipeTransmissionMode.Byte,
                PipeOptions.Asynchronous | PipeOptions.WriteThrough,
                PipeBufferSize, // Default input buffer
                PipeBufferSize, // Default output buffer
                security,
                HandleInheritability.None);

            CompilerServerLogger.Log("Successfully constructed pipe '{0}'.", pipeName);

            return pipeStream;
        }
Exemple #25
0
        /// <summary>
        /// Default Constructor
        /// </summary>
        /// <param name="options">the pipe options</param>
        public IpcPipe(IpcPipeOps options)
        {
            if (options == null)
                options = IpcPipeOps.defaultIpcPIpeOps;
            if (options.m_callBackObj != null)
                throw new ArgumentException("callBackObj is null!");
            lock (m_generalLock)
            {
                m_options = options;
                if (options.m_numOfWriteBytes == 0)
                    m_options.m_numOfWriteBytes = IpcConf.DEFAULT_WRITE_BUF_SIZE;
                if (options.m_numOfReadBytes == 0)
                    m_options.m_numOfReadBytes = IpcConf.DEFAULT_READ_BUF_SIZE;

            }
            m_readBuffer = new byte[m_options.m_numOfReadBytes];
             // Provide full access to the current user so more pipe instances can be created
            m_ps = new PipeSecurity();
            m_ps.AddAccessRule(
                new PipeAccessRule(WindowsIdentity.GetCurrent().User, PipeAccessRights.FullControl, AccessControlType.Allow)
            );
            m_ps.AddAccessRule(
                new PipeAccessRule(
                    new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow
                )
            );
        }
Exemple #26
0
        private void ServerThread()
        {
            PipeSecurity security = new PipeSecurity();

            using (WindowsIdentity myself = WindowsIdentity.GetCurrent())
            {
                try
                {
                    // Anyone can talk to us
                    LibraryLogging.Debug("Setting PipeAccess R/W for world: {0}", Abstractions.Windows.Security.GetWellknownSID(WellKnownSidType.WorldSid));
                    security.AddAccessRule(new PipeAccessRule(Abstractions.Windows.Security.GetWellknownSID(WellKnownSidType.WorldSid), PipeAccessRights.ReadWrite, AccessControlType.Allow));

                    // But only we have full control (including the 'create' right, which allows us to be the server side of this equation)
                    LibraryLogging.Debug("Setting PipeAccess FullControl for myself: {0}", WindowsIdentity.GetCurrent().Name);
                    security.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().Owner, PipeAccessRights.FullControl, AccessControlType.Allow));
                }
                catch (Exception e)
                {
                    LibraryLogging.Error("Unable to set all pipe access rules, the security of the Toopher service pipe is in an unknown state!: {0}", e);
                }
            }

            while (Running)
            {
                try
                {
                    using (NamedPipeServerStream pipeServer = new NamedPipeServerStream(Name, PipeDirection.InOut, MaxClients,
                            PipeTransmissionMode.Byte, PipeOptions.WriteThrough, 0, 0, security, HandleInheritability.None))
                    {
                        try
                        {
                            pipeServer.WaitForConnection();
                        }
                        catch (Exception e)
                        {
                            LibraryLogging.Error("Error in server connection handler: {0}", e);
                            continue;
                        }

                        // Handle this connection, note that we always expect client to initiate the
                        //  flow of messages, so we do not include an initial message
                        HandlePipeConnection(pipeServer, null);
                    }
                }
                catch (Exception e)
                {
                    LibraryLogging.Error("Error while trying to open pipe server: {0}", e);
                    Thread.Sleep(500);
                }
            }
        }
Exemple #27
0
        // This overload is used in Mono to implement public constructors.
        private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                            PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                            PipeSecurity?pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights)
        {
            Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty");
            Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
            Debug.Assert(inBufferSize >= 0, "inBufferSize is negative");
            Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
            Debug.Assert((maxNumberOfServerInstances >= 1 && maxNumberOfServerInstances <= 254) || (maxNumberOfServerInstances == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
            Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");

            string fullPipeName = Path.GetFullPath(@"\\.\pipe\" + pipeName);

            // Make sure the pipe name isn't one of our reserved names for anonymous pipes.
            if (string.Equals(fullPipeName, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved);
            }

            if (IsCurrentUserOnly)
            {
                Debug.Assert(pipeSecurity == null);

                using (WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent())
                {
                    SecurityIdentifier identifier = currentIdentity.Owner !;

                    // Grant full control to the owner so multiple servers can be opened.
                    // Full control is the default per MSDN docs for CreateNamedPipe.
                    PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.FullControl, AccessControlType.Allow);
                    pipeSecurity = new PipeSecurity();

                    pipeSecurity.AddAccessRule(rule);
                    pipeSecurity.SetOwner(identifier);
                }

                // PipeOptions.CurrentUserOnly is special since it doesn't match directly to a corresponding Win32 valid flag.
                // Remove it, while keeping others untouched since historically this has been used as a way to pass flags to CreateNamedPipe
                // that were not defined in the enumeration.
                options &= ~PipeOptions.CurrentUserOnly;
            }

            int openMode = ((int)direction) |
                           (maxNumberOfServerInstances == 1 ? Interop.Kernel32.FileOperations.FILE_FLAG_FIRST_PIPE_INSTANCE : 0) |
                           (int)options |
                           (int)additionalAccessRights;

            // We automatically set the ReadMode to match the TransmissionMode.
            int pipeModes = (int)transmissionMode << 2 | (int)transmissionMode << 1;

            // Convert -1 to 255 to match win32 (we asserted that it is between -1 and 254).
            if (maxNumberOfServerInstances == MaxAllowedServerInstances)
            {
                maxNumberOfServerInstances = 255;
            }

            GCHandle pinningHandle = default;

            try
            {
                Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability, pipeSecurity, ref pinningHandle);
                SafePipeHandle handle = Interop.Kernel32.CreateNamedPipe(fullPipeName, openMode, pipeModes,
                                                                         maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, ref secAttrs);

                if (handle.IsInvalid)
                {
                    throw Win32Marshal.GetExceptionForLastWin32Error();
                }

                InitializeHandle(handle, false, (options & PipeOptions.Asynchronous) != 0);
            }
            finally
            {
                if (pinningHandle.IsAllocated)
                {
                    pinningHandle.Free();
                }
            }
        }
Exemple #28
0
        /// <summary>
        ///   Mains this instance.
        /// </summary>
        /// <remarks>
        /// </remarks>
        private Task Main()
        {
            if (IsRunning) {
                return _engineTask;
            }
            Signals.EngineStartupStatus = 0;

            if (!IsInteractive) {
                EngineServiceManager.EnsureServiceAclsCorrect();
            }

            var npmi = PackageManagerImpl.Instance;

            _cancellationTokenSource = new CancellationTokenSource();
            _isRunning = true;

            Signals.StartingUp = true;
            // make sure coapp is properly set up.
            Task.Factory.StartNew(() => {
                try {
                    Logger.Warning("CoApp Startup Beginning------------------------------------------");

                    // this ensures that composition rules are run for toolkit.
                    Signals.EngineStartupStatus = 5;
                    EnsureCanonicalFoldersArePresent();
                    Signals.EngineStartupStatus = 10;
                    var v = Package.GetCurrentPackageVersion(CanonicalName.CoAppItself);
                    if( v > 0 ) {
                        var p = InstalledPackageFeed.Instance.FindPackages(CanonicalName.CoAppItself).HighestPackages().FirstOrDefault();
                        if( p != null ) {
                            p.DoPackageComposition();
                        }
                    }
                    Signals.EngineStartupStatus = 95;
                    Logger.Warning("CoApp Version : " + v);

                    /*
                     * what can we do if the right version isn't here?
                     *
                    FourPartVersion thisVersion = Assembly.GetExecutingAssembly().Version();
                    if( thisVersion > v ) {

                    }
                     * */

                    // Completes startup.

                    Signals.EngineStartupStatus = 100;
                    Signals.Available = true;
                    Logger.Warning("CoApp Startup Finished------------------------------------------");
                } catch (Exception e) {
                    Logger.Error(e);
                    RequestStop();
                }
            });

            _engineTask = Task.Factory.StartNew(() => {
                _pipeSecurity = new PipeSecurity();
                _pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow));
                _pipeSecurity.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().Owner, PipeAccessRights.FullControl, AccessControlType.Allow));

                // start a few listeners by default--each listener will also spawn a new empty one.
                StartListener();
                StartListener();
            }, _cancellationTokenSource.Token).AutoManage();

            _engineTask = _engineTask.ContinueWith(antecedent => {
                RequestStop();
                // ensure the sessions are all getting closed.
                Session.CancelAll();
                _engineTask = null;
            }, TaskContinuationOptions.AttachedToParent).AutoManage();
            return _engineTask;
        }
Exemple #29
0
 void NewServerThread(string cachedir)
 {
     var t = new Thread(new ParameterizedThreadStart(ConnectionThreadFn));
     t.IsBackground = true;
     serverThreads.Add(t);
     var nss = new NamedPipeServerStream(MakePipeName(cachedir), PipeDirection.InOut, MaxServerThreads, PipeTransmissionMode.Message, PipeOptions.WriteThrough | PipeOptions.Asynchronous);
     if (Settings.PipeSecurityEveryone) {
         var npa = new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
         var nps = new PipeSecurity();
         nps.AddAccessRule(npa);
         nss.SetAccessControl(nps);
     }
     t.Start(nss);
     Logging.Emit("server thread started");
 }
Exemple #30
0
 private void ServerMain()
 {
     while (pipeServer.ThreadState != System.Threading.ThreadState.AbortRequested)
        {
     PipeSecurity security = new PipeSecurity();
     security.AddAccessRule(new PipeAccessRule(
      WindowsIdentity.GetCurrent().User,
      PipeAccessRights.FullControl, AccessControlType.Allow));
     using (NamedPipeServerStream server = new NamedPipeServerStream(instanceID,
      PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous,
      128, 128, security))
     {
      ServerAsyncInfo async = new ServerAsyncInfo();
      async.Server = server;
      async.WaitHandle = new AutoResetEvent(false);
      IAsyncResult result = server.BeginWaitForConnection(WaitForConnection, async);
      if (result.AsyncWaitHandle.WaitOne())
       async.WaitHandle.WaitOne();
     }
        }
 }
Exemple #31
-1
        public static void Start()
        {
            if (pipeServer != null)
                throw new InvalidOperationException("Server already started. First call Close.");

            PipeSecurity ps = new PipeSecurity();
            PipeAccessRule par = new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
            ps.AddAccessRule(par);

            pipeServer = new NamedPipeServerStream(SERVERNAME,
                PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 4096, 4096, ps);

            Log.Write("NamedPipeServerStream object created, waiting for client connection...");
            pipeServer.BeginWaitForConnection(onReceive, new object());
        }