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 Identity ident = GetIdentityForUri (uri);
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 // FIXME: use type name when fRefine==true
171 Type classToProxy = fRefine ? objref.ServerType : typeof (MarshalByRefObject);
172 if (classToProxy == null) classToProxy = typeof (MarshalByRefObject);
174 if (objref.IsReferenceToWellKnow)
175 return GetRemoteObject(objref, classToProxy);
178 if (classToProxy.IsContextful)
180 // Look for a ProxyAttribute
181 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (classToProxy, typeof(ProxyAttribute),true);
183 return att.CreateProxy (objref, classToProxy, null, null).GetTransparentProxy();
185 return GetProxyForRemoteObject (objref, classToProxy);
189 public static ObjRef Marshal (MarshalByRefObject obj)
191 return Marshal (obj, null, null);
194 public static ObjRef Marshal (MarshalByRefObject obj, string uri)
196 return Marshal (obj, uri, null);
199 public static ObjRef Marshal (MarshalByRefObject obj, string uri, Type requested_type)
201 if (IsTransparentProxy (obj))
203 RealProxy proxy = RemotingServices.GetRealProxy(obj);
204 Identity identity = proxy.ObjectIdentity;
206 if (identity != null)
208 if (identity.ObjectType.IsContextful && !identity.IsConnected)
210 // Unregistered local contextbound object. Register now.
211 ClientActivatedIdentity cboundIdentity = (ClientActivatedIdentity)identity;
212 if (uri == null) uri = NewUri();
213 cboundIdentity.ObjectUri = uri;
214 RegisterServerIdentity (cboundIdentity);
215 cboundIdentity.StartTrackingLifetime ((ILease)obj.InitializeLifetimeService());
216 return cboundIdentity.CreateObjRef(requested_type);
218 else if (uri != null)
219 throw new RemotingException ("It is not possible marshal a proxy of a remote object");
221 return proxy.ObjectIdentity.CreateObjRef(requested_type);
225 if (requested_type == null) requested_type = obj.GetType();
230 CreateClientActivatedServerIdentity (obj, requested_type, uri);
234 ClientActivatedIdentity identity = GetIdentityForUri ("/" + uri) as ClientActivatedIdentity;
235 if (identity == null || obj != identity.GetServerObject())
236 CreateClientActivatedServerIdentity (obj, requested_type, uri);
239 return obj.CreateObjRef(requested_type);
242 static string NewUri ()
244 return app_id + Environment.TickCount + "_" + next_id++;
247 public static RealProxy GetRealProxy (object proxy)
249 if (!IsTransparentProxy(proxy)) throw new RemotingException("Cannot get the real proxy from an object that is not a transparent proxy");
250 return (RealProxy)((TransparentProxy)proxy)._rp;
253 public static MethodBase GetMethodBaseFromMethodMessage(IMethodMessage msg)
255 Type type = Type.GetType (msg.TypeName);
257 throw new RemotingException ("Type '" + msg.TypeName + "' not found!");
259 BindingFlags bflags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
260 if (msg.MethodSignature == null)
261 return type.GetMethod (msg.MethodName, bflags);
263 return type.GetMethod (msg.MethodName, bflags, null, (Type[]) msg.MethodSignature, null);
266 public static void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
268 if (obj == null) throw new ArgumentNullException ("obj");
270 ObjRef oref = Marshal ((MarshalByRefObject)obj);
271 oref.GetObjectData (info, context);
274 public static ObjRef GetObjRefForProxy(MarshalByRefObject obj)
276 Identity ident = GetObjectIdentity(obj);
277 if (ident == null) return null;
278 else return ident.CreateObjRef(null);
281 public static object GetLifetimeService (MarshalByRefObject obj)
283 if (obj == null) return null;
284 return obj.GetLifetimeService ();
287 public static IMessageSink GetEnvoyChainForProxy (MarshalByRefObject obj)
289 if (IsTransparentProxy(obj))
290 return ((ClientIdentity)GetRealProxy (obj).ObjectIdentity).EnvoySink;
292 throw new ArgumentException ("obj must be a proxy","obj");
295 public static void LogRemotingStage (int stage)
297 throw new NotImplementedException ();
301 public static string GetSessionIdForMethodMessage(IMethodMessage msg)
303 throw new NotImplementedException ();
306 public static bool IsMethodOverloaded(IMethodMessage msg)
308 Type type = msg.MethodBase.DeclaringType;
309 MemberInfo[] members = type.GetMember (msg.MethodName, MemberTypes.Method, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
310 return members.Length > 1;
313 public static bool IsObjectOutOfAppDomain(object tp)
315 Identity ident = GetObjectIdentity((MarshalByRefObject)tp);
316 if (ident != null) return !ident.IsFromThisAppDomain;
320 public static bool IsObjectOutOfContext(object tp)
322 ServerIdentity ident = GetObjectIdentity((MarshalByRefObject)tp) as ServerIdentity;
323 if (ident != null) return ident.Context != System.Threading.Thread.CurrentContext;
327 public static bool IsOneWay(MethodBase method)
329 // TODO: use internal call for better performance
330 object[] atts = method.GetCustomAttributes (typeof (OneWayAttribute), false);
331 return atts.Length > 0;
334 public static bool IsAsyncMessage(IMessage msg)
336 if (! (msg is MonoMethodMessage)) return false;
337 else if (((MonoMethodMessage)msg).IsAsync) return true;
338 else if (IsOneWay (((MonoMethodMessage)msg).MethodBase)) return true;
342 public static void SetObjectUriForMarshal(MarshalByRefObject obj, string uri)
344 if (IsTransparentProxy (obj)) throw new RemotingException ("SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.");
348 #region Internal Methods
350 internal static object CreateClientProxy (ActivatedClientTypeEntry entry, object[] activationAttributes)
352 if (entry.ContextAttributes != null || activationAttributes != null)
354 ArrayList props = new ArrayList ();
355 if (entry.ContextAttributes != null) props.AddRange (entry.ContextAttributes);
356 if (activationAttributes != null) props.AddRange (activationAttributes);
357 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, props.ToArray ());
360 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, null);
363 internal static object CreateClientProxy (Type objectType, string url, object[] activationAttributes)
365 string activationUrl = url + "/RemoteActivationService.rem";
368 IMessageSink sink = GetClientChannelSinkChain (activationUrl, null, out objectUri);
370 RemotingProxy proxy = new RemotingProxy (objectType, activationUrl, activationAttributes);
371 return proxy.GetTransparentProxy();
374 internal static object CreateClientProxy (WellKnownClientTypeEntry entry)
376 return Connect (entry.ObjectType, entry.ObjectUrl, null);
379 internal static object CreateClientProxyForContextBound (Type type, object[] activationAttributes)
381 if (type.IsContextful)
383 // Look for a ProxyAttribute
384 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (type, typeof(ProxyAttribute), true);
386 return att.CreateInstance (type);
388 RemotingProxy proxy = new RemotingProxy (type, ChannelServices.CrossContextUrl, activationAttributes);
389 return proxy.GetTransparentProxy();
392 internal static Identity GetIdentityForUri (string uri)
396 return (Identity)uri_hash [GetNormalizedUri(uri)];
400 internal static Identity GetObjectIdentity (MarshalByRefObject obj)
402 if (IsTransparentProxy(obj))
403 return GetRealProxy (obj).ObjectIdentity;
405 return obj.ObjectIdentity;
408 internal static ClientIdentity GetOrCreateClientIdentity(ObjRef objRef, Type proxyType, out object clientProxy)
410 // This method looks for an identity for the given url.
411 // If an identity is not found, it creates the identity and
412 // assigns it a proxy to the remote object.
414 // Creates the client sink chain for the given url or channelData.
415 // It will also get the object uri from the url.
417 object channelData = objRef.ChannelInfo != null ? objRef.ChannelInfo.ChannelData : null;
418 string url = (channelData == null) ? objRef.URI : null;
421 IMessageSink sink = GetClientChannelSinkChain (url, channelData, out objectUri);
423 if (objectUri == null) objectUri = objRef.URI;
428 string uri = GetNormalizedUri (objRef.URI);
430 ClientIdentity identity = uri_hash [uri] as ClientIdentity;
431 if (identity != null)
433 // Object already registered
434 clientProxy = identity.ClientProxy;
435 if (clientProxy != null) return identity;
437 // The proxy has just been GCed, so its identity cannot
438 // be reused. Just dispose it.
439 DisposeIdentity (identity);
442 // Creates an identity and a proxy for the remote object
444 identity = new ClientIdentity (objectUri, objRef);
445 identity.ChannelSink = sink;
447 // Registers the identity
448 uri_hash [uri] = identity;
450 if (proxyType != null)
452 RemotingProxy proxy = new RemotingProxy (proxyType, identity);
453 clientProxy = proxy.GetTransparentProxy();
454 identity.ClientProxy = (MarshalByRefObject) clientProxy;
461 static IMessageSink GetClientChannelSinkChain(string url, object channelData, out string objectUri)
463 IMessageSink sink = ChannelServices.CreateClientChannelSinkChain (url, channelData, out objectUri);
468 string msg = String.Format ("Cannot create channel sink to connect to URL {0}. An appropriate channel has probably not been registered.", url);
469 throw new RemotingException (msg);
473 string msg = String.Format ("Cannot create channel sink to connect to the remote object. An appropriate channel has probably not been registered.", url);
474 throw new RemotingException (msg);
480 internal static ClientActivatedIdentity CreateContextBoundObjectIdentity(Type objectType)
482 ClientActivatedIdentity identity = new ClientActivatedIdentity (null, objectType);
483 identity.ChannelSink = ChannelServices.CrossContextChannel;
487 internal static ClientActivatedIdentity CreateClientActivatedServerIdentity(MarshalByRefObject realObject, Type objectType, string objectUri)
489 ClientActivatedIdentity identity = new ClientActivatedIdentity (objectUri, objectType);
490 identity.AttachServerObject (realObject, Context.DefaultContext);
491 RegisterServerIdentity (identity);
492 identity.StartTrackingLifetime ((ILease)realObject.InitializeLifetimeService ());
496 internal static ServerIdentity CreateWellKnownServerIdentity(Type objectType, string objectUri, WellKnownObjectMode mode)
498 ServerIdentity identity;
500 if (mode == WellKnownObjectMode.SingleCall)
501 identity = new SingleCallIdentity(objectUri, Context.DefaultContext, objectType);
503 identity = new SingletonIdentity(objectUri, Context.DefaultContext, objectType);
505 RegisterServerIdentity (identity);
509 private static void RegisterServerIdentity(ServerIdentity identity)
513 if (uri_hash.ContainsKey (identity.ObjectUri))
514 throw new RemotingException ("Uri already in use: " + identity.ObjectUri);
516 uri_hash[identity.ObjectUri] = identity;
520 internal static object GetProxyForRemoteObject (ObjRef objref, Type classToProxy)
522 ClientActivatedIdentity identity = GetIdentityForUri (objref.URI) as ClientActivatedIdentity;
523 if (identity != null) return identity.GetServerObject ();
524 else return GetRemoteObject (objref, classToProxy);
527 internal static object GetRemoteObject(ObjRef objRef, Type proxyType)
530 GetOrCreateClientIdentity (objRef, proxyType, out proxy);
534 internal static object GetDomainProxy(AppDomain domain)
538 Context currentContext = Thread.CurrentContext;
539 AppDomain currentDomain = AppDomain.InternalSetDomain (domain);
542 data = domain.GetMarshalledDomainObjRef ();
546 AppDomain.InternalSetDomain (currentDomain);
547 AppDomain.InternalSetContext (currentContext);
550 MemoryStream stream = new MemoryStream (data);
551 ObjRef appref = (ObjRef) CADSerializer.DeserializeObject (stream);
552 return (AppDomain) RemotingServices.Unmarshal(appref);
555 private static void RegisterInternalChannels()
557 CrossAppDomainChannel.RegisterCrossAppDomainChannel();
560 internal static void DisposeIdentity (Identity ident)
564 if (!ident.Disposed) {
565 uri_hash.Remove (ident.ObjectUri);
566 ident.Disposed = true;
571 internal static Identity GetMessageTargetIdentity (IMessage msg)
573 // Returns the identity where the message is sent
575 if (msg is IInternalMessage)
576 return ((IInternalMessage)msg).TargetIdentity;
580 string uri = GetNormalizedUri (((IMethodMessage)msg).Uri);
581 return uri_hash [uri] as ServerIdentity;
585 internal static void SetMessageTargetIdentity (IMessage msg, Identity ident)
587 if (msg is IInternalMessage)
588 ((IInternalMessage)msg).TargetIdentity = ident;
591 internal static bool UpdateOutArgObject (ParameterInfo pi, object local, object remote)
593 if (local is StringBuilder)
595 StringBuilder sb = local as StringBuilder;
596 sb.Remove (0, sb.Length);
597 sb.Append (remote.ToString());
600 else if (pi.ParameterType.IsArray && ((Array)local).Rank == 1)
602 Array alocal = (Array) local;
603 if (alocal.Rank == 1)
605 Array.Copy ((Array) remote, alocal, alocal.Length);
616 static string GetNormalizedUri (string uri)
618 if (uri.StartsWith ("/")) return uri.Substring (1);