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;
52 namespace System.Runtime.Remoting
54 public sealed class RemotingServices
56 // Holds the identities of the objects, using uri as index
57 static Hashtable uri_hash = new Hashtable ();
59 static BinaryFormatter _serializationFormatter;
60 static BinaryFormatter _deserializationFormatter;
62 internal static string app_id;
63 static int next_id = 1;
64 static readonly BindingFlags methodBindings = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
66 // Holds information in xdomain calls. Names are short to minimize serialized size.
69 public object d; /* call data */
70 public object c; /* call context */
73 static RemotingServices ()
75 RemotingSurrogateSelector surrogateSelector = new RemotingSurrogateSelector ();
76 StreamingContext context = new StreamingContext (StreamingContextStates.Remoting, null);
77 _serializationFormatter = new BinaryFormatter (surrogateSelector, context);
78 _deserializationFormatter = new BinaryFormatter (null, context);
80 RegisterInternalChannels ();
81 app_id = Guid.NewGuid().ToString().Replace('-', '_') + "/";
82 CreateWellKnownServerIdentity (typeof(RemoteActivator), "RemoteActivationService.rem", WellKnownObjectMode.Singleton);
85 private RemotingServices () {}
87 [MethodImplAttribute(MethodImplOptions.InternalCall)]
88 internal extern static object InternalExecute (MethodBase method, Object obj,
89 Object[] parameters, out object [] out_args);
91 [MethodImplAttribute(MethodImplOptions.InternalCall)]
92 public extern static bool IsTransparentProxy (object proxy);
94 internal static IMethodReturnMessage InternalExecuteMessage (
95 MarshalByRefObject target, IMethodCallMessage reqMsg)
99 Type tt = target.GetType ();
100 MethodBase method = reqMsg.MethodBase.DeclaringType == tt ? reqMsg.MethodBase : tt.GetMethod(reqMsg.MethodName, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance, null, (Type[]) reqMsg.MethodSignature, null);
101 object oldContext = CallContext.SetCurrentCallContext (reqMsg.LogicalCallContext);
106 object rval = InternalExecute (method, target, reqMsg.Args, out out_args);
108 // Collect parameters with Out flag from the request message
109 // FIXME: This can be done in the unmanaged side and will be
112 ParameterInfo[] parameters = method.GetParameters();
113 object[] returnArgs = new object [parameters.Length];
117 foreach (ParameterInfo par in parameters)
119 if (par.IsOut && !par.ParameterType.IsByRef)
120 returnArgs [n++] = reqMsg.GetArg (par.Position);
121 else if (par.ParameterType.IsByRef)
122 returnArgs [n++] = out_args [noa++];
124 returnArgs [n++] = null;
127 result = new ReturnMessage (rval, returnArgs, n, CallContext.CreateLogicalCallContext (true), reqMsg);
131 result = new ReturnMessage (e, reqMsg);
134 CallContext.RestoreCallContext (oldContext);
138 public static IMethodReturnMessage ExecuteMessage (
139 MarshalByRefObject target, IMethodCallMessage reqMsg)
141 if (IsTransparentProxy(target))
143 // Message must go through all chain of sinks
144 RealProxy rp = GetRealProxy (target);
145 return (IMethodReturnMessage) rp.Invoke (reqMsg);
148 return InternalExecuteMessage (target, reqMsg);
151 public static object Connect (Type classToProxy, string url)
153 ObjRef objRef = new ObjRef (classToProxy, url, null);
154 return GetRemoteObject (objRef, classToProxy);
157 public static object Connect (Type classToProxy, string url, object data)
159 ObjRef objRef = new ObjRef (classToProxy, url, data);
160 return GetRemoteObject (objRef, classToProxy);
163 public static bool Disconnect (MarshalByRefObject obj)
165 if (obj == null) throw new ArgumentNullException ("obj");
167 ServerIdentity identity;
169 if (IsTransparentProxy (obj))
171 // CBOs are always accessed through a proxy, even in the server, so
172 // for server CBOs it is ok to disconnect a proxy
174 RealProxy proxy = GetRealProxy(obj);
175 if (proxy.GetProxiedType().IsContextful && (proxy.ObjectIdentity is ServerIdentity))
176 identity = proxy.ObjectIdentity as ServerIdentity;
178 throw new ArgumentException ("The obj parameter is a proxy.");
181 identity = obj.ObjectIdentity;
182 obj.ObjectIdentity = null;
185 if (identity == null || !identity.IsConnected)
189 LifetimeServices.StopTrackingLifetime (identity);
190 DisposeIdentity (identity);
195 public static Type GetServerTypeForUri (string uri)
197 ServerIdentity ident = GetIdentityForUri (uri) as ServerIdentity;
198 if (ident == null) return null;
199 return ident.ObjectType;
202 public static string GetObjectUri (MarshalByRefObject obj)
204 Identity ident = GetObjectIdentity(obj);
205 if (ident is ClientIdentity) return ((ClientIdentity)ident).TargetUri;
206 else if (ident != null) return ident.ObjectUri;
210 public static object Unmarshal (ObjRef objref)
212 return Unmarshal(objref, true);
215 public static object Unmarshal (ObjRef objref, bool fRefine)
217 Type classToProxy = fRefine ? objref.ServerType : typeof (MarshalByRefObject);
218 if (classToProxy == null) classToProxy = typeof (MarshalByRefObject);
220 if (objref.IsReferenceToWellKnow)
221 return GetRemoteObject(objref, classToProxy);
224 if (classToProxy.IsContextful)
226 // Look for a ProxyAttribute
227 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (classToProxy, typeof(ProxyAttribute),true);
229 return att.CreateProxy (objref, classToProxy, null, null).GetTransparentProxy();
231 return GetProxyForRemoteObject (objref, classToProxy);
235 public static ObjRef Marshal (MarshalByRefObject obj)
237 return Marshal (obj, null, null);
240 public static ObjRef Marshal (MarshalByRefObject obj, string uri)
242 return Marshal (obj, uri, null);
245 public static ObjRef Marshal (MarshalByRefObject obj, string uri, Type requested_type)
247 if (IsTransparentProxy (obj))
249 RealProxy proxy = RemotingServices.GetRealProxy(obj);
250 Identity identity = proxy.ObjectIdentity;
252 if (identity != null)
254 if (proxy.GetProxiedType().IsContextful && !identity.IsConnected)
256 // Unregistered local contextbound object. Register now.
257 ClientActivatedIdentity cboundIdentity = (ClientActivatedIdentity)identity;
258 if (uri == null) uri = NewUri();
259 cboundIdentity.ObjectUri = uri;
260 RegisterServerIdentity (cboundIdentity);
261 cboundIdentity.StartTrackingLifetime ((ILease)obj.InitializeLifetimeService());
262 return cboundIdentity.CreateObjRef(requested_type);
264 else if (uri != null)
265 throw new RemotingException ("It is not possible marshal a proxy of a remote object.");
267 return proxy.ObjectIdentity.CreateObjRef(requested_type);
271 if (requested_type == null) requested_type = obj.GetType();
275 if (obj.ObjectIdentity == null)
278 CreateClientActivatedServerIdentity (obj, requested_type, uri);
283 ClientActivatedIdentity identity = GetIdentityForUri ("/" + uri) as ClientActivatedIdentity;
284 if (identity == null || obj != identity.GetServerObject())
285 CreateClientActivatedServerIdentity (obj, requested_type, uri);
288 if (IsTransparentProxy (obj))
289 return RemotingServices.GetRealProxy(obj).ObjectIdentity.CreateObjRef (requested_type);
291 return obj.CreateObjRef(requested_type);
294 static string NewUri ()
296 int n = Interlocked.Increment (ref next_id);
297 return app_id + Environment.TickCount + "_" + n + ".rem";
300 public static RealProxy GetRealProxy (object proxy)
302 if (!IsTransparentProxy(proxy)) throw new RemotingException("Cannot get the real proxy from an object that is not a transparent proxy.");
303 return (RealProxy)((TransparentProxy)proxy)._rp;
306 public static MethodBase GetMethodBaseFromMethodMessage(IMethodMessage msg)
308 Type type = Type.GetType (msg.TypeName);
310 throw new RemotingException ("Type '" + msg.TypeName + "' not found.");
312 return GetMethodBaseFromName (type, msg.MethodName, (Type[]) msg.MethodSignature);
315 internal static MethodBase GetMethodBaseFromName (Type type, string methodName, Type[] signature)
317 if (type.IsInterface) {
318 return FindInterfaceMethod (type, methodName, signature);
321 MethodBase method = null;
322 if (signature == null)
323 method = type.GetMethod (methodName, methodBindings);
325 method = type.GetMethod (methodName, methodBindings, null, (Type[]) signature, null);
330 if (signature == null)
331 return type.GetConstructor (methodBindings, null, Type.EmptyTypes, null);
333 return type.GetConstructor (methodBindings, null, signature, null);
337 static MethodBase FindInterfaceMethod (Type type, string methodName, Type[] signature)
339 MethodBase method = null;
341 if (signature == null)
342 method = type.GetMethod (methodName, methodBindings);
344 method = type.GetMethod (methodName, methodBindings, null, signature, null);
346 if (method != null) return method;
348 foreach (Type t in type.GetInterfaces ()) {
349 method = FindInterfaceMethod (t, methodName, signature);
350 if (method != null) return method;
356 public static void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
358 if (obj == null) throw new ArgumentNullException ("obj");
360 ObjRef oref = Marshal ((MarshalByRefObject)obj);
361 oref.GetObjectData (info, context);
364 public static ObjRef GetObjRefForProxy(MarshalByRefObject obj)
366 Identity ident = GetObjectIdentity(obj);
367 if (ident == null) return null;
368 else return ident.CreateObjRef(null);
371 public static object GetLifetimeService (MarshalByRefObject obj)
373 if (obj == null) return null;
374 return obj.GetLifetimeService ();
377 public static IMessageSink GetEnvoyChainForProxy (MarshalByRefObject obj)
379 if (IsTransparentProxy(obj))
380 return ((ClientIdentity)GetRealProxy (obj).ObjectIdentity).EnvoySink;
382 throw new ArgumentException ("obj must be a proxy.","obj");
386 [Conditional ("REMOTING_PERF")]
387 public static void LogRemotingStage (int stage)
389 throw new NotImplementedException ();
392 public static string GetSessionIdForMethodMessage(IMethodMessage msg)
394 // It seems that this it what MS returns.
398 public static bool IsMethodOverloaded(IMethodMessage msg)
400 const BindingFlags bfinst = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
401 MonoType type = (MonoType) msg.MethodBase.DeclaringType;
402 return type.GetMethodsByName (msg.MethodName, bfinst, false, type).Length > 1;
405 public static bool IsObjectOutOfAppDomain(object tp)
407 // TODO: use internal call for better performance
408 Identity ident = GetObjectIdentity((MarshalByRefObject)tp);
409 return ident is ClientIdentity;
412 public static bool IsObjectOutOfContext(object tp)
414 // TODO: use internal call for better performance
415 Identity ident = GetObjectIdentity((MarshalByRefObject)tp);
416 if (ident == null) return false;
418 ServerIdentity sident = ident as ServerIdentity;
419 if (sident != null) return sident.Context != System.Threading.Thread.CurrentContext;
423 public static bool IsOneWay(MethodBase method)
425 return method.IsDefined (typeof (OneWayAttribute), false);
428 internal static bool IsAsyncMessage(IMessage msg)
430 if (! (msg is MonoMethodMessage)) return false;
431 else if (((MonoMethodMessage)msg).IsAsync) return true;
432 else if (IsOneWay (((MonoMethodMessage)msg).MethodBase)) return true;
436 public static void SetObjectUriForMarshal(MarshalByRefObject obj, string uri)
438 if (IsTransparentProxy (obj)) {
439 RealProxy proxy = RemotingServices.GetRealProxy(obj);
440 Identity identity = proxy.ObjectIdentity;
442 if (identity != null && !(identity is ServerIdentity) && !proxy.GetProxiedType().IsContextful)
443 throw new RemotingException ("SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.");
449 #region Internal Methods
451 internal static object CreateClientProxy (ActivatedClientTypeEntry entry, object[] activationAttributes)
453 if (entry.ContextAttributes != null || activationAttributes != null)
455 ArrayList props = new ArrayList ();
456 if (entry.ContextAttributes != null) props.AddRange (entry.ContextAttributes);
457 if (activationAttributes != null) props.AddRange (activationAttributes);
458 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, props.ToArray ());
461 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, null);
464 internal static object CreateClientProxy (Type objectType, string url, object[] activationAttributes)
466 string activationUrl = url + "/RemoteActivationService.rem";
469 IMessageSink sink = GetClientChannelSinkChain (activationUrl, null, out objectUri);
471 RemotingProxy proxy = new RemotingProxy (objectType, activationUrl, activationAttributes);
472 return proxy.GetTransparentProxy();
475 internal static object CreateClientProxy (WellKnownClientTypeEntry entry)
477 return Connect (entry.ObjectType, entry.ObjectUrl, null);
480 internal static object CreateClientProxyForContextBound (Type type, object[] activationAttributes)
482 if (type.IsContextful)
484 // Look for a ProxyAttribute
485 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (type, typeof(ProxyAttribute), true);
487 return att.CreateInstance (type);
489 RemotingProxy proxy = new RemotingProxy (type, ChannelServices.CrossContextUrl, activationAttributes);
490 return proxy.GetTransparentProxy();
493 internal static Identity GetIdentityForUri (string uri)
497 return (Identity)uri_hash [GetNormalizedUri(uri)];
501 internal static Identity GetObjectIdentity (MarshalByRefObject obj)
503 if (IsTransparentProxy(obj))
504 return GetRealProxy (obj).ObjectIdentity;
506 return obj.ObjectIdentity;
509 internal static ClientIdentity GetOrCreateClientIdentity(ObjRef objRef, Type proxyType, out object clientProxy)
511 // This method looks for an identity for the given url.
512 // If an identity is not found, it creates the identity and
513 // assigns it a proxy to the remote object.
515 // Creates the client sink chain for the given url or channelData.
516 // It will also get the object uri from the url.
518 object channelData = objRef.ChannelInfo != null ? objRef.ChannelInfo.ChannelData : null;
521 IMessageSink sink = GetClientChannelSinkChain (objRef.URI, channelData, out objectUri);
523 if (objectUri == null) objectUri = objRef.URI;
528 string uri = GetNormalizedUri (objRef.URI);
530 ClientIdentity identity = uri_hash [uri] as ClientIdentity;
531 if (identity != null)
533 // Object already registered
534 clientProxy = identity.ClientProxy;
535 if (clientProxy != null) return identity;
537 // The proxy has just been GCed, so its identity cannot
538 // be reused. Just dispose it.
539 DisposeIdentity (identity);
542 // Creates an identity and a proxy for the remote object
544 identity = new ClientIdentity (objectUri, objRef);
545 identity.ChannelSink = sink;
547 // Registers the identity
548 uri_hash [uri] = identity;
550 if (proxyType != null)
552 RemotingProxy proxy = new RemotingProxy (proxyType, identity);
553 CrossAppDomainSink cds = sink as CrossAppDomainSink;
555 proxy.SetTargetDomain (cds.TargetDomainId);
557 clientProxy = proxy.GetTransparentProxy();
558 identity.ClientProxy = (MarshalByRefObject) clientProxy;
565 static IMessageSink GetClientChannelSinkChain(string url, object channelData, out string objectUri)
567 IMessageSink sink = ChannelServices.CreateClientChannelSinkChain (url, channelData, out objectUri);
572 string msg = String.Format ("Cannot create channel sink to connect to URL {0}. An appropriate channel has probably not been registered.", url);
573 throw new RemotingException (msg);
577 string msg = String.Format ("Cannot create channel sink to connect to the remote object. An appropriate channel has probably not been registered.", url);
578 throw new RemotingException (msg);
584 internal static ClientActivatedIdentity CreateContextBoundObjectIdentity(Type objectType)
586 ClientActivatedIdentity identity = new ClientActivatedIdentity (null, objectType);
587 identity.ChannelSink = ChannelServices.CrossContextChannel;
591 internal static ClientActivatedIdentity CreateClientActivatedServerIdentity(MarshalByRefObject realObject, Type objectType, string objectUri)
593 ClientActivatedIdentity identity = new ClientActivatedIdentity (objectUri, objectType);
594 identity.AttachServerObject (realObject, Context.DefaultContext);
595 RegisterServerIdentity (identity);
596 identity.StartTrackingLifetime ((ILease)realObject.InitializeLifetimeService ());
600 internal static ServerIdentity CreateWellKnownServerIdentity(Type objectType, string objectUri, WellKnownObjectMode mode)
602 ServerIdentity identity;
604 if (mode == WellKnownObjectMode.SingleCall)
605 identity = new SingleCallIdentity(objectUri, Context.DefaultContext, objectType);
607 identity = new SingletonIdentity(objectUri, Context.DefaultContext, objectType);
609 RegisterServerIdentity (identity);
613 private static void RegisterServerIdentity(ServerIdentity identity)
617 if (uri_hash.ContainsKey (identity.ObjectUri))
618 throw new RemotingException ("Uri already in use: " + identity.ObjectUri + ".");
620 uri_hash[identity.ObjectUri] = identity;
624 internal static object GetProxyForRemoteObject (ObjRef objref, Type classToProxy)
626 ClientActivatedIdentity identity = GetIdentityForUri (objref.URI) as ClientActivatedIdentity;
627 if (identity != null) return identity.GetServerObject ();
628 else return GetRemoteObject (objref, classToProxy);
631 internal static object GetRemoteObject(ObjRef objRef, Type proxyType)
634 GetOrCreateClientIdentity (objRef, proxyType, out proxy);
638 // This method is called by the runtime
639 internal static object GetServerObject (string uri)
641 ClientActivatedIdentity identity = GetIdentityForUri (uri) as ClientActivatedIdentity;
642 if (identity == null) throw new RemotingException ("Server for uri '" + uri + "' not found");
643 return identity.GetServerObject ();
646 // This method is called by the runtime
647 internal static byte[] SerializeCallData (object obj)
649 LogicalCallContext ctx = CallContext.CreateLogicalCallContext (false);
651 CACD cad = new CACD ();
657 if (obj == null) return null;
658 MemoryStream ms = new MemoryStream ();
659 _serializationFormatter.Serialize (ms, obj);
660 return ms.ToArray ();
663 // This method is called by the runtime
664 internal static object DeserializeCallData (byte[] array)
666 if (array == null) return null;
668 MemoryStream ms = new MemoryStream (array);
669 object obj = _deserializationFormatter.Deserialize (ms);
672 CACD cad = (CACD) obj;
674 CallContext.UpdateCurrentCallContext ((LogicalCallContext) cad.c);
679 // This method is called by the runtime
680 internal static byte[] SerializeExceptionData (Exception ex)
687 MemoryStream ms = new MemoryStream ();
688 _serializationFormatter.Serialize (ms, ex);
689 return ms.ToArray ();
691 catch (Exception e) {
692 if (e is ThreadAbortException) {
693 Thread.ResetAbort ();
697 else if (retry == 2) {
698 ex = new Exception ();
699 ex.SetMessage (e.Message);
700 ex.SetStackTrace (e.StackTrace);
711 catch (Exception tex)
713 byte[] data = SerializeExceptionData (tex);
714 Thread.ResetAbort ();
719 internal static object GetDomainProxy(AppDomain domain)
723 Context currentContext = Thread.CurrentContext;
727 data = (byte[])AppDomain.InvokeInDomain (domain, typeof (AppDomain).GetMethod ("GetMarshalledDomainObjRef", BindingFlags.Instance|BindingFlags.NonPublic), domain, null);
731 AppDomain.InternalSetContext (currentContext);
734 MemoryStream stream = new MemoryStream (data);
735 ObjRef appref = (ObjRef) CADSerializer.DeserializeObject (stream);
736 return (AppDomain) RemotingServices.Unmarshal(appref);
739 private static void RegisterInternalChannels()
741 CrossAppDomainChannel.RegisterCrossAppDomainChannel();
744 internal static void DisposeIdentity (Identity ident)
748 if (!ident.Disposed) {
749 ClientIdentity clientId = ident as ClientIdentity;
750 if (clientId != null)
751 uri_hash.Remove (GetNormalizedUri (clientId.TargetUri));
753 uri_hash.Remove (ident.ObjectUri);
755 ident.Disposed = true;
760 internal static Identity GetMessageTargetIdentity (IMessage msg)
762 // Returns the identity where the message is sent
764 if (msg is IInternalMessage)
765 return ((IInternalMessage)msg).TargetIdentity;
769 string uri = GetNormalizedUri (((IMethodMessage)msg).Uri);
770 return uri_hash [uri] as ServerIdentity;
774 internal static void SetMessageTargetIdentity (IMessage msg, Identity ident)
776 if (msg is IInternalMessage)
777 ((IInternalMessage)msg).TargetIdentity = ident;
780 internal static bool UpdateOutArgObject (ParameterInfo pi, object local, object remote)
782 if (local is StringBuilder)
784 StringBuilder sb = local as StringBuilder;
785 sb.Remove (0, sb.Length);
786 sb.Append (remote.ToString());
789 else if (pi.ParameterType.IsArray && ((Array)local).Rank == 1)
791 Array alocal = (Array) local;
792 if (alocal.Rank == 1)
794 Array.Copy ((Array) remote, alocal, alocal.Length);
805 static string GetNormalizedUri (string uri)
807 if (uri.StartsWith ("/")) return uri.Substring (1);