internal static byte[] DoDispatch(byte[] reqStmBuff, SmuggledMethodCallMessage smuggledMcm, out SmuggledMethodReturnMessage smuggledMrm) { IMessage msg = null; if (smuggledMcm != null) { ArrayList deserializedArgs = smuggledMcm.FixupForNewAppDomain(); msg = new MethodCall(smuggledMcm, deserializedArgs); } else { MemoryStream stm = new MemoryStream(reqStmBuff); msg = CrossAppDomainSerializer.DeserializeMessage(stm); } LogicalCallContext logicalCallContext = CallContext.GetLogicalCallContext(); logicalCallContext.SetData("__xADCall", true); IMessage message2 = ChannelServices.SyncDispatchMessage(msg); logicalCallContext.FreeNamedDataSlot("__xADCall"); smuggledMrm = SmuggledMethodReturnMessage.SmuggleIfPossible(message2); if (smuggledMrm != null) { return null; } if (message2 == null) { return null; } LogicalCallContext context2 = (LogicalCallContext) message2.Properties[Message.CallContextKey]; if ((context2 != null) && (context2.Principal != null)) { context2.Principal = null; } return CrossAppDomainSerializer.SerializeMessage(message2).GetBuffer(); }
public void WriteRequestAndReadResponse() { //var properties = new Hashtable() { { "port", 8080 } }; //var channel = new TcpChannel(properties, null, new SoapServerFormatterSinkProvider()); //if using SOAP via TCP, messageRequestStream must be SOAP format var channel = new TcpChannel(8080); ChannelServices.RegisterChannel(channel, false); var service = new ServiceClass(); ObjRef obj = RemotingServices.Marshal(service, "Remote"); var uri = "tcp://localhost:8080/Remote"; using (var client = new TcpClient()) { client.Connect("localhost", 8080); using (var stream = client.GetStream()) { var messageRequest = new MethodCall(new Header[] { new Header("__Uri", uri), new Header("__MethodName", "Do"), new Header("__MethodSignature", new Type[] { typeof(string) }), new Header("__TypeName", typeof(ServiceClass).AssemblyQualifiedName), new Header("__Args", new object[] { "Hi" }) }); var messageRequestStream = BinaryFormatterHelper.SerializeObject(messageRequest); var writer = new ProtocolWriter(stream); writer.WritePreamble(); writer.WriteMajorVersion(); writer.WriteMinorVersion(); writer.WriteOperation(TcpOperations.Request); writer.WriteContentDelimiter(TcpContentDelimiter.ContentLength); writer.WriteContentLength(messageRequestStream.Length); writer.WriteTransportHeaders(uri); writer.WriteBytes(messageRequestStream); var reader = new ProtocolReader(stream); Console.WriteLine("Preamble: {0}", reader.ReadPreamble()); Console.WriteLine("MajorVersion: {0}", reader.ReadMajorVersion()); Console.WriteLine("MinorVersion: {0}", reader.ReadMinorVersion()); var op = reader.ReadOperation(); Assert.AreEqual(TcpOperations.Reply, op); Console.WriteLine("Operation: {0}", op); Console.WriteLine("ContentDelimiter: {0}", reader.ReadContentDelimiter()); var length = reader.ReadContentLength(); Console.WriteLine("ContentLength: {0}", length); reader.ReadTransportHeaders(); var messageResponse = BinaryFormatterHelper.DeserializeObject(reader.ReadBytes(length)) as MethodResponse; Assert.IsNotNull(messageResponse); DumpHelper.DumpMessage(messageResponse); if (messageResponse.Exception != null) throw messageResponse.Exception; Assert.AreEqual("Hi", messageResponse.ReturnValue); } } }
IMessage IMessageSink.SyncProcessMessage(IMessage msg) { Console.WriteLine("Remoting call:" + msg.Properties["__MethodName"]); MethodCall methodCall = new MethodCall(msg); if (methodCall.ArgCount == 1 && methodCall.Args[0] is Delegate) { Delegate realDelegate = methodCall.Args[0] as Delegate; methodCall.Args[0] = new EventForwarder(realDelegate).ProxyDelegate; } AsyncMessageResponseSink responseSink = new AsyncMessageResponseSink(); // Send the message nextSink.AsyncProcessMessage(methodCall, responseSink); return responseSink.WaitForResponse(); }
public override IMessage Invoke(IMessage msg) { var call = new MethodCall(msg); ParameterInfo[] parameters = call.MethodBase.GetParameters(); var invocation = new Invocation( GetTransparentProxy(), (MethodInfo) call.MethodBase, call.Args); invokable.Invoke(invocation); if (invocation.IsThrowing) { // TODO: it is impossible to set output parameters and throw an exception, // even though this is allowed by .NET method call semantics. return new ReturnMessage(invocation.Exception, call); } else { object[] outArgs = CollectOutputArguments(invocation, call, parameters); var methodInfo = (MethodInfo) call.MethodBase; if (invocation.Result == Missing.Value && methodInfo.ReturnType != typeof (void)) { throw new InvalidOperationException( string.Format( "You have to set the return value for method '{0}' on '{1}' mock.", call.MethodName, call.MethodBase.DeclaringType.Name)); } return new ReturnMessage( invocation.Result, outArgs, outArgs.Length, call.LogicalCallContext, call); } }
} // classUriHeaderHandler internal static IMessage DeserializeSoapRequestMessage( Stream inputStream, Header[] h, bool bStrictBinding, TypeFilterLevel securityLevel) { SoapFormatter fmt = CreateSoapFormatter(false, bStrictBinding); fmt.FilterLevel = securityLevel; MethodCall mc = new MethodCall(h); fmt.Deserialize(inputStream, new HeaderHandler(mc.HeaderHandler)); IMessage resMessage = (IMessage)mc; return resMessage; } // DeserializeSoapRequestMessage
internal void InternalInvokeAsync(IMessageSink ar, Message reqMsg, bool useDispatchMessage, int callType) { Identity identityObject = this.IdentityObject; ServerIdentity identity2 = identityObject as ServerIdentity; MethodCall msg = new MethodCall(reqMsg); IInternalMessage message = msg; message.IdentityObject = identityObject; if (identity2 != null) { message.ServerIdentityObject = identity2; } if (useDispatchMessage) { ChannelServices.AsyncDispatchMessage(msg, ((callType & 8) != 0) ? null : ar); } else { if (identityObject.EnvoyChain == null) { throw new InvalidOperationException(Environment.GetResourceString("Remoting_Proxy_InvalidState")); } identityObject.EnvoyChain.AsyncProcessMessage(msg, ((callType & 8) != 0) ? null : ar); } if (((callType & 1) != 0) && ((callType & 8) != 0)) { ar.SyncProcessMessage(null); } }
// ProtocolRequestToMessage // // Converts an incoming Ice Protocol Request stream from requestStream // into a new IMethodCallMessage. isBatched specifies if the request // is a batched request or not. public static IMessage ProtocolRequestToMessage (Stream requestStream, bool isBatched) { Ice.ProtocolReader pr = new Ice.ProtocolReader (requestStream); Ice.Identity id; string methodname; int requestId; Ice.OperationMode mode; Ice.Context context; if (!isBatched) { Ice.MessageRequest req = pr.ReadMessageRequest(); requestId = req.requestId; id = req.id; methodname = req.operation; mode = (Ice.OperationMode) Enum.ToObject (typeof(Ice.OperationMode), req.mode); context = req.context; } else { Ice.MessageBatchRequest req = pr.ReadMessageBatchRequest(); requestId = 0; id = req.id; methodname = req.operation; mode = (Ice.OperationMode) Enum.ToObject (typeof(Ice.OperationMode), req.mode); context = req.context; // FIXME -- if this is a batch, we really want to return multiple // messages. We need to extend both this function and the callee // to understand an array return. throw new NotImplementedException ("Batch execution detected"); } string uri = id.ToUri(); Type svrType = RemotingServices.GetServerTypeForUri (uri); if (svrType == null) throw new RemotingException ("No registered server for uri " + uri); MethodInfo mi = svrType.GetMethod (methodname); if (mi == null) throw new Ice.OperationNotExistException(); int encapsSize = pr.ReadEncapsulationHeader(); Trace.WriteLine ("ProtocolRequestToMessage method: " + methodname + " -> " + mi); ParameterInfo[] paramInfos = mi.GetParameters(); int inParams = 0, outParams = 0; int readInParams = 0; object[] methodArgs; if (encapsSize == 0) { for (int i = 0; i < paramInfos.Length; i++) { if (paramInfos[i].IsOut) outParams++; else inParams++; } methodArgs = new object[0]; } else { ArrayList args = new ArrayList(); for (int i = 0; i < paramInfos.Length; i++) { if (!paramInfos[i].IsOut) { object o; if (Attribute.GetCustomAttribute (paramInfos[i], typeof(Ice.AsProxy)) != null) { o = pr.ReadObjectProxy (paramInfos[i].ParameterType); args.Add (o); } else if (!IceByValue (paramInfos[i].ParameterType)) { // add a placeholder that will get replaced by // patch call below. args.Add (null); pr.ReadClassInstanceParameterRef (args, readInParams); } else { o = pr.ReadObject (paramInfos[i].ParameterType); args.Add (o); } inParams++; readInParams++; } else { outParams++; } } pr.ReadClassInstancesAndPatch(); methodArgs = args.ToArray(); } if (readInParams != inParams) { // FIXME throw new InvalidOperationException("Wrong number of parameters for operation, expected " + inParams + " got " + readInParams); } // I need: uri, typeNAme, methodName, object[] args System.Runtime.Remoting.Messaging.Header[] hs = new System.Runtime.Remoting.Messaging.Header[4]; hs[0] = new Header ("__TypeName", svrType.FullName); hs[1] = new Header ("__MethodName",methodname); hs[2] = new Header ("__Uri", uri); hs[3] = new Header ("__Args", methodArgs); MethodCall mc = new MethodCall (hs); mc.Properties["__iceRequestId"] = requestId; mc.Properties["__iceIdentity"] = id; mc.Properties["__iceMode"] = mode; mc.Properties["__iceContext"] = context; return mc; }
public static void SetServerIdentity(MethodCall m, Object srvID) { IInternalMessage im = (IInternalMessage) m; im.ServerIdentityObject = (ServerIdentity)srvID; }
[System.Security.SecurityCritical] // auto-generated internal static byte[] DoDispatch(byte[] reqStmBuff, SmuggledMethodCallMessage smuggledMcm, out SmuggledMethodReturnMessage smuggledMrm) { //*********************** DE-SERIALIZE REQ-MSG ******************** IMessage desReqMsg = null; if (smuggledMcm != null) { ArrayList deserializedArgs = smuggledMcm.FixupForNewAppDomain(); desReqMsg = new MethodCall(smuggledMcm, deserializedArgs); } else { MemoryStream reqStm = new MemoryStream(reqStmBuff); desReqMsg = CrossAppDomainSerializer.DeserializeMessage(reqStm); } LogicalCallContext lcc = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext; lcc.SetData(LCC_DATA_KEY, true); // now we can delegate to the DispatchMessage to do the rest IMessage retMsg = ChannelServices.SyncDispatchMessage(desReqMsg); lcc.FreeNamedDataSlot(LCC_DATA_KEY); smuggledMrm = SmuggledMethodReturnMessage.SmuggleIfPossible(retMsg); if (smuggledMrm != null) { return null; } else { if (retMsg != null) { // Null out the principal since we won't use it on the other side. // This is handled inside of SmuggleIfPossible for method call // messages. LogicalCallContext callCtx = (LogicalCallContext) retMsg.Properties[Message.CallContextKey]; if (callCtx != null) { if (callCtx.Principal != null) callCtx.Principal = null; } return CrossAppDomainSerializer.SerializeMessage(retMsg).GetBuffer(); } //*********************** SERIALIZE RET-MSG ******************** return null; } } // DoDispatch
public static object ReadMethodCall (BinaryElement elem, BinaryReader reader, bool hasHeaders, HeaderHandler headerHandler, BinaryFormatter formatter) { if (elem != BinaryElement.MethodCall) throw new SerializationException("Invalid format. Expected BinaryElement.MethodCall, found " + elem); MethodFlags flags = (MethodFlags) reader.ReadInt32(); if (((BinaryTypeCode)reader.ReadByte()) != BinaryTypeCode.String) throw new SerializationException ("Invalid format"); string methodName = reader.ReadString(); if (((BinaryTypeCode)reader.ReadByte()) != BinaryTypeCode.String) throw new SerializationException ("Invalid format"); string className = reader.ReadString(); //bool hasContextInfo = (flags & MethodFlags.IncludesLogicalCallContext) > 0; object[] arguments = null; object methodSignature = null; object callContext = null; object[] extraProperties = null; Header[] headers = null; #if NET_2_0 Type[] genericArguments = null; #endif if ((flags & MethodFlags.PrimitiveArguments) > 0) { uint count = reader.ReadUInt32(); arguments = new object[count]; for (int n=0; n<count; n++) { Type type = BinaryCommon.GetTypeFromCode (reader.ReadByte()); arguments[n] = ObjectReader.ReadPrimitiveTypeValue (reader, type); } } if ((flags & MethodFlags.NeedsInfoArrayMask) > 0) { ObjectReader objectReader = new ObjectReader (formatter); object result; objectReader.ReadObjectGraph (reader, hasHeaders, out result, out headers); object[] msgInfo = (object[]) result; if ((flags & MethodFlags.ArgumentsInSimpleArray) > 0) { arguments = msgInfo; } else { int n = 0; if ((flags & MethodFlags.ArgumentsInMultiArray) > 0) { if (msgInfo.Length > 1) arguments = (object[]) msgInfo[n++]; else arguments = new object[0]; } #if NET_2_0 if ((flags & MethodFlags.GenericArguments) > 0) genericArguments = (Type[]) msgInfo[n++]; #endif if ((flags & MethodFlags.IncludesSignature) > 0) methodSignature = msgInfo[n++]; if ((flags & MethodFlags.IncludesLogicalCallContext) > 0) callContext = msgInfo[n++]; if (n < msgInfo.Length) extraProperties = (object[]) msgInfo[n]; } } else { reader.ReadByte (); // Reads the stream ender } if (arguments == null) arguments = new object[0]; string uri = null; if (headerHandler != null) uri = headerHandler(headers) as string; #if NET_2_0 Header[] methodInfo = new Header[7]; #else Header[] methodInfo = new Header[6]; #endif methodInfo[0] = new Header("__MethodName", methodName); methodInfo[1] = new Header("__MethodSignature", methodSignature); methodInfo[2] = new Header("__TypeName", className); methodInfo[3] = new Header("__Args", arguments); methodInfo[4] = new Header("__CallContext", callContext); methodInfo[5] = new Header("__Uri", uri); #if NET_2_0 methodInfo[6] = new Header("__GenericArguments", genericArguments); #endif MethodCall call = new MethodCall (methodInfo); if (extraProperties != null) { foreach (DictionaryEntry entry in extraProperties) call.Properties [(string)entry.Key] = entry.Value; } return call; }
private static object[] CollectOutputArguments( Invocation invocation, MethodCall call, ParameterInfo[] parameters) { var outArgs = new ArrayList(call.ArgCount); for (int i = 0; i < call.ArgCount; i++) { if (!parameters[i].IsIn) { outArgs.Add(invocation.Parameters[i]); } } return outArgs.ToArray(); }
private MethodCall DeserializeRequest(ITransportHeaders requestHeaders, Stream requestStream, IXmlRpcStreamRequestConfig config) { String requestUri = GetRequestUri(requestHeaders); Type svcType = GetServerTypeForUri(requestUri); if (!_mapping.Has(svcType)) _mapping.Register(svcType); IXmlRpcRequest request = GetRequest(config, requestStream); IXmlRpcHandler handler = GetHandler(request); Header[] headers = GetChannelHeaders(requestUri, request, handler, svcType); MethodCall call = new MethodCall(headers); call.ResolveMethod(); return call; }
public void WriteRequestAndReadResponse() { var properties = new Hashtable() { { "port", 8080 } }; var channel = new HttpChannel(properties, null, new BinaryServerFormatterSinkProvider()); ChannelServices.RegisterChannel(channel, false); RemotingServices.Marshal(new ServiceClass(), "Remote"); var uri = "http://localhost:8080/Remote"; var messageRequest = new MethodCall(new Header[] { new Header(MessageHeader.Uri, uri), new Header(MessageHeader.MethodName, "Do"), new Header(MessageHeader.MethodSignature, new Type[] { typeof(string) }), new Header(MessageHeader.TypeName, typeof(ServiceClass).AssemblyQualifiedName), new Header(MessageHeader.Args, new object[] { "Hi" }) }); var messageRequestStream = BinaryFormatterHelper.SerializeObject(messageRequest); var wc = new WebClient(); var messageResponse = BinaryFormatterHelper.DeserializeObject(wc.UploadData(uri, messageRequestStream)) as MethodResponse; Assert.IsNotNull(messageResponse); DumpHelper.DumpMessage(messageResponse); if (messageResponse.Exception != null) throw messageResponse.Exception; Assert.AreEqual("Hi", messageResponse.ReturnValue); //handle.WriteRequestFirstLine("POST", "/Remote"); //handle.WriteHeaders(new Dictionary<string, object>() { { HttpHeader.ContentLength, messageRequestStream.Length } }); //HACK:http will send 100 continue after read http header //handle.WriteContent(messageRequestStream); ChannelServices.UnregisterChannel(channel); }
public static void SetServerIdentity(MethodCall m, Object srvID) { m.SetServerIdentity(srvID); }
internal byte[] DoDispatch(byte[] reqStmBuff, SmuggledMethodCallMessage smuggledMcm, out SmuggledMethodReturnMessage smuggledMrm) { RemotingServices.LogRemotingStage(RemotingServices.SERVER_MSG_DESER); //*********************** DE-SERIALIZE REQ-MSG ******************** IMessage desReqMsg = null; if (smuggledMcm != null) { ArrayList deserializedArgs = smuggledMcm.FixupForNewAppDomain(); desReqMsg = new MethodCall(smuggledMcm, deserializedArgs); } else { MemoryStream reqStm = new MemoryStream(reqStmBuff); desReqMsg = CrossAppDomainSerializer.DeserializeMessage(reqStm); } // now we can delegate to the DispatchMessage to do the rest RemotingServices.LogRemotingStage(RemotingServices.SERVER_MSG_SINK_CHAIN); IMessage retMsg = ChannelServices.SyncDispatchMessage(desReqMsg); RemotingServices.LogRemotingStage(RemotingServices.SERVER_RET_SER); smuggledMrm = SmuggledMethodReturnMessage.SmuggleIfPossible(retMsg); if (smuggledMrm != null) { return null; } else { if (retMsg != null) { // Null out the principal since we won't use it on the other side. // This is handled inside of SmuggleIfPossible for method call // messages. LogicalCallContext callCtx = (LogicalCallContext) retMsg.Properties[Message.CallContextKey]; if (callCtx != null) { if (callCtx.Principal != null) callCtx.Principal = null; } } //*********************** SERIALIZE RET-MSG ******************** return CrossAppDomainSerializer.SerializeMessage(retMsg).GetBuffer(); } } // DoDispatch
public void WriteRequestAndReadResponse() { var channel = new TcpChannel(8080); ChannelServices.RegisterChannel(channel, false); RemotingServices.Marshal(new ServiceClass(), "Remote"); var uri = "tcp://localhost:8080/Remote"; using (var client = new TcpClient()) { client.Connect("localhost", 8080); using (var stream = client.GetStream()) { var messageRequest = new MethodCall(new Header[] { new Header(MessageHeader.Uri, uri), new Header(MessageHeader.MethodName, "Do"), new Header(MessageHeader.MethodSignature, new Type[] { typeof(string) }), new Header(MessageHeader.TypeName, typeof(ServiceClass).AssemblyQualifiedName), new Header(MessageHeader.Args, new object[] { "Hi" }) }); var messageRequestStream = BinaryFormatterHelper.SerializeObject(messageRequest); var handle = new TcpProtocolHandle(stream); //send remoting request handle.WritePreamble(); handle.WriteMajorVersion(); handle.WriteMinorVersion(); handle.WriteOperation(TcpOperations.Request); handle.WriteContentDelimiter(TcpContentDelimiter.ContentLength); handle.WriteContentLength(messageRequestStream.Length); handle.WriteTransportHeaders(new Dictionary<string, object>() { { TcpTransportHeader.RequestUri, uri } }); handle.WriteContent(messageRequestStream); //read remoting response Console.WriteLine("Preamble: {0}", handle.ReadPreamble()); Console.WriteLine("MajorVersion: {0}", handle.ReadMajorVersion()); Console.WriteLine("MinorVersion: {0}", handle.ReadMinorVersion()); var op = handle.ReadOperation(); Assert.AreEqual(TcpOperations.Reply, op); Console.WriteLine("Operation: {0}", op); Console.WriteLine("ContentDelimiter: {0}", handle.ReadContentDelimiter()); Console.WriteLine("ContentLength: {0}", handle.ReadContentLength()); handle.ReadTransportHeaders(); var messageResponse = BinaryFormatterHelper.DeserializeObject(handle.ReadContent()) as MethodResponse; Assert.IsNotNull(messageResponse); DumpHelper.DumpMessage(messageResponse); if (messageResponse.Exception != null) throw messageResponse.Exception; Assert.AreEqual("Hi", messageResponse.ReturnValue); } } }
private MethodCall DeserializeRequest( ITransportHeaders requestHeaders, Stream requestStream) { var requestUri = (string)requestHeaders["__RequestUri"]; var svcType = GetServiceType(requestUri); var deserializer = new XmlRpcRequestDeserializer(); var xmlRpcReq = deserializer.DeserializeRequest(requestStream, svcType); var headers = GetChannelHeaders(requestHeaders, xmlRpcReq, svcType); var mthdCall = new MethodCall(headers); mthdCall.ResolveMethod(); return mthdCall; }
internal static IMessage DeserializeMessage(String mimeType, Stream xstm, bool methodRequest, IMessage msg, Header[] h) { InternalRemotingServices.RemotingTrace("DeserializeMessage"); InternalRemotingServices.RemotingTrace("MimeType: " + mimeType); CoreChannel.DebugOutXMLStream(xstm, "Deserializing"); Stream fmtStm = null; bool bin64encode = false; bool doHeaderBodyAsOne = true; if (string.Compare(mimeType, BinaryMimeType, StringComparison.Ordinal) == 0) { doHeaderBodyAsOne = true; } if (string.Compare(mimeType, SOAPMimeType, StringComparison.Ordinal) == 0) { doHeaderBodyAsOne = false; } if (bin64encode == false) { fmtStm = xstm; } else { InternalRemotingServices.RemotingTrace("***************** Before base64 decode *****"); long Position = xstm.Position; MemoryStream inStm = (MemoryStream)xstm; byte[] byteArray = inStm.ToArray(); xstm.Position = Position; String base64String = Encoding.ASCII.GetString(byteArray,0, byteArray.Length); byte[] byteArrayContent = Convert.FromBase64String(base64String); MemoryStream memStm = new MemoryStream(byteArrayContent); fmtStm = memStm; InternalRemotingServices.RemotingTrace("***************** after base64 decode *****"); } Object ret; IRemotingFormatter fmt = MimeTypeToFormatter(mimeType, false); if (doHeaderBodyAsOne == true) { ret = ((BinaryFormatter)fmt).UnsafeDeserializeMethodResponse(fmtStm, null, (IMethodCallMessage)msg); } else { InternalRemotingServices.RemotingTrace("Content"); InternalRemotingServices.RemotingTrace("***************** Before Deserialize Headers *****"); InternalRemotingServices.RemotingTrace("***************** After Deserialize Headers *****"); InternalRemotingServices.RemotingTrace("***************** Before Deserialize Message *****"); if (methodRequest == true) { MethodCall mc = new MethodCall(h); InternalRemotingServices.RemotingTrace("***************** Before Deserialize Message - as MethodCall *****"); fmt.Deserialize(fmtStm, new HeaderHandler(mc.HeaderHandler)); ret = mc; } else { IMethodCallMessage mcm = (IMethodCallMessage)msg; MethodResponse mr = new MethodResponse(h, mcm); InternalRemotingServices.RemotingTrace("***************** Before Deserialize Message - as MethodResponse *****"); fmt.Deserialize(fmtStm, new HeaderHandler(mr.HeaderHandler)); ret = mr; } InternalRemotingServices.RemotingTrace("***************** After Deserialize Message *****"); } // Workaround to make this method verifiable IMessage resMessage = (IMessage) ret; InternalRemotingServices.RemotingTrace("CoreChannel::DeserializeMessage OUT"); CoreChannel.DebugMessage(resMessage); return resMessage; }
// used by the server internal IMessage BuildMethodCallFromSoapMessage(SoapMessage soapMessage, string uri) { ArrayList headersList = new ArrayList(); Type[] signature = null; headersList.Add(new Header("__Uri", uri)); headersList.Add(new Header("__MethodName", soapMessage.MethodName)); string typeNamespace, assemblyName; SoapServices.DecodeXmlNamespaceForClrTypeNamespace(soapMessage.XmlNameSpace, out typeNamespace, out assemblyName); _serverType = RemotingServices.GetServerTypeForUri(uri); headersList.Add(new Header("__TypeName", _serverType.FullName, false)); if (soapMessage.Headers != null) { foreach (Header h in soapMessage.Headers) { headersList.Add (h); if (h.Name == "__MethodSignature") signature = (Type[]) h.Value; } } _xmlNamespace = soapMessage.XmlNameSpace; //RemMessageType messageType; BindingFlags bflags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; if (signature == null) _methodCallInfo = _serverType.GetMethod(soapMessage.MethodName, bflags); else _methodCallInfo = _serverType.GetMethod(soapMessage.MethodName, bflags, null, signature, null); // the *out* parameters aren't serialized // have to add them here _methodCallParameters = _methodCallInfo.GetParameters(); object[] args = new object[_methodCallParameters.Length]; int sn = 0; for (int n=0; n<_methodCallParameters.Length; n++) { ParameterInfo paramInfo = _methodCallParameters [n]; Type paramType = (paramInfo.ParameterType.IsByRef ? paramInfo.ParameterType.GetElementType() : paramInfo.ParameterType); if (paramInfo.IsOut && paramInfo.ParameterType.IsByRef) { args [n] = GetNullValue (paramType); } else{ object val = soapMessage.ParamValues[sn++]; if(val is IConvertible) args [n] = Convert.ChangeType (val, paramType); else args [n] = val; } } headersList.Add(new Header("__Args", args, false)); Header[] headers = (Header[])headersList.ToArray(typeof(Header)); // build the MethodCall from the headers MethodCall mthCall = new MethodCall(headers); return (IMessage)mthCall; }
// This is called from InternalInvoke above when someone makes an // Async (or a one way) call on a TP internal void InternalInvokeAsync(IMessageSink ar, Message reqMsg, bool useDispatchMessage, int callType) { IMessageCtrl cc = null; Identity idObj = IdentityObject; ServerIdentity serverID = idObj as ServerIdentity; MethodCall cpyMsg= new MethodCall(reqMsg); IInternalMessage iim = ((IInternalMessage)cpyMsg); // Set the identity in the message object iim.IdentityObject = idObj; if (null != serverID) { Message.DebugOut("Setting SrvID on deser msg\n"); iim.ServerIdentityObject = serverID; } if (useDispatchMessage) { Message.DebugOut( "RemotingProxy.Invoke: Calling AsyncDispatchMessage\n"); BCLDebug.Assert(ar != null,"ar != null"); BCLDebug.Assert( (callType & Message.BeginAsync) != 0, "BeginAsync flag not set!"); Message.DebugOut("Calling AsynDispatchMessage \n"); cc = ChannelServices.AsyncDispatchMessage( cpyMsg, ((callType & Message.OneWay) != 0) ? null : ar); } else if (null != idObj.EnvoyChain) { Message.DebugOut("RemotingProxy.Invoke: Calling AsyncProcessMsg on the envoy chain\n"); cc = idObj.EnvoyChain.AsyncProcessMessage( cpyMsg, ((callType & Message.OneWay) != 0) ? null : ar); } else { // Channel sink cannot be null since it is the last sink in // the client context // Assert if Invoke is called without a channel sink BCLDebug.Assert(false, "How did we get here?"); throw new ExecutionEngineException( Environment.GetResourceString("Remoting_Proxy_InvalidState")); } if ((callType & Message.BeginAsync) != 0) { if ((callType & Message.OneWay) != 0) { ar.SyncProcessMessage(null); } } }
/// <summary> /// Invokes the message. /// </summary> /// <param name="msg">The message.</param> /// <returns>The result of invocation.</returns> public override IMessage Invoke(IMessage msg) { IConstructionCallMessage constructorCall = msg as IConstructionCallMessage; if (constructorCall != null) { if (this.target == null) { MethodInfo factoryMethodInfo = Utility.GetInheritedMethod(constructorCall.ActivationType, DynamicConstructionAttribute.InstantiateMethodName, new[] { typeof(Type), typeof(object[]) }); if (factoryMethodInfo == null) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Cannot create an instance of type '{0}' because there is no '{1}' static method defined in its inheritance hierarchy. See '{2}' methods for an example of corresponding method signature.", constructorCall.ActivationType.AssemblyQualifiedName, DynamicConstructionAttribute.InstantiateMethodName, typeof(LiveTest).AssemblyQualifiedName)); } if (!DynamicConstructionAttribute.EnterInstantiationPhase()) { throw new InvalidOperationException("Error in instantiation workflow. Object is already in the middle of instantiation when another instance of the object is created."); } try { this.target = (LiveTest)factoryMethodInfo.Invoke(null, new object[] { constructorCall.ActivationType, constructorCall.Args }); } finally { DynamicConstructionAttribute.LeaveInstantiationPhase(); } } return EnterpriseServicesHelper.CreateConstructionReturnMessage(constructorCall, (MarshalByRefObject)this.GetTransparentProxy()); } IMethodCallMessage methodCall = msg as IMethodCallMessage; if (methodCall != null) { methodCall = new MethodCall(methodCall); MethodCallEventArgs eventArgs = typeof(LiveTest).IsAssignableFrom(methodCall.MethodBase.DeclaringType) ? new MethodCallEventArgs(Interlocked.Increment(ref methodCallId), methodCall.MethodBase, methodCall.Args) : null; if (eventArgs != null) { this.target.OnBeforeMethodCall(this.target, eventArgs); } IMessage result = RemotingServices.GetRealProxy(this.target).Invoke(methodCall); if (eventArgs != null) { this.target.OnAfterMethodCall(this.target, eventArgs); } return result; } throw new NotSupportedException("Operations other than constructor and method calls are not supported."); }
/// <summary> /// Deserialises the Giop Message body for a request /// </summary> /// <param name="cdrStream"></param> /// <param name="version"></param> /// <returns></returns> internal IMessage DeserialiseRequest(CdrInputStream cdrStream, GiopVersion version, GiopConnectionDesc conDesc, IInterceptionOption[] interceptionOptions) { MethodCall methodCallInfo = null; GiopServerRequest serverRequest = new GiopServerRequest(conDesc, interceptionOptions); serverRequest.Version = version; try { ServiceContextList cntxColl = null; if (version.IsBeforeGiop1_2()) { // GIOP 1.0 / 1.1 cntxColl = DeserialiseContext(cdrStream); // Service context deser } // read the request-ID and set it as a message property uint requestId = cdrStream.ReadULong(); serverRequest.RequestId = requestId; Trace.WriteLine("received a message with reqId: " + requestId); // read response-flags: byte respFlags = cdrStream.ReadOctet(); Debug.WriteLine("response-flags: " + respFlags); cdrStream.ReadPadding(3); // read reserved bytes serverRequest.ResponseFlags = respFlags; // decode the target of this request byte[] objectKey; serverRequest.RequestUri = ReadTarget(cdrStream, version, out objectKey); serverRequest.ObjectKey = objectKey; serverRequest.RequestMethodName = cdrStream.ReadString(); Trace.WriteLine("call for .NET object: " + serverRequest.RequestUri + ", methodName: " + serverRequest.RequestMethodName); if (version.IsBeforeGiop1_2()) { // GIOP 1.0 / 1.1 uint principalLength = cdrStream.ReadULong(); cdrStream.ReadOpaque((int)principalLength); } else { cntxColl = DeserialiseContext(cdrStream); // Service context deser } PerformCodeSetEstablishmentServer(version, conDesc, cntxColl); // set codeset for stream SetCodeSet(cdrStream, conDesc); // request header deserialised serverRequest.RequestServiceContext = cntxColl; serverRequest.InterceptReceiveRequestServiceContexts(); serverRequest.SetThreadScopeCurrentFromPICurrent(); // copy request scope picurrent to thread scope pi-current serverRequest.ResolveTargetType(); // determine the .net target object type and check if target object is available ArgumentsSerializer argSer = m_argSerFactory.Create(serverRequest.ServerTypeType); MethodInfo called = argSer.GetMethodInfoFor(serverRequest.RequestMethodName); serverRequest.ResolveCalledMethod(called); // set target method and handle special cases IDictionary contextElements; DeserialiseRequestBody(cdrStream, version, serverRequest, argSer, out contextElements); methodCallInfo = new MethodCall(serverRequest.Request); if (contextElements != null) { AddContextElementsToCallContext(methodCallInfo.LogicalCallContext, contextElements); } serverRequest.UpdateWithFinalRequest(methodCallInfo); serverRequest.InterceptReceiveRequest(); // all information now available return methodCallInfo; } catch (Exception e) { // an Exception encountered during deserialisation try { cdrStream.SkipRest(); // skip rest of the message, to not corrupt the stream } catch (Exception) { // ignore exception here, already an other exception leading to problems } ReturnMessage exceptionResponse; exceptionResponse = new ReturnMessage(e, methodCallInfo); throw new RequestDeserializationException(e, serverRequest.Request, exceptionResponse); // send exception interception point will be called when serialising exception response } }
// private methods // MethodCall DeserializeRequest( ITransportHeaders requestHeaders, Stream requestStream) { string requestUri = (string) requestHeaders["__RequestUri"]; Type svcType = GetServiceType(requestUri); XmlRpcSerializer serializer = new XmlRpcSerializer(); XmlRpcRequest xmlRpcReq = serializer.DeserializeRequest(requestStream, svcType); Header[] headers = GetChannelHeaders(requestHeaders, xmlRpcReq, svcType); MethodCall mthdCall = new MethodCall(headers); mthdCall.ResolveMethod(); return mthdCall; }
internal static IMessage DeserializeMessage(string mimeType, Stream xstm, bool methodRequest, IMessage msg, Header[] h) { Stream serializationStream = null; object obj2; bool flag = false; bool flag2 = true; if (string.Compare(mimeType, "application/octet-stream", StringComparison.Ordinal) == 0) { flag2 = true; } if (string.Compare(mimeType, "text/xml", StringComparison.Ordinal) == 0) { flag2 = false; } if (!flag) { serializationStream = xstm; } else { long position = xstm.Position; byte[] bytes = ((MemoryStream) xstm).ToArray(); xstm.Position = position; MemoryStream stream3 = new MemoryStream(Convert.FromBase64String(Encoding.ASCII.GetString(bytes, 0, bytes.Length))); serializationStream = stream3; } IRemotingFormatter formatter = MimeTypeToFormatter(mimeType, false); if (flag2) { obj2 = ((BinaryFormatter) formatter).UnsafeDeserializeMethodResponse(serializationStream, null, (IMethodCallMessage) msg); } else if (methodRequest) { MethodCall call = new MethodCall(h); formatter.Deserialize(serializationStream, new HeaderHandler(call.HeaderHandler)); obj2 = call; } else { IMethodCallMessage mcm = (IMethodCallMessage) msg; MethodResponse response = new MethodResponse(h, mcm); formatter.Deserialize(serializationStream, new HeaderHandler(response.HeaderHandler)); obj2 = response; } return (IMessage) obj2; }
// used by the server internal IMessage BuildMethodCallFromSoapMessage(SoapMessage soapMessage, string uri) { ArrayList headersList = new ArrayList(); Type[] signature = null; headersList.Add(new Header("__Uri", uri)); headersList.Add(new Header("__MethodName", soapMessage.MethodName)); string typeNamespace, assemblyName; if (!SoapServices.DecodeXmlNamespaceForClrTypeNamespace(soapMessage.XmlNameSpace, out typeNamespace, out assemblyName)) throw new RemotingException ("Could not decode SoapMessage"); // Note that we don't need to validate the type in // this place because MethodCall will do it anyway. if (assemblyName == null) // corlib _serverType = Type.GetType (typeNamespace, true); else _serverType = Type.GetType (typeNamespace + ", " + assemblyName, true); headersList.Add(new Header("__TypeName", _serverType.FullName, false)); if (soapMessage.Headers != null) { foreach (Header h in soapMessage.Headers) { headersList.Add (h); if (h.Name == "__MethodSignature") signature = (Type[]) h.Value; } } _xmlNamespace = soapMessage.XmlNameSpace; //RemMessageType messageType; BindingFlags bflags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; if (signature == null) _methodCallInfo = _serverType.GetMethod(soapMessage.MethodName, bflags); else _methodCallInfo = _serverType.GetMethod(soapMessage.MethodName, bflags, null, signature, null); if (_methodCallInfo == null && (soapMessage.MethodName == "FieldSetter" || soapMessage.MethodName == "FieldGetter")) _methodCallInfo = typeof(object).GetMethod (soapMessage.MethodName, bflags); // the *out* parameters aren't serialized // have to add them here _methodCallParameters = _methodCallInfo.GetParameters(); object[] args = new object[_methodCallParameters.Length]; int sn = 0; for (int n=0; n<_methodCallParameters.Length; n++) { ParameterInfo paramInfo = _methodCallParameters [n]; Type paramType = (paramInfo.ParameterType.IsByRef ? paramInfo.ParameterType.GetElementType() : paramInfo.ParameterType); if (paramInfo.IsOut && paramInfo.ParameterType.IsByRef) { args [n] = GetNullValue (paramType); } else{ object val = soapMessage.ParamValues[sn++]; if(val is IConvertible) args [n] = Convert.ChangeType (val, paramType); else args [n] = val; } } headersList.Add(new Header("__Args", args, false)); Header[] headers = (Header[])headersList.ToArray(typeof(Header)); // build the MethodCall from the headers MethodCall mthCall = new MethodCall(headers); return (IMessage)mthCall; }
internal static IMessage DeserializeSoapRequestMessage(Stream inputStream, Header[] h, bool bStrictBinding, TypeFilterLevel securityLevel) { SoapFormatter formatter = CreateSoapFormatter(false, bStrictBinding); formatter.FilterLevel = securityLevel; MethodCall call = new MethodCall(h); formatter.Deserialize(inputStream, new HeaderHandler(call.HeaderHandler)); return call; }
public IMessageCtrl AsyncProcessMessage (IMessage msg, IMessageSink replySink) { if (syncContext == null) return nextSink.AsyncProcessMessage (msg, replySink); // Make a copy of the message since MS.NET seems to free the original message // once it has been dispatched. if (!isMono) msg = new MethodCall (msg); MsgData md = new MsgData (); md.InMessage = msg; md.ReplySink = replySink; syncContext.AsyncDispatch (new StatefulMessageHandler (AsyncDispatchMessage), md); return null; }
public static void SetServerIdentity (MethodCall m, object srvID) { Identity ident = srvID as Identity; if (ident == null) throw new ArgumentException ("srvID"); RemotingServices.SetMessageTargetIdentity (m, ident); }
internal void ProcessMessageInDomain (byte[] arrRequest, CADMethodCallMessage cadMsg, out byte[] arrResponse, out CADMethodReturnMessage cadMrm) { IMessage reqDomMsg; if (null != arrRequest) reqDomMsg = CADSerializer.DeserializeMessage (new MemoryStream(arrRequest), null); else reqDomMsg = new MethodCall (cadMsg); IMessage retDomMsg = ChannelServices.SyncDispatchMessage (reqDomMsg); cadMrm = CADMethodReturnMessage.Create (retDomMsg); if (null == cadMrm) { arrResponse = CADSerializer.SerializeMessage (retDomMsg).GetBuffer(); } else arrResponse = null; }
public static void SetServerIdentity(MethodCall m, object srvID) { IInternalMessage message = m; message.ServerIdentityObject = (ServerIdentity) srvID; }