PeerDuplexChannel.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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 : IPeerReceiverContract
  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. try {
  78. var ch = OperationContext.Current.GetCallbackChannel<IPeerConnectorContract> ();
  79. // FIXME: check and reject if inappropriate.
  80. ch.Welcome (new WelcomeInfo () { NodeId = connect.NodeId });
  81. } catch (Exception ex) {
  82. Console.WriteLine ("Exception during Connect()");
  83. Console.WriteLine (ex);
  84. throw;
  85. }
  86. }
  87. public void Welcome (WelcomeInfo welcome)
  88. {
  89. }
  90. public void Refuse (RefuseInfo refuse)
  91. {
  92. }
  93. public void SendMessage (Message msg)
  94. {
  95. owner.EnqueueMessage (msg);
  96. }
  97. }
  98. interface IPeerConnectorClient : IClientChannel, IPeerConnectorContract
  99. {
  100. }
  101. IChannelFactory<IDuplexSessionChannel> client_factory;
  102. ChannelFactory<IPeerConnectorClient> channel_factory;
  103. PeerTransportBindingElement binding;
  104. PeerResolver resolver;
  105. PeerNode node;
  106. ServiceHost listener_host;
  107. TcpChannelInfo info;
  108. List<RemotePeerConnection> peers = new List<RemotePeerConnection> ();
  109. public PeerDuplexChannel (IPeerChannelManager factory, EndpointAddress address, Uri via, PeerResolver resolver)
  110. : base ((ChannelFactoryBase) factory, address, via)
  111. {
  112. binding = factory.Source;
  113. this.resolver = factory.Resolver;
  114. info = new TcpChannelInfo (binding, factory.MessageEncoder, null); // FIXME: fill properties correctly.
  115. // It could be opened even with empty list of PeerNodeAddresses.
  116. // So, do not create PeerNode per PeerNodeAddress, but do it with PeerNodeAddress[].
  117. node = new PeerNodeImpl (RemoteAddress.Uri.Host, factory.Source.ListenIPAddress, factory.Source.Port);
  118. }
  119. public PeerDuplexChannel (IPeerChannelManager listener)
  120. : base ((ChannelListenerBase) listener)
  121. {
  122. binding = listener.Source;
  123. this.resolver = listener.Resolver;
  124. info = new TcpChannelInfo (binding, listener.MessageEncoder, null); // FIXME: fill properties correctly.
  125. node = new PeerNodeImpl (((ChannelListenerBase) listener).Uri.Host, listener.Source.ListenIPAddress, listener.Source.Port);
  126. }
  127. public override T GetProperty<T> ()
  128. {
  129. if (typeof (T).IsInstanceOfType (node))
  130. return (T) (object) node;
  131. return base.GetProperty<T> ();
  132. }
  133. // DuplexChannelBase
  134. IPeerConnectorClient CreateInnerClient (PeerNodeAddress pna)
  135. {
  136. // FIXME: pass more setup parameters
  137. if (channel_factory == null) {
  138. var binding = new NetTcpBinding ();
  139. binding.Security.Mode = SecurityMode.None;
  140. channel_factory = new ChannelFactory<IPeerConnectorClient> (binding);
  141. }
  142. return channel_factory.CreateChannel (new EndpointAddress ("net.p2p://" + node.MeshId), pna.EndpointAddress.Uri);
  143. }
  144. public override void Send (Message message, TimeSpan timeout)
  145. {
  146. ThrowIfDisposedOrNotOpen ();
  147. DateTime start = DateTime.Now;
  148. foreach (var pc in peers) {
  149. if (pc.Status == RemotePeerStatus.None) {
  150. var inner = CreateInnerClient (pc.Address);
  151. pc.Channel = inner;
  152. inner.Open (timeout - (DateTime.Now - start));
  153. inner.OperationTimeout = timeout - (DateTime.Now - start);
  154. inner.Connect (new ConnectInfo () { PeerNodeAddress = pc.Address, NodeId = (uint) node.NodeId });
  155. // FIXME: wait for Welcome or Reject and take further action.
  156. throw new NotImplementedException ();
  157. }
  158. pc.Channel.OperationTimeout = timeout - (DateTime.Now - start);
  159. pc.Channel.SendMessage (message);
  160. }
  161. }
  162. internal void EnqueueMessage (Message message)
  163. {
  164. Console.WriteLine ("###########################");
  165. var mb = message.CreateBufferedCopy (0x10000);
  166. Console.WriteLine (mb.CreateMessage ());
  167. message = mb.CreateMessage ();
  168. queue.Enqueue (message);
  169. receive_handle.Set ();
  170. }
  171. Queue<Message> queue = new Queue<Message> ();
  172. AutoResetEvent receive_handle = new AutoResetEvent (false);
  173. public override Message Receive (TimeSpan timeout)
  174. {
  175. ThrowIfDisposedOrNotOpen ();
  176. DateTime start = DateTime.Now;
  177. if (queue.Count > 0)
  178. return queue.Dequeue ();
  179. receive_handle.WaitOne ();
  180. return queue.Dequeue ();
  181. }
  182. public override bool WaitForMessage (TimeSpan timeout)
  183. {
  184. ThrowIfDisposedOrNotOpen ();
  185. throw new NotImplementedException ();
  186. }
  187. // CommunicationObject
  188. protected override void OnAbort ()
  189. {
  190. if (client_factory != null) {
  191. client_factory.Abort ();
  192. client_factory = null;
  193. }
  194. OnClose (TimeSpan.Zero);
  195. }
  196. protected override void OnClose (TimeSpan timeout)
  197. {
  198. DateTime start = DateTime.Now;
  199. if (client_factory != null)
  200. client_factory.Close (timeout - (DateTime.Now - start));
  201. peers.Clear ();
  202. resolver.Unregister (node.RegisteredId, timeout - (DateTime.Now - start));
  203. node.SetOffline ();
  204. if (listener_host != null)
  205. listener_host.Close (timeout - (DateTime.Now - start));
  206. node.RegisteredId = null;
  207. }
  208. protected override void OnOpen (TimeSpan timeout)
  209. {
  210. DateTime start = DateTime.Now;
  211. // FIXME: supply maxAddresses
  212. foreach (var a in resolver.Resolve (node.MeshId, 3, timeout))
  213. peers.Add (new RemotePeerConnection (a));
  214. // FIXME: pass more configuration
  215. var binding = new NetTcpBinding ();
  216. binding.Security.Mode = SecurityMode.None;
  217. int port = 0;
  218. var rnd = new Random ();
  219. for (int i = 0; i < 1000; i++) {
  220. if (DateTime.Now - start > timeout)
  221. throw new TimeoutException ();
  222. try {
  223. port = rnd.Next (50000, 51000);
  224. var t = new TcpListener (port);
  225. t.Start ();
  226. t.Stop ();
  227. break;
  228. } catch (SocketException) {
  229. continue;
  230. }
  231. }
  232. string name = Dns.GetHostName ();
  233. var uri = new Uri ("net.tcp://" + name + ":" + port + "/PeerChannelEndpoints/" + Guid.NewGuid ());
  234. var peer_receiver = new LocalPeerReceiver (this);
  235. listener_host = new ServiceHost (peer_receiver);
  236. var sba = listener_host.Description.Behaviors.Find<ServiceBehaviorAttribute> ();
  237. sba.InstanceContextMode = InstanceContextMode.Single;
  238. sba.IncludeExceptionDetailInFaults = true;
  239. var se = listener_host.AddServiceEndpoint (typeof (IPeerReceiverContract), binding, "net.p2p://" + node.MeshId);
  240. se.ListenUri = uri;
  241. listener_host.Open (timeout - (DateTime.Now - start));
  242. var nid = new Random ().Next (0, int.MaxValue);
  243. var ea = new EndpointAddress (uri);
  244. var pna = new PeerNodeAddress (ea, new ReadOnlyCollection<IPAddress> (Dns.GetHostEntry (name).AddressList));
  245. node.RegisteredId = resolver.Register (node.MeshId, pna, timeout - (DateTime.Now - start));
  246. node.NodeId = nid;
  247. // Add itself to the local list as well.
  248. // FIXME: it might become unnecessary once it implemented new node registration from peer resolver service.
  249. peers.Add (new RemotePeerConnection (pna));
  250. node.SetOnline ();
  251. }
  252. }
  253. }