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
14 using System.Reflection;
15 using System.Threading;
16 using System.Collections;
17 using System.Runtime.Remoting.Messaging;
18 using System.Runtime.Remoting.Proxies;
19 using System.Runtime.Remoting.Channels;
20 using System.Runtime.Remoting.Contexts;
21 using System.Runtime.Remoting.Activation;
22 using System.Runtime.Remoting.Lifetime;
23 using System.Runtime.CompilerServices;
24 using System.Runtime.Serialization;
27 namespace System.Runtime.Remoting
29 public sealed class RemotingServices
31 // Holds the identities of the objects, using uri as index
32 static Hashtable uri_hash = new Hashtable ();
34 internal static string app_id;
35 static int next_id = 1;
37 static RemotingServices ()
39 RegisterInternalChannels ();
40 app_id = Guid.NewGuid().ToString().Replace('-', '_') + "/";
41 CreateWellKnownServerIdentity (typeof(RemoteActivator), "RemoteActivationService.rem", WellKnownObjectMode.Singleton);
44 private RemotingServices () {}
46 [MethodImplAttribute(MethodImplOptions.InternalCall)]
47 internal extern static object InternalExecute (MonoMethod method, Object obj,
48 Object[] parameters, out object [] out_args);
50 [MethodImplAttribute(MethodImplOptions.InternalCall)]
51 public extern static bool IsTransparentProxy (object proxy);
53 internal static IMethodReturnMessage InternalExecuteMessage (
54 MarshalByRefObject target, IMethodCallMessage reqMsg)
58 MonoMethod method = (MonoMethod) target.GetType().GetMethod(reqMsg.MethodName, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance, null, (Type[]) reqMsg.MethodSignature, null);
59 object oldContext = CallContext.SetCurrentCallContext (reqMsg.LogicalCallContext);
64 object rval = InternalExecute (method, target, reqMsg.Args, out out_args);
66 // Collect parameters with Out flag from the request message
68 ParameterInfo[] parameters = method.GetParameters();
69 object[] returnArgs = new object [parameters.Length];
73 foreach (ParameterInfo par in parameters)
75 if (par.IsOut && !par.ParameterType.IsByRef)
76 returnArgs [n++] = reqMsg.GetArg (par.Position);
77 else if (par.ParameterType.IsByRef)
78 returnArgs [n++] = out_args [noa++];
81 result = new ReturnMessage (rval, returnArgs, n, CallContext.CreateLogicalCallContext(), reqMsg);
85 result = new ReturnMessage (e, reqMsg);
88 CallContext.RestoreCallContext (oldContext);
92 public static IMethodReturnMessage ExecuteMessage (
93 MarshalByRefObject target, IMethodCallMessage reqMsg)
95 if (IsTransparentProxy(target))
97 // Message must go through all chain of sinks
98 RealProxy rp = GetRealProxy (target);
99 return (IMethodReturnMessage) rp.Invoke (reqMsg);
102 return InternalExecuteMessage (target, reqMsg);
105 public static object Connect (Type classToProxy, string url)
107 ObjRef objRef = new ObjRef (classToProxy, url, null);
108 return GetRemoteObject (objRef, classToProxy);
111 public static object Connect (Type classToProxy, string url, object data)
113 ObjRef objRef = new ObjRef (classToProxy, url, data);
114 return GetRemoteObject (objRef, classToProxy);
117 public static bool Disconnect (MarshalByRefObject obj)
119 if (obj == null) throw new ArgumentNullException ("obj");
121 ServerIdentity identity;
123 if (IsTransparentProxy (obj))
125 // CBOs are always accessed through a proxy, even in the server, so
126 // for server CBOs it is ok to disconnect a proxy
128 RealProxy proxy = GetRealProxy(obj);
129 if (proxy.GetProxiedType().IsContextful && (proxy.ObjectIdentity is ServerIdentity))
130 identity = proxy.ObjectIdentity as ServerIdentity;
132 throw new ArgumentException ("The obj parameter is a proxy");
135 identity = obj.ObjectIdentity;
137 if (identity == null || !identity.IsConnected)
141 LifetimeServices.StopTrackingLifetime (identity);
142 DisposeIdentity (identity);
147 public static Type GetServerTypeForUri (string uri)
149 ServerIdentity ident = GetIdentityForUri (uri) as ServerIdentity;
150 if (ident == null) return null;
151 return ident.ObjectType;
154 public static string GetObjectUri (MarshalByRefObject obj)
156 Identity ident = GetObjectIdentity(obj);
157 if (ident is ClientIdentity) return ((ClientIdentity)ident).TargetUri;
158 else if (ident != null) return ident.ObjectUri;
162 public static object Unmarshal (ObjRef objref)
164 return Unmarshal(objref, true);
167 public static object Unmarshal (ObjRef objref, bool fRefine)
169 Type classToProxy = fRefine ? objref.ServerType : typeof (MarshalByRefObject);
170 if (classToProxy == null) classToProxy = typeof (MarshalByRefObject);
172 if (objref.IsReferenceToWellKnow)
173 return GetRemoteObject(objref, classToProxy);
176 if (classToProxy.IsContextful)
178 // Look for a ProxyAttribute
179 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (classToProxy, typeof(ProxyAttribute),true);
181 return att.CreateProxy (objref, classToProxy, null, null).GetTransparentProxy();
183 return GetProxyForRemoteObject (objref, classToProxy);
187 public static ObjRef Marshal (MarshalByRefObject obj)
189 return Marshal (obj, null, null);
192 public static ObjRef Marshal (MarshalByRefObject obj, string uri)
194 return Marshal (obj, uri, null);
197 public static ObjRef Marshal (MarshalByRefObject obj, string uri, Type requested_type)
199 if (IsTransparentProxy (obj))
201 RealProxy proxy = RemotingServices.GetRealProxy(obj);
202 Identity identity = proxy.ObjectIdentity;
204 if (identity != null)
206 if (proxy.GetProxiedType().IsContextful && !identity.IsConnected)
208 // Unregistered local contextbound object. Register now.
209 ClientActivatedIdentity cboundIdentity = (ClientActivatedIdentity)identity;
210 if (uri == null) uri = NewUri();
211 cboundIdentity.ObjectUri = uri;
212 RegisterServerIdentity (cboundIdentity);
213 cboundIdentity.StartTrackingLifetime ((ILease)obj.InitializeLifetimeService());
214 return cboundIdentity.CreateObjRef(requested_type);
216 else if (uri != null)
217 throw new RemotingException ("It is not possible marshal a proxy of a remote object");
219 return proxy.ObjectIdentity.CreateObjRef(requested_type);
223 if (requested_type == null) requested_type = obj.GetType();
227 if (obj.ObjectIdentity == null)
230 CreateClientActivatedServerIdentity (obj, requested_type, uri);
235 ClientActivatedIdentity identity = GetIdentityForUri ("/" + uri) as ClientActivatedIdentity;
236 if (identity == null || obj != identity.GetServerObject())
237 CreateClientActivatedServerIdentity (obj, requested_type, uri);
240 return obj.CreateObjRef(requested_type);
243 static string NewUri ()
245 int n = Interlocked.Increment (ref next_id);
246 return app_id + Environment.TickCount + "_" + n + ".rem";
249 public static RealProxy GetRealProxy (object proxy)
251 if (!IsTransparentProxy(proxy)) throw new RemotingException("Cannot get the real proxy from an object that is not a transparent proxy");
252 return (RealProxy)((TransparentProxy)proxy)._rp;
255 public static MethodBase GetMethodBaseFromMethodMessage(IMethodMessage msg)
257 Type type = Type.GetType (msg.TypeName);
259 throw new RemotingException ("Type '" + msg.TypeName + "' not found!");
261 BindingFlags bflags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
262 if (msg.MethodSignature == null)
263 return type.GetMethod (msg.MethodName, bflags);
265 return type.GetMethod (msg.MethodName, bflags, null, (Type[]) msg.MethodSignature, null);
268 public static void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
270 if (obj == null) throw new ArgumentNullException ("obj");
272 ObjRef oref = Marshal ((MarshalByRefObject)obj);
273 oref.GetObjectData (info, context);
276 public static ObjRef GetObjRefForProxy(MarshalByRefObject obj)
278 Identity ident = GetObjectIdentity(obj);
279 if (ident == null) return null;
280 else return ident.CreateObjRef(null);
283 public static object GetLifetimeService (MarshalByRefObject obj)
285 if (obj == null) return null;
286 return obj.GetLifetimeService ();
289 public static IMessageSink GetEnvoyChainForProxy (MarshalByRefObject obj)
291 if (IsTransparentProxy(obj))
292 return ((ClientIdentity)GetRealProxy (obj).ObjectIdentity).EnvoySink;
294 throw new ArgumentException ("obj must be a proxy","obj");
297 public static void LogRemotingStage (int stage)
299 throw new NotImplementedException ();
302 public static string GetSessionIdForMethodMessage(IMethodMessage msg)
304 // It seems that this it what MS returns.
308 public static bool IsMethodOverloaded(IMethodMessage msg)
310 // TODO: use internal call for better performance
311 Type type = msg.MethodBase.DeclaringType;
312 MemberInfo[] members = type.GetMember (msg.MethodName, MemberTypes.Method, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
313 return members.Length > 1;
316 public static bool IsObjectOutOfAppDomain(object tp)
318 // TODO: use internal call for better performance
319 Identity ident = GetObjectIdentity((MarshalByRefObject)tp);
320 if (ident != null) return !ident.IsFromThisAppDomain;
324 public static bool IsObjectOutOfContext(object tp)
326 // TODO: use internal call for better performance
327 ServerIdentity ident = GetObjectIdentity((MarshalByRefObject)tp) as ServerIdentity;
328 if (ident != null) return ident.Context != System.Threading.Thread.CurrentContext;
332 public static bool IsOneWay(MethodBase method)
334 // TODO: use internal call for better performance
335 object[] atts = method.GetCustomAttributes (typeof (OneWayAttribute), false);
336 return atts.Length > 0;
339 internal static bool IsAsyncMessage(IMessage msg)
341 if (! (msg is MonoMethodMessage)) return false;
342 else if (((MonoMethodMessage)msg).IsAsync) return true;
343 else if (IsOneWay (((MonoMethodMessage)msg).MethodBase)) return true;
347 public static void SetObjectUriForMarshal(MarshalByRefObject obj, string uri)
349 if (IsTransparentProxy (obj)) throw new RemotingException ("SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.");
353 #region Internal Methods
355 internal static object CreateClientProxy (ActivatedClientTypeEntry entry, object[] activationAttributes)
357 if (entry.ContextAttributes != null || activationAttributes != null)
359 ArrayList props = new ArrayList ();
360 if (entry.ContextAttributes != null) props.AddRange (entry.ContextAttributes);
361 if (activationAttributes != null) props.AddRange (activationAttributes);
362 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, props.ToArray ());
365 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, null);
368 internal static object CreateClientProxy (Type objectType, string url, object[] activationAttributes)
370 string activationUrl = url + "/RemoteActivationService.rem";
373 IMessageSink sink = GetClientChannelSinkChain (activationUrl, null, out objectUri);
375 RemotingProxy proxy = new RemotingProxy (objectType, activationUrl, activationAttributes);
376 return proxy.GetTransparentProxy();
379 internal static object CreateClientProxy (WellKnownClientTypeEntry entry)
381 return Connect (entry.ObjectType, entry.ObjectUrl, null);
384 internal static object CreateClientProxyForContextBound (Type type, object[] activationAttributes)
386 if (type.IsContextful)
388 // Look for a ProxyAttribute
389 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (type, typeof(ProxyAttribute), true);
391 return att.CreateInstance (type);
393 RemotingProxy proxy = new RemotingProxy (type, ChannelServices.CrossContextUrl, activationAttributes);
394 return proxy.GetTransparentProxy();
397 internal static Identity GetIdentityForUri (string uri)
401 return (Identity)uri_hash [GetNormalizedUri(uri)];
405 internal static Identity GetObjectIdentity (MarshalByRefObject obj)
407 if (IsTransparentProxy(obj))
408 return GetRealProxy (obj).ObjectIdentity;
410 return obj.ObjectIdentity;
413 internal static ClientIdentity GetOrCreateClientIdentity(ObjRef objRef, Type proxyType, out object clientProxy)
415 // This method looks for an identity for the given url.
416 // If an identity is not found, it creates the identity and
417 // assigns it a proxy to the remote object.
419 // Creates the client sink chain for the given url or channelData.
420 // It will also get the object uri from the url.
422 object channelData = objRef.ChannelInfo != null ? objRef.ChannelInfo.ChannelData : null;
423 string url = (channelData == null) ? objRef.URI : null;
426 IMessageSink sink = GetClientChannelSinkChain (url, channelData, out objectUri);
428 if (objectUri == null) objectUri = objRef.URI;
433 string uri = GetNormalizedUri (objRef.URI);
435 ClientIdentity identity = uri_hash [uri] as ClientIdentity;
436 if (identity != null)
438 // Object already registered
439 clientProxy = identity.ClientProxy;
440 if (clientProxy != null) return identity;
442 // The proxy has just been GCed, so its identity cannot
443 // be reused. Just dispose it.
444 DisposeIdentity (identity);
447 // Creates an identity and a proxy for the remote object
449 identity = new ClientIdentity (objectUri, objRef);
450 identity.ChannelSink = sink;
452 // Registers the identity
453 uri_hash [uri] = identity;
455 if (proxyType != null)
457 RemotingProxy proxy = new RemotingProxy (proxyType, identity);
458 clientProxy = proxy.GetTransparentProxy();
459 identity.ClientProxy = (MarshalByRefObject) clientProxy;
466 static IMessageSink GetClientChannelSinkChain(string url, object channelData, out string objectUri)
468 IMessageSink sink = ChannelServices.CreateClientChannelSinkChain (url, channelData, out objectUri);
473 string msg = String.Format ("Cannot create channel sink to connect to URL {0}. An appropriate channel has probably not been registered.", url);
474 throw new RemotingException (msg);
478 string msg = String.Format ("Cannot create channel sink to connect to the remote object. An appropriate channel has probably not been registered.", url);
479 throw new RemotingException (msg);
485 internal static ClientActivatedIdentity CreateContextBoundObjectIdentity(Type objectType)
487 ClientActivatedIdentity identity = new ClientActivatedIdentity (null, objectType);
488 identity.ChannelSink = ChannelServices.CrossContextChannel;
492 internal static ClientActivatedIdentity CreateClientActivatedServerIdentity(MarshalByRefObject realObject, Type objectType, string objectUri)
494 ClientActivatedIdentity identity = new ClientActivatedIdentity (objectUri, objectType);
495 identity.AttachServerObject (realObject, Context.DefaultContext);
496 RegisterServerIdentity (identity);
497 identity.StartTrackingLifetime ((ILease)realObject.InitializeLifetimeService ());
501 internal static ServerIdentity CreateWellKnownServerIdentity(Type objectType, string objectUri, WellKnownObjectMode mode)
503 ServerIdentity identity;
505 if (mode == WellKnownObjectMode.SingleCall)
506 identity = new SingleCallIdentity(objectUri, Context.DefaultContext, objectType);
508 identity = new SingletonIdentity(objectUri, Context.DefaultContext, objectType);
510 RegisterServerIdentity (identity);
514 private static void RegisterServerIdentity(ServerIdentity identity)
518 if (uri_hash.ContainsKey (identity.ObjectUri))
519 throw new RemotingException ("Uri already in use: " + identity.ObjectUri);
521 uri_hash[identity.ObjectUri] = identity;
525 internal static object GetProxyForRemoteObject (ObjRef objref, Type classToProxy)
527 ClientActivatedIdentity identity = GetIdentityForUri (objref.URI) as ClientActivatedIdentity;
528 if (identity != null) return identity.GetServerObject ();
529 else return GetRemoteObject (objref, classToProxy);
532 internal static object GetRemoteObject(ObjRef objRef, Type proxyType)
535 GetOrCreateClientIdentity (objRef, proxyType, out proxy);
539 internal static object GetDomainProxy(AppDomain domain)
543 Context currentContext = Thread.CurrentContext;
547 data = (byte[])AppDomain.InvokeInDomain (domain, typeof (AppDomain).GetMethod ("GetMarshalledDomainObjRef", BindingFlags.Instance|BindingFlags.NonPublic), domain, null);
551 AppDomain.InternalSetContext (currentContext);
554 MemoryStream stream = new MemoryStream (data);
555 ObjRef appref = (ObjRef) CADSerializer.DeserializeObject (stream);
556 return (AppDomain) RemotingServices.Unmarshal(appref);
559 private static void RegisterInternalChannels()
561 CrossAppDomainChannel.RegisterCrossAppDomainChannel();
564 internal static void DisposeIdentity (Identity ident)
568 if (!ident.Disposed) {
569 ClientIdentity clientId = ident as ClientIdentity;
570 if (clientId != null)
571 uri_hash.Remove (GetNormalizedUri (clientId.TargetUri));
573 uri_hash.Remove (ident.ObjectUri);
575 ident.Disposed = true;
580 internal static Identity GetMessageTargetIdentity (IMessage msg)
582 // Returns the identity where the message is sent
584 if (msg is IInternalMessage)
585 return ((IInternalMessage)msg).TargetIdentity;
589 string uri = GetNormalizedUri (((IMethodMessage)msg).Uri);
590 return uri_hash [uri] as ServerIdentity;
594 internal static void SetMessageTargetIdentity (IMessage msg, Identity ident)
596 if (msg is IInternalMessage)
597 ((IInternalMessage)msg).TargetIdentity = ident;
600 internal static bool UpdateOutArgObject (ParameterInfo pi, object local, object remote)
602 if (local is StringBuilder)
604 StringBuilder sb = local as StringBuilder;
605 sb.Remove (0, sb.Length);
606 sb.Append (remote.ToString());
609 else if (pi.ParameterType.IsArray && ((Array)local).Rank == 1)
611 Array alocal = (Array) local;
612 if (alocal.Rank == 1)
614 Array.Copy ((Array) remote, alocal, alocal.Length);
625 static string GetNormalizedUri (string uri)
627 if (uri.StartsWith ("/")) return uri.Substring (1);