PeerDuplexChannel.cs 12 KB

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