* RemotingServices.cs: Do not create an identity for an object if it
[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                         Identity ident = GetIdentityForUri (uri);
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                         // FIXME: use type name when fRefine==true
170
171                         Type classToProxy = fRefine ? objref.ServerType : typeof (MarshalByRefObject);
172                         if (classToProxy == null) classToProxy = typeof (MarshalByRefObject);
173
174                         if (objref.IsReferenceToWellKnow)
175                                 return GetRemoteObject(objref, classToProxy);
176                         else
177                         {
178                                 if (classToProxy.IsContextful)
179                                 {
180                                         // Look for a ProxyAttribute
181                                         ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (classToProxy, typeof(ProxyAttribute),true);
182                                         if (att != null)
183                                                 return att.CreateProxy (objref, classToProxy, null, null).GetTransparentProxy();
184                                 }
185                                 return GetProxyForRemoteObject (objref, classToProxy);
186                         }
187                 }
188
189                 public static ObjRef Marshal (MarshalByRefObject obj)
190                 {
191                         return Marshal (obj, null, null);
192                 }
193                 
194                 public static ObjRef Marshal (MarshalByRefObject obj, string uri)
195                 {
196                         return Marshal (obj, uri, null);
197                 }
198                 
199                 public static ObjRef Marshal (MarshalByRefObject obj, string uri, Type requested_type)
200                 {
201                         if (IsTransparentProxy (obj))
202                         {
203                                 RealProxy proxy = RemotingServices.GetRealProxy(obj);
204                                 Identity identity = proxy.ObjectIdentity;
205
206                                 if (identity != null)
207                                 {
208                                         if (identity.ObjectType.IsContextful && !identity.IsConnected)
209                                         {
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);
217                                         }
218                                         else if (uri != null)
219                                                 throw new RemotingException ("It is not possible marshal a proxy of a remote object");
220
221                                         return proxy.ObjectIdentity.CreateObjRef(requested_type);
222                                 }
223                                 else
224                                         throw new NotSupportedException ();     // TODO
225                         }
226
227                         if (requested_type == null) requested_type = obj.GetType();
228
229                         if (uri == null) 
230                         {
231                                 if (obj.ObjectIdentity == null)
232                                 {
233                                         uri = NewUri();
234                                         CreateClientActivatedServerIdentity (obj, requested_type, uri);
235                                 }
236                         }
237                         else
238                         {
239                                 ClientActivatedIdentity identity = GetIdentityForUri ("/" + uri) as ClientActivatedIdentity;
240                                 if (identity == null || obj != identity.GetServerObject()) 
241                                         CreateClientActivatedServerIdentity (obj, requested_type, uri);
242                         }
243
244                         return obj.CreateObjRef(requested_type);
245                 }
246
247                 static string NewUri ()
248                 {
249                         int n = Interlocked.Increment (ref next_id);
250                         return app_id + Environment.TickCount + "_" + n;
251                 }
252
253                 public static RealProxy GetRealProxy (object proxy)
254                 {
255                         if (!IsTransparentProxy(proxy)) throw new RemotingException("Cannot get the real proxy from an object that is not a transparent proxy");
256                         return (RealProxy)((TransparentProxy)proxy)._rp;
257                 }
258
259                 public static MethodBase GetMethodBaseFromMethodMessage(IMethodMessage msg)
260                 {
261                         Type type = Type.GetType (msg.TypeName);
262                         if (type == null)
263                                 throw new RemotingException ("Type '" + msg.TypeName + "' not found!");
264
265                         BindingFlags bflags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
266                         if (msg.MethodSignature == null)
267                                 return type.GetMethod (msg.MethodName, bflags);
268                         else
269                                 return type.GetMethod (msg.MethodName, bflags, null, (Type[]) msg.MethodSignature, null);
270                 }
271
272                 public static void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
273                 {
274                         if (obj == null) throw new ArgumentNullException ("obj");
275
276                         ObjRef oref = Marshal ((MarshalByRefObject)obj);
277                         oref.GetObjectData (info, context);
278                 }
279
280                 public static ObjRef GetObjRefForProxy(MarshalByRefObject obj)
281                 {
282                         Identity ident = GetObjectIdentity(obj);
283                         if (ident == null) return null;
284                         else return ident.CreateObjRef(null);
285                 }
286
287                 public static object GetLifetimeService (MarshalByRefObject obj)
288                 {
289                         if (obj == null) return null;
290                         return obj.GetLifetimeService ();
291                 }
292
293                 public static IMessageSink GetEnvoyChainForProxy (MarshalByRefObject obj)
294                 {
295                         if (IsTransparentProxy(obj))
296                                 return ((ClientIdentity)GetRealProxy (obj).ObjectIdentity).EnvoySink;
297                         else
298                                 throw new ArgumentException ("obj must be a proxy","obj");                      
299                 }
300
301                 public static void LogRemotingStage (int stage)
302                 {
303                         throw new NotImplementedException ();
304                 }
305
306                 [MonoTODO]
307                 public static string GetSessionIdForMethodMessage(IMethodMessage msg)
308                 {
309                         throw new NotImplementedException (); 
310                 }
311
312                 public static bool IsMethodOverloaded(IMethodMessage msg)
313                 {
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                         Identity ident = GetObjectIdentity((MarshalByRefObject)tp);
322                         if (ident != null) return !ident.IsFromThisAppDomain;
323                         else return false;
324                 }
325
326                 public static bool IsObjectOutOfContext(object tp)
327                 {
328                         ServerIdentity ident = GetObjectIdentity((MarshalByRefObject)tp) as ServerIdentity;
329                         if (ident != null) return ident.Context != System.Threading.Thread.CurrentContext;
330                         else return false;
331                 }
332
333                 public static bool IsOneWay(MethodBase method)
334                 {
335                         // TODO: use internal call for better performance
336                         object[] atts = method.GetCustomAttributes (typeof (OneWayAttribute), false);
337                         return atts.Length > 0;
338                 }
339
340                 public static bool IsAsyncMessage(IMessage msg)
341                 {
342                         if (! (msg is MonoMethodMessage)) return false;
343                         else if (((MonoMethodMessage)msg).IsAsync) return true;
344                         else if (IsOneWay (((MonoMethodMessage)msg).MethodBase)) return true;
345                         else return false;
346                 }
347
348                 public static void SetObjectUriForMarshal(MarshalByRefObject obj, string uri)
349                 {
350                         if (IsTransparentProxy (obj)) throw new RemotingException ("SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.");
351                         Marshal (obj, uri);
352                 }
353
354                 #region Internal Methods
355                 
356                 internal static object CreateClientProxy (ActivatedClientTypeEntry entry, object[] activationAttributes)
357                 {
358                         if (entry.ContextAttributes != null || activationAttributes != null)
359                         {
360                                 ArrayList props = new ArrayList ();
361                                 if (entry.ContextAttributes != null) props.AddRange (entry.ContextAttributes);
362                                 if (activationAttributes != null) props.AddRange (activationAttributes);
363                                 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, props.ToArray ());
364                         }
365                         else
366                                 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, null);
367                 }
368         
369                 internal static object CreateClientProxy (Type objectType, string url, object[] activationAttributes)
370                 {
371                         string activationUrl = url + "/RemoteActivationService.rem";
372
373                         string objectUri;
374                         IMessageSink sink = GetClientChannelSinkChain (activationUrl, null, out objectUri);
375
376                         RemotingProxy proxy = new RemotingProxy (objectType, activationUrl, activationAttributes);
377                         return proxy.GetTransparentProxy();
378                 }
379         
380                 internal static object CreateClientProxy (WellKnownClientTypeEntry entry)
381                 {
382                         return Connect (entry.ObjectType, entry.ObjectUrl, null);
383                 }
384         
385                 internal static object CreateClientProxyForContextBound (Type type, object[] activationAttributes)
386                 {
387                         if (type.IsContextful)
388                         {
389                                 // Look for a ProxyAttribute
390                                 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (type, typeof(ProxyAttribute), true);
391                                 if (att != null)
392                                         return att.CreateInstance (type);
393                         }
394                         RemotingProxy proxy = new RemotingProxy (type, ChannelServices.CrossContextUrl, activationAttributes);
395                         return proxy.GetTransparentProxy();
396                 }
397         
398                 internal static Identity GetIdentityForUri (string uri)
399                 {
400                         lock (uri_hash)
401                         {
402                                 return (Identity)uri_hash [GetNormalizedUri(uri)];
403                         }
404                 }
405
406                 internal static Identity GetObjectIdentity (MarshalByRefObject obj)
407                 {
408                         if (IsTransparentProxy(obj))
409                                 return GetRealProxy (obj).ObjectIdentity;
410                         else
411                                 return obj.ObjectIdentity;
412                 }
413
414                 internal static ClientIdentity GetOrCreateClientIdentity(ObjRef objRef, Type proxyType, out object clientProxy)
415                 {
416                         // This method looks for an identity for the given url. 
417                         // If an identity is not found, it creates the identity and 
418                         // assigns it a proxy to the remote object.
419
420                         // Creates the client sink chain for the given url or channelData.
421                         // It will also get the object uri from the url.
422
423                         object channelData = objRef.ChannelInfo != null ? objRef.ChannelInfo.ChannelData : null;
424                         string url = (channelData == null) ? objRef.URI : null;
425
426                         string objectUri;
427                         IMessageSink sink = GetClientChannelSinkChain (url, channelData, out objectUri);
428
429                         if (objectUri == null) objectUri = objRef.URI;
430
431                         lock (uri_hash)
432                         {
433                                 clientProxy = null;
434                                 string uri = GetNormalizedUri (objRef.URI);
435                                 
436                                 ClientIdentity identity = uri_hash [uri] as ClientIdentity;
437                                 if (identity != null)
438                                 {
439                                         // Object already registered
440                                         clientProxy = identity.ClientProxy;
441                                         if (clientProxy != null) return identity;
442                                         
443                                         // The proxy has just been GCed, so its identity cannot
444                                         // be reused. Just dispose it.
445                                         DisposeIdentity (identity);
446                                 }
447
448                                 // Creates an identity and a proxy for the remote object
449
450                                 identity = new ClientIdentity (objectUri, objRef);
451                                 identity.ChannelSink = sink;
452
453                                 // Registers the identity
454                                 uri_hash [uri] = identity;
455                                 
456                                 if (proxyType != null)
457                                 {
458                                         RemotingProxy proxy = new RemotingProxy (proxyType, identity);
459                                         clientProxy = proxy.GetTransparentProxy();
460                                         identity.ClientProxy = (MarshalByRefObject) clientProxy;
461                                 }
462
463                                 return identity;
464                         }
465                 }
466
467                 static IMessageSink GetClientChannelSinkChain(string url, object channelData, out string objectUri)
468                 {
469                         IMessageSink sink = ChannelServices.CreateClientChannelSinkChain (url, channelData, out objectUri);
470                         if (sink == null) 
471                         {
472                                 if (url != null) 
473                                 {
474                                         string msg = String.Format ("Cannot create channel sink to connect to URL {0}. An appropriate channel has probably not been registered.", url); 
475                                         throw new RemotingException (msg);
476                                 }
477                                 else 
478                                 {
479                                         string msg = String.Format ("Cannot create channel sink to connect to the remote object. An appropriate channel has probably not been registered.", url); 
480                                         throw new RemotingException (msg);
481                                 }
482                         }
483                         return sink;
484                 }
485
486                 internal static ClientActivatedIdentity CreateContextBoundObjectIdentity(Type objectType)
487                 {
488                         ClientActivatedIdentity identity = new ClientActivatedIdentity (null, objectType);
489                         identity.ChannelSink = ChannelServices.CrossContextChannel;
490                         return identity;
491                 }
492
493                 internal static ClientActivatedIdentity CreateClientActivatedServerIdentity(MarshalByRefObject realObject, Type objectType, string objectUri)
494                 {
495                         ClientActivatedIdentity identity = new ClientActivatedIdentity (objectUri, objectType);
496                         identity.AttachServerObject (realObject, Context.DefaultContext);
497                         RegisterServerIdentity (identity);
498                         identity.StartTrackingLifetime ((ILease)realObject.InitializeLifetimeService ());
499                         return identity;
500                 }
501
502                 internal static ServerIdentity CreateWellKnownServerIdentity(Type objectType, string objectUri, WellKnownObjectMode mode)
503                 {
504                         ServerIdentity identity;
505
506                         if (mode == WellKnownObjectMode.SingleCall)
507                                 identity = new  SingleCallIdentity(objectUri, Context.DefaultContext, objectType);
508                         else
509                                 identity = new  SingletonIdentity(objectUri, Context.DefaultContext, objectType);
510
511                         RegisterServerIdentity (identity);
512                         return identity;
513                 }
514
515                 private static void RegisterServerIdentity(ServerIdentity identity)
516                 {
517                         lock (uri_hash)
518                         {
519                                 if (uri_hash.ContainsKey (identity.ObjectUri)) 
520                                         throw new RemotingException ("Uri already in use: " + identity.ObjectUri);
521
522                                 uri_hash[identity.ObjectUri] = identity;
523                         }
524                 }
525
526                 internal static object GetProxyForRemoteObject (ObjRef objref, Type classToProxy)
527                 {
528                         ClientActivatedIdentity identity = GetIdentityForUri (objref.URI) as ClientActivatedIdentity;
529                         if (identity != null) return identity.GetServerObject ();
530                         else return GetRemoteObject (objref, classToProxy);
531                 }
532
533                 internal static object GetRemoteObject(ObjRef objRef, Type proxyType)
534                 {
535                         object proxy;
536                         GetOrCreateClientIdentity (objRef, proxyType, out proxy);
537                         return proxy;
538                 }
539
540                 internal static object GetDomainProxy(AppDomain domain) 
541                 {
542                         byte[] data = null;
543
544                         Context currentContext = Thread.CurrentContext;
545                         AppDomain currentDomain = AppDomain.InternalSetDomain (domain);
546                         try 
547                         {
548                                 data = domain.GetMarshalledDomainObjRef ();
549                         }
550                         finally 
551                         {
552                                 AppDomain.InternalSetDomain (currentDomain);
553                                 AppDomain.InternalSetContext (currentContext);
554                         }
555
556                         MemoryStream stream = new MemoryStream (data);
557                         ObjRef appref = (ObjRef) CADSerializer.DeserializeObject (stream);
558                         return (AppDomain) RemotingServices.Unmarshal(appref);
559                 }
560
561                 private static void RegisterInternalChannels() 
562                 {
563                         CrossAppDomainChannel.RegisterCrossAppDomainChannel();
564                 }
565                 
566                 internal static void DisposeIdentity (Identity ident)
567                 {
568                         lock (uri_hash)
569                         {
570                                 if (!ident.Disposed) {
571                                         uri_hash.Remove (ident.ObjectUri);
572                                         ident.Disposed = true;
573                                 }
574                         }
575                 }
576
577                 internal static Identity GetMessageTargetIdentity (IMessage msg)
578                 {
579                         // Returns the identity where the message is sent
580
581                         if (msg is IInternalMessage) 
582                                 return ((IInternalMessage)msg).TargetIdentity;
583
584                         lock (uri_hash)
585                         {
586                                 string uri = GetNormalizedUri (((IMethodMessage)msg).Uri);
587                                 return uri_hash [uri] as ServerIdentity;
588                         }
589                 }
590
591                 internal static void SetMessageTargetIdentity (IMessage msg, Identity ident)
592                 {
593                         if (msg is IInternalMessage) 
594                                 ((IInternalMessage)msg).TargetIdentity = ident;
595                 }
596                 
597                 internal static bool UpdateOutArgObject (ParameterInfo pi, object local, object remote)
598                 {
599                         if (local is StringBuilder) 
600                         {
601                                 StringBuilder sb = local as StringBuilder;
602                                 sb.Remove (0, sb.Length);
603                                 sb.Append (remote.ToString());
604                                 return true;
605                         }
606                         else if (pi.ParameterType.IsArray && ((Array)local).Rank == 1)
607                         {
608                                 Array alocal = (Array) local;
609                                 if (alocal.Rank == 1)
610                                 {
611                                         Array.Copy ((Array) remote, alocal, alocal.Length);
612                                         return true;
613                                 }
614                                 else
615                                 {
616                                         // TODO
617                                 }
618                         }
619                         return false;
620                 }
621                 
622                 static string GetNormalizedUri (string uri)
623                 {
624                         if (uri.StartsWith ("/")) return uri.Substring (1);
625                         else return uri;
626                 }
627
628                 #endregion
629         }
630 }