* RemotingServices.cs: Marshal(): If the object is a proxy, return the ObjRef stored...
[mono.git] / mcs / class / corlib / System.Runtime.Remoting / RemotingServices.cs
1 //
2 // System.Runtime.Remoting.RemotingServices.cs
3 //
4 // Authors:
5 //   Dietmar Maurer (dietmar@ximian.com)
6 //   Lluis Sanchez Gual (lluis@ideary.com)
7 //   Patrik Torstensson
8 //
9 // (C) 2001 Ximian, Inc.  http://www.ximian.com
10 //
11
12 using System;
13 using System.Text;
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;
25 using System.IO;
26
27 namespace System.Runtime.Remoting
28 {
29         public sealed class RemotingServices 
30         {
31                 // Holds the identities of the objects, using uri as index
32                 static Hashtable uri_hash = new Hashtable ();           
33
34                 internal static string app_id;
35                 static int next_id = 1;
36                 
37                 static RemotingServices ()
38                 {
39                         RegisterInternalChannels ();
40                         app_id = Guid.NewGuid().ToString().Replace('-', '_') + "/";
41                         CreateWellKnownServerIdentity (typeof(RemoteActivator), "RemoteActivationService.rem", WellKnownObjectMode.Singleton);
42                 }
43         
44                 private RemotingServices () {}
45
46                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
47                 internal extern static object InternalExecute (MonoMethod method, Object obj,
48                                                                Object[] parameters, out object [] out_args);
49
50                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
51                 public extern static bool IsTransparentProxy (object proxy);
52                 
53                 internal static IMethodReturnMessage InternalExecuteMessage (
54                         MarshalByRefObject target, IMethodCallMessage reqMsg)
55                 {
56                         ReturnMessage result;
57                         
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);
60                         
61                         try 
62                         {
63                                 object [] out_args;
64                                 object rval = InternalExecute (method, target, reqMsg.Args, out out_args);
65                         
66                                 // Collect parameters with Out flag from the request message
67
68                                 ParameterInfo[] parameters = method.GetParameters();
69                                 object[] returnArgs = new object [parameters.Length];
70                                 
71                                 int n = 0;
72                                 int noa = 0;
73                                 foreach (ParameterInfo par in parameters)
74                                 {
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++]; 
79                                 }
80                                 
81                                 result = new ReturnMessage (rval, returnArgs, n, CallContext.CreateLogicalCallContext(), reqMsg);
82                         } 
83                         catch (Exception e) 
84                         {
85                                 result = new ReturnMessage (e, reqMsg);
86                         }
87                         
88                         CallContext.RestoreCallContext (oldContext);
89                         return result;
90                 }
91
92                 public static IMethodReturnMessage ExecuteMessage (
93                         MarshalByRefObject target, IMethodCallMessage reqMsg)
94                 {
95                         if (IsTransparentProxy(target))
96                         {
97                                 // Message must go through all chain of sinks
98                                 RealProxy rp = GetRealProxy (target);
99                                 return (IMethodReturnMessage) rp.Invoke (reqMsg);
100                         }
101                         else    // Direct call
102                                 return InternalExecuteMessage (target, reqMsg);
103                 }
104
105                 public static object Connect (Type classToProxy, string url)
106                 {
107                         ObjRef objRef = new ObjRef (classToProxy, url, null);
108                         return GetRemoteObject (objRef, classToProxy);
109                 }
110
111                 public static object Connect (Type classToProxy, string url, object data)
112                 {
113                         ObjRef objRef = new ObjRef (classToProxy, url, data);
114                         return GetRemoteObject (objRef, classToProxy);
115                 }
116
117                 public static bool Disconnect (MarshalByRefObject obj)
118                 {
119                         if (obj == null) throw new ArgumentNullException ("obj");
120
121                         ServerIdentity identity;
122
123                         if (IsTransparentProxy (obj))
124                         {
125                                 // CBOs are always accessed through a proxy, even in the server, so
126                                 // for server CBOs it is ok to disconnect a proxy
127
128                                 RealProxy proxy = GetRealProxy(obj);
129                                 if (proxy.GetProxiedType().IsContextful && (proxy.ObjectIdentity is ServerIdentity))
130                                         identity = proxy.ObjectIdentity as ServerIdentity;
131                                 else
132                                         throw new ArgumentException ("The obj parameter is a proxy.");
133                         }
134                         else
135                                 identity = obj.ObjectIdentity;
136
137                         if (identity == null || !identity.IsConnected)
138                                 return false;
139                         else
140                         {
141                                 LifetimeServices.StopTrackingLifetime (identity);
142                                 DisposeIdentity (identity);
143                                 return true;
144                         }
145                 }
146
147                 public static Type GetServerTypeForUri (string uri)
148                 {
149                         ServerIdentity ident = GetIdentityForUri (uri) as ServerIdentity;
150                         if (ident == null) return null;
151                         return ident.ObjectType;
152                 }
153
154                 public static string GetObjectUri (MarshalByRefObject obj)
155                 {
156                         Identity ident = GetObjectIdentity(obj);
157                         if (ident is ClientIdentity) return ((ClientIdentity)ident).TargetUri;
158                         else if (ident != null) return ident.ObjectUri;
159                         else return null;
160                 }
161
162                 public static object Unmarshal (ObjRef objref)
163                 {
164                         return Unmarshal(objref, true);
165                 }
166
167                 public static object Unmarshal (ObjRef objref, bool fRefine)
168                 {
169                         Type classToProxy = fRefine ? objref.ServerType : typeof (MarshalByRefObject);
170                         if (classToProxy == null) classToProxy = typeof (MarshalByRefObject);
171
172                         if (objref.IsReferenceToWellKnow)
173                                 return GetRemoteObject(objref, classToProxy);
174                         else
175                         {
176                                 if (classToProxy.IsContextful)
177                                 {
178                                         // Look for a ProxyAttribute
179                                         ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (classToProxy, typeof(ProxyAttribute),true);
180                                         if (att != null)
181                                                 return att.CreateProxy (objref, classToProxy, null, null).GetTransparentProxy();
182                                 }
183                                 return GetProxyForRemoteObject (objref, classToProxy);
184                         }
185                 }
186
187                 public static ObjRef Marshal (MarshalByRefObject obj)
188                 {
189                         return Marshal (obj, null, null);
190                 }
191                 
192                 public static ObjRef Marshal (MarshalByRefObject obj, string uri)
193                 {
194                         return Marshal (obj, uri, null);
195                 }
196                 
197                 public static ObjRef Marshal (MarshalByRefObject obj, string uri, Type requested_type)
198                 {
199                         if (IsTransparentProxy (obj))
200                         {
201                                 RealProxy proxy = RemotingServices.GetRealProxy(obj);
202                                 Identity identity = proxy.ObjectIdentity;
203
204                                 if (identity != null)
205                                 {
206                                         if (proxy.GetProxiedType().IsContextful && !identity.IsConnected)
207                                         {
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);
215                                         }
216                                         else if (uri != null)
217                                                 throw new RemotingException ("It is not possible marshal a proxy of a remote object.");
218
219                                         return proxy.ObjectIdentity.CreateObjRef(requested_type);
220                                 }
221                         }
222
223                         if (requested_type == null) requested_type = obj.GetType();
224
225                         if (uri == null) 
226                         {
227                                 if (obj.ObjectIdentity == null)
228                                 {
229                                         uri = NewUri();
230                                         CreateClientActivatedServerIdentity (obj, requested_type, uri);
231                                 }
232                         }
233                         else
234                         {
235                                 ClientActivatedIdentity identity = GetIdentityForUri ("/" + uri) as ClientActivatedIdentity;
236                                 if (identity == null || obj != identity.GetServerObject()) 
237                                         CreateClientActivatedServerIdentity (obj, requested_type, uri);
238                         }
239
240                         if (IsTransparentProxy (obj))
241                                 return RemotingServices.GetRealProxy(obj).ObjectIdentity.CreateObjRef (requested_type);
242                         else
243                                 return obj.CreateObjRef(requested_type);
244                 }
245
246                 static string NewUri ()
247                 {
248                         int n = Interlocked.Increment (ref next_id);
249                         return app_id + Environment.TickCount + "_" + n + ".rem";
250                 }
251
252                 public static RealProxy GetRealProxy (object proxy)
253                 {
254                         if (!IsTransparentProxy(proxy)) throw new RemotingException("Cannot get the real proxy from an object that is not a transparent proxy.");
255                         return (RealProxy)((TransparentProxy)proxy)._rp;
256                 }
257
258                 public static MethodBase GetMethodBaseFromMethodMessage(IMethodMessage msg)
259                 {
260                         Type type = Type.GetType (msg.TypeName);
261                         if (type == null)
262                                 throw new RemotingException ("Type '" + msg.TypeName + "' not found.");
263
264                         BindingFlags bflags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
265                         if (msg.MethodSignature == null)
266                                 return type.GetMethod (msg.MethodName, bflags);
267                         else
268                                 return type.GetMethod (msg.MethodName, bflags, null, (Type[]) msg.MethodSignature, null);
269                 }
270
271                 public static void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
272                 {
273                         if (obj == null) throw new ArgumentNullException ("obj");
274
275                         ObjRef oref = Marshal ((MarshalByRefObject)obj);
276                         oref.GetObjectData (info, context);
277                 }
278
279                 public static ObjRef GetObjRefForProxy(MarshalByRefObject obj)
280                 {
281                         Identity ident = GetObjectIdentity(obj);
282                         if (ident == null) return null;
283                         else return ident.CreateObjRef(null);
284                 }
285
286                 public static object GetLifetimeService (MarshalByRefObject obj)
287                 {
288                         if (obj == null) return null;
289                         return obj.GetLifetimeService ();
290                 }
291
292                 public static IMessageSink GetEnvoyChainForProxy (MarshalByRefObject obj)
293                 {
294                         if (IsTransparentProxy(obj))
295                                 return ((ClientIdentity)GetRealProxy (obj).ObjectIdentity).EnvoySink;
296                         else
297                                 throw new ArgumentException ("obj must be a proxy.","obj");                     
298                 }
299
300                 public static void LogRemotingStage (int stage)
301                 {
302                         throw new NotImplementedException ();
303                 }
304
305                 public static string GetSessionIdForMethodMessage(IMethodMessage msg)
306                 {
307                         // It seems that this it what MS returns.
308                         return msg.Uri;
309                 }
310
311                 public static bool IsMethodOverloaded(IMethodMessage msg)
312                 {
313                         // TODO: use internal call for better performance
314                         Type type = msg.MethodBase.DeclaringType;
315                         MemberInfo[] members = type.GetMember (msg.MethodName, MemberTypes.Method, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
316                         return members.Length > 1;
317                 }
318
319                 public static bool IsObjectOutOfAppDomain(object tp)
320                 {
321                         // TODO: use internal call for better performance
322                         Identity ident = GetObjectIdentity((MarshalByRefObject)tp);
323                         if (ident != null) return !ident.IsFromThisAppDomain;
324                         else return false;
325                 }
326
327                 public static bool IsObjectOutOfContext(object tp)
328                 {
329                         // TODO: use internal call for better performance
330                         ServerIdentity ident = GetObjectIdentity((MarshalByRefObject)tp) as ServerIdentity;
331                         if (ident != null) return ident.Context != System.Threading.Thread.CurrentContext;
332                         else return false;
333                 }
334
335                 public static bool IsOneWay(MethodBase method)
336                 {
337                         // TODO: use internal call for better performance
338                         object[] atts = method.GetCustomAttributes (typeof (OneWayAttribute), false);
339                         return atts.Length > 0;
340                 }
341
342                 internal static bool IsAsyncMessage(IMessage msg)
343                 {
344                         if (! (msg is MonoMethodMessage)) return false;
345                         else if (((MonoMethodMessage)msg).IsAsync) return true;
346                         else if (IsOneWay (((MonoMethodMessage)msg).MethodBase)) return true;
347                         else return false;
348                 }
349
350                 public static void SetObjectUriForMarshal(MarshalByRefObject obj, string uri)
351                 {
352                         if (IsTransparentProxy (obj)) throw new RemotingException ("SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.");
353                         Marshal (obj, uri);
354                 }
355
356                 #region Internal Methods
357                 
358                 internal static object CreateClientProxy (ActivatedClientTypeEntry entry, object[] activationAttributes)
359                 {
360                         if (entry.ContextAttributes != null || activationAttributes != null)
361                         {
362                                 ArrayList props = new ArrayList ();
363                                 if (entry.ContextAttributes != null) props.AddRange (entry.ContextAttributes);
364                                 if (activationAttributes != null) props.AddRange (activationAttributes);
365                                 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, props.ToArray ());
366                         }
367                         else
368                                 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, null);
369                 }
370         
371                 internal static object CreateClientProxy (Type objectType, string url, object[] activationAttributes)
372                 {
373                         string activationUrl = url + "/RemoteActivationService.rem";
374
375                         string objectUri;
376                         IMessageSink sink = GetClientChannelSinkChain (activationUrl, null, out objectUri);
377
378                         RemotingProxy proxy = new RemotingProxy (objectType, activationUrl, activationAttributes);
379                         return proxy.GetTransparentProxy();
380                 }
381         
382                 internal static object CreateClientProxy (WellKnownClientTypeEntry entry)
383                 {
384                         return Connect (entry.ObjectType, entry.ObjectUrl, null);
385                 }
386         
387                 internal static object CreateClientProxyForContextBound (Type type, object[] activationAttributes)
388                 {
389                         if (type.IsContextful)
390                         {
391                                 // Look for a ProxyAttribute
392                                 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (type, typeof(ProxyAttribute), true);
393                                 if (att != null)
394                                         return att.CreateInstance (type);
395                         }
396                         RemotingProxy proxy = new RemotingProxy (type, ChannelServices.CrossContextUrl, activationAttributes);
397                         return proxy.GetTransparentProxy();
398                 }
399         
400                 internal static Identity GetIdentityForUri (string uri)
401                 {
402                         lock (uri_hash)
403                         {
404                                 return (Identity)uri_hash [GetNormalizedUri(uri)];
405                         }
406                 }
407
408                 internal static Identity GetObjectIdentity (MarshalByRefObject obj)
409                 {
410                         if (IsTransparentProxy(obj))
411                                 return GetRealProxy (obj).ObjectIdentity;
412                         else
413                                 return obj.ObjectIdentity;
414                 }
415
416                 internal static ClientIdentity GetOrCreateClientIdentity(ObjRef objRef, Type proxyType, out object clientProxy)
417                 {
418                         // This method looks for an identity for the given url. 
419                         // If an identity is not found, it creates the identity and 
420                         // assigns it a proxy to the remote object.
421
422                         // Creates the client sink chain for the given url or channelData.
423                         // It will also get the object uri from the url.
424
425                         object channelData = objRef.ChannelInfo != null ? objRef.ChannelInfo.ChannelData : null;
426                         string url = (channelData == null) ? objRef.URI : null;
427
428                         string objectUri;
429                         IMessageSink sink = GetClientChannelSinkChain (url, channelData, out objectUri);
430
431                         if (objectUri == null) objectUri = objRef.URI;
432
433                         lock (uri_hash)
434                         {
435                                 clientProxy = null;
436                                 string uri = GetNormalizedUri (objRef.URI);
437                                 
438                                 ClientIdentity identity = uri_hash [uri] as ClientIdentity;
439                                 if (identity != null)
440                                 {
441                                         // Object already registered
442                                         clientProxy = identity.ClientProxy;
443                                         if (clientProxy != null) return identity;
444                                         
445                                         // The proxy has just been GCed, so its identity cannot
446                                         // be reused. Just dispose it.
447                                         DisposeIdentity (identity);
448                                 }
449
450                                 // Creates an identity and a proxy for the remote object
451
452                                 identity = new ClientIdentity (objectUri, objRef);
453                                 identity.ChannelSink = sink;
454
455                                 // Registers the identity
456                                 uri_hash [uri] = identity;
457                                 
458                                 if (proxyType != null)
459                                 {
460                                         RemotingProxy proxy = new RemotingProxy (proxyType, identity);
461                                         clientProxy = proxy.GetTransparentProxy();
462                                         identity.ClientProxy = (MarshalByRefObject) clientProxy;
463                                 }
464
465                                 return identity;
466                         }
467                 }
468
469                 static IMessageSink GetClientChannelSinkChain(string url, object channelData, out string objectUri)
470                 {
471                         IMessageSink sink = ChannelServices.CreateClientChannelSinkChain (url, channelData, out objectUri);
472                         if (sink == null) 
473                         {
474                                 if (url != null) 
475                                 {
476                                         string msg = String.Format ("Cannot create channel sink to connect to URL {0}. An appropriate channel has probably not been registered.", url); 
477                                         throw new RemotingException (msg);
478                                 }
479                                 else 
480                                 {
481                                         string msg = String.Format ("Cannot create channel sink to connect to the remote object. An appropriate channel has probably not been registered.", url); 
482                                         throw new RemotingException (msg);
483                                 }
484                         }
485                         return sink;
486                 }
487
488                 internal static ClientActivatedIdentity CreateContextBoundObjectIdentity(Type objectType)
489                 {
490                         ClientActivatedIdentity identity = new ClientActivatedIdentity (null, objectType);
491                         identity.ChannelSink = ChannelServices.CrossContextChannel;
492                         return identity;
493                 }
494
495                 internal static ClientActivatedIdentity CreateClientActivatedServerIdentity(MarshalByRefObject realObject, Type objectType, string objectUri)
496                 {
497                         ClientActivatedIdentity identity = new ClientActivatedIdentity (objectUri, objectType);
498                         identity.AttachServerObject (realObject, Context.DefaultContext);
499                         RegisterServerIdentity (identity);
500                         identity.StartTrackingLifetime ((ILease)realObject.InitializeLifetimeService ());
501                         return identity;
502                 }
503
504                 internal static ServerIdentity CreateWellKnownServerIdentity(Type objectType, string objectUri, WellKnownObjectMode mode)
505                 {
506                         ServerIdentity identity;
507
508                         if (mode == WellKnownObjectMode.SingleCall)
509                                 identity = new  SingleCallIdentity(objectUri, Context.DefaultContext, objectType);
510                         else
511                                 identity = new  SingletonIdentity(objectUri, Context.DefaultContext, objectType);
512
513                         RegisterServerIdentity (identity);
514                         return identity;
515                 }
516
517                 private static void RegisterServerIdentity(ServerIdentity identity)
518                 {
519                         lock (uri_hash)
520                         {
521                                 if (uri_hash.ContainsKey (identity.ObjectUri)) 
522                                         throw new RemotingException ("Uri already in use: " + identity.ObjectUri + ".");
523
524                                 uri_hash[identity.ObjectUri] = identity;
525                         }
526                 }
527
528                 internal static object GetProxyForRemoteObject (ObjRef objref, Type classToProxy)
529                 {
530                         ClientActivatedIdentity identity = GetIdentityForUri (objref.URI) as ClientActivatedIdentity;
531                         if (identity != null) return identity.GetServerObject ();
532                         else return GetRemoteObject (objref, classToProxy);
533                 }
534
535                 internal static object GetRemoteObject(ObjRef objRef, Type proxyType)
536                 {
537                         object proxy;
538                         GetOrCreateClientIdentity (objRef, proxyType, out proxy);
539                         return proxy;
540                 }
541
542                 internal static object GetDomainProxy(AppDomain domain) 
543                 {
544                         byte[] data = null;
545
546                         Context currentContext = Thread.CurrentContext;
547
548                         try
549                         {
550                                 data = (byte[])AppDomain.InvokeInDomain (domain, typeof (AppDomain).GetMethod ("GetMarshalledDomainObjRef", BindingFlags.Instance|BindingFlags.NonPublic), domain, null);
551                         }
552                         finally
553                         {
554                                 AppDomain.InternalSetContext (currentContext);
555                         }                               
556
557                         MemoryStream stream = new MemoryStream (data);
558                         ObjRef appref = (ObjRef) CADSerializer.DeserializeObject (stream);
559                         return (AppDomain) RemotingServices.Unmarshal(appref);
560                 }
561
562                 private static void RegisterInternalChannels() 
563                 {
564                         CrossAppDomainChannel.RegisterCrossAppDomainChannel();
565                 }
566                 
567                 internal static void DisposeIdentity (Identity ident)
568                 {
569                         lock (uri_hash)
570                         {
571                                 if (!ident.Disposed) {
572                                         ClientIdentity clientId = ident as ClientIdentity;
573                                         if (clientId != null)
574                                                 uri_hash.Remove (GetNormalizedUri (clientId.TargetUri));
575                                         else
576                                                 uri_hash.Remove (ident.ObjectUri);
577                                                 
578                                         ident.Disposed = true;
579                                 }
580                         }
581                 }
582
583                 internal static Identity GetMessageTargetIdentity (IMessage msg)
584                 {
585                         // Returns the identity where the message is sent
586
587                         if (msg is IInternalMessage) 
588                                 return ((IInternalMessage)msg).TargetIdentity;
589
590                         lock (uri_hash)
591                         {
592                                 string uri = GetNormalizedUri (((IMethodMessage)msg).Uri);
593                                 return uri_hash [uri] as ServerIdentity;
594                         }
595                 }
596
597                 internal static void SetMessageTargetIdentity (IMessage msg, Identity ident)
598                 {
599                         if (msg is IInternalMessage) 
600                                 ((IInternalMessage)msg).TargetIdentity = ident;
601                 }
602                 
603                 internal static bool UpdateOutArgObject (ParameterInfo pi, object local, object remote)
604                 {
605                         if (local is StringBuilder) 
606                         {
607                                 StringBuilder sb = local as StringBuilder;
608                                 sb.Remove (0, sb.Length);
609                                 sb.Append (remote.ToString());
610                                 return true;
611                         }
612                         else if (pi.ParameterType.IsArray && ((Array)local).Rank == 1)
613                         {
614                                 Array alocal = (Array) local;
615                                 if (alocal.Rank == 1)
616                                 {
617                                         Array.Copy ((Array) remote, alocal, alocal.Length);
618                                         return true;
619                                 }
620                                 else
621                                 {
622                                         // TODO
623                                 }
624                         }
625                         return false;
626                 }
627                 
628                 static string GetNormalizedUri (string uri)
629                 {
630                         if (uri.StartsWith ("/")) return uri.Substring (1);
631                         else return uri;
632                 }
633
634                 #endregion
635         }
636 }