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