/// <summary> /// Execute method. /// </summary> internal T ExecuteMethod <T>(RemoteHostMethodId methodId, object[] parameters) { Dbg.Assert(parameters != null, "Expected parameters != null"); // Create the method call object. long callId = _serverDispatchTable.CreateNewCallId(); RemoteHostCall remoteHostCall = new RemoteHostCall(callId, methodId, parameters); RemoteDataObject <PSObject> dataToBeSent = RemoteDataObject <PSObject> .CreateFrom(RemotingDestination.Client, _remoteHostCallDataType, _clientRunspacePoolId, _clientPowerShellId, remoteHostCall.Encode()); // report that execution is pending host response _transportManager.SendDataToClient(dataToBeSent, false, true); // Wait for response. RemoteHostResponse remoteHostResponse = _serverDispatchTable.GetResponse(callId, null); // Null means that the response PSObject was not received and there was an error. if (remoteHostResponse == null) { throw RemoteHostExceptions.NewRemoteHostCallFailedException(methodId); } // Process the response. object returnValue = remoteHostResponse.SimulateExecution(); Dbg.Assert(returnValue is T, "Expected returnValue is T"); return((T)remoteHostResponse.SimulateExecution()); }
/// <summary> /// Get the object that this method should be invoked on. /// </summary> private object SelectTargetObject(PSHost host) { if (host == null || host.UI == null) { return(null); } if (_methodInfo.InterfaceType == typeof(PSHost)) { return(host); } if (_methodInfo.InterfaceType == typeof(IHostSupportsInteractiveSession)) { return(host); } if (_methodInfo.InterfaceType == typeof(PSHostUserInterface)) { return(host.UI); } if (_methodInfo.InterfaceType == typeof(IHostUISupportsMultipleChoiceSelection)) { return(host.UI); } if (_methodInfo.InterfaceType == typeof(PSHostRawUserInterface)) { return(host.UI.RawUI); } throw RemoteHostExceptions.NewUnknownTargetClassException(_methodInfo.InterfaceType.ToString()); }
/// <summary> /// Get buffer contents. /// </summary> public override BufferCell[,] GetBufferContents(Rectangle rectangle) { // This method had an implementation earlier. However, owing // to a potential security risk of a malicious server scrapping // the screen contents of a client, this is now removed throw RemoteHostExceptions.NewNotImplementedException(RemoteHostMethodId.GetBufferContents); }
private static T SafelyGetBaseObject <T>(PSObject psObject) { if (((psObject == null) || (psObject.BaseObject == null)) || !(psObject.BaseObject is T)) { throw RemoteHostExceptions.NewDecodingFailedException(); } return((T)psObject.BaseObject); }
private static T SafelyCastObject <T>(object obj) { if (!(obj is T)) { throw RemoteHostExceptions.NewDecodingFailedException(); } return((T)obj); }
private static Exception DecodeException(PSObject psObject) { ErrorRecord record = ErrorRecord.FromPSObjectForRemoting(psObject); if (record == null) { throw RemoteHostExceptions.NewDecodingErrorForErrorRecordException(); } return(record.Exception); }
internal RemoteHostResponse ExecuteNonVoidMethod(PSHost clientHost) { if (clientHost == null) { throw RemoteHostExceptions.NewNullClientHostException(); } object instance = this.SelectTargetObject(clientHost); return(this.ExecuteNonVoidMethodOnObject(instance)); }
private static T SafelyGetPropertyValue <T>(PSObject psObject, string key) { PSPropertyInfo info = psObject.Properties[key]; if (((info == null) || (info.Value == null)) || !(info.Value is T)) { throw RemoteHostExceptions.NewDecodingFailedException(); } return((T)info.Value); }
/// <summary> /// Push runspace. /// </summary> public virtual void PushRunspace(Runspace runspace) { if (_serverDriverRemoteHost != null) { _serverDriverRemoteHost.PushRunspace(runspace); } else { throw RemoteHostExceptions.NewNotImplementedException(RemoteHostMethodId.PushRunspace); } }
internal void Override(RemoteRunspace remoteRunspace, object syncObject, out bool isRunspacePushed) { lock (this._localSyncObject) { this._stopInvoke = false; } try { if (syncObject != null) { lock (syncObject) { this._runspaceRef.Override(remoteRunspace); isRunspacePushed = true; goto Label_0063; } } this._runspaceRef.Override(remoteRunspace); isRunspacePushed = true; Label_0063: using (PowerShell shell = PowerShell.Create()) { shell.AddCommand("Get-Command"); shell.AddParameter("Name", new string[] { "Out-Default", "Exit-PSSession" }); shell.Runspace = this._runspaceRef.Value; bool flag2 = this._runspaceRef.Value.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersionWin7RC; shell.IsGetCommandMetadataSpecialPipeline = !flag2; int num = flag2 ? 2 : 3; shell.RemotePowerShell.HostCallReceived += new EventHandler <RemoteDataEventArgs <RemoteHostCall> >(this.HandleHostCall); IAsyncResult asyncResult = shell.BeginInvoke(); PSDataCollection <PSObject> datas = new PSDataCollection <PSObject>(); while (!this._stopInvoke) { asyncResult.AsyncWaitHandle.WaitOne(0x3e8); if (asyncResult.IsCompleted) { datas = shell.EndInvoke(asyncResult); break; } } if ((shell.Streams.Error.Count > 0) || (datas.Count < num)) { throw RemoteHostExceptions.NewRemoteRunspaceDoesNotSupportPushRunspaceException(); } return; } } catch (Exception) { this._runspaceRef.Revert(); isRunspacePushed = false; throw; } }
/// <summary> /// Safely get property value. /// </summary> private static T SafelyGetPropertyValue <T>(PSObject psObject, string key) { PSPropertyInfo propertyInfo = psObject.Properties[key]; if (propertyInfo == null || propertyInfo.Value == null || propertyInfo.Value is not T) { throw RemoteHostExceptions.NewDecodingFailedException(); } return((T)propertyInfo.Value); }
internal T ExecuteMethod <T>(RemoteHostMethodId methodId, object[] parameters) { long newCallId = this._serverDispatchTable.CreateNewCallId(); this._transportManager.SendDataToClient <PSObject>(RemoteDataObject <PSObject> .CreateFrom(RemotingDestination.Client, this._remoteHostCallDataType, this._clientRunspacePoolId, this._clientPowerShellId, new RemoteHostCall(newCallId, methodId, parameters).Encode()), false); RemoteHostResponse response = this._serverDispatchTable.GetResponse(newCallId, (RemoteHostResponse)null); if (response == null) { throw RemoteHostExceptions.NewRemoteHostCallFailedException(methodId); } response.SimulateExecution(); return((T)response.SimulateExecution()); }
private static Exception DecodeException(PSObject psObject) { object obj2 = RemoteHostEncoder.DecodePropertyValue(psObject, "me", typeof(Exception)); if (obj2 == null) { return(null); } if (!(obj2 is Exception)) { throw RemoteHostExceptions.NewDecodingFailedException(); } return((Exception)obj2); }
/// <summary> /// Execute non void method. /// </summary> internal RemoteHostResponse ExecuteNonVoidMethod(PSHost clientHost) { // The clientHost can be null if the user creates a runspace object without providing // a host parameter. if (clientHost == null) { throw RemoteHostExceptions.NewNullClientHostException(); } object targetObject = this.SelectTargetObject(clientHost); RemoteHostResponse remoteHostResponse = this.ExecuteNonVoidMethodOnObject(targetObject); return(remoteHostResponse); }
/// <summary> /// Decode exception. /// </summary> private static Exception DecodeException(PSObject psObject) { object result = RemoteHostEncoder.DecodePropertyValue(psObject, RemoteDataNameStrings.MethodException, typeof(Exception)); if (result == null) { return(null); } if (result is Exception) { return((Exception)result); } throw RemoteHostExceptions.NewDecodingFailedException(); }
private static object DecodeClassOrStruct(PSObject psObject, Type type) { object uninitializedObject = FormatterServices.GetUninitializedObject(type); foreach (PSPropertyInfo property in psObject.Properties) { FieldInfo field = type.GetField(property.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (property.Value == null) { throw RemoteHostExceptions.NewDecodingFailedException(); } field.SetValue(uninitializedObject, RemoteHostEncoder.DecodeObject(property.Value, field.FieldType) ?? throw RemoteHostExceptions.NewDecodingFailedException()); } return(uninitializedObject); }
/// <summary> /// Decode class or struct. /// </summary> private static object DecodeClassOrStruct(PSObject psObject, Type type) { object obj = ClrFacade.GetUninitializedObject(type); // Field values cannot be null - because for null fields we simply don't transport them. foreach (PSPropertyInfo propertyInfo in psObject.Properties) { FieldInfo fieldInfo = type.GetField(propertyInfo.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (propertyInfo.Value == null) { throw RemoteHostExceptions.NewDecodingFailedException(); } object fieldValue = DecodeObject(propertyInfo.Value, fieldInfo.FieldType); if (fieldValue == null) { throw RemoteHostExceptions.NewDecodingFailedException(); } fieldInfo.SetValue(obj, fieldValue); } return(obj); }
/// <summary> /// Exit nested prompt. /// </summary> public override void ExitNestedPrompt() { throw RemoteHostExceptions.NewNotImplementedException(RemoteHostMethodId.ExitNestedPrompt); }
/// <summary> /// Override inside a safe lock. /// </summary> /// <param name="remoteRunspace">Runspace to override.</param> /// <param name="syncObject">Object to use in synchronization.</param> /// <param name="isRunspacePushed">Set is runspace pushed.</param> internal void Override(RemoteRunspace remoteRunspace, object syncObject, out bool isRunspacePushed) { lock (_localSyncObject) { _stopInvoke = false; } try { if (syncObject != null) { lock (syncObject) { _runspaceRef.Override(remoteRunspace); isRunspacePushed = true; } } else { _runspaceRef.Override(remoteRunspace); isRunspacePushed = true; } if ((remoteRunspace.GetCurrentlyRunningPipeline() != null)) { // Don't execute command if pushed runspace is already running one. return; } using (PowerShell powerShell = PowerShell.Create()) { powerShell.AddCommand("Get-Command"); powerShell.AddParameter("Name", new string[] { "Out-Default", "Exit-PSSession" }); powerShell.Runspace = _runspaceRef.Value; bool isReleaseCandidateBackcompatibilityMode = _runspaceRef.Value.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersionWin7RC; powerShell.IsGetCommandMetadataSpecialPipeline = !isReleaseCandidateBackcompatibilityMode; int expectedNumberOfResults = isReleaseCandidateBackcompatibilityMode ? 2 : 3; powerShell.RemotePowerShell.HostCallReceived += HandleHostCall; IAsyncResult asyncResult = powerShell.BeginInvoke(); PSDataCollection <PSObject> results = new PSDataCollection <PSObject>(); while (!_stopInvoke) { asyncResult.AsyncWaitHandle.WaitOne(1000); if (asyncResult.IsCompleted) { results = powerShell.EndInvoke(asyncResult); break; } } if (powerShell.Streams.Error.Count > 0 || results.Count < expectedNumberOfResults) { throw RemoteHostExceptions.NewRemoteRunspaceDoesNotSupportPushRunspaceException(); } } } catch (Exception) { _runspaceRef.Revert(); isRunspacePushed = false; throw; } }
/// <summary> /// Decode object. /// </summary> internal static object DecodeObject(object obj, Type type) { if (obj == null) { return(null); } Dbg.Assert(type != null, "Expected type != null"); if (type == typeof(PSObject)) { return(DecodePSObject(obj)); } else if (type == typeof(ProgressRecord)) { return(ProgressRecord.FromPSObjectForRemoting(PSObject.AsPSObject(obj))); } else if (IsKnownType(type)) { return(obj); } else if (obj is SecureString) { return(obj); } else if (obj is PSCredential) { return(obj); } else if (obj is PSObject && type == typeof(PSCredential)) { // BUGBUG: The following piece of code is a workaround // because custom serialization is busted. If rehydration // works correctly then PSCredential should be available PSObject objAsPSObject = (PSObject)obj; PSCredential cred = null; try { cred = new PSCredential((string)objAsPSObject.Properties["UserName"].Value, (SecureString)objAsPSObject.Properties["Password"].Value); } catch (GetValueException) { cred = null; } return(cred); } else if (obj is int && type.IsEnum) { return(Enum.ToObject(type, (int)obj)); } else if (obj is string && type == typeof(CultureInfo)) { return(new CultureInfo((string)obj)); } else if (obj is PSObject && type == typeof(Exception)) { return(DecodeException((PSObject)obj)); } else if (obj is PSObject && type == typeof(object[])) { return(DecodeObjectArray((PSObject)obj)); } else if (obj is PSObject && type.IsArray) { return(DecodeArray((PSObject)obj, type)); } else if (obj is PSObject && IsCollection(type)) { return(DecodeCollection((PSObject)obj, type)); } else if (obj is PSObject && IsDictionary(type)) { return(DecodeDictionary((PSObject)obj, type)); } else if (obj is PSObject && IsEncodingAllowedForClassOrStruct(type)) { return(DecodeClassOrStruct((PSObject)obj, type)); } else if (obj is PSObject && IsGenericIEnumerableOfInt(type)) { // we cannot create an instance of interface type like IEnumerable // Since a Collection implements IEnumerable, falling back to use // that. return(DecodeCollection((PSObject)obj, typeof(Collection <int>))); } else if (obj is PSObject && type == typeof(RemoteHostCall)) { return(RemoteHostCall.Decode((PSObject)obj)); } else if (obj is PSObject && type == typeof(RemoteHostResponse)) { return(RemoteHostResponse.Decode((PSObject)obj)); } else { throw RemoteHostExceptions.NewRemoteHostDataDecodingNotSupportedException(type); } }
/// <summary> /// Encode object. /// </summary> internal static object EncodeObject(object obj) { if (obj == null) { return(null); } Type type = obj.GetType(); if (obj is PSObject) { // The "is" keyword takes care of PSObject and subclasses. return(EncodePSObject((PSObject)obj)); } else if (obj is ProgressRecord) { return(((ProgressRecord)obj).ToPSObjectForRemoting()); } else if (IsKnownType(type)) { return(obj); } else if (type.IsEnum) { return((int)obj); } else if (obj is CultureInfo) { // The "is" keyword takes care of CultureInfo and subclasses. return(obj.ToString()); } else if (obj is Exception) { return(EncodeException((Exception)obj)); } else if (type == typeof(object[])) { return(EncodeObjectArray((object[])obj)); } else if (type.IsArray) { return(EncodeArray((Array)obj)); } else if (obj is IList && IsCollection(type)) { return(EncodeCollection((IList)obj)); } else if (obj is IDictionary && IsDictionary(type)) { return(EncodeDictionary((IDictionary)obj)); } else if (type.IsSubclassOf(typeof(FieldDescription)) || type == typeof(FieldDescription)) { // The upcasting removes the Attributes, so we want to do this both when it // is a subclass and when it is a FieldDescription object. return(EncodeClassOrStruct(UpcastFieldDescriptionSubclassAndDropAttributes((FieldDescription)obj))); } else if (IsEncodingAllowedForClassOrStruct(type)) { return(EncodeClassOrStruct(obj)); } else if (obj is RemoteHostCall) { return(((RemoteHostCall)obj).Encode()); } else if (obj is RemoteHostResponse) { return(((RemoteHostResponse)obj).Encode()); } else if (obj is SecureString) { return(obj); } else if (obj is PSCredential) { return(obj); } else if (IsGenericIEnumerableOfInt(type)) { return(EncodeCollection((IList)obj)); } else { throw RemoteHostExceptions.NewRemoteHostDataEncodingNotSupportedException(type); } }
public void PushRunspace(Runspace runspace) => throw RemoteHostExceptions.NewNotImplementedException(RemoteHostMethodId.PushRunspace);
public override BufferCell[,] GetBufferContents(Rectangle rectangle) { throw RemoteHostExceptions.NewNotImplementedException(RemoteHostMethodId.GetBufferContents); }
internal static object DecodeObject(object obj, Type type) { if (obj == null) { return(obj); } if (type == typeof(PSObject)) { return(DecodePSObject(obj)); } if (type == typeof(System.Management.Automation.Runspaces.Runspace)) { return(RemoteRunspace.FromPSObjectForRemoting(PSObject.AsPSObject(obj))); } if (type == typeof(ProgressRecord)) { return(ProgressRecord.FromPSObjectForRemoting(PSObject.AsPSObject(obj))); } if (IsKnownType(type)) { return(obj); } if (obj is SecureString) { return(obj); } if (obj is PSCredential) { return(obj); } if ((obj is PSObject) && (type == typeof(PSCredential))) { PSObject obj2 = (PSObject)obj; try { return(new PSCredential((string)obj2.Properties["UserName"].Value, (SecureString)obj2.Properties["Password"].Value)); } catch (GetValueException) { return(null); } } if ((obj is int) && type.IsEnum) { return(Enum.ToObject(type, (int)obj)); } if ((obj is string) && (type == typeof(CultureInfo))) { return(new CultureInfo((string)obj)); } if ((obj is PSObject) && (type == typeof(Exception))) { return(DecodeException((PSObject)obj)); } if ((obj is PSObject) && (type == typeof(object[]))) { return(DecodeObjectArray((PSObject)obj)); } if ((obj is PSObject) && type.IsArray) { return(DecodeArray((PSObject)obj, type)); } if ((obj is PSObject) && IsCollection(type)) { return(DecodeCollection((PSObject)obj, type)); } if ((obj is PSObject) && IsDictionary(type)) { return(DecodeDictionary((PSObject)obj, type)); } if ((obj is PSObject) && IsEncodingAllowedForClassOrStruct(type)) { return(DecodeClassOrStruct((PSObject)obj, type)); } if ((obj is PSObject) && IsGenericIEnumerableOfInt(type)) { return(DecodeCollection((PSObject)obj, typeof(Collection <int>))); } if ((obj is PSObject) && (type == typeof(RemoteHostCall))) { return(RemoteHostCall.Decode((PSObject)obj)); } if (!(obj is PSObject) || (type != typeof(RemoteHostResponse))) { throw RemoteHostExceptions.NewRemoteHostDataDecodingNotSupportedException(type); } return(RemoteHostResponse.Decode((PSObject)obj)); }
internal static object EncodeObject(object obj) { if (obj == null) { return(null); } Type type = obj.GetType(); if (obj is PSObject) { return(EncodePSObject((PSObject)obj)); } if (obj is RemoteRunspace) { return(EncodePSObject(((RemoteRunspace)obj).ToPSObjectForRemoting())); } if (obj is ProgressRecord) { return(((ProgressRecord)obj).ToPSObjectForRemoting()); } if (IsKnownType(type)) { return(obj); } if (type.IsEnum) { return((int)obj); } if (obj is CultureInfo) { return(obj.ToString()); } if (obj is Exception) { return(EncodeException((Exception)obj)); } if (type == typeof(object[])) { return(EncodeObjectArray((object[])obj)); } if (type.IsArray) { return(EncodeArray((Array)obj)); } if (!(obj is IList) || !IsCollection(type)) { if ((obj is IDictionary) && IsDictionary(type)) { return(EncodeDictionary((IDictionary)obj)); } if (type.IsSubclassOf(typeof(FieldDescription)) || (type == typeof(FieldDescription))) { return(EncodeClassOrStruct(UpcastFieldDescriptionSubclassAndDropAttributes((FieldDescription)obj))); } if (IsEncodingAllowedForClassOrStruct(type)) { return(EncodeClassOrStruct(obj)); } if (obj is RemoteHostCall) { return(((RemoteHostCall)obj).Encode()); } if (obj is RemoteHostResponse) { return(((RemoteHostResponse)obj).Encode()); } if (obj is SecureString) { return(obj); } if (obj is PSCredential) { return(obj); } if (!IsGenericIEnumerableOfInt(type)) { throw RemoteHostExceptions.NewRemoteHostDataEncodingNotSupportedException(type); } } return(EncodeCollection((IList)obj)); }