This commit was manufactured by cvs2svn to create branch 'mono-1-0'.
[mono.git] / mcs / class / corlib / System.Runtime.Remoting.Channels / ChannelServices.cs
1 //
2 // System.Runtime.Remoting.Channels.ChannelServices.cs
3 //
4 // Author: Rodrigo Moya (rodrigo@ximian.com)
5 //         Dietmar Maurer (dietmar@ximian.com)
6 //         Lluis Sanchez Gual (lluis@ideary.com)
7 //
8 // 2002 (C) Copyright, Ximian, Inc.
9 //
10
11 //
12 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
13 //
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
21 // 
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
24 // 
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 //
33
34 using System.Collections;
35 using System.Reflection;
36 using System.Runtime.Remoting;
37 using System.Runtime.Remoting.Channels;
38 using System.Runtime.Remoting.Messaging;
39 using System.Runtime.Remoting.Contexts;
40
41 namespace System.Runtime.Remoting
42 {
43         [Serializable]
44         internal class ChannelInfo : IChannelInfo
45         {
46                 object [] channelData = null;
47
48                 public ChannelInfo ()
49                 {
50                         channelData = ChannelServices.GetCurrentChannelInfo ();
51                 }
52
53                 public ChannelInfo (object remoteChannelData)
54                 {
55                         channelData = new object[] { remoteChannelData };
56                 }
57                 
58                 public object[] ChannelData 
59                 {
60                         get {
61                                 return channelData;
62                         }
63                         
64                         set {
65                                 channelData = value;
66                         }
67                 }
68         }
69 }
70
71 namespace System.Runtime.Remoting.Channels
72 {
73         public sealed class ChannelServices
74         {
75                 private static ArrayList registeredChannels = new ArrayList ();
76                 private static ArrayList delayedClientChannels = new ArrayList ();
77                 
78                 private static CrossContextChannel _crossContextSink = new CrossContextChannel();
79                 
80                 internal static string CrossContextUrl = "__CrossContext";
81
82                 private ChannelServices ()
83                 {
84                 }
85
86                 internal static CrossContextChannel CrossContextChannel
87                 {
88                         get { return _crossContextSink; }
89                 }
90
91                 internal static IMessageSink CreateClientChannelSinkChain(string url, object remoteChannelData, out string objectUri)
92                 {
93                         // Locate a channel that can parse the url. This channel will be used to
94                         // create the sink chain.
95
96                         object[] channelDataArray = (object[])remoteChannelData;
97
98                         lock (registeredChannels.SyncRoot)
99                         {
100                                 // First of all, try registered channels
101                                 foreach (IChannel c in registeredChannels) 
102                                 {
103                                         IChannelSender sender = c as IChannelSender;
104                                         if (sender == null) continue;
105         
106                                         IMessageSink sink = CreateClientChannelSinkChain (sender, url, channelDataArray, out objectUri);
107                                         if (sink != null) return sink;
108                                 }
109                                 
110                                 // Not found. Try now creation delayed channels
111                                 RemotingConfiguration.LoadDefaultDelayedChannels ();
112                                 foreach (IChannelSender sender in delayedClientChannels) 
113                                 {
114                                         IMessageSink sink = CreateClientChannelSinkChain (sender, url, channelDataArray, out objectUri);
115                                         if (sink != null) {
116                                                 delayedClientChannels.Remove (sender);
117                                                 RegisterChannel (sender);
118                                                 return sink;
119                                         }
120                                 }
121                         }
122                         
123                         objectUri = null;
124                         return null;
125                 }
126                 
127                 internal static IMessageSink CreateClientChannelSinkChain (IChannelSender sender, string url, object[] channelDataArray, out string objectUri)
128                 {
129                         objectUri = null;
130                         if (channelDataArray == null) {
131                                 return sender.CreateMessageSink (url, null, out objectUri);
132                         }
133                         else {
134                                 foreach (object data in channelDataArray) {
135                                         IMessageSink sink = sender.CreateMessageSink (url, data, out objectUri);
136                                         if (sink != null) return sink;          
137                                 }
138                         }
139                         return null;
140                 }
141                 
142                 public static IChannel[] RegisteredChannels
143                 {
144                         get {
145                                 lock (registeredChannels.SyncRoot)
146                                 {
147                                         IChannel[] channels = new IChannel[registeredChannels.Count];
148         
149                                         for (int i = 0; i < registeredChannels.Count; i++)
150                                                 channels[i] = (IChannel) registeredChannels[i];
151         
152                                         return channels;
153                                 }
154                         }
155                 }
156
157                 public static IServerChannelSink CreateServerChannelSinkChain (
158                         IServerChannelSinkProvider provider, IChannelReceiver channel)
159             {
160                         IServerChannelSinkProvider tmp = provider;
161                         while (tmp.Next != null) tmp = tmp.Next;
162                         tmp.Next = new ServerDispatchSinkProvider ();
163
164                         // Every provider has to call CreateSink() of its next provider
165                         return  provider.CreateSink (channel);
166                 }
167
168                 public static ServerProcessing DispatchMessage (
169                         IServerChannelSinkStack sinkStack,
170                         IMessage msg,
171                         out IMessage replyMsg)
172                 {
173                         if (msg == null) throw new ArgumentNullException ("msg");
174                         
175                         // Async processing is not done here because there isn't any way
176                         // to know if a message is to be dispatched sync or asynchronously.
177
178                         replyMsg = SyncDispatchMessage (msg);
179
180                         if (RemotingServices.IsOneWay (((IMethodMessage) msg).MethodBase))
181                                 return ServerProcessing.OneWay;
182                         else
183                                 return ServerProcessing.Complete;
184                 }
185
186                 public static IChannel GetChannel (string name)
187                 {
188                         lock (registeredChannels.SyncRoot)
189                         {
190                                 foreach (IChannel chnl in registeredChannels) {
191                                         if (chnl.ChannelName == name && !(chnl is CrossAppDomainChannel)) return chnl;
192                                 }
193                                 return null;
194                         }
195                 }
196
197                 public static IDictionary GetChannelSinkProperties (object obj)
198                 {
199                         if (!RemotingServices.IsTransparentProxy (obj))
200                                 throw new ArgumentException ("obj must be a proxy","obj");
201                                 
202                         ClientIdentity ident = (ClientIdentity) RemotingServices.GetRealProxy (obj).ObjectIdentity;
203                         IMessageSink sink = ident.ChannelSink;
204                         ArrayList dics = new ArrayList ();
205                         
206                         while (sink != null && !(sink is IClientChannelSink))
207                                 sink = sink.NextSink;
208
209                         if (sink == null)
210                                 return new Hashtable ();
211
212                         IClientChannelSink csink = sink as IClientChannelSink;
213                         while (csink != null)
214                         {
215                                 dics.Add (csink.Properties);
216                                 csink = csink.NextChannelSink;
217                         }
218
219                         IDictionary[] adics = (IDictionary[]) dics.ToArray (typeof(IDictionary[]));
220                         return new AggregateDictionary (adics);
221                 }
222
223                 public static string[] GetUrlsForObject (MarshalByRefObject obj)
224                 {
225                         string uri = RemotingServices.GetObjectUri (obj);
226                         if (uri == null) return new string [0];
227
228                         ArrayList list = new ArrayList ();
229
230                         lock (registeredChannels.SyncRoot)
231                         {
232                                 foreach (object chnl_obj in registeredChannels) {
233                                         if (chnl_obj is CrossAppDomainChannel) continue;
234                                         
235                                         IChannelReceiver chnl = chnl_obj as IChannelReceiver;
236         
237                                         if (chnl != null)
238                                                 list.AddRange (chnl.GetUrlsForUri (uri));
239                                 }
240                         }
241                         
242                         return  (string[]) list.ToArray (typeof(string));
243                 }
244
245                 public static void RegisterChannel (IChannel chnl)
246                 {
247                         // Put the channel in the correct place according to its priority.
248                         // Since there are not many channels, a linear search is ok.
249
250                         lock (registeredChannels.SyncRoot)
251                         {
252                                 int pos = -1;
253                                 for (int n = 0; n < registeredChannels.Count; n++) 
254                                 {
255                                         IChannel regc = (IChannel) registeredChannels[n];
256                                         
257                                         if (regc.ChannelName == chnl.ChannelName && chnl.ChannelName != "")
258                                                 throw new RemotingException ("Channel " + regc.ChannelName + " already registered");
259                                                 
260                                         if (regc.ChannelPriority < chnl.ChannelPriority && pos==-1)
261                                                 pos = n;
262                                 }
263                                 
264                                 if (pos != -1) registeredChannels.Insert (pos, chnl);
265                                 else registeredChannels.Add (chnl);
266                                 
267                                 IChannelReceiver receiver = chnl as IChannelReceiver;
268                                 if (receiver != null) receiver.StartListening (null);
269                         }
270                 }
271
272                 internal static void RegisterChannelConfig (ChannelData channel)
273                 {
274                         IServerChannelSinkProvider serverSinks = null;
275                         IClientChannelSinkProvider clientSinks = null;
276                         
277                         // Create server providers
278                         for (int n=channel.ServerProviders.Count-1; n>=0; n--)
279                         {
280                                 ProviderData prov = channel.ServerProviders[n] as ProviderData;
281                                 IServerChannelSinkProvider sinkp = (IServerChannelSinkProvider) CreateProvider (prov);
282                                 sinkp.Next = serverSinks;
283                                 serverSinks = sinkp;
284                         }
285                         
286                         // Create client providers
287                         for (int n=channel.ClientProviders.Count-1; n>=0; n--)
288                         {
289                                 ProviderData prov = channel.ClientProviders[n] as ProviderData;
290                                 IClientChannelSinkProvider sinkp = (IClientChannelSinkProvider) CreateProvider (prov);
291                                 sinkp.Next = clientSinks;
292                                 clientSinks = sinkp;
293                         }
294
295                         // Create the channel
296                         
297                         Type type = Type.GetType (channel.Type);
298                         if (type == null) throw new RemotingException ("Type '" + channel.Type + "' not found");
299                         
300                         Object[] parms;                 
301                         Type[] signature;                       
302                         bool clienc = typeof (IChannelSender).IsAssignableFrom (type);
303                         bool serverc = typeof (IChannelReceiver).IsAssignableFrom (type);
304                         
305                         if (clienc && serverc) {
306                                 signature = new Type [] {typeof(IDictionary), typeof(IClientChannelSinkProvider), typeof(IServerChannelSinkProvider)};
307                                 parms = new Object[] {channel.CustomProperties, clientSinks, serverSinks};
308                         }
309                         else if (clienc) {
310                                 signature = new Type [] {typeof(IDictionary), typeof(IClientChannelSinkProvider)};
311                                 parms = new Object[] {channel.CustomProperties, clientSinks};
312                         }
313                         else if (serverc) {
314                                 signature = new Type [] {typeof(IDictionary), typeof(IServerChannelSinkProvider)};
315                                 parms = new Object[] {channel.CustomProperties, serverSinks};
316                         }
317                         else
318                                 throw new RemotingException (type + " is not a valid channel type");
319                                 
320                         ConstructorInfo ctor = type.GetConstructor (signature);
321                         if (ctor == null)
322                                 throw new RemotingException (type + " does not have a valid constructor");
323
324                         IChannel ch;
325                         try
326                         {
327                                 ch = (IChannel) ctor.Invoke (parms);
328                         }
329                         catch (TargetInvocationException ex)
330                         {
331                                 throw ex.InnerException;
332                         }
333                         
334                         lock (registeredChannels.SyncRoot)
335                         {
336                                 if (channel.DelayLoadAsClientChannel == "true" && !(ch is IChannelReceiver))
337                                         delayedClientChannels.Add (ch);
338                                 else
339                                         RegisterChannel (ch);
340                         }
341                 }
342                 
343                 static object CreateProvider (ProviderData prov)
344                 {
345                         Type pvtype = Type.GetType (prov.Type);
346                         if (pvtype == null) throw new RemotingException ("Type '" + prov.Type + "' not found");
347                         Object[] pvparms = new Object[] {prov.CustomProperties, prov.CustomData};
348                         
349                         try
350                         {
351                                 return Activator.CreateInstance (pvtype, pvparms);
352                         }
353                         catch (Exception ex)
354                         {
355                                 if (ex is TargetInvocationException) ex = ((TargetInvocationException)ex).InnerException;
356                                 throw new RemotingException ("An instance of provider '" + pvtype + "' could not be created: " + ex.Message);
357                         }
358                 }
359
360                 public static IMessage SyncDispatchMessage (IMessage msg)
361                 {
362                         IMessage ret = CheckIncomingMessage (msg);
363                         if (ret != null) return CheckReturnMessage (msg, ret);
364                         ret = _crossContextSink.SyncProcessMessage (msg);
365                         return CheckReturnMessage (msg, ret);
366                 }
367
368                 public static IMessageCtrl AsyncDispatchMessage (IMessage msg, IMessageSink replySink)
369                 {
370                         IMessage ret = CheckIncomingMessage (msg);
371                         if (ret != null) {
372                                 replySink.SyncProcessMessage (CheckReturnMessage (msg, ret));
373                                 return null;
374                         }
375                         
376 #if NET_1_1
377                         if (RemotingConfiguration.CustomErrorsEnabled (IsLocalCall (msg)))
378                                 replySink = new ExceptionFilterSink (msg, replySink);
379 #endif
380                         
381                         return _crossContextSink.AsyncProcessMessage (msg, replySink);          
382                 }
383                 
384                 static ReturnMessage CheckIncomingMessage (IMessage msg)
385                 {
386                         IMethodMessage call = (IMethodMessage)msg;
387                         ServerIdentity identity = RemotingServices.GetIdentityForUri (call.Uri) as ServerIdentity;
388
389                         if (identity == null) 
390                                 return new ReturnMessage (new RemotingException ("No receiver for uri " + call.Uri), (IMethodCallMessage) msg);
391
392                         RemotingServices.SetMessageTargetIdentity (msg, identity);
393                         return null;
394                 }
395
396                 internal static IMessage CheckReturnMessage (IMessage callMsg, IMessage retMsg)
397                 {
398 #if NET_1_1
399                         IMethodReturnMessage ret = retMsg as IMethodReturnMessage;
400                         if (ret != null && ret.Exception != null)
401                         {
402                                 if (RemotingConfiguration.CustomErrorsEnabled (IsLocalCall (callMsg)))
403                                 {
404                                         Exception ex = new Exception ("Server encountered an internal error. For more information, turn off customErrors in the server's .config file.");
405                                         retMsg = new MethodResponse (ex, (IMethodCallMessage)callMsg);
406                                 }
407                         }
408 #endif
409                         return retMsg;
410                 }
411                 
412                 static bool IsLocalCall (IMessage callMsg)
413                 {
414                         return true;
415                         
416 /*                      How can I know if a call is local?!?
417                         
418                         object isLocal = callMsg.Properties ["__isLocalCall"];
419                         if (isLocal == null) return false;
420                         return (bool)isLocal;
421 */
422                 }
423
424                 public static void UnregisterChannel (IChannel chnl)
425                 {
426                         if (chnl == null)
427                                 throw new ArgumentNullException ();
428                                 
429                         lock (registeredChannels.SyncRoot)
430                         {
431                                 if (!registeredChannels.Contains ((object) chnl))
432                                         throw new RemotingException ();
433         
434                                 registeredChannels.Remove ((object) chnl);
435         
436                                 IChannelReceiver chnlReceiver = chnl as IChannelReceiver;
437                                 if(chnlReceiver != null)
438                                         chnlReceiver.StopListening(null);
439                         }
440                 }
441
442                 internal static object [] GetCurrentChannelInfo ()
443                 {
444                         ArrayList list = new ArrayList ();
445                         
446                         lock (registeredChannels.SyncRoot)
447                         {
448                                 foreach (object chnl_obj in registeredChannels) {
449                                         IChannelReceiver chnl = chnl_obj as IChannelReceiver;
450                                 
451                                         if (chnl != null) {
452                                                 object chnl_data = chnl.ChannelData;
453                                                 if (chnl_data != null)
454                                                         list.Add (chnl_data);
455                                         }
456                                 }
457                         }
458                         
459                         return  list.ToArray ();
460                 }
461         }
462         
463         internal class ExceptionFilterSink: IMessageSink
464         {
465                 IMessageSink _next;
466                 IMessage _call;
467                 
468                 public ExceptionFilterSink (IMessage call, IMessageSink next)
469                 {
470                         _call = call;
471                         _next = next;
472                 }
473                 
474                 public IMessage SyncProcessMessage (IMessage msg)
475                 {
476                         return _next.SyncProcessMessage (ChannelServices.CheckReturnMessage (_call, msg));
477                 }
478
479                 public IMessageCtrl AsyncProcessMessage (IMessage msg, IMessageSink replySink)
480                 {
481                         throw new InvalidOperationException();
482                 }
483
484                 public IMessageSink NextSink 
485                 { 
486                         get { return _next; }
487                 }
488         }
489 }