2 // System.Runtime.Remoting.Channels.CrossAppDomainChannel.cs
4 // Author: Patrik Torstensson (totte_mono@yahoo.com)
5 // Lluis Sanchez Gual (lluis@ximian.com)
7 // 2003 (C) Copyright, Ximian, Inc.
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 using System.Collections;
35 using System.Threading;
36 using System.Runtime.Remoting;
37 using System.Runtime.Remoting.Messaging;
38 using System.Runtime.Remoting.Channels;
39 using System.Runtime.Remoting.Contexts;
40 using System.Runtime.Serialization;
41 using System.Runtime.Serialization.Formatters.Binary;
42 using System.Reflection;
44 namespace System.Runtime.Remoting.Channels
47 // Holds the cross appdomain channel data (used to get/create the correct sink)
49 internal class CrossAppDomainData
51 // TODO: Add context support
52 // Required for .NET compatibility
53 private object _ContextID;
54 private int _DomainID;
55 private string _processGuid;
57 internal CrossAppDomainData(int domainId)
61 _processGuid = RemotingConfiguration.ProcessId;
66 get { return _DomainID; }
69 internal string ProcessID
71 get { return _processGuid; }
75 // Responsible for marshalling objects between appdomains
77 internal class CrossAppDomainChannel : IChannel, IChannelSender, IChannelReceiver
79 private const String _strName = "MONOCAD";
80 private const String _strBaseURI = "MONOCADURI";
82 private static Object s_lock = new Object();
84 internal static void RegisterCrossAppDomainChannel()
88 // todo: make singleton
89 CrossAppDomainChannel monocad = new CrossAppDomainChannel();
90 ChannelServices.RegisterChannel ((IChannel) monocad);
94 // IChannel implementation
95 public virtual String ChannelName
97 get { return _strName; }
100 public virtual int ChannelPriority
105 public String Parse(String url, out String objectURI)
112 public virtual Object ChannelData
114 get { return new CrossAppDomainData(Thread.GetDomainID()); }
117 public virtual String[] GetUrlsForUri(String objectURI)
119 throw new NotSupportedException("CrossAppdomain channel dont support UrlsForUri");
123 public virtual void StartListening(Object data) {}
124 public virtual void StopListening(Object data) {}
127 public virtual IMessageSink CreateMessageSink(String url, Object data, out String uri)
133 // Get the data and then get the sink
134 CrossAppDomainData cadData = data as CrossAppDomainData;
135 if (cadData != null && cadData.ProcessID == RemotingConfiguration.ProcessId)
136 // GetSink creates a new sink if we don't have any (use contexts here later)
137 return CrossAppDomainSink.GetSink(cadData.DomainID);
139 if (url != null && url.StartsWith(_strName))
140 throw new NotSupportedException("Can't create a named channel via crossappdomain");
146 [MonoTODO("Handle domain unloading?")]
147 internal class CrossAppDomainSink : IMessageSink
149 private static Hashtable s_sinks = new Hashtable();
151 private static MethodInfo processMessageMethod =
152 typeof (CrossAppDomainSink).GetMethod ("ProcessMessageInDomain", BindingFlags.NonPublic|BindingFlags.Static);
155 private int _domainID;
157 internal CrossAppDomainSink(int domainID)
159 _domainID = domainID;
162 internal static CrossAppDomainSink GetSink(int domainID)
164 // Check if we have a sink for the current domainID
165 // note, locking is not to bad here, very few class to GetSink
166 lock (s_sinks.SyncRoot)
168 if (s_sinks.ContainsKey(domainID))
169 return (CrossAppDomainSink) s_sinks[domainID];
172 CrossAppDomainSink sink = new CrossAppDomainSink(domainID);
173 s_sinks[domainID] = sink;
180 internal int TargetDomainId {
181 get { return _domainID; }
184 private struct ProcessMessageRes {
185 public byte[] arrResponse;
186 public CADMethodReturnMessage cadMrm;
189 #pragma warning disable 169
190 private static ProcessMessageRes ProcessMessageInDomain (
192 CADMethodCallMessage cadMsg)
194 ProcessMessageRes res = new ProcessMessageRes ();
198 AppDomain.CurrentDomain.ProcessMessageInDomain (arrRequest, cadMsg, out res.arrResponse, out res.cadMrm);
202 IMessage errorMsg = new MethodResponse (e, new ErrorMessage());
203 res.arrResponse = CADSerializer.SerializeMessage (errorMsg).GetBuffer();
207 #pragma warning restore 169
209 public virtual IMessage SyncProcessMessage(IMessage msgRequest)
211 IMessage retMessage = null;
215 // Time to transit into the "our" domain
216 byte [] arrResponse = null;
217 byte [] arrRequest = null;
219 CADMethodReturnMessage cadMrm = null;
220 CADMethodCallMessage cadMsg;
222 cadMsg = CADMethodCallMessage.Create (msgRequest);
223 if (null == cadMsg) {
224 // Serialize the request message
225 MemoryStream reqMsgStream = CADSerializer.SerializeMessage(msgRequest);
226 arrRequest = reqMsgStream.GetBuffer();
229 Context currentContext = Thread.CurrentContext;
232 // InternalInvoke can't handle out arguments, this is why
233 // we return the results in a structure
234 ProcessMessageRes res = (ProcessMessageRes)AppDomain.InvokeInDomainByID (_domainID, processMessageMethod, null, new object [] { arrRequest, cadMsg });
235 arrResponse = res.arrResponse;
238 AppDomain.InternalSetContext (currentContext);
242 if (null != arrResponse) {
243 // Time to deserialize the message
244 MemoryStream respMsgStream = new MemoryStream(arrResponse);
246 // Deserialize the response message
247 retMessage = CADSerializer.DeserializeMessage(respMsgStream, msgRequest as IMethodCallMessage);
249 retMessage = new MethodResponse (msgRequest as IMethodCallMessage, cadMrm);
255 retMessage = new ReturnMessage (e, msgRequest as IMethodCallMessage);
259 // this is just to be sure
266 public virtual IMessageCtrl AsyncProcessMessage (IMessage reqMsg, IMessageSink replySink)
268 AsyncRequest req = new AsyncRequest (reqMsg, replySink);
269 ThreadPool.QueueUserWorkItem (new WaitCallback (SendAsyncMessage), req);
273 public void SendAsyncMessage (object data)
275 AsyncRequest req = (AsyncRequest)data;
276 IMessage response = SyncProcessMessage (req.MsgRequest);
277 req.ReplySink.SyncProcessMessage (response);
280 public IMessageSink NextSink { get { return null; } }
283 internal class CADSerializer
285 internal static IMessage DeserializeMessage(MemoryStream mem, IMethodCallMessage msg)
287 BinaryFormatter serializer = new BinaryFormatter();
289 serializer.SurrogateSelector = null;
293 return (IMessage) serializer.Deserialize(mem, null);
295 return (IMessage) serializer.DeserializeMethodResponse(mem, null, msg);
298 internal static MemoryStream SerializeMessage(IMessage msg)
300 MemoryStream mem = new MemoryStream ();
301 BinaryFormatter serializer = new BinaryFormatter ();
303 serializer.SurrogateSelector = new RemotingSurrogateSelector ();
304 serializer.Serialize (mem, msg);
311 internal static MemoryStream SerializeObject(object obj)
313 MemoryStream mem = new MemoryStream ();
314 BinaryFormatter serializer = new BinaryFormatter ();
316 serializer.SurrogateSelector = new RemotingSurrogateSelector ();
317 serializer.Serialize (mem, obj);
324 internal static object DeserializeObject(MemoryStream mem)
326 BinaryFormatter serializer = new BinaryFormatter();
328 serializer.SurrogateSelector = null;
331 return serializer.Deserialize (mem);
335 internal class AsyncRequest
337 internal IMessageSink ReplySink;
338 internal IMessage MsgRequest;
340 public AsyncRequest (IMessage msgRequest, IMessageSink replySink)
342 ReplySink = replySink;
343 MsgRequest = msgRequest;