internal RemoteRunspacePoolInternal(int minRunspaces, int maxRunspaces, TypeTable typeTable, PSHost host, PSPrimitiveDictionary applicationArguments, RunspaceConnectionInfo connectionInfo, string name = null) : base(minRunspaces, maxRunspaces) { this.applicationPrivateDataReceived = new ManualResetEvent(false); this.friendlyName = string.Empty; if (connectionInfo == null) { throw PSTraceSource.NewArgumentNullException("WSManConnectionInfo"); } PSEtwLog.LogOperationalVerbose(PSEventId.RunspacePoolConstructor, PSOpcode.Constructor, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, new object[] { this.instanceId.ToString(), this.minPoolSz.ToString(CultureInfo.InvariantCulture), this.maxPoolSz.ToString(CultureInfo.InvariantCulture) }); if (connectionInfo is WSManConnectionInfo) { this.connectionInfo = ((WSManConnectionInfo) connectionInfo).Copy(); } else if (connectionInfo is NewProcessConnectionInfo) { this.connectionInfo = ((NewProcessConnectionInfo) connectionInfo).Copy(); } base.host = host; this.applicationArguments = applicationArguments; this.availableForConnection = false; this.dispatchTable = new DispatchTable<object>(); if (!string.IsNullOrEmpty(name)) { this.Name = name; } this.CreateDSHandler(typeTable); }
private PSSenderInfo(SerializationInfo info, StreamingContext context) { if (info != null) { string source = null; try { source = info.GetValue("CliXml", typeof(string)) as string; } catch (Exception) { return; } if (source != null) { try { PSSenderInfo info2 = DeserializingTypeConverter.RehydratePSSenderInfo(PSObject.AsPSObject(PSSerializer.Deserialize(source))); this.userPrinicpal = info2.userPrinicpal; this.clientTimeZone = info2.ClientTimeZone; this.connectionString = info2.connectionString; this.applicationArguments = info2.applicationArguments; } catch (Exception) { return; } } } }
internal RemoteRunspace(TypeTable typeTable, RunspaceConnectionInfo connectionInfo, PSHost host, PSPrimitiveDictionary applicationArguments, string name = null, int id = -1) { this._runningPipelines = new ArrayList(); this._syncRoot = new object(); this._runspaceStateInfo = new System.Management.Automation.Runspaces.RunspaceStateInfo(RunspaceState.BeforeOpen); this._version = PSVersionInfo.PSVersion; this._runspaceEventQueue = new Queue <RunspaceEventQueueItem>(); this.id = -1; PSEtwLog.SetActivityIdForCurrentThread(base.InstanceId); this._applicationArguments = applicationArguments; PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceConstructor, PSOpcode.Constructor, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, new object[] { base.InstanceId.ToString() }); if (connectionInfo is WSManConnectionInfo) { this._connectionInfo = ((WSManConnectionInfo)connectionInfo).Copy(); this._originalConnectionInfo = ((WSManConnectionInfo)connectionInfo).Copy(); } else if (connectionInfo is NewProcessConnectionInfo) { this._connectionInfo = ((NewProcessConnectionInfo)connectionInfo).Copy(); this._originalConnectionInfo = ((NewProcessConnectionInfo)connectionInfo).Copy(); } this._runspacePool = new System.Management.Automation.Runspaces.RunspacePool(1, 1, typeTable, host, applicationArguments, connectionInfo, name); this.Id = id; this.SetEventHandlers(); }
internal RemoteRunspace(TypeTable typeTable, RunspaceConnectionInfo connectionInfo, PSHost host, PSPrimitiveDictionary applicationArguments, string name = null, int id = -1) { this._runningPipelines = new ArrayList(); this._syncRoot = new object(); this._runspaceStateInfo = new System.Management.Automation.Runspaces.RunspaceStateInfo(RunspaceState.BeforeOpen); this._version = PSVersionInfo.PSVersion; this._runspaceEventQueue = new Queue<RunspaceEventQueueItem>(); this.id = -1; PSEtwLog.SetActivityIdForCurrentThread(base.InstanceId); this._applicationArguments = applicationArguments; PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceConstructor, PSOpcode.Constructor, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, new object[] { base.InstanceId.ToString() }); if (connectionInfo is WSManConnectionInfo) { this._connectionInfo = ((WSManConnectionInfo) connectionInfo).Copy(); this._originalConnectionInfo = ((WSManConnectionInfo) connectionInfo).Copy(); } else if (connectionInfo is NewProcessConnectionInfo) { this._connectionInfo = ((NewProcessConnectionInfo) connectionInfo).Copy(); this._originalConnectionInfo = ((NewProcessConnectionInfo) connectionInfo).Copy(); } this._runspacePool = new System.Management.Automation.Runspaces.RunspacePool(1, 1, typeTable, host, applicationArguments, connectionInfo, name); this.Id = id; this.SetEventHandlers(); }
internal static RemoteDataObject GenerateApplicationPrivateData( Guid clientRunspacePoolId, PSPrimitiveDictionary applicationPrivateData) { using (RemotingEncoder._trace.TraceMethod()) { PSObject emptyPsObject = RemotingEncoder.CreateEmptyPSObject(); emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("ApplicationPrivateData", (object)applicationPrivateData)); return(RemoteDataObject.CreateFrom(RemotingDestination.Client, RemotingDataType.ApplicationPrivateData, clientRunspacePoolId, Guid.Empty, (object)emptyPsObject)); } }
internal void SendApplicationPrivateDataToClient(PSPrimitiveDictionary applicationPrivateData, RemoteSessionCapability serverCapability) { PSPrimitiveDictionary dictionary = PSPrimitiveDictionary.CloneAndAddPSVersionTable(applicationPrivateData); PSPrimitiveDictionary dictionary2 = (PSPrimitiveDictionary)dictionary["PSVersionTable"]; dictionary2["PSRemotingProtocolVersion"] = serverCapability.ProtocolVersion; dictionary2["SerializationVersion"] = serverCapability.SerializationVersion; dictionary2["PSVersion"] = serverCapability.PSVersion; RemoteDataObject data = RemotingEncoder.GenerateApplicationPrivateData(this.clientRunspacePoolId, dictionary); this.SendDataAsync(data); }
internal ServerRunspacePoolDriver( Guid clientRunspacePoolId, int minRunspaces, int maxRunspaces, PSThreadOptions threadOptions, ApartmentState apartmentState, HostInfo hostInfo, InitialSessionState initialSessionState, PSPrimitiveDictionary applicationPrivateData, ConfigurationDataFromXML configData, AbstractServerSessionTransportManager transportManager, bool isAdministrator, RemoteSessionCapability serverCapability) { using (ServerRunspacePoolDriver.tracer.TraceConstructor((object)this)) { this.serverCapability = serverCapability; ServerRemoteHost serverRemoteHost = new ServerRemoteHost(clientRunspacePoolId, Guid.Empty, hostInfo, (AbstractServerTransportManager)transportManager); this.remoteHost = serverRemoteHost; this.configData = configData; this.applicationPrivateData = applicationPrivateData; this.localRunspacePool = RunspaceFactory.CreateRunspacePool(minRunspaces, maxRunspaces, initialSessionState, (PSHost)serverRemoteHost); PSThreadOptions psThreadOptions = configData.ShellThreadOptions.HasValue ? configData.ShellThreadOptions.Value : PSThreadOptions.UseCurrentThread; if (threadOptions == PSThreadOptions.Default || threadOptions == psThreadOptions) { this.localRunspacePool.ThreadOptions = psThreadOptions; } else { if (!isAdministrator) { throw new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(PSRemotingErrorId.MustBeAdminToOverrideThreadOptions)); } this.localRunspacePool.ThreadOptions = threadOptions; } ApartmentState apartmentState1 = configData.ShellThreadApartmentState.HasValue ? configData.ShellThreadApartmentState.Value : ApartmentState.Unknown; this.localRunspacePool.ApartmentState = apartmentState == ApartmentState.Unknown || apartmentState == apartmentState1 ? apartmentState1 : apartmentState; this.clientRunspacePoolId = clientRunspacePoolId; this.dsHandler = new ServerRunspacePoolDataStructureHandler(this, transportManager); this.localRunspacePool.StateChanged += new EventHandler <RunspacePoolStateChangedEventArgs>(this.HandleRunspacePoolStateChanged); this.localRunspacePool.ForwardEvent += new EventHandler <PSEventArgs>(this.HandleRunspacePoolForwardEvent); this.localRunspacePool.RunspaceCreated += new EventHandler <RunspaceCreatedEventArgs>(this.HandleRunspaceCreated); this.localRunspacePool.RunspaceCreated += new EventHandler <RunspaceCreatedEventArgs>(this.HandleRunspaceCreatedForTypeTable); this.dsHandler.CreateAndInvokePowerShell += new EventHandler <RemoteDataEventArgs <RemoteDataObject <PSObject> > >(this.HandleCreateAndInvokePowerShell); this.dsHandler.GetCommandMetadata += new EventHandler <RemoteDataEventArgs <RemoteDataObject <PSObject> > >(this.HandleGetCommandMetadata); this.dsHandler.HostResponseReceived += new EventHandler <RemoteDataEventArgs <RemoteHostResponse> >(this.HandleHostResponseReceived); this.dsHandler.SetMaxRunspacesReceived += new EventHandler <RemoteDataEventArgs <PSObject> >(this.HandleSetMaxRunspacesReceived); this.dsHandler.SetMinRunspacesReceived += new EventHandler <RemoteDataEventArgs <PSObject> >(this.HandleSetMinRunspacesReceived); this.dsHandler.GetAvailableRunspacesReceived += new EventHandler <RemoteDataEventArgs <PSObject> >(this.HandleGetAvailalbeRunspacesReceived); } }
public static RemoteRunspace FromPSObjectForRemoting(PSObject obj) { int id = RemotingDecoder.GetPropertyValue <int> (obj, "Id"); string name = RemotingDecoder.GetPropertyValue <string> (obj, "Name"); PSPrimitiveDictionary appArgs = RemotingDecoder.GetPropertyValue <PSPrimitiveDictionary> (obj, "ApplicationArguments"); string connectionInfoType = RemotingDecoder.GetPropertyValue <string> (obj, "ConnectionInfoType"); PSObject connectionObj = RemotingDecoder.GetPropertyValue <PSObject> (obj, "ConnectionInfo"); RunspaceConnectionInfo connectionInfo = null; if (connectionInfoType == "WSManConnectionInfo") { connectionInfo = WSManConnectionInfo.FromPSObjectForRemoting(connectionObj); } else { var securePassord = new System.Security.SecureString(); securePassord.AppendChar('z'); connectionInfo = new NewProcessConnectionInfo(new PSCredential("Anonymous", securePassord)); } var runspace = new RemoteRunspace(new TypeTable(), connectionInfo, null, appArgs, name, id); runspace._version = RemotingDecoder.GetPropertyValue <Version>(obj, "Version"); runspace.ApartmentState = RemotingDecoder.GetPropertyValue <ApartmentState>(obj, "ApartmentState"); runspace.InstanceId = RemotingDecoder.GetPropertyValue <Guid>(obj, "InstanceId"); runspace._shouldCloseOnPop = RemotingDecoder.GetPropertyValue <bool>(obj, "ShouldCloseOnPop"); runspace._runspaceStateInfo = new System.Management.Automation.Runspaces.RunspaceStateInfo(RemotingDecoder.GetPropertyValue <RunspaceState>(obj, "RunspaceStateInfo")); runspace._runspaceAvailability = RemotingDecoder.GetPropertyValue <RunspaceAvailability>(obj, "RunspaceAvailability"); runspace.ThreadOptions = RemotingDecoder.GetPropertyValue <PSThreadOptions>(obj, "ThreadOptions"); runspace.EngineActivityId = RemotingDecoder.GetPropertyValue <Guid>(obj, "EngineActivityId"); runspace._bSessionStateProxyCallInProgress = RemotingDecoder.GetPropertyValue <bool>(obj, "SessionStateProxyCallInProgress"); runspace._bypassRunspaceStateCheck = RemotingDecoder.GetPropertyValue <bool>(obj, "ByPassRunspaceStateCheck"); PSEtwLog.SetActivityIdForCurrentThread(runspace.InstanceId); string originalConnectionInfoType = RemotingDecoder.GetPropertyValue <string> (obj, "OriginalConnectionInfoType"); PSObject originalConnectionObj = RemotingDecoder.GetPropertyValue <PSObject> (obj, "OriginalConnectionInfo"); RunspaceConnectionInfo originalConnectionInfo = null; if (originalConnectionInfoType == "WSManConnectionInfo") { originalConnectionInfo = WSManConnectionInfo.FromPSObjectForRemoting(originalConnectionObj); } else { var securePassord = new System.Security.SecureString(); securePassord.AppendChar('z'); originalConnectionInfo = new NewProcessConnectionInfo(new PSCredential("Anonymous", securePassord)); } runspace._originalConnectionInfo = originalConnectionInfo; runspace.RunspacePool.RemoteRunspacePoolInternal.SetStateInfo(new RunspacePoolStateInfo(RunspacePoolState.Opened, null)); return(runspace); }
internal void SendApplicationPrivateDataToClient( PSPrimitiveDictionary applicationPrivateData, RemoteSessionCapability serverCapability) { using (ServerRunspacePoolDataStructureHandler.tracer.TraceMethod()) { PSPrimitiveDictionary applicationPrivateData1 = PSPrimitiveDictionary.CloneAndAddPSVersionTable(applicationPrivateData); PSPrimitiveDictionary primitiveDictionary = (PSPrimitiveDictionary)applicationPrivateData1["PSVersionTable"]; primitiveDictionary["PSRemotingProtocolVersion"] = (object)serverCapability.ProtocolVersion; primitiveDictionary["SerializationVersion"] = (object)serverCapability.SerializationVersion; primitiveDictionary["PSVersion"] = (object)serverCapability.PSVersion; this.SendDataAsync(RemotingEncoder.GenerateApplicationPrivateData(this.clientRunspacePoolId, applicationPrivateData1)); } }
internal ServerRunspacePoolDriver(Guid clientRunspacePoolId, int minRunspaces, int maxRunspaces, PSThreadOptions threadOptions, ApartmentState apartmentState, HostInfo hostInfo, InitialSessionState initialSessionState, PSPrimitiveDictionary applicationPrivateData, ConfigurationDataFromXML configData, AbstractServerSessionTransportManager transportManager, bool isAdministrator, RemoteSessionCapability serverCapability, Hashtable configHash) { this.serverCapability = serverCapability; System.Management.Automation.Remoting.ServerRemoteHost host = new System.Management.Automation.Remoting.ServerRemoteHost(clientRunspacePoolId, Guid.Empty, hostInfo, transportManager); this.remoteHost = host; this.configData = configData; this.configHash = configHash; this.applicationPrivateData = applicationPrivateData; this.localRunspacePool = RunspaceFactory.CreateRunspacePool(minRunspaces, maxRunspaces, initialSessionState, host); PSThreadOptions options = configData.ShellThreadOptions.HasValue ? configData.ShellThreadOptions.Value : PSThreadOptions.UseCurrentThread; if ((threadOptions == PSThreadOptions.Default) || (threadOptions == options)) { this.localRunspacePool.ThreadOptions = options; } else { if (!isAdministrator) { throw new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.MustBeAdminToOverrideThreadOptions, new object[0])); } this.localRunspacePool.ThreadOptions = threadOptions; } ApartmentState state = configData.ShellThreadApartmentState.HasValue ? configData.ShellThreadApartmentState.Value : ApartmentState.Unknown; if ((apartmentState == ApartmentState.Unknown) || (apartmentState == state)) { this.localRunspacePool.ApartmentState = state; } else { this.localRunspacePool.ApartmentState = apartmentState; } this.clientRunspacePoolId = clientRunspacePoolId; this.dsHandler = new ServerRunspacePoolDataStructureHandler(this, transportManager); this.localRunspacePool.StateChanged += new EventHandler<RunspacePoolStateChangedEventArgs>(this.HandleRunspacePoolStateChanged); this.localRunspacePool.ForwardEvent += new EventHandler<PSEventArgs>(this.HandleRunspacePoolForwardEvent); this.localRunspacePool.RunspaceCreated += new EventHandler<RunspaceCreatedEventArgs>(this.HandleRunspaceCreated); this.localRunspacePool.RunspaceCreated += new EventHandler<RunspaceCreatedEventArgs>(this.HandleRunspaceCreatedForTypeTable); this.dsHandler.CreateAndInvokePowerShell += new EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>>(this.HandleCreateAndInvokePowerShell); this.dsHandler.GetCommandMetadata += new EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>>(this.HandleGetCommandMetadata); this.dsHandler.HostResponseReceived += new EventHandler<RemoteDataEventArgs<RemoteHostResponse>>(this.HandleHostResponseReceived); this.dsHandler.SetMaxRunspacesReceived += new EventHandler<RemoteDataEventArgs<PSObject>>(this.HandleSetMaxRunspacesReceived); this.dsHandler.SetMinRunspacesReceived += new EventHandler<RemoteDataEventArgs<PSObject>>(this.HandleSetMinRunspacesReceived); this.dsHandler.GetAvailableRunspacesReceived += new EventHandler<RemoteDataEventArgs<PSObject>>(this.HandleGetAvailalbeRunspacesReceived); }
/// <summary> /// Send a message with application private data to the client /// </summary> /// <param name="applicationPrivateData">applicationPrivateData to send</param> /// <param name="serverCapability">server capability negotiated during initial exchange of remoting messages / session capabilities of client and server</param> internal void SendApplicationPrivateDataToClient(PSPrimitiveDictionary applicationPrivateData, RemoteSessionCapability serverCapability) { // make server's PSVersionTable available to the client using ApplicationPrivateData PSPrimitiveDictionary applicationPrivateDataWithVersionTable = PSPrimitiveDictionary.CloneAndAddPSVersionTable(applicationPrivateData); // override the hardcoded version numbers with the stuff that was reported to the client during negotiation PSPrimitiveDictionary versionTable = (PSPrimitiveDictionary)applicationPrivateDataWithVersionTable[PSVersionInfo.PSVersionTableName]; versionTable[PSVersionInfo.PSRemotingProtocolVersionName] = serverCapability.ProtocolVersion; versionTable[PSVersionInfo.SerializationVersionName] = serverCapability.SerializationVersion; // Pass back the true PowerShell version to the client via application private data. versionTable[PSVersionInfo.PSVersionName] = PSVersionInfo.PSVersion; RemoteDataObject data = RemotingEncoder.GenerateApplicationPrivateData( _clientRunspacePoolId, applicationPrivateDataWithVersionTable); SendDataAsync(data); }
/// <summary> /// Send a message with application private data to the client. /// </summary> /// <param name="applicationPrivateData">ApplicationPrivateData to send.</param> /// <param name="serverCapability">Server capability negotiated during initial exchange of remoting messages / session capabilities of client and server.</param> internal void SendApplicationPrivateDataToClient(PSPrimitiveDictionary applicationPrivateData, RemoteSessionCapability serverCapability) { // make server's PSVersionTable available to the client using ApplicationPrivateData PSPrimitiveDictionary applicationPrivateDataWithVersionTable = PSPrimitiveDictionary.CloneAndAddPSVersionTable(applicationPrivateData); // override the hardcoded version numbers with the stuff that was reported to the client during negotiation PSPrimitiveDictionary versionTable = (PSPrimitiveDictionary)applicationPrivateDataWithVersionTable[PSVersionInfo.PSVersionTableName]; versionTable[PSVersionInfo.PSRemotingProtocolVersionName] = serverCapability.ProtocolVersion; versionTable[PSVersionInfo.SerializationVersionName] = serverCapability.SerializationVersion; // Pass back the true PowerShell version to the client via application private data. versionTable[PSVersionInfo.PSVersionName] = PSVersionInfo.PSVersion; RemoteDataObject data = RemotingEncoder.GenerateApplicationPrivateData( _clientRunspacePoolId, applicationPrivateDataWithVersionTable); SendDataAsync(data); }
internal static RemoteDataObject GenerateCreateRunspacePool( Guid clientRunspacePoolId, int minRunspaces, int maxRunspaces, RemoteRunspacePoolInternal runspacePool, PSHost host, PSPrimitiveDictionary applicationArguments) { using (RemotingEncoder._trace.TraceMethod()) { PSObject emptyPsObject = RemotingEncoder.CreateEmptyPSObject(); emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("MinRunspaces", (object)minRunspaces)); emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("MaxRunspaces", (object)maxRunspaces)); emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("PSThreadOptions", (object)runspacePool.ThreadOptions)); emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("ApartmentState", (object)runspacePool.ApartmentState)); emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("ApplicationArguments", (object)applicationArguments)); emptyPsObject.Properties.Add((PSPropertyInfo)RemotingEncoder.CreateHostInfoProperty(new HostInfo(host))); return(RemoteDataObject.CreateFrom(RemotingDestination.Server, RemotingDataType.CreateRunspacePool, clientRunspacePoolId, Guid.Empty, (object)emptyPsObject)); } }
internal static PSPrimitiveDictionary CloneAndAddPSVersionTable(PSPrimitiveDictionary originalHash) { if ((originalHash != null) && originalHash.ContainsKey("PSVersionTable")) { return((PSPrimitiveDictionary)originalHash.Clone()); } PSPrimitiveDictionary dictionary = originalHash; if (originalHash != null) { dictionary = (PSPrimitiveDictionary)originalHash.Clone(); } else { dictionary = new PSPrimitiveDictionary(); } PSPrimitiveDictionary dictionary2 = new PSPrimitiveDictionary(PSVersionInfo.GetPSVersionTable()); dictionary.Add("PSVersionTable", dictionary2); return(dictionary); }
public static RunspacePool CreateRunspacePool(int minRunspaces, int maxRunspaces, RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable, PSPrimitiveDictionary applicationArguments) { if (!(connectionInfo is WSManConnectionInfo) && !(connectionInfo is NewProcessConnectionInfo)) { throw new NotSupportedException(); } if (connectionInfo is WSManConnectionInfo) { RemotingCommandUtil.CheckHostRemotingPrerequisites(); } return new RunspacePool(minRunspaces, maxRunspaces, typeTable, host, applicationArguments, connectionInfo, null); }
internal override void SetApplicationPrivateData(PSPrimitiveDictionary applicationPrivateData) { Dbg.Assert(false, "RemoteRunspace.SetApplicationPrivateData shouldn't be called - this runspace does not belong to a runspace pool [although it does use a remote runspace pool internally]"); }
internal virtual PSPrimitiveDictionary GetApplicationPrivateData() { if (this.applicationPrivateData == null) { lock (this.syncObject) { if (this.applicationPrivateData == null) { this.applicationPrivateData = new PSPrimitiveDictionary(); } } } return this.applicationPrivateData; }
public void Add(string key, PSPrimitiveDictionary value) { this.Add(key, value); }
internal static PSPrimitiveDictionary CloneAndAddPSVersionTable(PSPrimitiveDictionary originalHash) { throw new NotImplementedException(); }
/// <summary> /// Send application private data to client /// will be called during runspace creation /// and each time a new client connects to the server session /// </summary> internal void SendApplicationPrivateDataToClient() { // Include Debug mode information. if (_applicationPrivateData == null) { _applicationPrivateData = new PSPrimitiveDictionary(); } if (_serverRemoteDebugger != null) { // Current debug mode. DebugModes debugMode = _serverRemoteDebugger.DebugMode; if (_applicationPrivateData.ContainsKey(RemoteDebugger.DebugModeSetting)) { _applicationPrivateData[RemoteDebugger.DebugModeSetting] = (int)debugMode; } else { _applicationPrivateData.Add(RemoteDebugger.DebugModeSetting, (int)debugMode); } // Current debug state. bool inBreakpoint = _serverRemoteDebugger.InBreakpoint; if (_applicationPrivateData.ContainsKey(RemoteDebugger.DebugStopState)) { _applicationPrivateData[RemoteDebugger.DebugStopState] = inBreakpoint; } else { _applicationPrivateData.Add(RemoteDebugger.DebugStopState, inBreakpoint); } // Current debug breakpoint count. int breakpointCount = _serverRemoteDebugger.GetBreakpointCount(); if (_applicationPrivateData.ContainsKey(RemoteDebugger.DebugBreakpointCount)) { _applicationPrivateData[RemoteDebugger.DebugBreakpointCount] = breakpointCount; } else { _applicationPrivateData.Add(RemoteDebugger.DebugBreakpointCount, breakpointCount); } // Current debugger BreakAll option setting. bool breakAll = _serverRemoteDebugger.IsDebuggerSteppingEnabled; if (_applicationPrivateData.ContainsKey(RemoteDebugger.BreakAllSetting)) { _applicationPrivateData[RemoteDebugger.BreakAllSetting] = breakAll; } else { _applicationPrivateData.Add(RemoteDebugger.BreakAllSetting, breakAll); } // Current debugger PreserveUnhandledBreakpoints setting. UnhandledBreakpointProcessingMode bpMode = _serverRemoteDebugger.UnhandledBreakpointMode; if (_applicationPrivateData.ContainsKey(RemoteDebugger.UnhandledBreakpointModeSetting)) { _applicationPrivateData[RemoteDebugger.UnhandledBreakpointModeSetting] = (int)bpMode; } else { _applicationPrivateData.Add(RemoteDebugger.UnhandledBreakpointModeSetting, (int)bpMode); } } DataStructureHandler.SendApplicationPrivateDataToClient(_applicationPrivateData, _serverCapability); }
/// <summary> /// Creates the runspace pool driver /// </summary> /// <param name="clientRunspacePoolId">client runspace pool id to associate</param> /// <param name="transportManager">transport manager associated with this /// runspace pool driver</param> /// <param name="maxRunspaces">maximum runspaces to open</param> /// <param name="minRunspaces">minimum runspaces to open</param> /// <param name="threadOptions">threading options for the runspaces in the pool</param> /// <param name="hostInfo">host information about client side host</param> /// <param name="configData"> /// Contains: /// 1. Script to run after a RunspacePool/Runspace is created in this session. /// For RunspacePool case, every newly created Runspace (in the pool) will run /// this script. /// 2. ThreadOptions for RunspacePool/Runspace /// 3. ThreadApartment for RunspacePool/Runspace /// </param> /// <param name="initialSessionState">configuration of the runspace</param> /// <param name="applicationPrivateData">application private data</param> /// <param name="isAdministrator">True if the driver is being created by an administrator</param> /// <param name="serverCapability">server capability reported to the client during negotiation (not the actual capability)</param> /// <param name="psClientVersion">Client PowerShell version.</param> /// <param name="configurationName">Optional endpoint configuration name to create a pushed configured runspace.</param> internal ServerRunspacePoolDriver( Guid clientRunspacePoolId, int minRunspaces, int maxRunspaces, PSThreadOptions threadOptions, HostInfo hostInfo, InitialSessionState initialSessionState, PSPrimitiveDictionary applicationPrivateData, ConfigurationDataFromXML configData, AbstractServerSessionTransportManager transportManager, bool isAdministrator, RemoteSessionCapability serverCapability, Version psClientVersion, string configurationName)
private void HandleRunspacePoolStateChanged(object sender, RunspacePoolStateChangedEventArgs e) { RunspaceState newState = (RunspaceState)e.RunspacePoolStateInfo.State; RunspaceState prevState = SetRunspaceState(newState, e.RunspacePoolStateInfo.Reason); switch (newState) { case RunspaceState.Opened: switch (prevState) { case RunspaceState.Opening: // For newly opened remote runspaces, set the debug mode based on the // associated host. This involves running a remote command and is Ok // since this event is called on a worker thread and not a WinRM callback. SetDebugModeOnOpen(); break; case RunspaceState.Connecting: UpdateDisconnectExpiresOn(); // Application private data containing server debug state is updated on // a *reconstruct* connect operation when _applicationPrivateData is null. // Pass new information to the debugger. if (_applicationPrivateData == null) { _applicationPrivateData = GetApplicationPrivateData(); SetDebugInfo(_applicationPrivateData); } break; } break; case RunspaceState.Disconnected: UpdateDisconnectExpiresOn(); break; } RaiseRunspaceStateEvents(); }
/// <summary> /// Set debug mode on remote session based on the interactive host /// setting, if available. /// </summary> private void SetDebugModeOnOpen() { // Update client remote debugger based on server capabilities. _applicationPrivateData = GetApplicationPrivateData(); bool serverSupportsDebugging = SetDebugInfo(_applicationPrivateData); if (!serverSupportsDebugging) { return; } // Set server side initial debug mode based on interactive host. DebugModes hostDebugMode = DebugModes.Default; try { IHostSupportsInteractiveSession interactiveHost = RunspacePool.RemoteRunspacePoolInternal.Host as IHostSupportsInteractiveSession; if (interactiveHost != null && interactiveHost.Runspace != null && interactiveHost.Runspace.Debugger != null) { hostDebugMode = interactiveHost.Runspace.Debugger.DebugMode; } } catch (PSNotImplementedException) { } if ((hostDebugMode & DebugModes.RemoteScript) == DebugModes.RemoteScript) { try { _remoteDebugger.SetDebugMode(hostDebugMode); } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); } } }
/// <summary> /// Construct a remote runspace based on the connection information /// and the specified host /// </summary> /// <param name="typeTable"> /// The TypeTable to use while deserializing/serializing remote objects. /// TypeTable has the following information used by serializer: /// 1. SerializationMethod /// 2. SerializationDepth /// 3. SpecificSerializationProperties /// TypeTable has the following information used by deserializer: /// 1. TargetTypeForDeserialization /// 2. TypeConverter /// </param> /// <param name="connectionInfo">connection information which identifies /// the remote computer</param> /// <param name="host">host on the client</param> /// <param name="applicationArguments"> /// <param name="name">Friendly name for remote runspace session.</param> /// <param name="id">Id for remote runspace.</param> /// Application arguments the server can see in <see cref="System.Management.Automation.Remoting.PSSenderInfo.ApplicationArguments"/> /// </param> internal RemoteRunspace(TypeTable typeTable, RunspaceConnectionInfo connectionInfo, PSHost host, PSPrimitiveDictionary applicationArguments, string name = null, int id = -1) { PSEtwLog.SetActivityIdForCurrentThread(this.InstanceId); PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceConstructor, PSOpcode.Constructor, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, InstanceId.ToString()); _connectionInfo = connectionInfo.InternalCopy(); OriginalConnectionInfo = connectionInfo.InternalCopy(); RunspacePool = new RunspacePool(1, 1, typeTable, host, applicationArguments, connectionInfo, name); this.PSSessionId = id; SetEventHandlers(); }
internal override void SetApplicationPrivateData(PSPrimitiveDictionary applicationPrivateData) { }
public void Add(string key, PSPrimitiveDictionary[] value) { this.Add(key, value); }
private void HandleRunspaceCreated(object sender, RunspaceCreatedEventArgs args) { try { string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); args.Runspace.ExecutionContext.EngineSessionState.SetLocation(folderPath); } catch (ArgumentException ex) { } catch (ProviderNotFoundException ex) { } catch (DriveNotFoundException ex) { } catch (ProviderInvocationException ex) { } Command command = (Command)null; if (!string.IsNullOrEmpty(this.configData.StartupScript)) { command = new Command(this.configData.StartupScript, false, false); } else if (!string.IsNullOrEmpty(this.configData.InitializationScriptForOutOfProcessRunspace)) { command = new Command(this.configData.InitializationScriptForOutOfProcessRunspace, true, false); } if (command == null) { return; } HostInfo hostInfo = this.remoteHost.HostInfo; command.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); PowerShell powershell = PowerShell.Create(); powershell.AddCommand(command).AddCommand("out-default"); IAsyncResult asyncResult = new ServerPowerShellDriver(powershell, (PowerShell)null, true, Guid.Empty, this.InstanceId, this, args.Runspace.ApartmentState, hostInfo, RemoteStreamOptions.AddInvocationInfo, false, args.Runspace).Start(); powershell.EndInvoke(asyncResult); ArrayList dollarErrorVariable = (ArrayList)powershell.Runspace.GetExecutionContext.DollarErrorVariable; if (dollarErrorVariable.Count > 0) { string str = (dollarErrorVariable[0] as ErrorRecord).ToString(); throw ServerRunspacePoolDriver.tracer.NewInvalidOperationException("RemotingErrorIdStrings", PSRemotingErrorId.StartupScriptThrewTerminatingError.ToString(), (object)str); } if (this.localRunspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Opening) { return; } object valueToConvert = args.Runspace.SessionStateProxy.PSVariable.GetValue("global:PSApplicationPrivateData"); if (valueToConvert == null) { return; } this.applicationPrivateData = (PSPrimitiveDictionary)LanguagePrimitives.ConvertTo(valueToConvert, typeof(PSPrimitiveDictionary), true, (IFormatProvider)CultureInfo.InvariantCulture, (TypeTable)null); }
private void HandleRunspaceCreated(object sender, RunspaceCreatedEventArgs args) { bool flag = false; if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { args.Runspace.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage; flag = true; } try { string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); args.Runspace.ExecutionContext.EngineSessionState.SetLocation(folderPath); } catch (ArgumentException) { } catch (ProviderNotFoundException) { } catch (DriveNotFoundException) { } catch (ProviderInvocationException) { } if (this.configHash != null) { if (this.configHash.ContainsKey(ConfigFileContants.EnvironmentVariables)) { Hashtable hashtable = this.configHash[ConfigFileContants.EnvironmentVariables] as Hashtable; if (hashtable != null) { foreach (DictionaryEntry entry in hashtable) { string introduced76 = entry.Key.ToString(); this.InvokeScript(new Command(StringUtil.Format("$env:{0} = \"{1}\"", introduced76, entry.Value.ToString()), true, false), args); } } } if (this.configHash.ContainsKey(ConfigFileContants.VariableDefinitions)) { Hashtable[] hashtableArray = DISCPowerShellConfiguration.TryGetHashtableArray(this.configHash[ConfigFileContants.VariableDefinitions]); if (hashtableArray != null) { foreach (Hashtable hashtable2 in hashtableArray) { if (hashtable2.ContainsKey(ConfigFileContants.VariableValueToken)) { string str2 = DISCPowerShellConfiguration.TryGetValue(hashtable2, ConfigFileContants.VariableNameToken); ScriptBlock block = hashtable2[ConfigFileContants.VariableValueToken] as ScriptBlock; if (!string.IsNullOrEmpty(str2) && (block != null)) { block.SessionStateInternal = args.Runspace.ExecutionContext.EngineSessionState; PowerShell powershell = PowerShell.Create(); powershell.AddCommand(new Command("Invoke-Command")).AddParameter("ScriptBlock", block).AddParameter("NoNewScope"); powershell.AddCommand(new Command("Set-Variable")).AddParameter("Name", str2); this.InvokePowerShell(powershell, args); } } } } } if (this.configHash.ContainsKey(ConfigFileContants.ScriptsToProcess)) { string[] strArray = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.ScriptsToProcess]); if (strArray != null) { foreach (string str3 in strArray) { if (!string.IsNullOrEmpty(str3)) { this.InvokeScript(new Command(str3, true, false), args); } } } } bool flag2 = false; if (this.configHash.ContainsKey(ConfigFileContants.VisibleAliases)) { string[] strArray2 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleAliases]); if (strArray2 != null) { flag2 = true; foreach (KeyValuePair<string, AliasInfo> pair in args.Runspace.ExecutionContext.EngineSessionState.GetAliasTable()) { bool flag3 = false; foreach (string str4 in strArray2) { if (!string.IsNullOrEmpty(str4)) { IEnumerable<WildcardPattern> patternList = this.CreateKeyPatternList(str4); if (this.MatchKeyPattern(patternList, pair.Key)) { pair.Value.Visibility = SessionStateEntryVisibility.Public; flag3 = true; } } } if (!flag3) { pair.Value.Visibility = SessionStateEntryVisibility.Private; } } } } if (this.configHash.ContainsKey(ConfigFileContants.VisibleCmdlets)) { string[] strArray3 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleCmdlets]); if (strArray3 != null) { flag2 = true; foreach (KeyValuePair<string, List<CmdletInfo>> pair2 in args.Runspace.ExecutionContext.EngineSessionState.GetCmdletTable()) { bool flag4 = false; foreach (string str5 in strArray3) { if (!string.IsNullOrEmpty(str5)) { IEnumerable<WildcardPattern> enumerable2 = this.CreateKeyPatternList(str5); if (this.MatchKeyPattern(enumerable2, pair2.Key)) { foreach (CmdletInfo info in pair2.Value) { info.Visibility = SessionStateEntryVisibility.Public; flag4 = true; } } } } if (!flag4) { foreach (CmdletInfo info2 in pair2.Value) { info2.Visibility = SessionStateEntryVisibility.Private; } } } } } List<string> list = new List<string>(); bool flag5 = false; if (this.configHash.ContainsKey(ConfigFileContants.VisibleFunctions)) { string[] strArray4 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleFunctions]); if (strArray4 != null) { flag2 = true; flag5 = true; list.AddRange(strArray4); } } if (!flag5 && this.configHash.ContainsKey(ConfigFileContants.FunctionDefinitions)) { Hashtable[] hashtableArray2 = DISCPowerShellConfiguration.TryGetHashtableArray(this.configHash[ConfigFileContants.FunctionDefinitions]); if (hashtableArray2 != null) { foreach (Hashtable hashtable3 in hashtableArray2) { string str6 = DISCPowerShellConfiguration.TryGetValue(hashtable3, ConfigFileContants.FunctionNameToken); if (!string.IsNullOrEmpty(str6)) { list.Add(str6); } } } } string str7 = DISCPowerShellConfiguration.TryGetValue(this.configHash, ConfigFileContants.SessionType); if (!string.IsNullOrEmpty(str7)) { SessionType type = (SessionType) Enum.Parse(typeof(SessionType), str7, true); if (type == SessionType.RestrictedRemoteServer) { list.Add("Get-Command"); list.Add("Get-FormatData"); list.Add("Select-Object"); list.Add("Get-Help"); list.Add("Measure-Object"); list.Add("Out-Default"); list.Add("Exit-PSSession"); } } if (list.Count > 0) { foreach (DictionaryEntry entry2 in args.Runspace.ExecutionContext.EngineSessionState.GetFunctionTable()) { bool flag6 = false; string key = entry2.Key.ToString(); FunctionInfo info3 = entry2.Value as FunctionInfo; if (info3 != null) { foreach (string str9 in list) { if (!string.IsNullOrEmpty(str9)) { IEnumerable<WildcardPattern> enumerable3 = this.CreateKeyPatternList(str9); if (this.MatchKeyPattern(enumerable3, key)) { info3.Visibility = SessionStateEntryVisibility.Public; flag6 = true; } } } if (!flag6 && flag5) { info3.Visibility = SessionStateEntryVisibility.Private; } } } } if (this.configHash.ContainsKey(ConfigFileContants.VisibleProviders)) { string[] strArray5 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleProviders]); if (strArray5 != null) { flag2 = true; IDictionary<string, List<ProviderInfo>> providers = args.Runspace.ExecutionContext.EngineSessionState.Providers; Collection<string> collection = new Collection<string>(); foreach (KeyValuePair<string, List<ProviderInfo>> pair3 in providers) { bool flag7 = false; foreach (string str10 in strArray5) { if (!string.IsNullOrEmpty(str10)) { IEnumerable<WildcardPattern> enumerable4 = this.CreateKeyPatternList(str10); if (this.MatchKeyPattern(enumerable4, pair3.Key)) { flag7 = true; } } } if (!flag7) { collection.Add(pair3.Key); } } foreach (string str11 in collection) { args.Runspace.ExecutionContext.EngineSessionState.Providers.Remove(str11); } } } if (flag2) { CmdletInfo cmdlet = args.Runspace.ExecutionContext.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Import-Module"); IDictionary<string, AliasInfo> aliasTable = args.Runspace.ExecutionContext.EngineSessionState.GetAliasTable(); PSModuleAutoLoadingPreference preference = CommandDiscovery.GetCommandDiscoveryPreference(args.Runspace.ExecutionContext, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference"); bool flag8 = (cmdlet != null) && (cmdlet.Visibility != SessionStateEntryVisibility.Private); bool flag9 = ((aliasTable != null) && aliasTable.ContainsKey("ipmo")) && (aliasTable["ipmo"].Visibility != SessionStateEntryVisibility.Private); if ((flag8 || flag9) && (preference == PSModuleAutoLoadingPreference.None)) { throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.DISCVisibilityAndAutoLoadingCannotBeBothSpecified, new object[] { "Import-Module", "ipmo", ConfigFileContants.VisibleCmdlets, ConfigFileContants.VisibleAliases, ConfigFileContants.VisibleFunctions, ConfigFileContants.VisibleProviders })); } } if (this.configHash.ContainsKey(ConfigFileContants.LanguageMode)) { PSLanguageMode mode = (PSLanguageMode) Enum.Parse(typeof(PSLanguageMode), this.configHash[ConfigFileContants.LanguageMode].ToString(), true); if (flag && (mode != PSLanguageMode.ConstrainedLanguage)) { throw new PSInvalidOperationException(RemotingErrorIdStrings.CannotCreateRunspaceInconsistentState); } args.Runspace.ExecutionContext.LanguageMode = mode; } if (this.configHash.ContainsKey(ConfigFileContants.ExecutionPolicy)) { ExecutionPolicy policy = (ExecutionPolicy) Enum.Parse(typeof(ExecutionPolicy), this.configHash[ConfigFileContants.ExecutionPolicy].ToString(), true); string shellID = args.Runspace.ExecutionContext.ShellID; SecuritySupport.SetExecutionPolicy(ExecutionPolicyScope.Process, policy, shellID); } } Command cmdToRun = null; if (!string.IsNullOrEmpty(this.configData.StartupScript)) { cmdToRun = new Command(this.configData.StartupScript, false, false); } else if (!string.IsNullOrEmpty(this.configData.InitializationScriptForOutOfProcessRunspace)) { cmdToRun = new Command(this.configData.InitializationScriptForOutOfProcessRunspace, true, false); } if (cmdToRun != null) { this.InvokeScript(cmdToRun, args); if (this.localRunspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opening) { object valueToConvert = args.Runspace.SessionStateProxy.PSVariable.GetValue("global:PSApplicationPrivateData"); if (valueToConvert != null) { this.applicationPrivateData = (PSPrimitiveDictionary) LanguagePrimitives.ConvertTo(valueToConvert, typeof(PSPrimitiveDictionary), true, CultureInfo.InvariantCulture, null); } } } }
internal abstract void SetApplicationPrivateData(PSPrimitiveDictionary applicationPrivateData);
/// <summary> /// Creates the runspace pool driver /// </summary> /// <param name="clientRunspacePoolId">client runspace pool id to associate</param> /// <param name="transportManager">transport manager associated with this /// runspace pool driver</param> /// <param name="maxRunspaces">maximum runspaces to open</param> /// <param name="minRunspaces">minimum runspaces to open</param> /// <param name="threadOptions">threading options for the runspaces in the pool</param> /// <param name="apartmentState">apartment state for the runspaces in the pool</param> /// <param name="hostInfo">host information about client side host</param> /// <param name="configData"> /// Contains: /// 1. Script to run after a RunspacePool/Runspace is created in this session. /// For RunspacePool case, every newly created Runspace (in the pool) will run /// this script. /// 2. ThreadOptions for RunspacePool/Runspace /// 3. ThreadApartment for RunspacePool/Runspace /// </param> /// <param name="initialSessionState">configuration of the runspace</param> /// <param name="applicationPrivateData">application private data</param> /// <param name="isAdministrator">True if the driver is being created by an administrator</param> /// <param name="serverCapability">server capability reported to the client during negotiation (not the actual capability)</param> /// <param name="psClientVersion">Client PowerShell version.</param> /// <param name="configurationName">Optional endpoint configuration name to create a pushed configured runspace.</param> internal ServerRunspacePoolDriver( Guid clientRunspacePoolId, int minRunspaces, int maxRunspaces, PSThreadOptions threadOptions, ApartmentState apartmentState, HostInfo hostInfo, InitialSessionState initialSessionState, PSPrimitiveDictionary applicationPrivateData, ConfigurationDataFromXML configData, AbstractServerSessionTransportManager transportManager, bool isAdministrator, RemoteSessionCapability serverCapability, Version psClientVersion, string configurationName) #endif { Dbg.Assert(null != configData, "ConfigurationData cannot be null"); _serverCapability = serverCapability; _clientPSVersion = psClientVersion; _configurationName = configurationName; // Create a new server host and associate for host call // integration _remoteHost = new ServerDriverRemoteHost(clientRunspacePoolId, Guid.Empty, hostInfo, transportManager, null); _configData = configData; _applicationPrivateData = applicationPrivateData; RunspacePool = RunspaceFactory.CreateRunspacePool( minRunspaces, maxRunspaces, initialSessionState, _remoteHost); // Set ThreadOptions for this RunspacePool // The default server settings is to make new commands execute in the calling thread...this saves // thread switching time and thread pool pressure on the service. // Users can override the server settings only if they are administrators PSThreadOptions serverThreadOptions = configData.ShellThreadOptions.HasValue ? configData.ShellThreadOptions.Value : PSThreadOptions.UseCurrentThread; if (threadOptions == PSThreadOptions.Default || threadOptions == serverThreadOptions) { RunspacePool.ThreadOptions = serverThreadOptions; } else { if (!isAdministrator) { throw new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.MustBeAdminToOverrideThreadOptions)); } RunspacePool.ThreadOptions = threadOptions; } #if !CORECLR // No ApartmentState In CoreCLR // Set Thread ApartmentState for this RunspacePool ApartmentState serverApartmentState = configData.ShellThreadApartmentState.HasValue ? configData.ShellThreadApartmentState.Value : Runspace.DefaultApartmentState; if (apartmentState == ApartmentState.Unknown || apartmentState == serverApartmentState) { RunspacePool.ApartmentState = serverApartmentState; } else { RunspacePool.ApartmentState = apartmentState; } #endif // If we have a runspace pool with a single runspace then we can run nested pipelines on // on it in a single pipeline invoke thread. if (maxRunspaces == 1 && (RunspacePool.ThreadOptions == PSThreadOptions.Default || RunspacePool.ThreadOptions == PSThreadOptions.UseCurrentThread)) { _driverNestedInvoker = new PowerShellDriverInvoker(); } InstanceId = clientRunspacePoolId; DataStructureHandler = new ServerRunspacePoolDataStructureHandler(this, transportManager); // handle the StateChanged event of the runspace pool RunspacePool.StateChanged += new EventHandler<RunspacePoolStateChangedEventArgs>(HandleRunspacePoolStateChanged); // listen for events on the runspace pool RunspacePool.ForwardEvent += new EventHandler<PSEventArgs>(HandleRunspacePoolForwardEvent); RunspacePool.RunspaceCreated += HandleRunspaceCreated; // register for all the events from the data structure handler DataStructureHandler.CreateAndInvokePowerShell += new EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>>(HandleCreateAndInvokePowerShell); DataStructureHandler.GetCommandMetadata += new EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>>(HandleGetCommandMetadata); DataStructureHandler.HostResponseReceived += new EventHandler<RemoteDataEventArgs<RemoteHostResponse>>(HandleHostResponseReceived); DataStructureHandler.SetMaxRunspacesReceived += new EventHandler<RemoteDataEventArgs<PSObject>>(HandleSetMaxRunspacesReceived); DataStructureHandler.SetMinRunspacesReceived += new EventHandler<RemoteDataEventArgs<PSObject>>(HandleSetMinRunspacesReceived); DataStructureHandler.GetAvailableRunspacesReceived += new EventHandler<RemoteDataEventArgs<PSObject>>(HandleGetAvailableRunspacesReceived); DataStructureHandler.ResetRunspaceState += new EventHandler<RemoteDataEventArgs<PSObject>>(HandleResetRunspaceState); }
internal static RemoteDataObject GenerateApplicationPrivateData(Guid clientRunspacePoolId, PSPrimitiveDictionary applicationPrivateData) { PSObject data = CreateEmptyPSObject(); data.Properties.Add(new PSNoteProperty("ApplicationPrivateData", applicationPrivateData)); return(RemoteDataObject.CreateFrom(RemotingDestination.InvalidDestination | RemotingDestination.Client, RemotingDataType.ApplicationPrivateData, clientRunspacePoolId, Guid.Empty, data)); }
private void InvokeStartupScripts(RunspaceCreatedEventArgs args) { Command cmdToRun = null; if (!string.IsNullOrEmpty(_configData.StartupScript)) { // build the startup script..merge output / error. cmdToRun = new Command(_configData.StartupScript, false, false); } else if (!string.IsNullOrEmpty(_configData.InitializationScriptForOutOfProcessRunspace)) { cmdToRun = new Command(_configData.InitializationScriptForOutOfProcessRunspace, true, false); } if (null != cmdToRun) { InvokeScript(cmdToRun, args); // if startup script set $PSApplicationPrivateData, then use that value as ApplicationPrivateData // instead of using results from PSSessionConfiguration.GetApplicationPrivateData() if (RunspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opening) { object privateDataVariable = args.Runspace.SessionStateProxy.PSVariable.GetValue("global:PSApplicationPrivateData"); if (privateDataVariable != null) { _applicationPrivateData = (PSPrimitiveDictionary)LanguagePrimitives.ConvertTo( privateDataVariable, typeof(PSPrimitiveDictionary), true, CultureInfo.InvariantCulture, null); } } } }
private void HandleRunspaceCreated(object sender, RunspaceCreatedEventArgs args) { bool flag = false; if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { args.Runspace.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage; flag = true; } try { string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); args.Runspace.ExecutionContext.EngineSessionState.SetLocation(folderPath); } catch (ArgumentException) { } catch (ProviderNotFoundException) { } catch (DriveNotFoundException) { } catch (ProviderInvocationException) { } if (this.configHash != null) { if (this.configHash.ContainsKey(ConfigFileContants.EnvironmentVariables)) { Hashtable hashtable = this.configHash[ConfigFileContants.EnvironmentVariables] as Hashtable; if (hashtable != null) { foreach (DictionaryEntry entry in hashtable) { string introduced76 = entry.Key.ToString(); this.InvokeScript(new Command(StringUtil.Format("$env:{0} = \"{1}\"", introduced76, entry.Value.ToString()), true, false), args); } } } if (this.configHash.ContainsKey(ConfigFileContants.VariableDefinitions)) { Hashtable[] hashtableArray = DISCPowerShellConfiguration.TryGetHashtableArray(this.configHash[ConfigFileContants.VariableDefinitions]); if (hashtableArray != null) { foreach (Hashtable hashtable2 in hashtableArray) { if (hashtable2.ContainsKey(ConfigFileContants.VariableValueToken)) { string str2 = DISCPowerShellConfiguration.TryGetValue(hashtable2, ConfigFileContants.VariableNameToken); ScriptBlock block = hashtable2[ConfigFileContants.VariableValueToken] as ScriptBlock; if (!string.IsNullOrEmpty(str2) && (block != null)) { block.SessionStateInternal = args.Runspace.ExecutionContext.EngineSessionState; PowerShell powershell = PowerShell.Create(); powershell.AddCommand(new Command("Invoke-Command")).AddParameter("ScriptBlock", block).AddParameter("NoNewScope"); powershell.AddCommand(new Command("Set-Variable")).AddParameter("Name", str2); this.InvokePowerShell(powershell, args); } } } } } if (this.configHash.ContainsKey(ConfigFileContants.ScriptsToProcess)) { string[] strArray = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.ScriptsToProcess]); if (strArray != null) { foreach (string str3 in strArray) { if (!string.IsNullOrEmpty(str3)) { this.InvokeScript(new Command(str3, true, false), args); } } } } bool flag2 = false; if (this.configHash.ContainsKey(ConfigFileContants.VisibleAliases)) { string[] strArray2 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleAliases]); if (strArray2 != null) { flag2 = true; foreach (KeyValuePair <string, AliasInfo> pair in args.Runspace.ExecutionContext.EngineSessionState.GetAliasTable()) { bool flag3 = false; foreach (string str4 in strArray2) { if (!string.IsNullOrEmpty(str4)) { IEnumerable <WildcardPattern> patternList = this.CreateKeyPatternList(str4); if (this.MatchKeyPattern(patternList, pair.Key)) { pair.Value.Visibility = SessionStateEntryVisibility.Public; flag3 = true; } } } if (!flag3) { pair.Value.Visibility = SessionStateEntryVisibility.Private; } } } } if (this.configHash.ContainsKey(ConfigFileContants.VisibleCmdlets)) { string[] strArray3 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleCmdlets]); if (strArray3 != null) { flag2 = true; foreach (KeyValuePair <string, List <CmdletInfo> > pair2 in args.Runspace.ExecutionContext.EngineSessionState.GetCmdletTable()) { bool flag4 = false; foreach (string str5 in strArray3) { if (!string.IsNullOrEmpty(str5)) { IEnumerable <WildcardPattern> enumerable2 = this.CreateKeyPatternList(str5); if (this.MatchKeyPattern(enumerable2, pair2.Key)) { foreach (CmdletInfo info in pair2.Value) { info.Visibility = SessionStateEntryVisibility.Public; flag4 = true; } } } } if (!flag4) { foreach (CmdletInfo info2 in pair2.Value) { info2.Visibility = SessionStateEntryVisibility.Private; } } } } } List <string> list = new List <string>(); bool flag5 = false; if (this.configHash.ContainsKey(ConfigFileContants.VisibleFunctions)) { string[] strArray4 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleFunctions]); if (strArray4 != null) { flag2 = true; flag5 = true; list.AddRange(strArray4); } } if (!flag5 && this.configHash.ContainsKey(ConfigFileContants.FunctionDefinitions)) { Hashtable[] hashtableArray2 = DISCPowerShellConfiguration.TryGetHashtableArray(this.configHash[ConfigFileContants.FunctionDefinitions]); if (hashtableArray2 != null) { foreach (Hashtable hashtable3 in hashtableArray2) { string str6 = DISCPowerShellConfiguration.TryGetValue(hashtable3, ConfigFileContants.FunctionNameToken); if (!string.IsNullOrEmpty(str6)) { list.Add(str6); } } } } string str7 = DISCPowerShellConfiguration.TryGetValue(this.configHash, ConfigFileContants.SessionType); if (!string.IsNullOrEmpty(str7)) { SessionType type = (SessionType)Enum.Parse(typeof(SessionType), str7, true); if (type == SessionType.RestrictedRemoteServer) { list.Add("Get-Command"); list.Add("Get-FormatData"); list.Add("Select-Object"); list.Add("Get-Help"); list.Add("Measure-Object"); list.Add("Out-Default"); list.Add("Exit-PSSession"); } } if (list.Count > 0) { foreach (DictionaryEntry entry2 in args.Runspace.ExecutionContext.EngineSessionState.GetFunctionTable()) { bool flag6 = false; string key = entry2.Key.ToString(); FunctionInfo info3 = entry2.Value as FunctionInfo; if (info3 != null) { foreach (string str9 in list) { if (!string.IsNullOrEmpty(str9)) { IEnumerable <WildcardPattern> enumerable3 = this.CreateKeyPatternList(str9); if (this.MatchKeyPattern(enumerable3, key)) { info3.Visibility = SessionStateEntryVisibility.Public; flag6 = true; } } } if (!flag6 && flag5) { info3.Visibility = SessionStateEntryVisibility.Private; } } } } if (this.configHash.ContainsKey(ConfigFileContants.VisibleProviders)) { string[] strArray5 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleProviders]); if (strArray5 != null) { flag2 = true; IDictionary <string, List <ProviderInfo> > providers = args.Runspace.ExecutionContext.EngineSessionState.Providers; Collection <string> collection = new Collection <string>(); foreach (KeyValuePair <string, List <ProviderInfo> > pair3 in providers) { bool flag7 = false; foreach (string str10 in strArray5) { if (!string.IsNullOrEmpty(str10)) { IEnumerable <WildcardPattern> enumerable4 = this.CreateKeyPatternList(str10); if (this.MatchKeyPattern(enumerable4, pair3.Key)) { flag7 = true; } } } if (!flag7) { collection.Add(pair3.Key); } } foreach (string str11 in collection) { args.Runspace.ExecutionContext.EngineSessionState.Providers.Remove(str11); } } } if (flag2) { CmdletInfo cmdlet = args.Runspace.ExecutionContext.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Import-Module"); IDictionary <string, AliasInfo> aliasTable = args.Runspace.ExecutionContext.EngineSessionState.GetAliasTable(); PSModuleAutoLoadingPreference preference = CommandDiscovery.GetCommandDiscoveryPreference(args.Runspace.ExecutionContext, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference"); bool flag8 = (cmdlet != null) && (cmdlet.Visibility != SessionStateEntryVisibility.Private); bool flag9 = ((aliasTable != null) && aliasTable.ContainsKey("ipmo")) && (aliasTable["ipmo"].Visibility != SessionStateEntryVisibility.Private); if ((flag8 || flag9) && (preference == PSModuleAutoLoadingPreference.None)) { throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.DISCVisibilityAndAutoLoadingCannotBeBothSpecified, new object[] { "Import-Module", "ipmo", ConfigFileContants.VisibleCmdlets, ConfigFileContants.VisibleAliases, ConfigFileContants.VisibleFunctions, ConfigFileContants.VisibleProviders })); } } if (this.configHash.ContainsKey(ConfigFileContants.LanguageMode)) { PSLanguageMode mode = (PSLanguageMode)Enum.Parse(typeof(PSLanguageMode), this.configHash[ConfigFileContants.LanguageMode].ToString(), true); if (flag && (mode != PSLanguageMode.ConstrainedLanguage)) { throw new PSInvalidOperationException(RemotingErrorIdStrings.CannotCreateRunspaceInconsistentState); } args.Runspace.ExecutionContext.LanguageMode = mode; } if (this.configHash.ContainsKey(ConfigFileContants.ExecutionPolicy)) { ExecutionPolicy policy = (ExecutionPolicy)Enum.Parse(typeof(ExecutionPolicy), this.configHash[ConfigFileContants.ExecutionPolicy].ToString(), true); string shellID = args.Runspace.ExecutionContext.ShellID; SecuritySupport.SetExecutionPolicy(ExecutionPolicyScope.Process, policy, shellID); } } Command cmdToRun = null; if (!string.IsNullOrEmpty(this.configData.StartupScript)) { cmdToRun = new Command(this.configData.StartupScript, false, false); } else if (!string.IsNullOrEmpty(this.configData.InitializationScriptForOutOfProcessRunspace)) { cmdToRun = new Command(this.configData.InitializationScriptForOutOfProcessRunspace, true, false); } if (cmdToRun != null) { this.InvokeScript(cmdToRun, args); if (this.localRunspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opening) { object valueToConvert = args.Runspace.SessionStateProxy.PSVariable.GetValue("global:PSApplicationPrivateData"); if (valueToConvert != null) { this.applicationPrivateData = (PSPrimitiveDictionary)LanguagePrimitives.ConvertTo(valueToConvert, typeof(PSPrimitiveDictionary), true, CultureInfo.InvariantCulture, null); } } } }
internal void SetApplicationPrivateData(PSPrimitiveDictionary applicationPrivateData) { lock (base.syncObject) { if (!this.applicationPrivateDataReceived.WaitOne(0, false)) { this.applicationPrivateData = applicationPrivateData; this.applicationPrivateDataReceived.Set(); foreach (Runspace runspace in base.runspaceList) { runspace.SetApplicationPrivateData(applicationPrivateData); } } } }
public override PSPrimitiveDictionary GetApplicationPrivateData() { if (this.applicationPrivateData == null) { lock (base.SyncRoot) { if (this.applicationPrivateData == null) { this.applicationPrivateData = new PSPrimitiveDictionary(); } } } return this.applicationPrivateData; }
internal override void SetApplicationPrivateData(PSPrimitiveDictionary applicationPrivateData) { this.applicationPrivateData = applicationPrivateData; }
public void Add(string key, PSPrimitiveDictionary value) { this.Add((object)key, (object)value); }
internal RunspacePool(int minRunspaces, int maxRunspaces, TypeTable typeTable, PSHost host, PSPrimitiveDictionary applicationArguments, RunspaceConnectionInfo connectionInfo, string name = null) { this.syncObject = new object(); if (!(connectionInfo is WSManConnectionInfo) && !(connectionInfo is NewProcessConnectionInfo)) { throw new NotSupportedException(); } this.internalPool = new System.Management.Automation.Runspaces.Internal.RemoteRunspacePoolInternal(minRunspaces, maxRunspaces, typeTable, host, applicationArguments, connectionInfo, name); this.isRemote = true; }
private bool SetDebugInfo(PSPrimitiveDictionary psApplicationPrivateData) { DebugModes? debugMode = null; bool inDebugger = false; int breakpointCount = 0; bool breakAll = false; UnhandledBreakpointProcessingMode unhandledBreakpointMode = UnhandledBreakpointProcessingMode.Ignore; if (psApplicationPrivateData != null) { if (psApplicationPrivateData.ContainsKey(RemoteDebugger.DebugModeSetting)) { debugMode = (DebugModes)(int)psApplicationPrivateData[RemoteDebugger.DebugModeSetting]; } if (psApplicationPrivateData.ContainsKey(RemoteDebugger.DebugStopState)) { inDebugger = (bool)psApplicationPrivateData[RemoteDebugger.DebugStopState]; } if (psApplicationPrivateData.ContainsKey(RemoteDebugger.DebugBreakpointCount)) { breakpointCount = (int)psApplicationPrivateData[RemoteDebugger.DebugBreakpointCount]; } if (psApplicationPrivateData.ContainsKey(RemoteDebugger.BreakAllSetting)) { breakAll = (bool)psApplicationPrivateData[RemoteDebugger.BreakAllSetting]; } if (psApplicationPrivateData.ContainsKey(RemoteDebugger.UnhandledBreakpointModeSetting)) { unhandledBreakpointMode = (UnhandledBreakpointProcessingMode)(int)psApplicationPrivateData[RemoteDebugger.UnhandledBreakpointModeSetting]; } if (psApplicationPrivateData.ContainsKey(PSVersionInfo.PSVersionTableName)) { var psVersionTable = psApplicationPrivateData[PSVersionInfo.PSVersionTableName] as PSPrimitiveDictionary; if (psVersionTable.ContainsKey(PSVersionInfo.PSVersionName)) { ServerVersion = psVersionTable[PSVersionInfo.PSVersionName] as Version; } } } if (debugMode != null) { // Server supports remote debugging. Create Debugger object for // this remote runspace. Dbg.Assert(_remoteDebugger == null, "Remote runspace should not have a debugger yet."); _remoteDebugger = new RemoteDebugger(this); // Set initial debugger state. _remoteDebugger.SetClientDebugInfo(debugMode, inDebugger, breakpointCount, breakAll, unhandledBreakpointMode, ServerVersion); return true; } return false; }
internal void SendApplicationPrivateDataToClient(PSPrimitiveDictionary applicationPrivateData, RemoteSessionCapability serverCapability) { PSPrimitiveDictionary dictionary = PSPrimitiveDictionary.CloneAndAddPSVersionTable(applicationPrivateData); PSPrimitiveDictionary dictionary2 = (PSPrimitiveDictionary) dictionary["PSVersionTable"]; dictionary2["PSRemotingProtocolVersion"] = serverCapability.ProtocolVersion; dictionary2["SerializationVersion"] = serverCapability.SerializationVersion; dictionary2["PSVersion"] = serverCapability.PSVersion; RemoteDataObject data = RemotingEncoder.GenerateApplicationPrivateData(this.clientRunspacePoolId, dictionary); this.SendDataAsync(data); }
internal static RemoteDataObject GenerateCreateRunspacePool(Guid clientRunspacePoolId, int minRunspaces, int maxRunspaces, RemoteRunspacePoolInternal runspacePool, PSHost host, PSPrimitiveDictionary applicationArguments) { PSObject data = CreateEmptyPSObject(); data.Properties.Add(new PSNoteProperty("MinRunspaces", minRunspaces)); data.Properties.Add(new PSNoteProperty("MaxRunspaces", maxRunspaces)); data.Properties.Add(new PSNoteProperty("PSThreadOptions", runspacePool.ThreadOptions)); data.Properties.Add(new PSNoteProperty("ApartmentState", runspacePool.ApartmentState)); data.Properties.Add(new PSNoteProperty("ApplicationArguments", applicationArguments)); data.Properties.Add(CreateHostInfoProperty(new HostInfo(host))); return(RemoteDataObject.CreateFrom(RemotingDestination.InvalidDestination | RemotingDestination.Server, RemotingDataType.CreateRunspacePool, clientRunspacePoolId, Guid.Empty, data)); }