2 // System.Runtime.Remoting.RemotingServices.cs
5 // Dietmar Maurer (dietmar@ximian.com)
6 // Lluis Sanchez Gual (lluis@ideary.com)
9 // (C) 2001 Ximian, Inc. http://www.ximian.com
13 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 using System.Diagnostics;
38 using System.Reflection;
39 using System.Threading;
40 using System.Collections;
41 using System.Runtime.Remoting.Messaging;
42 using System.Runtime.Remoting.Proxies;
43 using System.Runtime.Remoting.Channels;
44 using System.Runtime.Remoting.Contexts;
45 using System.Runtime.Remoting.Activation;
46 using System.Runtime.Remoting.Lifetime;
47 using System.Runtime.CompilerServices;
48 using System.Runtime.Serialization;
49 using System.Runtime.Serialization.Formatters.Binary;
53 using System.Runtime.ConstrainedExecution;
56 namespace System.Runtime.Remoting
58 public sealed class RemotingServices
60 // Holds the identities of the objects, using uri as index
61 static Hashtable uri_hash = new Hashtable ();
63 static BinaryFormatter _serializationFormatter;
64 static BinaryFormatter _deserializationFormatter;
66 internal static string app_id;
67 static int next_id = 1;
68 static readonly BindingFlags methodBindings = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
70 // Holds information in xdomain calls. Names are short to minimize serialized size.
73 public object d; /* call data */
74 public object c; /* call context */
77 static RemotingServices ()
79 RemotingSurrogateSelector surrogateSelector = new RemotingSurrogateSelector ();
80 StreamingContext context = new StreamingContext (StreamingContextStates.Remoting, null);
81 _serializationFormatter = new BinaryFormatter (surrogateSelector, context);
82 _deserializationFormatter = new BinaryFormatter (null, context);
84 RegisterInternalChannels ();
85 app_id = Guid.NewGuid().ToString().Replace('-', '_') + "/";
86 CreateWellKnownServerIdentity (typeof(RemoteActivator), "RemoteActivationService.rem", WellKnownObjectMode.Singleton);
89 private RemotingServices () {}
91 [MethodImplAttribute(MethodImplOptions.InternalCall)]
92 internal extern static object InternalExecute (MethodBase method, Object obj,
93 Object[] parameters, out object [] out_args);
96 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
98 [MethodImplAttribute(MethodImplOptions.InternalCall)]
99 public extern static bool IsTransparentProxy (object proxy);
101 internal static IMethodReturnMessage InternalExecuteMessage (
102 MarshalByRefObject target, IMethodCallMessage reqMsg)
104 ReturnMessage result;
106 Type tt = target.GetType ();
107 MethodBase method = reqMsg.MethodBase.DeclaringType == tt ? reqMsg.MethodBase : tt.GetMethod(reqMsg.MethodName, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance, null, (Type[]) reqMsg.MethodSignature, null);
108 object oldContext = CallContext.SetCurrentCallContext (reqMsg.LogicalCallContext);
113 object rval = InternalExecute (method, target, reqMsg.Args, out out_args);
115 // Collect parameters with Out flag from the request message
116 // FIXME: This can be done in the unmanaged side and will be
119 ParameterInfo[] parameters = method.GetParameters();
120 object[] returnArgs = new object [parameters.Length];
124 foreach (ParameterInfo par in parameters)
126 if (par.IsOut && !par.ParameterType.IsByRef)
127 returnArgs [n++] = reqMsg.GetArg (par.Position);
128 else if (par.ParameterType.IsByRef)
129 returnArgs [n++] = out_args [noa++];
131 returnArgs [n++] = null;
134 result = new ReturnMessage (rval, returnArgs, n, CallContext.CreateLogicalCallContext (true), reqMsg);
138 result = new ReturnMessage (e, reqMsg);
141 CallContext.RestoreCallContext (oldContext);
145 public static IMethodReturnMessage ExecuteMessage (
146 MarshalByRefObject target, IMethodCallMessage reqMsg)
148 if (IsTransparentProxy(target))
150 // Message must go through all chain of sinks
151 RealProxy rp = GetRealProxy (target);
152 return (IMethodReturnMessage) rp.Invoke (reqMsg);
155 return InternalExecuteMessage (target, reqMsg);
158 public static object Connect (Type classToProxy, string url)
160 ObjRef objRef = new ObjRef (classToProxy, url, null);
161 return GetRemoteObject (objRef, classToProxy);
164 public static object Connect (Type classToProxy, string url, object data)
166 ObjRef objRef = new ObjRef (classToProxy, url, data);
167 return GetRemoteObject (objRef, classToProxy);
170 public static bool Disconnect (MarshalByRefObject obj)
172 if (obj == null) throw new ArgumentNullException ("obj");
174 ServerIdentity identity;
176 if (IsTransparentProxy (obj))
178 // CBOs are always accessed through a proxy, even in the server, so
179 // for server CBOs it is ok to disconnect a proxy
181 RealProxy proxy = GetRealProxy(obj);
182 if (proxy.GetProxiedType().IsContextful && (proxy.ObjectIdentity is ServerIdentity))
183 identity = proxy.ObjectIdentity as ServerIdentity;
185 throw new ArgumentException ("The obj parameter is a proxy.");
188 identity = obj.ObjectIdentity;
189 obj.ObjectIdentity = null;
192 if (identity == null || !identity.IsConnected)
196 LifetimeServices.StopTrackingLifetime (identity);
197 DisposeIdentity (identity);
202 public static Type GetServerTypeForUri (string uri)
204 ServerIdentity ident = GetIdentityForUri (uri) as ServerIdentity;
205 if (ident == null) return null;
206 return ident.ObjectType;
209 public static string GetObjectUri (MarshalByRefObject obj)
211 Identity ident = GetObjectIdentity(obj);
212 if (ident is ClientIdentity) return ((ClientIdentity)ident).TargetUri;
213 else if (ident != null) return ident.ObjectUri;
217 public static object Unmarshal (ObjRef objref)
219 return Unmarshal(objref, true);
222 public static object Unmarshal (ObjRef objref, bool fRefine)
224 Type classToProxy = fRefine ? objref.ServerType : typeof (MarshalByRefObject);
225 if (classToProxy == null) classToProxy = typeof (MarshalByRefObject);
227 if (objref.IsReferenceToWellKnow)
228 return GetRemoteObject(objref, classToProxy);
231 if (classToProxy.IsContextful)
233 // Look for a ProxyAttribute
234 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (classToProxy, typeof(ProxyAttribute),true);
236 return att.CreateProxy (objref, classToProxy, null, null).GetTransparentProxy();
238 return GetProxyForRemoteObject (objref, classToProxy);
242 public static ObjRef Marshal (MarshalByRefObject obj)
244 return Marshal (obj, null, null);
247 public static ObjRef Marshal (MarshalByRefObject obj, string uri)
249 return Marshal (obj, uri, null);
252 public static ObjRef Marshal (MarshalByRefObject obj, string uri, Type requested_type)
254 if (IsTransparentProxy (obj))
256 RealProxy proxy = RemotingServices.GetRealProxy(obj);
257 Identity identity = proxy.ObjectIdentity;
259 if (identity != null)
261 if (proxy.GetProxiedType().IsContextful && !identity.IsConnected)
263 // Unregistered local contextbound object. Register now.
264 ClientActivatedIdentity cboundIdentity = (ClientActivatedIdentity)identity;
265 if (uri == null) uri = NewUri();
266 cboundIdentity.ObjectUri = uri;
267 RegisterServerIdentity (cboundIdentity);
268 cboundIdentity.StartTrackingLifetime ((ILease)obj.InitializeLifetimeService());
269 return cboundIdentity.CreateObjRef(requested_type);
271 else if (uri != null)
272 throw new RemotingException ("It is not possible marshal a proxy of a remote object.");
274 return proxy.ObjectIdentity.CreateObjRef(requested_type);
278 if (requested_type == null) requested_type = obj.GetType();
282 if (obj.ObjectIdentity == null)
285 CreateClientActivatedServerIdentity (obj, requested_type, uri);
290 ClientActivatedIdentity identity = GetIdentityForUri ("/" + uri) as ClientActivatedIdentity;
291 if (identity == null || obj != identity.GetServerObject())
292 CreateClientActivatedServerIdentity (obj, requested_type, uri);
295 if (IsTransparentProxy (obj))
296 return RemotingServices.GetRealProxy(obj).ObjectIdentity.CreateObjRef (requested_type);
298 return obj.CreateObjRef(requested_type);
301 static string NewUri ()
303 int n = Interlocked.Increment (ref next_id);
304 return app_id + Environment.TickCount + "_" + n + ".rem";
308 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
310 public static RealProxy GetRealProxy (object proxy)
312 if (!IsTransparentProxy(proxy)) throw new RemotingException("Cannot get the real proxy from an object that is not a transparent proxy.");
313 return (RealProxy)((TransparentProxy)proxy)._rp;
316 public static MethodBase GetMethodBaseFromMethodMessage(IMethodMessage msg)
318 Type type = Type.GetType (msg.TypeName);
320 throw new RemotingException ("Type '" + msg.TypeName + "' not found.");
322 return GetMethodBaseFromName (type, msg.MethodName, (Type[]) msg.MethodSignature);
325 internal static MethodBase GetMethodBaseFromName (Type type, string methodName, Type[] signature)
327 if (type.IsInterface) {
328 return FindInterfaceMethod (type, methodName, signature);
331 MethodBase method = null;
332 if (signature == null)
333 method = type.GetMethod (methodName, methodBindings);
335 method = type.GetMethod (methodName, methodBindings, null, (Type[]) signature, null);
340 if (signature == null)
341 return type.GetConstructor (methodBindings, null, Type.EmptyTypes, null);
343 return type.GetConstructor (methodBindings, null, signature, null);
347 static MethodBase FindInterfaceMethod (Type type, string methodName, Type[] signature)
349 MethodBase method = null;
351 if (signature == null)
352 method = type.GetMethod (methodName, methodBindings);
354 method = type.GetMethod (methodName, methodBindings, null, signature, null);
356 if (method != null) return method;
358 foreach (Type t in type.GetInterfaces ()) {
359 method = FindInterfaceMethod (t, methodName, signature);
360 if (method != null) return method;
366 public static void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
368 if (obj == null) throw new ArgumentNullException ("obj");
370 ObjRef oref = Marshal ((MarshalByRefObject)obj);
371 oref.GetObjectData (info, context);
374 public static ObjRef GetObjRefForProxy(MarshalByRefObject obj)
376 Identity ident = GetObjectIdentity(obj);
377 if (ident == null) return null;
378 else return ident.CreateObjRef(null);
381 public static object GetLifetimeService (MarshalByRefObject obj)
383 if (obj == null) return null;
384 return obj.GetLifetimeService ();
387 public static IMessageSink GetEnvoyChainForProxy (MarshalByRefObject obj)
389 if (IsTransparentProxy(obj))
390 return ((ClientIdentity)GetRealProxy (obj).ObjectIdentity).EnvoySink;
392 throw new ArgumentException ("obj must be a proxy.","obj");
396 [Conditional ("REMOTING_PERF")]
397 public static void LogRemotingStage (int stage)
399 throw new NotImplementedException ();
402 public static string GetSessionIdForMethodMessage(IMethodMessage msg)
404 // It seems that this it what MS returns.
408 public static bool IsMethodOverloaded(IMethodMessage msg)
410 const BindingFlags bfinst = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
411 MonoType type = (MonoType) msg.MethodBase.DeclaringType;
412 return type.GetMethodsByName (msg.MethodName, bfinst, false, type).Length > 1;
415 public static bool IsObjectOutOfAppDomain(object tp)
417 // TODO: use internal call for better performance
418 Identity ident = GetObjectIdentity((MarshalByRefObject)tp);
419 return ident is ClientIdentity;
422 public static bool IsObjectOutOfContext(object tp)
424 // TODO: use internal call for better performance
425 Identity ident = GetObjectIdentity((MarshalByRefObject)tp);
426 if (ident == null) return false;
428 ServerIdentity sident = ident as ServerIdentity;
429 if (sident != null) return sident.Context != System.Threading.Thread.CurrentContext;
433 public static bool IsOneWay(MethodBase method)
435 return method.IsDefined (typeof (OneWayAttribute), false);
438 internal static bool IsAsyncMessage(IMessage msg)
440 if (! (msg is MonoMethodMessage)) return false;
441 else if (((MonoMethodMessage)msg).IsAsync) return true;
442 else if (IsOneWay (((MonoMethodMessage)msg).MethodBase)) return true;
446 public static void SetObjectUriForMarshal(MarshalByRefObject obj, string uri)
448 if (IsTransparentProxy (obj)) {
449 RealProxy proxy = RemotingServices.GetRealProxy(obj);
450 Identity identity = proxy.ObjectIdentity;
452 if (identity != null && !(identity is ServerIdentity) && !proxy.GetProxiedType().IsContextful)
453 throw new RemotingException ("SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.");
459 #region Internal Methods
461 internal static object CreateClientProxy (ActivatedClientTypeEntry entry, object[] activationAttributes)
463 if (entry.ContextAttributes != null || activationAttributes != null)
465 ArrayList props = new ArrayList ();
466 if (entry.ContextAttributes != null) props.AddRange (entry.ContextAttributes);
467 if (activationAttributes != null) props.AddRange (activationAttributes);
468 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, props.ToArray ());
471 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, null);
474 internal static object CreateClientProxy (Type objectType, string url, object[] activationAttributes)
476 string activationUrl = url + "/RemoteActivationService.rem";
479 GetClientChannelSinkChain (activationUrl, null, out objectUri);
481 RemotingProxy proxy = new RemotingProxy (objectType, activationUrl, activationAttributes);
482 return proxy.GetTransparentProxy();
485 internal static object CreateClientProxy (WellKnownClientTypeEntry entry)
487 return Connect (entry.ObjectType, entry.ObjectUrl, null);
490 internal static object CreateClientProxyForContextBound (Type type, object[] activationAttributes)
492 if (type.IsContextful)
494 // Look for a ProxyAttribute
495 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (type, typeof(ProxyAttribute), true);
497 return att.CreateInstance (type);
499 RemotingProxy proxy = new RemotingProxy (type, ChannelServices.CrossContextUrl, activationAttributes);
500 return proxy.GetTransparentProxy();
503 internal static Identity GetIdentityForUri (string uri)
507 return (Identity)uri_hash [GetNormalizedUri(uri)];
511 internal static Identity GetObjectIdentity (MarshalByRefObject obj)
513 if (IsTransparentProxy(obj))
514 return GetRealProxy (obj).ObjectIdentity;
516 return obj.ObjectIdentity;
519 internal static ClientIdentity GetOrCreateClientIdentity(ObjRef objRef, Type proxyType, out object clientProxy)
521 // This method looks for an identity for the given url.
522 // If an identity is not found, it creates the identity and
523 // assigns it a proxy to the remote object.
525 // Creates the client sink chain for the given url or channelData.
526 // It will also get the object uri from the url.
528 object channelData = objRef.ChannelInfo != null ? objRef.ChannelInfo.ChannelData : null;
531 IMessageSink sink = GetClientChannelSinkChain (objRef.URI, channelData, out objectUri);
533 if (objectUri == null) objectUri = objRef.URI;
538 string uri = GetNormalizedUri (objRef.URI);
540 ClientIdentity identity = uri_hash [uri] as ClientIdentity;
541 if (identity != null)
543 // Object already registered
544 clientProxy = identity.ClientProxy;
545 if (clientProxy != null) return identity;
547 // The proxy has just been GCed, so its identity cannot
548 // be reused. Just dispose it.
549 DisposeIdentity (identity);
552 // Creates an identity and a proxy for the remote object
554 identity = new ClientIdentity (objectUri, objRef);
555 identity.ChannelSink = sink;
557 // Registers the identity
558 uri_hash [uri] = identity;
560 if (proxyType != null)
562 RemotingProxy proxy = new RemotingProxy (proxyType, identity);
563 CrossAppDomainSink cds = sink as CrossAppDomainSink;
565 proxy.SetTargetDomain (cds.TargetDomainId);
567 clientProxy = proxy.GetTransparentProxy();
568 identity.ClientProxy = (MarshalByRefObject) clientProxy;
575 static IMessageSink GetClientChannelSinkChain(string url, object channelData, out string objectUri)
577 IMessageSink sink = ChannelServices.CreateClientChannelSinkChain (url, channelData, out objectUri);
582 string msg = String.Format ("Cannot create channel sink to connect to URL {0}. An appropriate channel has probably not been registered.", url);
583 throw new RemotingException (msg);
587 string msg = String.Format ("Cannot create channel sink to connect to the remote object. An appropriate channel has probably not been registered.", url);
588 throw new RemotingException (msg);
594 internal static ClientActivatedIdentity CreateContextBoundObjectIdentity(Type objectType)
596 ClientActivatedIdentity identity = new ClientActivatedIdentity (null, objectType);
597 identity.ChannelSink = ChannelServices.CrossContextChannel;
601 internal static ClientActivatedIdentity CreateClientActivatedServerIdentity(MarshalByRefObject realObject, Type objectType, string objectUri)
603 ClientActivatedIdentity identity = new ClientActivatedIdentity (objectUri, objectType);
604 identity.AttachServerObject (realObject, Context.DefaultContext);
605 RegisterServerIdentity (identity);
606 identity.StartTrackingLifetime ((ILease)realObject.InitializeLifetimeService ());
610 internal static ServerIdentity CreateWellKnownServerIdentity(Type objectType, string objectUri, WellKnownObjectMode mode)
612 ServerIdentity identity;
614 if (mode == WellKnownObjectMode.SingleCall)
615 identity = new SingleCallIdentity(objectUri, Context.DefaultContext, objectType);
617 identity = new SingletonIdentity(objectUri, Context.DefaultContext, objectType);
619 RegisterServerIdentity (identity);
623 private static void RegisterServerIdentity(ServerIdentity identity)
627 if (uri_hash.ContainsKey (identity.ObjectUri))
628 throw new RemotingException ("Uri already in use: " + identity.ObjectUri + ".");
630 uri_hash[identity.ObjectUri] = identity;
634 internal static object GetProxyForRemoteObject (ObjRef objref, Type classToProxy)
636 ClientActivatedIdentity identity = GetIdentityForUri (objref.URI) as ClientActivatedIdentity;
637 if (identity != null) return identity.GetServerObject ();
638 else return GetRemoteObject (objref, classToProxy);
641 internal static object GetRemoteObject(ObjRef objRef, Type proxyType)
644 GetOrCreateClientIdentity (objRef, proxyType, out proxy);
648 // This method is called by the runtime
649 internal static object GetServerObject (string uri)
651 ClientActivatedIdentity identity = GetIdentityForUri (uri) as ClientActivatedIdentity;
652 if (identity == null) throw new RemotingException ("Server for uri '" + uri + "' not found");
653 return identity.GetServerObject ();
656 // This method is called by the runtime
657 internal static byte[] SerializeCallData (object obj)
659 LogicalCallContext ctx = CallContext.CreateLogicalCallContext (false);
661 CACD cad = new CACD ();
667 if (obj == null) return null;
668 MemoryStream ms = new MemoryStream ();
669 _serializationFormatter.Serialize (ms, obj);
670 return ms.ToArray ();
673 // This method is called by the runtime
674 internal static object DeserializeCallData (byte[] array)
676 if (array == null) return null;
678 MemoryStream ms = new MemoryStream (array);
679 object obj = _deserializationFormatter.Deserialize (ms);
682 CACD cad = (CACD) obj;
684 CallContext.UpdateCurrentCallContext ((LogicalCallContext) cad.c);
689 // This method is called by the runtime
690 internal static byte[] SerializeExceptionData (Exception ex)
697 MemoryStream ms = new MemoryStream ();
698 _serializationFormatter.Serialize (ms, ex);
699 return ms.ToArray ();
701 catch (Exception e) {
702 if (e is ThreadAbortException) {
703 Thread.ResetAbort ();
707 else if (retry == 2) {
708 ex = new Exception ();
709 ex.SetMessage (e.Message);
710 ex.SetStackTrace (e.StackTrace);
721 catch (Exception tex)
723 byte[] data = SerializeExceptionData (tex);
724 Thread.ResetAbort ();
729 internal static object GetDomainProxy(AppDomain domain)
733 Context currentContext = Thread.CurrentContext;
737 data = (byte[])AppDomain.InvokeInDomain (domain, typeof (AppDomain).GetMethod ("GetMarshalledDomainObjRef", BindingFlags.Instance|BindingFlags.NonPublic), domain, null);
741 AppDomain.InternalSetContext (currentContext);
744 MemoryStream stream = new MemoryStream (data);
745 ObjRef appref = (ObjRef) CADSerializer.DeserializeObject (stream);
746 return (AppDomain) RemotingServices.Unmarshal(appref);
749 private static void RegisterInternalChannels()
751 CrossAppDomainChannel.RegisterCrossAppDomainChannel();
754 internal static void DisposeIdentity (Identity ident)
758 if (!ident.Disposed) {
759 ClientIdentity clientId = ident as ClientIdentity;
760 if (clientId != null)
761 uri_hash.Remove (GetNormalizedUri (clientId.TargetUri));
763 uri_hash.Remove (ident.ObjectUri);
765 ident.Disposed = true;
770 internal static Identity GetMessageTargetIdentity (IMessage msg)
772 // Returns the identity where the message is sent
774 if (msg is IInternalMessage)
775 return ((IInternalMessage)msg).TargetIdentity;
779 string uri = GetNormalizedUri (((IMethodMessage)msg).Uri);
780 return uri_hash [uri] as ServerIdentity;
784 internal static void SetMessageTargetIdentity (IMessage msg, Identity ident)
786 if (msg is IInternalMessage)
787 ((IInternalMessage)msg).TargetIdentity = ident;
790 internal static bool UpdateOutArgObject (ParameterInfo pi, object local, object remote)
792 if (local is StringBuilder)
794 StringBuilder sb = local as StringBuilder;
795 sb.Remove (0, sb.Length);
796 sb.Append (remote.ToString());
799 else if (pi.ParameterType.IsArray && ((Array)local).Rank == 1)
801 Array alocal = (Array) local;
802 if (alocal.Rank == 1)
804 Array.Copy ((Array) remote, alocal, alocal.Length);
815 static string GetNormalizedUri (string uri)
817 if (uri.StartsWith ("/")) return uri.Substring (1);