Make a copy of the old ZipLib
[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                                         ArrayList list = new ArrayList ();
148                                         
149                                         for (int i = 0; i < registeredChannels.Count; i++) {
150                                                 IChannel ch = (IChannel) registeredChannels[i];
151                                                 if (ch is CrossAppDomainChannel) continue;
152                                                 list.Add (ch);
153                                         }
154
155                                         return (IChannel[]) list.ToArray (typeof(IChannel));
156                                 }
157                         }
158                 }
159
160                 public static IServerChannelSink CreateServerChannelSinkChain (
161                         IServerChannelSinkProvider provider, IChannelReceiver channel)
162             {
163                         IServerChannelSinkProvider tmp = provider;
164                         while (tmp.Next != null) tmp = tmp.Next;
165                         tmp.Next = new ServerDispatchSinkProvider ();
166
167                         // Every provider has to call CreateSink() of its next provider
168                         return  provider.CreateSink (channel);
169                 }
170
171                 public static ServerProcessing DispatchMessage (
172                         IServerChannelSinkStack sinkStack,
173                         IMessage msg,
174                         out IMessage replyMsg)
175                 {
176                         if (msg == null) throw new ArgumentNullException ("msg");
177                         
178                         // Async processing is not done here because there isn't any way
179                         // to know if a message is to be dispatched sync or asynchronously.
180
181                         replyMsg = SyncDispatchMessage (msg);
182
183                         if (RemotingServices.IsOneWay (((IMethodMessage) msg).MethodBase))
184                                 return ServerProcessing.OneWay;
185                         else
186                                 return ServerProcessing.Complete;
187                 }
188
189                 public static IChannel GetChannel (string name)
190                 {
191                         lock (registeredChannels.SyncRoot)
192                         {
193                                 foreach (IChannel chnl in registeredChannels) {
194                                         if (chnl.ChannelName == name && !(chnl is CrossAppDomainChannel)) return chnl;
195                                 }
196                                 return null;
197                         }
198                 }
199
200                 public static IDictionary GetChannelSinkProperties (object obj)
201                 {
202                         if (!RemotingServices.IsTransparentProxy (obj))
203                                 throw new ArgumentException ("obj must be a proxy","obj");
204                                 
205                         ClientIdentity ident = (ClientIdentity) RemotingServices.GetRealProxy (obj).ObjectIdentity;
206                         IMessageSink sink = ident.ChannelSink;
207                         ArrayList dics = new ArrayList ();
208                         
209                         while (sink != null && !(sink is IClientChannelSink))
210                                 sink = sink.NextSink;
211
212                         if (sink == null)
213                                 return new Hashtable ();
214
215                         IClientChannelSink csink = sink as IClientChannelSink;
216                         while (csink != null)
217                         {
218                                 dics.Add (csink.Properties);
219                                 csink = csink.NextChannelSink;
220                         }
221
222                         IDictionary[] adics = (IDictionary[]) dics.ToArray (typeof(IDictionary[]));
223                         return new AggregateDictionary (adics);
224                 }
225
226                 public static string[] GetUrlsForObject (MarshalByRefObject obj)
227                 {
228                         string uri = RemotingServices.GetObjectUri (obj);
229                         if (uri == null) return new string [0];
230
231                         ArrayList list = new ArrayList ();
232
233                         lock (registeredChannels.SyncRoot)
234                         {
235                                 foreach (object chnl_obj in registeredChannels) {
236                                         if (chnl_obj is CrossAppDomainChannel) continue;
237                                         
238                                         IChannelReceiver chnl = chnl_obj as IChannelReceiver;
239         
240                                         if (chnl != null)
241                                                 list.AddRange (chnl.GetUrlsForUri (uri));
242                                 }
243                         }
244                         
245                         return  (string[]) list.ToArray (typeof(string));
246                 }
247
248                 public static void RegisterChannel (IChannel chnl)
249                 {
250                         // Put the channel in the correct place according to its priority.
251                         // Since there are not many channels, a linear search is ok.
252
253                         lock (registeredChannels.SyncRoot)
254                         {
255                                 int pos = -1;
256                                 for (int n = 0; n < registeredChannels.Count; n++) 
257                                 {
258                                         IChannel regc = (IChannel) registeredChannels[n];
259                                         
260                                         if (regc.ChannelName == chnl.ChannelName && chnl.ChannelName != "")
261                                                 throw new RemotingException ("Channel " + regc.ChannelName + " already registered");
262                                                 
263                                         if (regc.ChannelPriority < chnl.ChannelPriority && pos==-1)
264                                                 pos = n;
265                                 }
266                                 
267                                 if (pos != -1) registeredChannels.Insert (pos, chnl);
268                                 else registeredChannels.Add (chnl);
269                                 
270                                 IChannelReceiver receiver = chnl as IChannelReceiver;
271                                 if (receiver != null) receiver.StartListening (null);
272                         }
273                 }
274
275                 internal static void RegisterChannelConfig (ChannelData channel)
276                 {
277                         IServerChannelSinkProvider serverSinks = null;
278                         IClientChannelSinkProvider clientSinks = null;
279                         
280                         // Create server providers
281                         for (int n=channel.ServerProviders.Count-1; n>=0; n--)
282                         {
283                                 ProviderData prov = channel.ServerProviders[n] as ProviderData;
284                                 IServerChannelSinkProvider sinkp = (IServerChannelSinkProvider) CreateProvider (prov);
285                                 sinkp.Next = serverSinks;
286                                 serverSinks = sinkp;
287                         }
288                         
289                         // Create client providers
290                         for (int n=channel.ClientProviders.Count-1; n>=0; n--)
291                         {
292                                 ProviderData prov = channel.ClientProviders[n] as ProviderData;
293                                 IClientChannelSinkProvider sinkp = (IClientChannelSinkProvider) CreateProvider (prov);
294                                 sinkp.Next = clientSinks;
295                                 clientSinks = sinkp;
296                         }
297
298                         // Create the channel
299                         
300                         Type type = Type.GetType (channel.Type);
301                         if (type == null) throw new RemotingException ("Type '" + channel.Type + "' not found");
302                         
303                         Object[] parms;                 
304                         Type[] signature;                       
305                         bool clienc = typeof (IChannelSender).IsAssignableFrom (type);
306                         bool serverc = typeof (IChannelReceiver).IsAssignableFrom (type);
307                         
308                         if (clienc && serverc) {
309                                 signature = new Type [] {typeof(IDictionary), typeof(IClientChannelSinkProvider), typeof(IServerChannelSinkProvider)};
310                                 parms = new Object[] {channel.CustomProperties, clientSinks, serverSinks};
311                         }
312                         else if (clienc) {
313                                 signature = new Type [] {typeof(IDictionary), typeof(IClientChannelSinkProvider)};
314                                 parms = new Object[] {channel.CustomProperties, clientSinks};
315                         }
316                         else if (serverc) {
317                                 signature = new Type [] {typeof(IDictionary), typeof(IServerChannelSinkProvider)};
318                                 parms = new Object[] {channel.CustomProperties, serverSinks};
319                         }
320                         else
321                                 throw new RemotingException (type + " is not a valid channel type");
322                                 
323                         ConstructorInfo ctor = type.GetConstructor (signature);
324                         if (ctor == null)
325                                 throw new RemotingException (type + " does not have a valid constructor");
326
327                         IChannel ch;
328                         try
329                         {
330                                 ch = (IChannel) ctor.Invoke (parms);
331                         }
332                         catch (TargetInvocationException ex)
333                         {
334                                 throw ex.InnerException;
335                         }
336                         
337                         lock (registeredChannels.SyncRoot)
338                         {
339                                 if (channel.DelayLoadAsClientChannel == "true" && !(ch is IChannelReceiver))
340                                         delayedClientChannels.Add (ch);
341                                 else
342                                         RegisterChannel (ch);
343                         }
344                 }
345                 
346                 static object CreateProvider (ProviderData prov)
347                 {
348                         Type pvtype = Type.GetType (prov.Type);
349                         if (pvtype == null) throw new RemotingException ("Type '" + prov.Type + "' not found");
350                         Object[] pvparms = new Object[] {prov.CustomProperties, prov.CustomData};
351                         
352                         try
353                         {
354                                 return Activator.CreateInstance (pvtype, pvparms);
355                         }
356                         catch (Exception ex)
357                         {
358                                 if (ex is TargetInvocationException) ex = ((TargetInvocationException)ex).InnerException;
359                                 throw new RemotingException ("An instance of provider '" + pvtype + "' could not be created: " + ex.Message);
360                         }
361                 }
362
363                 public static IMessage SyncDispatchMessage (IMessage msg)
364                 {
365                         IMessage ret = CheckIncomingMessage (msg);
366                         if (ret != null) return CheckReturnMessage (msg, ret);
367                         ret = _crossContextSink.SyncProcessMessage (msg);
368                         return CheckReturnMessage (msg, ret);
369                 }
370
371                 public static IMessageCtrl AsyncDispatchMessage (IMessage msg, IMessageSink replySink)
372                 {
373                         IMessage ret = CheckIncomingMessage (msg);
374                         if (ret != null) {
375                                 replySink.SyncProcessMessage (CheckReturnMessage (msg, ret));
376                                 return null;
377                         }
378                         
379 #if NET_1_1
380                         if (RemotingConfiguration.CustomErrorsEnabled (IsLocalCall (msg)))
381                                 replySink = new ExceptionFilterSink (msg, replySink);
382 #endif
383                         
384                         return _crossContextSink.AsyncProcessMessage (msg, replySink);          
385                 }
386                 
387                 static ReturnMessage CheckIncomingMessage (IMessage msg)
388                 {
389                         IMethodMessage call = (IMethodMessage)msg;
390                         ServerIdentity identity = RemotingServices.GetIdentityForUri (call.Uri) as ServerIdentity;
391
392                         if (identity == null) 
393                                 return new ReturnMessage (new RemotingException ("No receiver for uri " + call.Uri), (IMethodCallMessage) msg);
394
395                         RemotingServices.SetMessageTargetIdentity (msg, identity);
396                         return null;
397                 }
398
399                 internal static IMessage CheckReturnMessage (IMessage callMsg, IMessage retMsg)
400                 {
401 #if NET_1_1
402                         IMethodReturnMessage ret = retMsg as IMethodReturnMessage;
403                         if (ret != null && ret.Exception != null)
404                         {
405                                 if (RemotingConfiguration.CustomErrorsEnabled (IsLocalCall (callMsg)))
406                                 {
407                                         Exception ex = new Exception ("Server encountered an internal error. For more information, turn off customErrors in the server's .config file.");
408                                         retMsg = new MethodResponse (ex, (IMethodCallMessage)callMsg);
409                                 }
410                         }
411 #endif
412                         return retMsg;
413                 }
414                 
415                 static bool IsLocalCall (IMessage callMsg)
416                 {
417                         return true;
418                         
419 /*                      How can I know if a call is local?!?
420                         
421                         object isLocal = callMsg.Properties ["__isLocalCall"];
422                         if (isLocal == null) return false;
423                         return (bool)isLocal;
424 */
425                 }
426
427                 public static void UnregisterChannel (IChannel chnl)
428                 {
429                         if (chnl == null)
430                                 throw new ArgumentNullException ();
431                                 
432                         lock (registeredChannels.SyncRoot)
433                         {
434                                 for (int n=0; n<registeredChannels.Count; n++) 
435                                 {
436                                         if (registeredChannels [n] == (object)chnl) {
437                                                 registeredChannels.RemoveAt (n);
438                                                 IChannelReceiver chnlReceiver = chnl as IChannelReceiver;
439                                                 if(chnlReceiver != null)
440                                                         chnlReceiver.StopListening(null);
441                                                 return;
442                                         }
443                                 }
444                                 
445                                 throw new RemotingException ("Channel not registered");
446         
447                         }
448                 }
449
450                 internal static object [] GetCurrentChannelInfo ()
451                 {
452                         ArrayList list = new ArrayList ();
453                         
454                         lock (registeredChannels.SyncRoot)
455                         {
456                                 foreach (object chnl_obj in registeredChannels) {
457                                         IChannelReceiver chnl = chnl_obj as IChannelReceiver;
458                                 
459                                         if (chnl != null) {
460                                                 object chnl_data = chnl.ChannelData;
461                                                 if (chnl_data != null)
462                                                         list.Add (chnl_data);
463                                         }
464                                 }
465                         }
466                         
467                         return  list.ToArray ();
468                 }
469         }
470         
471         internal class ExceptionFilterSink: IMessageSink
472         {
473                 IMessageSink _next;
474                 IMessage _call;
475                 
476                 public ExceptionFilterSink (IMessage call, IMessageSink next)
477                 {
478                         _call = call;
479                         _next = next;
480                 }
481                 
482                 public IMessage SyncProcessMessage (IMessage msg)
483                 {
484                         return _next.SyncProcessMessage (ChannelServices.CheckReturnMessage (_call, msg));
485                 }
486
487                 public IMessageCtrl AsyncProcessMessage (IMessage msg, IMessageSink replySink)
488                 {
489                         throw new InvalidOperationException();
490                 }
491
492                 public IMessageSink NextSink 
493                 { 
494                         get { return _next; }
495                 }
496         }
497 }