PeerDuplexChannel.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. //
  2. // PeerDuplexChannel.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2009 Novell, Inc. http://www.novell.com
  8. //
  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:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  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.
  27. //
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Collections.ObjectModel;
  31. using System.IO;
  32. using System.Linq;
  33. using System.Net;
  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;
  42. using System.Xml;
  43. namespace System.ServiceModel.Channels
  44. {
  45. // PeerDuplexChannel can be created either from PeerChannelFactory
  46. // (as IOutputChannel) or PeerChannelListener (as IInputChannel).
  47. //
  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.
  51. internal class PeerDuplexChannel : DuplexChannelBase
  52. {
  53. enum RemotePeerStatus
  54. {
  55. None,
  56. Connected,
  57. Error,
  58. }
  59. class RemotePeerConnection
  60. {
  61. public RemotePeerConnection (PeerNodeAddress address)
  62. {
  63. Address = address;
  64. }
  65. public PeerNodeAddress Address { get; private set; }
  66. public RemotePeerStatus Status { get; set; }
  67. public LocalPeerReceiver Instance { get; set; }
  68. public IPeerConnectorClient Channel { get; set; }
  69. public ulong NodeId { get; set; }
  70. }
  71. class LocalPeerReceiver : IPeerConnectorContract
  72. {
  73. List<PeerNodeAddress> connections = new List<PeerNodeAddress> ();
  74. AutoResetEvent connect_handle = new AutoResetEvent (false);
  75. public event Action<WelcomeInfo> WelcomeReceived;
  76. public LocalPeerReceiver (PeerDuplexChannel owner)
  77. {
  78. this.owner = owner;
  79. }
  80. PeerDuplexChannel owner;
  81. public void Connect (ConnectInfo connect)
  82. {
  83. if (connect == null)
  84. throw new ArgumentNullException ("connect");
  85. var ch = OperationContext.Current.GetCallbackChannel<IPeerConnectorContract> ();
  86. connections.Add (connect.Address);
  87. // FIXME: check and reject if inappropriate. For example, maximum connection exceeded.
  88. using (var octx = new OperationContextScope ((IContextChannel) ch)) {
  89. OperationContext.Current.OutgoingMessageHeaders.To = new Uri (Constants.WsaAnonymousUri);
  90. if (!owner.peers.Any (p => p.Address.EndpointAddress.Equals (connect.Address.EndpointAddress)))
  91. owner.peers.Add (new RemotePeerConnection (connect.Address));
  92. ch.Welcome (new WelcomeInfo () { NodeId = owner.node.NodeId });
  93. }
  94. }
  95. internal void WaitForConnectResponse (TimeSpan timeout)
  96. {
  97. if (!connect_handle.WaitOne (timeout))
  98. throw new TimeoutException ();
  99. }
  100. public void Disconnect (DisconnectInfo disconnect)
  101. {
  102. if (disconnect == null)
  103. throw new ArgumentNullException ("disconnect");
  104. // Console.WriteLine ("DisconnectInfo.Reason: " + disconnect.Reason);
  105. // FIXME: handle disconnection in practice. So far I see nothing to do.
  106. }
  107. public void Welcome (WelcomeInfo welcome)
  108. {
  109. if (WelcomeReceived != null)
  110. WelcomeReceived (welcome);
  111. connect_handle.Set ();
  112. }
  113. public void Refuse (RefuseInfo refuse)
  114. {
  115. // FIXME: it should not probably actually throw an error.
  116. connect_handle.Set ();
  117. throw new InvalidOperationException ("Peer connection was refused");
  118. }
  119. public void LinkUtility (LinkUtilityInfo linkUtility)
  120. {
  121. throw new NotImplementedException ();
  122. }
  123. public void Ping ()
  124. {
  125. throw new NotImplementedException ();
  126. }
  127. public void SendMessage (Message msg)
  128. {
  129. int idx = msg.Headers.FindHeader ("PeerTo", Constants.NetPeer);
  130. if (idx >= 0)
  131. msg.Headers.To = msg.Headers.GetHeader<Uri> (idx);
  132. // FIXME: anything to do for PeerVia?
  133. owner.EnqueueMessage (msg);
  134. }
  135. }
  136. interface IPeerConnectorClient : IClientChannel, IPeerConnectorContract
  137. {
  138. }
  139. IChannelFactory<IDuplexSessionChannel> client_factory;
  140. PeerTransportBindingElement binding;
  141. PeerResolver resolver;
  142. PeerNode node;
  143. ServiceHost listener_host;
  144. TcpChannelInfo info;
  145. List<RemotePeerConnection> peers = new List<RemotePeerConnection> ();
  146. PeerNodeAddress local_node_address;
  147. public PeerDuplexChannel (IPeerChannelManager factory, EndpointAddress address, Uri via, PeerResolver resolver)
  148. : base ((ChannelFactoryBase) factory, address, via)
  149. {
  150. binding = factory.Source;
  151. this.resolver = factory.Resolver;
  152. info = new TcpChannelInfo (binding, factory.MessageEncoder, null); // FIXME: fill properties correctly.
  153. // It could be opened even with empty list of PeerNodeAddresses.
  154. // So, do not create PeerNode per PeerNodeAddress, but do it with PeerNodeAddress[].
  155. node = new PeerNodeImpl (RemoteAddress.Uri.Host, factory.Source.ListenIPAddress, factory.Source.Port);
  156. }
  157. public PeerDuplexChannel (IPeerChannelManager listener)
  158. : base ((ChannelListenerBase) listener)
  159. {
  160. binding = listener.Source;
  161. this.resolver = listener.Resolver;
  162. info = new TcpChannelInfo (binding, listener.MessageEncoder, null); // FIXME: fill properties correctly.
  163. node = new PeerNodeImpl (((ChannelListenerBase) listener).Uri.Host, listener.Source.ListenIPAddress, listener.Source.Port);
  164. }
  165. public override T GetProperty<T> ()
  166. {
  167. if (typeof (T).IsInstanceOfType (node))
  168. return (T) (object) node;
  169. return base.GetProperty<T> ();
  170. }
  171. // DuplexChannelBase
  172. IPeerConnectorClient CreateInnerClient (RemotePeerConnection conn)
  173. {
  174. conn.Instance = new LocalPeerReceiver (this);
  175. conn.Instance.WelcomeReceived += delegate (WelcomeInfo welcome) {
  176. conn.NodeId = welcome.NodeId;
  177. // FIXME: handle referrals
  178. };
  179. // FIXME: pass more setup parameters
  180. var binding = new NetTcpBinding ();
  181. binding.Security.Mode = SecurityMode.None;
  182. var channel_factory = new DuplexChannelFactory<IPeerConnectorClient> (conn.Instance, binding);
  183. channel_factory.Open ();
  184. var ch = channel_factory.CreateChannel (new EndpointAddress ("net.p2p://" + node.MeshId + "/"), conn.Address.EndpointAddress.Uri);
  185. ch.Closed += delegate {
  186. channel_factory.Close ();
  187. };
  188. return ch;
  189. }
  190. public override void Send (Message message, TimeSpan timeout)
  191. {
  192. ThrowIfDisposedOrNotOpen ();
  193. DateTime start = DateTime.Now;
  194. // FIXME: give max buffer size
  195. var mb = message.CreateBufferedCopy (0x10000);
  196. for (int i = 0; i < peers.Count; i++) {
  197. var pc = peers [i];
  198. message = mb.CreateMessage ();
  199. if (pc.Status == RemotePeerStatus.None) {
  200. pc.Status = RemotePeerStatus.Error; // prepare for cases that it resulted in an error in the middle.
  201. var inner = CreateInnerClient (pc);
  202. pc.Channel = inner;
  203. inner.Open (timeout - (DateTime.Now - start));
  204. inner.OperationTimeout = timeout - (DateTime.Now - start);
  205. inner.Connect (new ConnectInfo () { Address = local_node_address, NodeId = (uint) node.NodeId });
  206. pc.Instance.WaitForConnectResponse (timeout - (DateTime.Now - start));
  207. pc.Status = RemotePeerStatus.Connected;
  208. }
  209. pc.Channel.OperationTimeout = timeout - (DateTime.Now - start);
  210. // see [MC-PRCH] 3.2.4.1
  211. if (message.Headers.MessageId == null)
  212. message.Headers.MessageId = new UniqueId ();
  213. message.Headers.Add (MessageHeader.CreateHeader ("PeerTo", Constants.NetPeer, RemoteAddress.Uri));
  214. message.Headers.Add (MessageHeader.CreateHeader ("PeerVia", Constants.NetPeer, RemoteAddress.Uri));
  215. message.Headers.Add (MessageHeader.CreateHeader ("FloodMessage", Constants.NetPeer, "PeerFlooder"));
  216. pc.Channel.SendMessage (message);
  217. }
  218. }
  219. internal void EnqueueMessage (Message message)
  220. {
  221. queue.Enqueue (message);
  222. receive_handle.Set ();
  223. }
  224. Queue<Message> queue = new Queue<Message> ();
  225. AutoResetEvent receive_handle = new AutoResetEvent (false);
  226. public override bool TryReceive (TimeSpan timeout, out Message message)
  227. {
  228. ThrowIfDisposedOrNotOpen ();
  229. DateTime start = DateTime.Now;
  230. if (queue.Count > 0 || receive_handle.WaitOne (timeout)) {
  231. message = queue.Dequeue ();
  232. return message == null;
  233. } else {
  234. message = null;
  235. return false;
  236. }
  237. }
  238. public override bool WaitForMessage (TimeSpan timeout)
  239. {
  240. ThrowIfDisposedOrNotOpen ();
  241. throw new NotImplementedException ();
  242. }
  243. // CommunicationObject
  244. protected override void OnAbort ()
  245. {
  246. if (client_factory != null) {
  247. client_factory.Abort ();
  248. client_factory = null;
  249. }
  250. OnClose (TimeSpan.Zero);
  251. }
  252. protected override void OnClose (TimeSpan timeout)
  253. {
  254. DateTime start = DateTime.Now;
  255. if (client_factory != null)
  256. client_factory.Close (timeout - (DateTime.Now - start));
  257. peers.Clear ();
  258. resolver.Unregister (node.RegisteredId, timeout - (DateTime.Now - start));
  259. node.SetOffline ();
  260. if (listener_host != null)
  261. listener_host.Close (timeout - (DateTime.Now - start));
  262. node.RegisteredId = null;
  263. }
  264. protected override void OnOpen (TimeSpan timeout)
  265. {
  266. DateTime start = DateTime.Now;
  267. // FIXME: supply maxAddresses
  268. foreach (var a in resolver.Resolve (node.MeshId, 3, timeout))
  269. peers.Add (new RemotePeerConnection (a));
  270. // FIXME: pass more configuration
  271. var binding = new NetTcpBinding ();
  272. binding.Security.Mode = SecurityMode.None;
  273. int port = 0;
  274. var rnd = new Random ();
  275. for (int i = 0; i < 1000; i++) {
  276. if (DateTime.Now - start > timeout)
  277. throw new TimeoutException ();
  278. try {
  279. port = rnd.Next (50000, 51000);
  280. var t = new TcpListener (port);
  281. t.Start ();
  282. t.Stop ();
  283. break;
  284. } catch (SocketException) {
  285. continue;
  286. }
  287. }
  288. string name = Dns.GetHostName ();
  289. var uri = new Uri ("net.tcp://" + name + ":" + port + "/PeerChannelEndpoints/" + Guid.NewGuid ());
  290. var peer_receiver = new LocalPeerReceiver (this);
  291. listener_host = new ServiceHost (peer_receiver);
  292. var sba = listener_host.Description.Behaviors.Find<ServiceBehaviorAttribute> ();
  293. sba.InstanceContextMode = InstanceContextMode.Single;
  294. sba.IncludeExceptionDetailInFaults = true;
  295. var se = listener_host.AddServiceEndpoint (typeof (IPeerConnectorContract).FullName, binding, "net.p2p://" + node.MeshId + "/");
  296. se.ListenUri = uri;
  297. // FIXME: remove debugging code
  298. listener_host.UnknownMessageReceived += delegate (object obj, UnknownMessageReceivedEventArgs earg) { Console.WriteLine ("%%%%% UNKOWN MESSAGE " + earg.Message); };
  299. listener_host.Open (timeout - (DateTime.Now - start));
  300. var nid = (ulong) new Random ().Next (0, int.MaxValue);
  301. var ea = new EndpointAddress (uri);
  302. var pna = new PeerNodeAddress (ea, new ReadOnlyCollection<IPAddress> (Dns.GetHostEntry (name).AddressList));
  303. local_node_address = pna;
  304. node.RegisteredId = resolver.Register (node.MeshId, pna, timeout - (DateTime.Now - start));
  305. node.NodeId = nid;
  306. // Add itself to the local list as well.
  307. // FIXME: it might become unnecessary once it implemented new node registration from peer resolver service.
  308. peers.Add (new RemotePeerConnection (pna));
  309. node.SetOnline ();
  310. }
  311. }
  312. }