using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
+using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.ServiceModel.PeerResolvers;
using System.ServiceModel.Security;
using System.Threading;
+using System.Xml;
namespace System.ServiceModel.Channels
{
public PeerNodeAddress Address { get; private set; }
public RemotePeerStatus Status { get; set; }
+ public LocalPeerReceiver Instance { get; set; }
public IPeerConnectorClient Channel { get; set; }
+ public ulong NodeId { get; set; }
+ }
+
+ class LocalPeerReceiver : IPeerConnectorContract
+ {
+ List<PeerNodeAddress> connections = new List<PeerNodeAddress> ();
+ AutoResetEvent connect_handle = new AutoResetEvent (false);
+ public event Action<WelcomeInfo> WelcomeReceived;
+
+ public LocalPeerReceiver (PeerDuplexChannel owner)
+ {
+ this.owner = owner;
+ }
+
+ PeerDuplexChannel owner;
+
+ public void Connect (ConnectInfo connect)
+ {
+ if (connect == null)
+ throw new ArgumentNullException ("connect");
+ var ch = OperationContext.Current.GetCallbackChannel<IPeerConnectorContract> ();
+
+ connections.Add (connect.Address);
+ // FIXME: check and reject if inappropriate. For example, maximum connection exceeded.
+ using (var octx = new OperationContextScope ((IContextChannel) ch)) {
+ OperationContext.Current.OutgoingMessageHeaders.To = new Uri (Constants.WsaAnonymousUri);
+ if (!owner.peers.Any (p => p.Address.EndpointAddress.Equals (connect.Address.EndpointAddress)))
+ owner.peers.Add (new RemotePeerConnection (connect.Address));
+ ch.Welcome (new WelcomeInfo () { NodeId = owner.node.NodeId });
+ }
+ }
+
+ internal void WaitForConnectResponse (TimeSpan timeout)
+ {
+ if (!connect_handle.WaitOne (timeout))
+ throw new TimeoutException ();
+ }
+
+ public void Disconnect (DisconnectInfo disconnect)
+ {
+ if (disconnect == null)
+ throw new ArgumentNullException ("disconnect");
+ // Console.WriteLine ("DisconnectInfo.Reason: " + disconnect.Reason);
+ // FIXME: handle disconnection in practice. So far I see nothing to do.
+ }
+
+ public void Welcome (WelcomeInfo welcome)
+ {
+ if (WelcomeReceived != null)
+ WelcomeReceived (welcome);
+ connect_handle.Set ();
+ }
+
+ public void Refuse (RefuseInfo refuse)
+ {
+ // FIXME: it should not probably actually throw an error.
+ connect_handle.Set ();
+ throw new InvalidOperationException ("Peer connection was refused");
+ }
+
+ public void LinkUtility (LinkUtilityInfo linkUtility)
+ {
+ throw new NotImplementedException ();
+ }
+
+ public void Ping ()
+ {
+ throw new NotImplementedException ();
+ }
+
+ public void SendMessage (Message msg)
+ {
+ int idx = msg.Headers.FindHeader ("PeerTo", Constants.NetPeer);
+ if (idx >= 0)
+ msg.Headers.To = msg.Headers.GetHeader<Uri> (idx);
+ // FIXME: anything to do for PeerVia?
+
+ owner.EnqueueMessage (msg);
+ }
}
interface IPeerConnectorClient : IClientChannel, IPeerConnectorContract
}
IChannelFactory<IDuplexSessionChannel> client_factory;
- ChannelFactory<IPeerConnectorClient> channel_factory;
PeerTransportBindingElement binding;
PeerResolver resolver;
PeerNode node;
- IChannelListener<IDuplexSessionChannel> channel_listener;
+ ServiceHost listener_host;
TcpChannelInfo info;
List<RemotePeerConnection> peers = new List<RemotePeerConnection> ();
+ PeerNodeAddress local_node_address;
public PeerDuplexChannel (IPeerChannelManager factory, EndpointAddress address, Uri via, PeerResolver resolver)
: base ((ChannelFactoryBase) factory, address, via)
// DuplexChannelBase
- IPeerConnectorClient CreateInnerClient (PeerNodeAddress pna)
+ IPeerConnectorClient CreateInnerClient (RemotePeerConnection conn)
{
- // FIXME: pass more setup parameters
- if (channel_factory == null) {
- var binding = new NetTcpBinding ();
- binding.Security.Mode = SecurityMode.None;
- channel_factory = new ChannelFactory<IPeerConnectorClient> (binding);
- }
+ conn.Instance = new LocalPeerReceiver (this);
+ conn.Instance.WelcomeReceived += delegate (WelcomeInfo welcome) {
+ conn.NodeId = welcome.NodeId;
+ // FIXME: handle referrals
+ };
- // FIXME: EndpointAddress must be "net.p2p://{meshId}", eliminating the remaining path.
- return channel_factory.CreateChannel (RemoteAddress ?? LocalAddress, pna.EndpointAddress.Uri);
+ // FIXME: pass more setup parameters
+ var binding = new NetTcpBinding ();
+ binding.Security.Mode = SecurityMode.None;
+ var channel_factory = new DuplexChannelFactory<IPeerConnectorClient> (conn.Instance, binding);
+ channel_factory.Open ();
+
+ var ch = channel_factory.CreateChannel (new EndpointAddress ("net.p2p://" + node.MeshId + "/"), conn.Address.EndpointAddress.Uri);
+ ch.Closed += delegate {
+ channel_factory.Close ();
+ };
+ return ch;
}
public override void Send (Message message, TimeSpan timeout)
ThrowIfDisposedOrNotOpen ();
DateTime start = DateTime.Now;
-
- foreach (var pc in peers) {
+
+ // FIXME: give max buffer size
+ var mb = message.CreateBufferedCopy (0x10000);
+
+ for (int i = 0; i < peers.Count; i++) {
+ var pc = peers [i];
+ message = mb.CreateMessage ();
+
if (pc.Status == RemotePeerStatus.None) {
- var inner = CreateInnerClient (pc.Address);
+ pc.Status = RemotePeerStatus.Error; // prepare for cases that it resulted in an error in the middle.
+ var inner = CreateInnerClient (pc);
pc.Channel = inner;
inner.Open (timeout - (DateTime.Now - start));
inner.OperationTimeout = timeout - (DateTime.Now - start);
- inner.Connect (new ConnectInfo () { PeerNodeAddress = pc.Address, NodeId = (uint) node.NodeId });
-
- // FIXME: wait for Welcome or Reject and take further action.
- throw new NotImplementedException ();
+ inner.Connect (new ConnectInfo () { Address = local_node_address, NodeId = (uint) node.NodeId });
+ pc.Instance.WaitForConnectResponse (timeout - (DateTime.Now - start));
+ pc.Status = RemotePeerStatus.Connected;
}
pc.Channel.OperationTimeout = timeout - (DateTime.Now - start);
+
+ // see [MC-PRCH] 3.2.4.1
+ if (message.Headers.MessageId == null)
+ message.Headers.MessageId = new UniqueId ();
+ message.Headers.Add (MessageHeader.CreateHeader ("PeerTo", Constants.NetPeer, RemoteAddress.Uri));
+ message.Headers.Add (MessageHeader.CreateHeader ("PeerVia", Constants.NetPeer, RemoteAddress.Uri));
+ message.Headers.Add (MessageHeader.CreateHeader ("FloodMessage", Constants.NetPeer, "PeerFlooder"));
pc.Channel.SendMessage (message);
}
}
- public override Message Receive (TimeSpan timeout)
+ internal void EnqueueMessage (Message message)
+ {
+ queue.Enqueue (message);
+ receive_handle.Set ();
+ }
+
+ Queue<Message> queue = new Queue<Message> ();
+ AutoResetEvent receive_handle = new AutoResetEvent (false);
+
+ public override bool TryReceive (TimeSpan timeout, out Message message)
{
ThrowIfDisposedOrNotOpen ();
DateTime start = DateTime.Now;
- var ch = channel_listener.AcceptChannel (timeout);
- ch.Open (timeout - (DateTime.Now - start));
- try {
- return ch.Receive (timeout - (DateTime.Now - start));
- } finally {
- ch.Close ();
+ if (queue.Count > 0 || receive_handle.WaitOne (timeout)) {
+ message = queue.Dequeue ();
+ return message == null;
+ } else {
+ message = null;
+ return false;
}
}
peers.Clear ();
resolver.Unregister (node.RegisteredId, timeout - (DateTime.Now - start));
node.SetOffline ();
- if (channel_listener != null)
- channel_listener.Close (timeout - (DateTime.Now - start));
+ if (listener_host != null)
+ listener_host.Close (timeout - (DateTime.Now - start));
node.RegisteredId = null;
}
string name = Dns.GetHostName ();
var uri = new Uri ("net.tcp://" + name + ":" + port + "/PeerChannelEndpoints/" + Guid.NewGuid ());
- channel_listener = binding.BuildChannelListener<IDuplexSessionChannel> (uri, new object [0]);
- channel_listener.Open (timeout - (DateTime.Now - start));
+ var peer_receiver = new LocalPeerReceiver (this);
+ listener_host = new ServiceHost (peer_receiver);
+ var sba = listener_host.Description.Behaviors.Find<ServiceBehaviorAttribute> ();
+ sba.InstanceContextMode = InstanceContextMode.Single;
+ sba.IncludeExceptionDetailInFaults = true;
+
+ var se = listener_host.AddServiceEndpoint (typeof (IPeerConnectorContract).FullName, binding, "net.p2p://" + node.MeshId + "/");
+ se.ListenUri = uri;
+
+ // FIXME: remove debugging code
+ listener_host.UnknownMessageReceived += delegate (object obj, UnknownMessageReceivedEventArgs earg) { Console.WriteLine ("%%%%% UNKOWN MESSAGE " + earg.Message); };
+
+ listener_host.Open (timeout - (DateTime.Now - start));
- var nid = new Random ().Next (0, int.MaxValue);
+ var nid = (ulong) new Random ().Next (0, int.MaxValue);
var ea = new EndpointAddress (uri);
var pna = new PeerNodeAddress (ea, new ReadOnlyCollection<IPAddress> (Dns.GetHostEntry (name).AddressList));
+ local_node_address = pna;
node.RegisteredId = resolver.Register (node.MeshId, pna, timeout - (DateTime.Now - start));
node.NodeId = nid;