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;
41 namespace System.ServiceModel.Channels
44 // PeerDuplexChannel can be created either from PeerChannelFactory
45 // (as IOutputChannel) or PeerChannelListener (as IInputChannel).
47 // PeerNode has to be created before Open() (at least at client side).
48 // On open, it tries to resolve the nodes in the mesh (and do something
49 // - but what?). Then registers itself to the mesh and refreshes it.
51 internal class PeerDuplexChannel : DuplexChannelBase
60 class RemotePeerConnection
62 public RemotePeerConnection (PeerNodeAddress address)
67 public PeerNodeAddress Address { get; private set; }
68 public RemotePeerStatus Status { get; set; }
69 public IPeerConnectorClient Channel { get; set; }
72 class LocalPeerReceiver : IPeerReceiverContract
74 public LocalPeerReceiver (PeerDuplexChannel owner)
79 PeerDuplexChannel owner;
81 public void Connect (ConnectInfo connect)
84 throw new ArgumentNullException ("connect");
86 var ch = OperationContext.Current.GetCallbackChannel<IPeerConnectorContract> ();
87 // FIXME: so, this duplex channel, when created by a listener, lacks RemoteAddress to send callback. Get it from somewhere.
88 Console.WriteLine ("FIXME FIXME:" + ((IContextChannel) ch).RemoteAddress);
89 // FIXME: check and reject if inappropriate.
90 ch.Welcome (new WelcomeInfo () { NodeId = connect.NodeId });
92 } catch (Exception ex) {
93 Console.WriteLine ("Exception during Connect()");
94 Console.WriteLine (ex);
100 public void Welcome (WelcomeInfo welcome)
104 public void Refuse (RefuseInfo refuse)
108 public void SendMessage (Message msg)
110 owner.EnqueueMessage (msg);
114 interface IPeerConnectorClient : IClientChannel, IPeerConnectorContract
118 IChannelFactory<IDuplexSessionChannel> client_factory;
119 ChannelFactory<IPeerConnectorClient> channel_factory;
120 PeerTransportBindingElement binding;
121 PeerResolver resolver;
123 ServiceHost listener_host;
125 List<RemotePeerConnection> peers = new List<RemotePeerConnection> ();
127 public PeerDuplexChannel (IPeerChannelManager factory, EndpointAddress address, Uri via, PeerResolver resolver)
128 : base ((ChannelFactoryBase) factory, address, via)
130 binding = factory.Source;
131 this.resolver = factory.Resolver;
132 info = new TcpChannelInfo (binding, factory.MessageEncoder, null); // FIXME: fill properties correctly.
134 // It could be opened even with empty list of PeerNodeAddresses.
135 // So, do not create PeerNode per PeerNodeAddress, but do it with PeerNodeAddress[].
136 node = new PeerNodeImpl (RemoteAddress.Uri.Host, factory.Source.ListenIPAddress, factory.Source.Port);
139 public PeerDuplexChannel (IPeerChannelManager listener)
140 : base ((ChannelListenerBase) listener)
142 binding = listener.Source;
143 this.resolver = listener.Resolver;
144 info = new TcpChannelInfo (binding, listener.MessageEncoder, null); // FIXME: fill properties correctly.
146 node = new PeerNodeImpl (((ChannelListenerBase) listener).Uri.Host, listener.Source.ListenIPAddress, listener.Source.Port);
149 public override T GetProperty<T> ()
151 if (typeof (T).IsInstanceOfType (node))
152 return (T) (object) node;
153 return base.GetProperty<T> ();
158 IPeerConnectorClient CreateInnerClient (PeerNodeAddress pna)
160 // FIXME: pass more setup parameters
161 if (channel_factory == null) {
162 var binding = new NetTcpBinding ();
163 binding.Security.Mode = SecurityMode.None;
164 channel_factory = new ChannelFactory<IPeerConnectorClient> (binding);
167 return channel_factory.CreateChannel (new EndpointAddress ("net.p2p://" + node.MeshId), pna.EndpointAddress.Uri);
170 public override void Send (Message message, TimeSpan timeout)
172 ThrowIfDisposedOrNotOpen ();
174 DateTime start = DateTime.Now;
176 foreach (var pc in peers) {
177 if (pc.Status == RemotePeerStatus.None) {
178 var inner = CreateInnerClient (pc.Address);
180 inner.Open (timeout - (DateTime.Now - start));
181 inner.OperationTimeout = timeout - (DateTime.Now - start);
182 inner.Connect (new ConnectInfo () { PeerNodeAddress = pc.Address, NodeId = (uint) node.NodeId });
184 // FIXME: wait for Welcome or Reject and take further action.
185 throw new NotImplementedException ();
188 pc.Channel.OperationTimeout = timeout - (DateTime.Now - start);
189 pc.Channel.SendMessage (message);
193 internal void EnqueueMessage (Message message)
195 Console.WriteLine ("###########################");
196 var mb = message.CreateBufferedCopy (0x10000);
197 Console.WriteLine (mb.CreateMessage ());
198 message = mb.CreateMessage ();
199 queue.Enqueue (message);
200 receive_handle.Set ();
203 Queue<Message> queue = new Queue<Message> ();
204 AutoResetEvent receive_handle = new AutoResetEvent (false);
206 public override Message Receive (TimeSpan timeout)
208 ThrowIfDisposedOrNotOpen ();
209 DateTime start = DateTime.Now;
212 return queue.Dequeue ();
213 receive_handle.WaitOne ();
214 return queue.Dequeue ();
217 public override bool WaitForMessage (TimeSpan timeout)
219 ThrowIfDisposedOrNotOpen ();
221 throw new NotImplementedException ();
224 // CommunicationObject
226 protected override void OnAbort ()
228 if (client_factory != null) {
229 client_factory.Abort ();
230 client_factory = null;
232 OnClose (TimeSpan.Zero);
235 protected override void OnClose (TimeSpan timeout)
237 DateTime start = DateTime.Now;
238 if (client_factory != null)
239 client_factory.Close (timeout - (DateTime.Now - start));
241 resolver.Unregister (node.RegisteredId, timeout - (DateTime.Now - start));
243 if (listener_host != null)
244 listener_host.Close (timeout - (DateTime.Now - start));
245 node.RegisteredId = null;
249 protected override void OnOpen (TimeSpan timeout)
251 DateTime start = DateTime.Now;
253 // FIXME: supply maxAddresses
254 foreach (var a in resolver.Resolve (node.MeshId, 3, timeout))
255 peers.Add (new RemotePeerConnection (a));
257 // FIXME: pass more configuration
258 var binding = new NetTcpBinding ();
259 binding.Security.Mode = SecurityMode.None;
262 var rnd = new Random ();
263 for (int i = 0; i < 1000; i++) {
264 if (DateTime.Now - start > timeout)
265 throw new TimeoutException ();
267 port = rnd.Next (50000, 51000);
268 var t = new TcpListener (port);
272 } catch (SocketException) {
277 string name = Dns.GetHostName ();
278 var uri = new Uri ("net.tcp://" + name + ":" + port + "/PeerChannelEndpoints/" + Guid.NewGuid ());
280 var peer_receiver = new LocalPeerReceiver (this);
281 listener_host = new ServiceHost (peer_receiver);
282 var sba = listener_host.Description.Behaviors.Find<ServiceBehaviorAttribute> ();
283 sba.InstanceContextMode = InstanceContextMode.Single;
284 sba.IncludeExceptionDetailInFaults = true;
286 var se = listener_host.AddServiceEndpoint (typeof (IPeerReceiverContract), binding, "net.p2p://" + node.MeshId);
288 listener_host.Open (timeout - (DateTime.Now - start));
290 var nid = new Random ().Next (0, int.MaxValue);
291 var ea = new EndpointAddress (uri);
292 var pna = new PeerNodeAddress (ea, new ReadOnlyCollection<IPAddress> (Dns.GetHostEntry (name).AddressList));
293 node.RegisteredId = resolver.Register (node.MeshId, pna, timeout - (DateTime.Now - start));
296 // Add itself to the local list as well.
297 // FIXME: it might become unnecessary once it implemented new node registration from peer resolver service.
298 peers.Add (new RemotePeerConnection (pna));