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