2010-01-20 Zoltan Varga <vargaz@gmail.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 // Copyright (C) 2004, 2006 Novell, Inc (http://www.novell.com)
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System.Diagnostics;
33 using System.Text;
34 using System.Reflection;
35 using System.Threading;
36 using System.Collections;
37 using System.Runtime.Remoting.Messaging;
38 using System.Runtime.Remoting.Proxies;
39 using System.Runtime.Remoting.Channels;
40 using System.Runtime.Remoting.Contexts;
41 using System.Runtime.Remoting.Activation;
42 using System.Runtime.Remoting.Lifetime;
43 using System.Runtime.CompilerServices;
44 using System.Runtime.Serialization;
45 using System.Runtime.Serialization.Formatters.Binary;
46 using System.IO;
47 using System.Runtime.Remoting.Services;
48 using System.Security.Permissions;
49 using System.Runtime.ConstrainedExecution;
50 using System.Runtime.Serialization.Formatters;
51
52 namespace System.Runtime.Remoting
53 {
54         [System.Runtime.InteropServices.ComVisible (true)]
55         public sealed class RemotingServices 
56         {
57                 // Holds the identities of the objects, using uri as index
58                 static Hashtable uri_hash = new Hashtable ();           
59
60                 static BinaryFormatter _serializationFormatter;
61                 static BinaryFormatter _deserializationFormatter;
62                 
63                 static string app_id;
64                 static readonly object app_id_lock = new object ();
65                 
66                 static int next_id = 1;
67                 const BindingFlags methodBindings = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
68                 static readonly MethodInfo FieldSetterMethod;
69                 static readonly MethodInfo FieldGetterMethod;
70                 
71                 // Holds information in xdomain calls. Names are short to minimize serialized size.
72                 [Serializable]
73                 class CACD {
74                         public object d;        /* call data */
75                         public object c;        /* call context */
76                 }
77                 
78                 static RemotingServices ()
79                 {
80                         RemotingSurrogateSelector surrogateSelector = new RemotingSurrogateSelector ();
81                         StreamingContext context = new StreamingContext (StreamingContextStates.Remoting, null);
82                         _serializationFormatter = new BinaryFormatter (surrogateSelector, context);
83                         _deserializationFormatter = new BinaryFormatter (null, context);
84                         _serializationFormatter.AssemblyFormat = FormatterAssemblyStyle.Full;
85                         _deserializationFormatter.AssemblyFormat = FormatterAssemblyStyle.Full;
86                         
87                         RegisterInternalChannels ();
88                         CreateWellKnownServerIdentity (typeof(RemoteActivator), "RemoteActivationService.rem", WellKnownObjectMode.Singleton);
89                         
90                         FieldSetterMethod = typeof(object).GetMethod ("FieldSetter", BindingFlags.NonPublic|BindingFlags.Instance);
91                         FieldGetterMethod = typeof(object).GetMethod ("FieldGetter", BindingFlags.NonPublic|BindingFlags.Instance);
92                 }
93         
94                 private RemotingServices () {}
95
96                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
97                 internal extern static object InternalExecute (MethodBase method, Object obj,
98                                                                Object[] parameters, out object [] out_args);
99
100                 // Returns the actual implementation of @method in @type.
101                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
102                 internal extern static MethodBase GetVirtualMethod (Type type, MethodBase method);
103
104                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
105                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
106                 public extern static bool IsTransparentProxy (object proxy);
107                 
108                 internal static IMethodReturnMessage InternalExecuteMessage (
109                         MarshalByRefObject target, IMethodCallMessage reqMsg)
110                 {
111                         ReturnMessage result;
112                         
113                         Type tt = target.GetType ();
114                         MethodBase method;
115                         if (reqMsg.MethodBase.DeclaringType == tt ||
116                             reqMsg.MethodBase == FieldSetterMethod || 
117                             reqMsg.MethodBase == FieldGetterMethod) {
118                                 method = reqMsg.MethodBase;
119                         } else {
120                                 method = GetVirtualMethod (tt, reqMsg.MethodBase);
121
122                                 if (method == null)
123                                         throw new RemotingException (
124                                                 String.Format ("Cannot resolve method {0}:{1}", tt, reqMsg.MethodName));
125                         }
126
127                         if (reqMsg.MethodBase.IsGenericMethod) {
128                                 Type[] genericArguments = reqMsg.MethodBase.GetGenericArguments ();
129                                 method = ((MethodInfo)method).MakeGenericMethod (genericArguments);
130                         }
131
132                         object oldContext = CallContext.SetCurrentCallContext (reqMsg.LogicalCallContext);
133                         
134                         try 
135                         {
136                                 object [] out_args;
137                                 object rval = InternalExecute (method, target, reqMsg.Args, out out_args);
138                         
139                                 // Collect parameters with Out flag from the request message
140                                 // FIXME: This can be done in the unmanaged side and will be
141                                 // more efficient
142                                 
143                                 ParameterInfo[] parameters = method.GetParameters();
144                                 object[] returnArgs = new object [parameters.Length];
145                                 
146                                 int n = 0;
147                                 int noa = 0;
148                                 foreach (ParameterInfo par in parameters)
149                                 {
150                                         if (par.IsOut && !par.ParameterType.IsByRef) 
151                                                 returnArgs [n++] = reqMsg.GetArg (par.Position);
152                                         else if (par.ParameterType.IsByRef)
153                                                 returnArgs [n++] = out_args [noa++]; 
154                                         else
155                                                 returnArgs [n++] = null; 
156                                 }
157                                 
158                                 result = new ReturnMessage (rval, returnArgs, n, CallContext.CreateLogicalCallContext (true), reqMsg);
159                         } 
160                         catch (Exception e) 
161                         {
162                                 result = new ReturnMessage (e, reqMsg);
163                         }
164                         
165                         CallContext.RestoreCallContext (oldContext);
166                         return result;
167                 }
168
169                 public static IMethodReturnMessage ExecuteMessage (
170                         MarshalByRefObject target, IMethodCallMessage reqMsg)
171                 {
172                         if (IsTransparentProxy(target))
173                         {
174                                 // Message must go through all chain of sinks
175                                 RealProxy rp = GetRealProxy (target);
176                                 return (IMethodReturnMessage) rp.Invoke (reqMsg);
177                         }
178                         else    // Direct call
179                                 return InternalExecuteMessage (target, reqMsg);
180                 }
181
182                 [System.Runtime.InteropServices.ComVisible (true)]
183                 public static object Connect (Type classToProxy, string url)
184                 {
185                         ObjRef objRef = new ObjRef (classToProxy, url, null);
186                         return GetRemoteObject (objRef, classToProxy);
187                 }
188
189                 [System.Runtime.InteropServices.ComVisible (true)]
190                 public static object Connect (Type classToProxy, string url, object data)
191                 {
192                         ObjRef objRef = new ObjRef (classToProxy, url, data);
193                         return GetRemoteObject (objRef, classToProxy);
194                 }
195
196                 public static bool Disconnect (MarshalByRefObject obj)
197                 {
198                         if (obj == null) throw new ArgumentNullException ("obj");
199
200                         ServerIdentity identity;
201
202                         if (IsTransparentProxy (obj))
203                         {
204                                 // CBOs are always accessed through a proxy, even in the server, so
205                                 // for server CBOs it is ok to disconnect a proxy
206
207                                 RealProxy proxy = GetRealProxy(obj);
208                                 if (proxy.GetProxiedType().IsContextful && (proxy.ObjectIdentity is ServerIdentity))
209                                         identity = proxy.ObjectIdentity as ServerIdentity;
210                                 else
211                                         throw new ArgumentException ("The obj parameter is a proxy.");
212                         }
213                         else {
214                                 identity = obj.ObjectIdentity;
215                                 obj.ObjectIdentity = null;
216                         }
217
218                         if (identity == null || !identity.IsConnected)
219                                 return false;
220                         else
221                         {
222                                 LifetimeServices.StopTrackingLifetime (identity);
223                                 DisposeIdentity (identity);
224                                 TrackingServices.NotifyDisconnectedObject (obj);
225                                 return true;
226                         }
227                 }
228
229                 public static Type GetServerTypeForUri (string URI)
230                 {
231                         ServerIdentity ident = GetIdentityForUri (URI) as ServerIdentity;
232                         if (ident == null) return null;
233                         return ident.ObjectType;
234                 }
235
236                 public static string GetObjectUri (MarshalByRefObject obj)
237                 {
238                         Identity ident = GetObjectIdentity(obj);
239                         if (ident is ClientIdentity) return ((ClientIdentity)ident).TargetUri;
240                         else if (ident != null) return ident.ObjectUri;
241                         else return null;
242                 }
243
244                 public static object Unmarshal (ObjRef objectRef)
245                 {
246                         return Unmarshal (objectRef, true);
247                 }
248
249                 public static object Unmarshal (ObjRef objectRef, bool fRefine)
250                 {
251                         Type classToProxy = fRefine ? objectRef.ServerType : typeof (MarshalByRefObject);
252                         if (classToProxy == null) classToProxy = typeof (MarshalByRefObject);
253
254                         if (objectRef.IsReferenceToWellKnow) {
255                                 object obj = GetRemoteObject (objectRef, classToProxy);
256                                 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
257                                 return obj;
258                         }
259                         else
260                         {
261                                 object obj;
262                                 
263                                 if (classToProxy.IsContextful) {
264                                         // Look for a ProxyAttribute
265                                         ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (classToProxy, typeof(ProxyAttribute), true);
266                                         if (att != null) {
267                                                 obj = att.CreateProxy (objectRef, classToProxy, null, null).GetTransparentProxy();
268                                                 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
269                                                 return obj;
270                                         }
271                                 }
272                                 obj = GetProxyForRemoteObject (objectRef, classToProxy);
273                                 TrackingServices.NotifyUnmarshaledObject (obj, objectRef);
274                                 return obj;
275                         }
276                 }
277
278                 public static ObjRef Marshal (MarshalByRefObject Obj)
279                 {
280                         return Marshal (Obj, null, null);
281                 }
282                 
283                 public static ObjRef Marshal (MarshalByRefObject Obj, string URI)
284                 {
285                         return Marshal (Obj, URI, null);
286                 }
287                 
288                 public static ObjRef Marshal (MarshalByRefObject Obj, string ObjURI, Type RequestedType)
289                 {
290                         if (IsTransparentProxy (Obj))
291                         {
292                                 RealProxy proxy = RemotingServices.GetRealProxy (Obj);
293                                 Identity identity = proxy.ObjectIdentity;
294
295                                 if (identity != null)
296                                 {
297                                         if (proxy.GetProxiedType().IsContextful && !identity.IsConnected)
298                                         {
299                                                 // Unregistered local contextbound object. Register now.
300                                                 ClientActivatedIdentity cboundIdentity = (ClientActivatedIdentity)identity;
301                                                 if (ObjURI == null) ObjURI = NewUri();
302                                                 cboundIdentity.ObjectUri = ObjURI;
303                                                 RegisterServerIdentity (cboundIdentity);
304                                                 cboundIdentity.StartTrackingLifetime ((ILease)Obj.InitializeLifetimeService());
305                                                 return cboundIdentity.CreateObjRef (RequestedType);
306                                         }
307                                         else if (ObjURI != null)
308                                                 throw new RemotingException ("It is not possible marshal a proxy of a remote object.");
309
310                                         ObjRef or = proxy.ObjectIdentity.CreateObjRef (RequestedType);
311                                         TrackingServices.NotifyMarshaledObject (Obj, or);
312                                         return or;
313                                 }
314                         }
315
316                         if (RequestedType == null) RequestedType = Obj.GetType ();
317
318                         if (ObjURI == null) 
319                         {
320                                 if (Obj.ObjectIdentity == null)
321                                 {
322                                         ObjURI = NewUri();
323                                         CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
324                                 }
325                         }
326                         else
327                         {
328                                 ClientActivatedIdentity identity = GetIdentityForUri ("/" + ObjURI) as ClientActivatedIdentity;
329                                 if (identity == null || Obj != identity.GetServerObject()) 
330                                         CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
331                         }
332
333                         ObjRef oref;
334                         
335                         if (IsTransparentProxy (Obj))
336                                 oref = RemotingServices.GetRealProxy (Obj).ObjectIdentity.CreateObjRef (RequestedType);
337                         else
338                                 oref = Obj.CreateObjRef (RequestedType);
339                         
340                         TrackingServices.NotifyMarshaledObject (Obj, oref);
341                         return oref;
342                 }
343
344                 static string NewUri ()
345                 {
346                         if (app_id == null) {
347                                 lock (app_id_lock) {
348                                         if (app_id == null)
349                                                 app_id = Guid.NewGuid().ToString().Replace('-', '_') + "/";
350                                 }
351                         }
352
353                         int n = Interlocked.Increment (ref next_id);
354                         return app_id + Environment.TickCount.ToString("x") + "_" + n + ".rem";
355                 }
356
357                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
358                 public static RealProxy GetRealProxy (object proxy)
359                 {
360                         if (!IsTransparentProxy(proxy)) throw new RemotingException("Cannot get the real proxy from an object that is not a transparent proxy.");
361                         return (RealProxy)((TransparentProxy)proxy)._rp;
362                 }
363
364                 public static MethodBase GetMethodBaseFromMethodMessage(IMethodMessage msg)
365                 {
366                         Type type = Type.GetType (msg.TypeName);
367                         if (type == null)
368                                 throw new RemotingException ("Type '" + msg.TypeName + "' not found.");
369
370                         return GetMethodBaseFromName (type, msg.MethodName, (Type[]) msg.MethodSignature);
371                 }
372
373                 internal static MethodBase GetMethodBaseFromName (Type type, string methodName, Type[] signature)
374                 {
375                         if (type.IsInterface) {
376                                 return FindInterfaceMethod (type, methodName, signature);
377                         }
378                         else {
379                                 MethodBase method = null;
380                                 if (signature == null)
381                                         method = type.GetMethod (methodName, methodBindings);
382                                 else
383                                         method = type.GetMethod (methodName, methodBindings, null, (Type[]) signature, null);
384                                 
385                                 if (method != null)
386                                         return method;
387                                         
388                                 if (methodName == "FieldSetter")
389                                         return FieldSetterMethod;
390
391                                 if (methodName == "FieldGetter")
392                                         return FieldGetterMethod;
393                                 
394                                 if (signature == null)
395                                         return type.GetConstructor (methodBindings, null, Type.EmptyTypes, null);
396                                 else
397                                         return type.GetConstructor (methodBindings, null, signature, null);
398                         }
399                 }
400                 
401                 static MethodBase FindInterfaceMethod (Type type, string methodName, Type[] signature)
402                 {
403                         MethodBase method = null;
404                         
405                         if (signature == null)
406                                 method = type.GetMethod (methodName, methodBindings);
407                         else
408                                 method = type.GetMethod (methodName, methodBindings, null, signature, null);
409                                 
410                         if (method != null) return method;
411                         
412                         foreach (Type t in type.GetInterfaces ()) {
413                                 method = FindInterfaceMethod (t, methodName, signature);
414                                 if (method != null) return method;
415                         }
416                         
417                         return null;
418                 }
419
420                 public static void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
421                 {
422                         if (obj == null) throw new ArgumentNullException ("obj");
423
424                         ObjRef oref = Marshal ((MarshalByRefObject)obj);
425                         oref.GetObjectData (info, context);
426                 }
427
428                 public static ObjRef GetObjRefForProxy(MarshalByRefObject obj)
429                 {
430                         Identity ident = GetObjectIdentity(obj);
431                         if (ident == null) return null;
432                         else return ident.CreateObjRef(null);
433                 }
434
435                 public static object GetLifetimeService (MarshalByRefObject obj)
436                 {
437                         if (obj == null) return null;
438                         return obj.GetLifetimeService ();
439                 }
440
441                 public static IMessageSink GetEnvoyChainForProxy (MarshalByRefObject obj)
442                 {
443                         if (IsTransparentProxy(obj))
444                                 return ((ClientIdentity)GetRealProxy (obj).ObjectIdentity).EnvoySink;
445                         else
446                                 throw new ArgumentException ("obj must be a proxy.","obj");                     
447                 }
448
449                 [MonoTODO]
450                 [Conditional ("REMOTING_PERF")]
451                 [Obsolete ("It existed for only internal use in .NET and unimplemented in mono")]
452                 public static void LogRemotingStage (int stage)
453                 {
454                         throw new NotImplementedException ();
455                 }
456
457                 public static string GetSessionIdForMethodMessage(IMethodMessage msg)
458                 {
459                         // It seems that this it what MS returns.
460                         return msg.Uri;
461                 }
462
463                 public static bool IsMethodOverloaded(IMethodMessage msg)
464                 {
465                         const BindingFlags bfinst = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
466                         MonoType type = (MonoType) msg.MethodBase.DeclaringType;
467                         return type.GetMethodsByName (msg.MethodName, bfinst, false, type).Length > 1;
468                 }
469
470                 public static bool IsObjectOutOfAppDomain(object tp)
471                 {
472                         MarshalByRefObject mbr = tp as MarshalByRefObject;
473
474                         if (mbr == null)
475                                 return false;
476
477                         // TODO: use internal call for better performance
478                         Identity ident = GetObjectIdentity (mbr);
479                         return ident is ClientIdentity;
480                 }
481
482                 public static bool IsObjectOutOfContext(object tp)
483                 {
484                         MarshalByRefObject mbr = tp as MarshalByRefObject;
485
486                         if (mbr == null)
487                                 return false;
488
489                         // TODO: use internal call for better performance
490                         Identity ident = GetObjectIdentity (mbr);
491                         if (ident == null) return false;
492                         
493                         ServerIdentity sident = ident as ServerIdentity;
494                         if (sident != null) return sident.Context != System.Threading.Thread.CurrentContext;
495                         else return true;
496                 }
497
498                 public static bool IsOneWay(MethodBase method)
499                 {
500                         return method.IsDefined (typeof (OneWayAttribute), false);
501                 }
502
503                 internal static bool IsAsyncMessage(IMessage msg)
504                 {
505                         if (! (msg is MonoMethodMessage)) return false;
506                         else if (((MonoMethodMessage)msg).IsAsync) return true;
507                         else if (IsOneWay (((MonoMethodMessage)msg).MethodBase)) return true;
508                         else return false;
509                 }
510
511                 public static void SetObjectUriForMarshal(MarshalByRefObject obj, string uri)
512                 {
513                         if (IsTransparentProxy (obj)) {
514                                 RealProxy proxy = RemotingServices.GetRealProxy(obj);
515                                 Identity identity = proxy.ObjectIdentity;
516
517                                 if (identity != null && !(identity is ServerIdentity) && !proxy.GetProxiedType().IsContextful)
518                                         throw new RemotingException ("SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.");
519                         }
520                         
521                         Marshal (obj, uri);
522                 }
523
524                 #region Internal Methods
525                 
526                 internal static object CreateClientProxy (ActivatedClientTypeEntry entry, object[] activationAttributes)
527                 {
528                         if (entry.ContextAttributes != null || activationAttributes != null)
529                         {
530                                 ArrayList props = new ArrayList ();
531                                 if (entry.ContextAttributes != null) props.AddRange (entry.ContextAttributes);
532                                 if (activationAttributes != null) props.AddRange (activationAttributes);
533                                 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, props.ToArray ());
534                         }
535                         else
536                                 return CreateClientProxy (entry.ObjectType, entry.ApplicationUrl, null);
537                 }
538         
539                 internal static object CreateClientProxy (Type objectType, string url, object[] activationAttributes)
540                 {
541                         string activationUrl = url;
542                         if (!activationUrl.EndsWith ("/"))
543                                 activationUrl += "/";
544                         activationUrl += "RemoteActivationService.rem";
545
546                         string objectUri;
547                         GetClientChannelSinkChain (activationUrl, null, out objectUri);
548
549                         RemotingProxy proxy = new RemotingProxy (objectType, activationUrl, activationAttributes);
550                         return proxy.GetTransparentProxy();
551                 }
552         
553                 internal static object CreateClientProxy (WellKnownClientTypeEntry entry)
554                 {
555                         return Connect (entry.ObjectType, entry.ObjectUrl, null);
556                 }
557         
558                 internal static object CreateClientProxyForContextBound (Type type, object[] activationAttributes)
559                 {
560                         if (type.IsContextful)
561                         {
562                                 // Look for a ProxyAttribute
563                                 ProxyAttribute att = (ProxyAttribute) Attribute.GetCustomAttribute (type, typeof(ProxyAttribute), true);
564                                 if (att != null)
565                                         return att.CreateInstance (type);
566                         }
567                         RemotingProxy proxy = new RemotingProxy (type, ChannelServices.CrossContextUrl, activationAttributes);
568                         return proxy.GetTransparentProxy();
569                 }
570 #if !NET_2_1
571                 internal static object CreateClientProxyForComInterop (Type type)
572                 {
573                         Mono.Interop.ComInteropProxy proxy = Mono.Interop.ComInteropProxy.CreateProxy (type);
574                         return proxy.GetTransparentProxy ();
575                 }
576 #endif
577                 internal static Identity GetIdentityForUri (string uri)
578                 {
579                         string normUri = GetNormalizedUri (uri);
580                         lock (uri_hash)
581                         {
582                                 Identity i = (Identity) uri_hash [normUri];
583
584                                 if (i == null) {
585                                         normUri = RemoveAppNameFromUri (uri);
586                                         if (normUri != null)
587                                                 i = (Identity) uri_hash [normUri];
588                                 }
589
590                                 return i;
591                         }
592                 }
593
594                 //
595                 // If the specified uri starts with the application name,
596                 // RemoveAppNameFromUri returns the uri w/out the leading
597                 // application name, otherwise it returns null.
598                 //
599                 // Assumes that the uri is not normalized.
600                 //
601                 static string RemoveAppNameFromUri (string uri)
602                 {
603                         string name = RemotingConfiguration.ApplicationName;
604                         if (name == null) return null;
605                         name = "/" + name + "/";
606                         if (uri.StartsWith (name))
607                                 return uri.Substring (name.Length);
608                         else
609                                 return null;
610                 }
611
612                 internal static Identity GetObjectIdentity (MarshalByRefObject obj)
613                 {
614                         if (IsTransparentProxy(obj))
615                                 return GetRealProxy (obj).ObjectIdentity;
616                         else
617                                 return obj.ObjectIdentity;
618                 }
619
620                 internal static ClientIdentity GetOrCreateClientIdentity(ObjRef objRef, Type proxyType, out object clientProxy)
621                 {
622                         // This method looks for an identity for the given url. 
623                         // If an identity is not found, it creates the identity and 
624                         // assigns it a proxy to the remote object.
625
626                         // Creates the client sink chain for the given url or channelData.
627                         // It will also get the object uri from the url.
628
629                         object channelData = objRef.ChannelInfo != null ? objRef.ChannelInfo.ChannelData : null;
630
631                         string objectUri;
632                         IMessageSink sink = GetClientChannelSinkChain (objRef.URI, channelData, out objectUri);
633
634                         if (objectUri == null) objectUri = objRef.URI;
635
636                         lock (uri_hash)
637                         {
638                                 clientProxy = null;
639                                 string uri = GetNormalizedUri (objRef.URI);
640                                 
641                                 ClientIdentity identity = uri_hash [uri] as ClientIdentity;
642                                 if (identity != null)
643                                 {
644                                         // Object already registered
645                                         clientProxy = identity.ClientProxy;
646                                         if (clientProxy != null) return identity;
647                                         
648                                         // The proxy has just been GCed, so its identity cannot
649                                         // be reused. Just dispose it.
650                                         DisposeIdentity (identity);
651                                 }
652
653                                 // Creates an identity and a proxy for the remote object
654
655                                 identity = new ClientIdentity (objectUri, objRef);
656                                 identity.ChannelSink = sink;
657
658                                 // Registers the identity
659                                 uri_hash [uri] = identity;
660                                 
661                                 if (proxyType != null)
662                                 {
663                                         RemotingProxy proxy = new RemotingProxy (proxyType, identity);
664                                         CrossAppDomainSink cds = sink as CrossAppDomainSink;
665                                         if (cds != null)
666                                                 proxy.SetTargetDomain (cds.TargetDomainId);
667
668                                         clientProxy = proxy.GetTransparentProxy();
669                                         identity.ClientProxy = (MarshalByRefObject) clientProxy;
670                                 }
671
672                                 return identity;
673                         }
674                 }
675
676                 static IMessageSink GetClientChannelSinkChain(string url, object channelData, out string objectUri)
677                 {
678                         IMessageSink sink = ChannelServices.CreateClientChannelSinkChain (url, channelData, out objectUri);
679                         if (sink == null) 
680                         {
681                                 if (url != null) 
682                                 {
683                                         string msg = String.Format ("Cannot create channel sink to connect to URL {0}. An appropriate channel has probably not been registered.", url); 
684                                         throw new RemotingException (msg);
685                                 }
686                                 else 
687                                 {
688                                         string msg = String.Format ("Cannot create channel sink to connect to the remote object. An appropriate channel has probably not been registered.", url); 
689                                         throw new RemotingException (msg);
690                                 }
691                         }
692                         return sink;
693                 }
694
695                 internal static ClientActivatedIdentity CreateContextBoundObjectIdentity(Type objectType)
696                 {
697                         ClientActivatedIdentity identity = new ClientActivatedIdentity (null, objectType);
698                         identity.ChannelSink = ChannelServices.CrossContextChannel;
699                         return identity;
700                 }
701
702                 internal static ClientActivatedIdentity CreateClientActivatedServerIdentity(MarshalByRefObject realObject, Type objectType, string objectUri)
703                 {
704                         ClientActivatedIdentity identity = new ClientActivatedIdentity (objectUri, objectType);
705                         identity.AttachServerObject (realObject, Context.DefaultContext);
706                         RegisterServerIdentity (identity);
707                         identity.StartTrackingLifetime ((ILease)realObject.InitializeLifetimeService ());
708                         return identity;
709                 }
710
711                 internal static ServerIdentity CreateWellKnownServerIdentity(Type objectType, string objectUri, WellKnownObjectMode mode)
712                 {
713                         ServerIdentity identity;
714
715                         if (mode == WellKnownObjectMode.SingleCall)
716                                 identity = new  SingleCallIdentity(objectUri, Context.DefaultContext, objectType);
717                         else
718                                 identity = new  SingletonIdentity(objectUri, Context.DefaultContext, objectType);
719
720                         RegisterServerIdentity (identity);
721                         return identity;
722                 }
723
724                 private static void RegisterServerIdentity(ServerIdentity identity)
725                 {
726                         lock (uri_hash)
727                         {
728                                 if (uri_hash.ContainsKey (identity.ObjectUri)) 
729                                         throw new RemotingException ("Uri already in use: " + identity.ObjectUri + ".");
730
731                                 uri_hash[identity.ObjectUri] = identity;
732                         }
733                 }
734
735                 internal static object GetProxyForRemoteObject (ObjRef objref, Type classToProxy)
736                 {
737                         ClientActivatedIdentity identity = GetIdentityForUri (objref.URI) as ClientActivatedIdentity;
738                         if (identity != null) return identity.GetServerObject ();
739                         else return GetRemoteObject (objref, classToProxy);
740                 }
741
742                 internal static object GetRemoteObject(ObjRef objRef, Type proxyType)
743                 {
744                         object proxy;
745                         GetOrCreateClientIdentity (objRef, proxyType, out proxy);
746                         return proxy;
747                 }
748                 
749                 // This method is called by the runtime
750                 internal static object GetServerObject (string uri)
751                 {
752                         ClientActivatedIdentity identity = GetIdentityForUri (uri) as ClientActivatedIdentity;
753                         if (identity == null) throw new RemotingException ("Server for uri '" + uri + "' not found");
754                         return identity.GetServerObject ();
755                 }
756
757                 // This method is called by the runtime
758                 [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
759                 internal static byte[] SerializeCallData (object obj)
760                 {
761                         LogicalCallContext ctx = CallContext.CreateLogicalCallContext (false);
762                         if (ctx != null) {
763                                 CACD cad = new CACD ();
764                                 cad.d = obj;
765                                 cad.c = ctx;
766                                 obj = cad;
767                         }
768                         
769                         if (obj == null) return null;
770                         MemoryStream ms = new MemoryStream ();
771                         _serializationFormatter.Serialize (ms, obj);
772                         return ms.ToArray ();
773                 }
774
775                 // This method is called by the runtime
776                 [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
777                 internal static object DeserializeCallData (byte[] array)
778                 {
779                         if (array == null) return null;
780                         
781                         MemoryStream ms = new MemoryStream (array);
782                         object obj = _deserializationFormatter.Deserialize (ms);
783                         
784                         if (obj is CACD) {
785                                 CACD cad = (CACD) obj;
786                                 obj = cad.d;
787                                 CallContext.UpdateCurrentCallContext ((LogicalCallContext) cad.c);
788                         }
789                         return obj;
790                 }
791                 
792                 // This method is called by the runtime
793                 [SecurityPermission (SecurityAction.Assert, SerializationFormatter = true)] // FIXME: to be reviewed
794                 internal static byte[] SerializeExceptionData (Exception ex)
795                 {
796                         try {
797                                 int retry = 4;
798                                 
799                                 do {
800                                         try {
801                                                 MemoryStream ms = new MemoryStream ();
802                                                 _serializationFormatter.Serialize (ms, ex);
803                                                 return ms.ToArray ();
804                                         }
805                                         catch (Exception e) {
806                                                 if (e is ThreadAbortException) {
807                                                         Thread.ResetAbort ();
808                                                         retry = 5;
809                                                         ex = e;
810                                                 }
811                                                 else if (retry == 2) {
812                                                         ex = new Exception ();
813                                                         ex.SetMessage (e.Message);
814                                                         ex.SetStackTrace (e.StackTrace);
815                                                 }
816                                                 else
817                                                         ex = e;
818                                         }
819                                         retry--;
820                                 }
821                                 while (retry > 0);
822                                 
823                                 return null;
824                         }
825                         catch (Exception tex)
826                         {
827                                 byte[] data = SerializeExceptionData (tex);
828                                 Thread.ResetAbort ();
829                                 return data;
830                         }
831                 }
832                 
833                 internal static object GetDomainProxy(AppDomain domain) 
834                 {
835                         byte[] data = null;
836
837                         Context currentContext = Thread.CurrentContext;
838
839                         try
840                         {
841                                 data = (byte[])AppDomain.InvokeInDomain (domain, typeof (AppDomain).GetMethod ("GetMarshalledDomainObjRef", BindingFlags.Instance|BindingFlags.NonPublic), domain, null);
842                         }
843                         finally
844                         {
845                                 AppDomain.InternalSetContext (currentContext);
846                         }                               
847
848                         byte[] data_copy = new byte [data.Length];
849                         data.CopyTo (data_copy, 0);
850                         MemoryStream stream = new MemoryStream (data_copy);
851                         ObjRef appref = (ObjRef) CADSerializer.DeserializeObject (stream);
852                         return (AppDomain) RemotingServices.Unmarshal(appref);
853                 }
854
855                 private static void RegisterInternalChannels() 
856                 {
857                         CrossAppDomainChannel.RegisterCrossAppDomainChannel();
858                 }
859                 
860                 internal static void DisposeIdentity (Identity ident)
861                 {
862                         lock (uri_hash)
863                         {
864                                 if (!ident.Disposed) {
865                                         ClientIdentity clientId = ident as ClientIdentity;
866                                         if (clientId != null)
867                                                 uri_hash.Remove (GetNormalizedUri (clientId.TargetUri));
868                                         else
869                                                 uri_hash.Remove (ident.ObjectUri);
870                                                 
871                                         ident.Disposed = true;
872                                 }
873                         }
874                 }
875
876                 internal static Identity GetMessageTargetIdentity (IMessage msg)
877                 {
878                         // Returns the identity where the message is sent
879
880                         if (msg is IInternalMessage) 
881                                 return ((IInternalMessage)msg).TargetIdentity;
882
883                         lock (uri_hash)
884                         {
885                                 string uri = GetNormalizedUri (((IMethodMessage)msg).Uri);
886                                 return uri_hash [uri] as ServerIdentity;
887                         }
888                 }
889
890                 internal static void SetMessageTargetIdentity (IMessage msg, Identity ident)
891                 {
892                         if (msg is IInternalMessage) 
893                                 ((IInternalMessage)msg).TargetIdentity = ident;
894                 }
895                 
896                 internal static bool UpdateOutArgObject (ParameterInfo pi, object local, object remote)
897                 {
898                         if (pi.ParameterType.IsArray && ((Array)local).Rank == 1)
899                         {
900                                 Array alocal = (Array) local;
901                                 if (alocal.Rank == 1)
902                                 {
903                                         Array.Copy ((Array) remote, alocal, alocal.Length);
904                                         return true;
905                                 }
906                                 else
907                                 {
908                                         // TODO
909                                 }
910                         }
911                         return false;
912                 }
913                 
914                 static string GetNormalizedUri (string uri)
915                 {
916                         if (uri.StartsWith ("/")) return uri.Substring (1);
917                         else return uri;
918                 }
919
920                 #endregion
921         }
922 }