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