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;
34 using System.Net.Security;
35 using System.Net.Sockets;
36 using System.ServiceModel;
37 using System.ServiceModel.Channels.NetTcp;
38 using System.ServiceModel.Description;
39 using System.ServiceModel.PeerResolvers;
40 using System.ServiceModel.Security;
41 using System.Threading;
44 namespace System.ServiceModel.Channels
47 // PeerDuplexChannel can be created either from PeerChannelFactory
48 // (as IOutputChannel) or PeerChannelListener (as IInputChannel).
50 // PeerNode has to be created before Open() (at least at client side).
51 // On open, it tries to resolve the nodes in the mesh (and do something
52 // - but what?). Then registers itself to the mesh and refreshes it.
54 internal class PeerDuplexChannel : DuplexChannelBase
63 class RemotePeerConnection
65 public RemotePeerConnection (PeerNodeAddress address)
70 public PeerNodeAddress Address { get; private set; }
71 public RemotePeerStatus Status { get; set; }
72 public LocalPeerReceiver Instance { get; set; }
73 public IPeerConnectorClient Channel { get; set; }
74 public ulong NodeId { get; set; }
77 class LocalPeerReceiver : IPeerConnectorContract
79 List<PeerNodeAddress> connections = new List<PeerNodeAddress> ();
80 AutoResetEvent connect_handle = new AutoResetEvent (false);
81 public event Action<WelcomeInfo> WelcomeReceived;
83 public LocalPeerReceiver (PeerDuplexChannel owner)
88 PeerDuplexChannel owner;
90 public void Connect (ConnectInfo connect)
93 throw new ArgumentNullException ("connect");
94 var ch = OperationContext.Current.GetCallbackChannel<IPeerConnectorContract> ();
96 connections.Add (connect.Address);
97 // FIXME: check and reject if inappropriate. For example, maximum connection exceeded.
98 using (var octx = new OperationContextScope ((IContextChannel) ch)) {
99 OperationContext.Current.OutgoingMessageHeaders.To = new Uri (Constants.WsaAnonymousUri);
100 if (!owner.peers.Any (p => p.Address.EndpointAddress.Equals (connect.Address.EndpointAddress)))
101 owner.peers.Add (new RemotePeerConnection (connect.Address));
102 ch.Welcome (new WelcomeInfo () { NodeId = owner.node.NodeId });
106 internal void WaitForConnectResponse (TimeSpan timeout)
108 if (!connect_handle.WaitOne (timeout))
109 throw new TimeoutException ();
112 public void Disconnect (DisconnectInfo disconnect)
114 if (disconnect == null)
115 throw new ArgumentNullException ("disconnect");
116 // Console.WriteLine ("DisconnectInfo.Reason: " + disconnect.Reason);
117 // FIXME: handle disconnection in practice. So far I see nothing to do.
120 public void Welcome (WelcomeInfo welcome)
122 if (WelcomeReceived != null)
123 WelcomeReceived (welcome);
124 connect_handle.Set ();
127 public void Refuse (RefuseInfo refuse)
129 // FIXME: it should not probably actually throw an error.
130 connect_handle.Set ();
131 throw new InvalidOperationException ("Peer connection was refused");
134 public void LinkUtility (LinkUtilityInfo linkUtility)
136 throw new NotImplementedException ();
141 throw new NotImplementedException ();
144 public void SendMessage (Message msg)
146 int idx = msg.Headers.FindHeader ("PeerTo", Constants.NetPeer);
148 msg.Headers.To = msg.Headers.GetHeader<Uri> (idx);
149 // FIXME: anything to do for PeerVia?
151 owner.EnqueueMessage (msg);
155 interface IPeerConnectorClient : IClientChannel, IPeerConnectorContract
159 IChannelFactory<IDuplexSessionChannel> client_factory;
160 PeerTransportBindingElement binding;
161 PeerResolver resolver;
163 ServiceHost listener_host;
165 List<RemotePeerConnection> peers = new List<RemotePeerConnection> ();
166 PeerNodeAddress local_node_address;
168 public PeerDuplexChannel (IPeerChannelManager factory, EndpointAddress address, Uri via, PeerResolver resolver)
169 : base ((ChannelFactoryBase) factory, address, via)
171 binding = factory.Source;
172 this.resolver = factory.Resolver;
173 info = new TcpChannelInfo (binding, factory.MessageEncoder, null); // FIXME: fill properties correctly.
175 // It could be opened even with empty list of PeerNodeAddresses.
176 // So, do not create PeerNode per PeerNodeAddress, but do it with PeerNodeAddress[].
177 node = new PeerNodeImpl (RemoteAddress.Uri.Host, factory.Source.ListenIPAddress, factory.Source.Port);
180 public PeerDuplexChannel (IPeerChannelManager listener)
181 : base ((ChannelListenerBase) listener)
183 binding = listener.Source;
184 this.resolver = listener.Resolver;
185 info = new TcpChannelInfo (binding, listener.MessageEncoder, null); // FIXME: fill properties correctly.
187 node = new PeerNodeImpl (((ChannelListenerBase) listener).Uri.Host, listener.Source.ListenIPAddress, listener.Source.Port);
190 public override T GetProperty<T> ()
192 if (typeof (T).IsInstanceOfType (node))
193 return (T) (object) node;
194 return base.GetProperty<T> ();
199 IPeerConnectorClient CreateInnerClient (RemotePeerConnection conn)
201 conn.Instance = new LocalPeerReceiver (this);
202 conn.Instance.WelcomeReceived += delegate (WelcomeInfo welcome) {
203 conn.NodeId = welcome.NodeId;
204 // FIXME: handle referrals
207 // FIXME: pass more setup parameters
208 var binding = new NetTcpBinding ();
209 binding.Security.Mode = SecurityMode.None;
210 var channel_factory = new DuplexChannelFactory<IPeerConnectorClient> (conn.Instance, binding);
211 channel_factory.Open ();
213 var ch = channel_factory.CreateChannel (new EndpointAddress ("net.p2p://" + node.MeshId + "/"), conn.Address.EndpointAddress.Uri);
214 ch.Closed += delegate {
215 channel_factory.Close ();
220 public override void Send (Message message, TimeSpan timeout)
222 ThrowIfDisposedOrNotOpen ();
224 DateTime start = DateTime.UtcNow;
226 // FIXME: give max buffer size
227 var mb = message.CreateBufferedCopy (0x10000);
229 for (int i = 0; i < peers.Count; i++) {
231 message = mb.CreateMessage ();
233 if (pc.Status == RemotePeerStatus.None) {
234 pc.Status = RemotePeerStatus.Error; // prepare for cases that it resulted in an error in the middle.
235 var inner = CreateInnerClient (pc);
237 inner.Open (timeout - (DateTime.UtcNow - start));
238 inner.OperationTimeout = timeout - (DateTime.UtcNow - start);
239 inner.Connect (new ConnectInfo () { Address = local_node_address, NodeId = (uint) node.NodeId });
240 pc.Instance.WaitForConnectResponse (timeout - (DateTime.UtcNow - start));
241 pc.Status = RemotePeerStatus.Connected;
244 pc.Channel.OperationTimeout = timeout - (DateTime.UtcNow - start);
246 // see [MC-PRCH] 3.2.4.1
247 if (message.Headers.MessageId == null)
248 message.Headers.MessageId = new UniqueId ();
249 message.Headers.Add (MessageHeader.CreateHeader ("PeerTo", Constants.NetPeer, RemoteAddress.Uri));
250 message.Headers.Add (MessageHeader.CreateHeader ("PeerVia", Constants.NetPeer, RemoteAddress.Uri));
251 message.Headers.Add (MessageHeader.CreateHeader ("FloodMessage", Constants.NetPeer, "PeerFlooder"));
252 pc.Channel.SendMessage (message);
256 internal void EnqueueMessage (Message message)
258 queue.Enqueue (message);
259 receive_handle.Set ();
262 Queue<Message> queue = new Queue<Message> ();
263 AutoResetEvent receive_handle = new AutoResetEvent (false);
265 public override bool TryReceive (TimeSpan timeout, out Message message)
267 ThrowIfDisposedOrNotOpen ();
269 if (queue.Count > 0 || receive_handle.WaitOne (timeout)) {
270 message = queue.Dequeue ();
271 return message == null;
278 public override bool WaitForMessage (TimeSpan timeout)
280 ThrowIfDisposedOrNotOpen ();
282 throw new NotImplementedException ();
285 // CommunicationObject
287 protected override void OnAbort ()
289 if (client_factory != null) {
290 client_factory.Abort ();
291 client_factory = null;
293 OnClose (TimeSpan.Zero);
296 protected override void OnClose (TimeSpan timeout)
298 DateTime start = DateTime.UtcNow;
299 if (client_factory != null)
300 client_factory.Close (timeout - (DateTime.UtcNow - start));
302 resolver.Unregister (node.RegisteredId, timeout - (DateTime.UtcNow - start));
304 if (listener_host != null)
305 listener_host.Close (timeout - (DateTime.UtcNow - start));
306 node.RegisteredId = null;
310 protected override void OnOpen (TimeSpan timeout)
312 DateTime start = DateTime.UtcNow;
314 // FIXME: supply maxAddresses
315 foreach (var a in resolver.Resolve (node.MeshId, 3, timeout))
316 peers.Add (new RemotePeerConnection (a));
318 // FIXME: pass more configuration
319 var binding = new NetTcpBinding ();
320 binding.Security.Mode = SecurityMode.None;
323 var rnd = new Random ();
324 for (int i = 0; i < 1000; i++) {
325 if (DateTime.UtcNow - start > timeout)
326 throw new TimeoutException ();
328 port = rnd.Next (50000, 51000);
329 var t = new TcpListener (port);
333 } catch (SocketException) {
338 string name = Dns.GetHostName ();
339 var uri = new Uri ("net.tcp://" + name + ":" + port + "/PeerChannelEndpoints/" + Guid.NewGuid ());
341 var peer_receiver = new LocalPeerReceiver (this);
342 listener_host = new ServiceHost (peer_receiver);
343 var sba = listener_host.Description.Behaviors.Find<ServiceBehaviorAttribute> ();
344 sba.InstanceContextMode = InstanceContextMode.Single;
345 sba.IncludeExceptionDetailInFaults = true;
347 var se = listener_host.AddServiceEndpoint (typeof (IPeerConnectorContract).FullName, binding, "net.p2p://" + node.MeshId + "/");
350 // FIXME: remove debugging code
351 listener_host.UnknownMessageReceived += delegate (object obj, UnknownMessageReceivedEventArgs earg) { Console.WriteLine ("%%%%% UNKOWN MESSAGE " + earg.Message); };
353 listener_host.Open (timeout - (DateTime.UtcNow - start));
355 var nid = (ulong) new Random ().Next (0, int.MaxValue);
356 var ea = new EndpointAddress (uri);
357 var pna = new PeerNodeAddress (ea, new ReadOnlyCollection<IPAddress> (Dns.GetHostEntry (name).AddressList));
358 local_node_address = pna;
359 node.RegisteredId = resolver.Register (node.MeshId, pna, timeout - (DateTime.UtcNow - start));
362 // Add itself to the local list as well.
363 // FIXME: it might become unnecessary once it implemented new node registration from peer resolver service.
364 peers.Add (new RemotePeerConnection (pna));