PeerDuplexChannel.cs 10 KB

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