2 // PeerDuplexChannel.cs
5 // Atsushi Enomoto <atsushi@ximian.com>
7 // Copyright (C) 2009 Novell, Inc. http://www.novell.com
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 using System.Collections.Generic;
30 using System.Collections.ObjectModel;
33 using System.Net.Security;
34 using System.Net.Sockets;
35 using System.ServiceModel;
36 using System.ServiceModel.Description;
37 using System.ServiceModel.PeerResolvers;
38 using System.ServiceModel.Security;
39 using System.Threading;
42 namespace System.ServiceModel.Channels
45 // PeerDuplexChannel can be created either from PeerChannelFactory
46 // (as IOutputChannel) or PeerChannelListener (as IInputChannel).
48 // PeerNode has to be created before Open() (at least at client side).
49 // On open, it tries to resolve the nodes in the mesh (and do something
50 // - but what?). Then registers itself to the mesh and refreshes it.
52 internal class PeerDuplexChannel : DuplexChannelBase
61 class RemotePeerConnection
63 public RemotePeerConnection (PeerNodeAddress address)
68 public PeerNodeAddress Address { get; private set; }
69 public RemotePeerStatus Status { get; set; }
70 public LocalPeerReceiver Instance { get; set; }
71 public IPeerConnectorClient Channel { get; set; }
74 class LocalPeerReceiver : IPeerConnectorContract
76 List<PeerNodeAddress> connections = new List<PeerNodeAddress> ();
77 AutoResetEvent connect_handle = new AutoResetEvent (false);
79 public LocalPeerReceiver (PeerDuplexChannel owner)
84 PeerDuplexChannel owner;
86 public void Connect (ConnectInfo connect)
89 throw new ArgumentNullException ("connect");
90 var ch = OperationContext.Current.GetCallbackChannel<IPeerConnectorContract> ();
92 connections.Add (connect.Address);
93 // FIXME: check and reject if inappropriate. For example, maximum connection exceeded.
94 using (var octx = new OperationContextScope ((IContextChannel) ch)) {
95 OperationContext.Current.OutgoingMessageHeaders.To = new Uri (Constants.WsaAnonymousUri);
96 ch.Welcome (new WelcomeInfo () { NodeId = connect.NodeId });
100 internal void WaitForConnectResponse (TimeSpan timeout)
102 Console.WriteLine ("##### Waiting for Welcome or Reject ...");
103 if (!connect_handle.WaitOne (timeout))
104 throw new TimeoutException ();
107 public void Disconnect (DisconnectInfo disconnect)
109 if (disconnect == null)
110 throw new ArgumentNullException ("disconnect");
111 // Console.WriteLine ("DisconnectInfo.Reason: " + disconnect.Reason);
112 // FIXME: handle disconnection in practice. So far I see nothing to do.
115 public void Welcome (WelcomeInfo welcome)
117 Console.WriteLine ("##### Welcome message received");
118 connect_handle.Set ();
121 public void Refuse (RefuseInfo refuse)
123 // FIXME: it should not probably actually throw an error.
124 connect_handle.Set ();
125 throw new InvalidOperationException ("Peer connection was refused");
128 public void LinkUtility (LinkUtilityInfo linkUtility)
130 throw new NotImplementedException ();
135 throw new NotImplementedException ();
138 public void SendMessage (Message msg)
140 Console.WriteLine ("##### non-connector message received: " + msg.Headers.Action);
141 owner.EnqueueMessage (msg);
145 interface IPeerConnectorClient : IClientChannel, IPeerConnectorContract
149 IChannelFactory<IDuplexSessionChannel> client_factory;
150 ChannelFactory<IPeerConnectorClient> channel_factory;
151 PeerTransportBindingElement binding;
152 PeerResolver resolver;
154 ServiceHost listener_host;
156 List<RemotePeerConnection> peers = new List<RemotePeerConnection> ();
157 PeerNodeAddress local_node_address;
159 public PeerDuplexChannel (IPeerChannelManager factory, EndpointAddress address, Uri via, PeerResolver resolver)
160 : base ((ChannelFactoryBase) factory, address, via)
162 binding = factory.Source;
163 this.resolver = factory.Resolver;
164 info = new TcpChannelInfo (binding, factory.MessageEncoder, null); // FIXME: fill properties correctly.
166 // It could be opened even with empty list of PeerNodeAddresses.
167 // So, do not create PeerNode per PeerNodeAddress, but do it with PeerNodeAddress[].
168 node = new PeerNodeImpl (RemoteAddress.Uri.Host, factory.Source.ListenIPAddress, factory.Source.Port);
171 public PeerDuplexChannel (IPeerChannelManager listener)
172 : base ((ChannelListenerBase) listener)
174 binding = listener.Source;
175 this.resolver = listener.Resolver;
176 info = new TcpChannelInfo (binding, listener.MessageEncoder, null); // FIXME: fill properties correctly.
178 node = new PeerNodeImpl (((ChannelListenerBase) listener).Uri.Host, listener.Source.ListenIPAddress, listener.Source.Port);
181 public override T GetProperty<T> ()
183 if (typeof (T).IsInstanceOfType (node))
184 return (T) (object) node;
185 return base.GetProperty<T> ();
190 IPeerConnectorClient CreateInnerClient (RemotePeerConnection conn)
192 conn.Instance = new LocalPeerReceiver (this);
194 // FIXME: pass more setup parameters
195 if (channel_factory == null) {
196 var binding = new NetTcpBinding ();
197 binding.Security.Mode = SecurityMode.None;
198 channel_factory = new DuplexChannelFactory<IPeerConnectorClient> (conn.Instance, binding);
201 return channel_factory.CreateChannel (new EndpointAddress ("net.p2p://" + node.MeshId + "/"), conn.Address.EndpointAddress.Uri);
204 public override void Send (Message message, TimeSpan timeout)
206 ThrowIfDisposedOrNotOpen ();
208 DateTime start = DateTime.Now;
210 // FIXME: give max buffer size
211 var mb = message.CreateBufferedCopy (0x10000);
213 foreach (var pc in peers) {
214 message = mb.CreateMessage ();
216 if (pc.Status == RemotePeerStatus.None) {
217 pc.Status = RemotePeerStatus.Error; // prepare for cases that it resulted in an error in the middle.
218 var inner = CreateInnerClient (pc);
220 inner.Open (timeout - (DateTime.Now - start));
221 inner.OperationTimeout = timeout - (DateTime.Now - start);
222 inner.Connect (new ConnectInfo () { Address = local_node_address, NodeId = (uint) node.NodeId });
223 pc.Instance.WaitForConnectResponse (timeout - (DateTime.Now - start));
224 pc.Status = RemotePeerStatus.Connected;
227 pc.Channel.OperationTimeout = timeout - (DateTime.Now - start);
229 if (message.Headers.MessageId == null)
230 message.Headers.MessageId = new UniqueId ();
231 message.Headers.Add (MessageHeader.CreateHeader ("PeerTo", Constants.NetPeer, RemoteAddress.Uri));
232 message.Headers.Add (MessageHeader.CreateHeader ("PeerVia", Constants.NetPeer, RemoteAddress.Uri));
233 pc.Channel.SendMessage (message);
237 internal void EnqueueMessage (Message message)
239 queue.Enqueue (message);
240 receive_handle.Set ();
243 Queue<Message> queue = new Queue<Message> ();
244 AutoResetEvent receive_handle = new AutoResetEvent (false);
246 public override Message Receive (TimeSpan timeout)
248 ThrowIfDisposedOrNotOpen ();
249 DateTime start = DateTime.Now;
252 return queue.Dequeue ();
253 receive_handle.WaitOne ();
254 return queue.Dequeue ();
257 public override bool WaitForMessage (TimeSpan timeout)
259 ThrowIfDisposedOrNotOpen ();
261 throw new NotImplementedException ();
264 // CommunicationObject
266 protected override void OnAbort ()
268 if (client_factory != null) {
269 client_factory.Abort ();
270 client_factory = null;
272 OnClose (TimeSpan.Zero);
275 protected override void OnClose (TimeSpan timeout)
277 DateTime start = DateTime.Now;
278 if (client_factory != null)
279 client_factory.Close (timeout - (DateTime.Now - start));
281 resolver.Unregister (node.RegisteredId, timeout - (DateTime.Now - start));
283 if (listener_host != null)
284 listener_host.Close (timeout - (DateTime.Now - start));
285 node.RegisteredId = null;
289 protected override void OnOpen (TimeSpan timeout)
291 DateTime start = DateTime.Now;
293 // FIXME: supply maxAddresses
294 foreach (var a in resolver.Resolve (node.MeshId, 3, timeout))
295 peers.Add (new RemotePeerConnection (a));
297 // FIXME: pass more configuration
298 var binding = new NetTcpBinding ();
299 binding.Security.Mode = SecurityMode.None;
302 var rnd = new Random ();
303 for (int i = 0; i < 1000; i++) {
304 if (DateTime.Now - start > timeout)
305 throw new TimeoutException ();
307 port = rnd.Next (50000, 51000);
308 var t = new TcpListener (port);
312 } catch (SocketException) {
317 string name = Dns.GetHostName ();
318 var uri = new Uri ("net.tcp://" + name + ":" + port + "/PeerChannelEndpoints/" + Guid.NewGuid ());
320 var peer_receiver = new LocalPeerReceiver (this);
321 listener_host = new ServiceHost (peer_receiver);
322 var sba = listener_host.Description.Behaviors.Find<ServiceBehaviorAttribute> ();
323 sba.InstanceContextMode = InstanceContextMode.Single;
324 sba.IncludeExceptionDetailInFaults = true;
326 var se = listener_host.AddServiceEndpoint (typeof (IPeerConnectorContract).FullName, binding, "net.p2p://" + node.MeshId + "/");
329 // FIXME: remove debugging code
330 listener_host.UnknownMessageReceived += delegate (object obj, UnknownMessageReceivedEventArgs earg) { Console.WriteLine ("%%%%% UNKOWN MESSAGE " + earg.Message); };
332 listener_host.Open (timeout - (DateTime.Now - start));
334 var nid = new Random ().Next (0, int.MaxValue);
335 var ea = new EndpointAddress (uri);
336 var pna = new PeerNodeAddress (ea, new ReadOnlyCollection<IPAddress> (Dns.GetHostEntry (name).AddressList));
337 local_node_address = pna;
338 node.RegisteredId = resolver.Register (node.MeshId, pna, timeout - (DateTime.Now - start));
341 // Add itself to the local list as well.
342 // FIXME: it might become unnecessary once it implemented new node registration from peer resolver service.
343 peers.Add (new RemotePeerConnection (pna));