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