PeerDuplexChannel.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. using System.Xml;
  41. namespace System.ServiceModel.Channels
  42. {
  43. // PeerDuplexChannel can be created either from PeerChannelFactory
  44. // (as IOutputChannel) or PeerChannelListener (as IInputChannel).
  45. //
  46. // PeerNode has to be created before Open() (at least at client side).
  47. // On open, it tries to resolve the nodes in the mesh (and do something
  48. // - but what?). Then registers itself to the mesh and refreshes it.
  49. internal class PeerDuplexChannel : DuplexChannelBase
  50. {
  51. enum RemotePeerStatus
  52. {
  53. None,
  54. Connected,
  55. Error,
  56. }
  57. class RemotePeerConnection
  58. {
  59. public RemotePeerConnection (PeerNodeAddress address)
  60. {
  61. Address = address;
  62. }
  63. public PeerNodeAddress Address { get; private set; }
  64. public RemotePeerStatus Status { get; set; }
  65. public LocalPeerReceiver Instance { get; set; }
  66. public IPeerConnectorClient Channel { get; set; }
  67. public ulong NodeId { get; set; }
  68. }
  69. class LocalPeerReceiver : IPeerConnectorContract
  70. {
  71. List<PeerNodeAddress> connections = new List<PeerNodeAddress> ();
  72. AutoResetEvent connect_handle = new AutoResetEvent (false);
  73. public event Action<WelcomeInfo> WelcomeReceived;
  74. public LocalPeerReceiver (PeerDuplexChannel owner)
  75. {
  76. this.owner = owner;
  77. }
  78. PeerDuplexChannel owner;
  79. public void Connect (ConnectInfo connect)
  80. {
  81. if (connect == null)
  82. throw new ArgumentNullException ("connect");
  83. var ch = OperationContext.Current.GetCallbackChannel<IPeerConnectorContract> ();
  84. connections.Add (connect.Address);
  85. // FIXME: check and reject if inappropriate. For example, maximum connection exceeded.
  86. using (var octx = new OperationContextScope ((IContextChannel) ch)) {
  87. OperationContext.Current.OutgoingMessageHeaders.To = new Uri (Constants.WsaAnonymousUri);
  88. ch.Welcome (new WelcomeInfo () { NodeId = owner.node.NodeId });
  89. }
  90. }
  91. internal void WaitForConnectResponse (TimeSpan timeout)
  92. {
  93. Console.WriteLine ("##### Waiting for Welcome or Reject ...");
  94. if (!connect_handle.WaitOne (timeout))
  95. throw new TimeoutException ();
  96. }
  97. public void Disconnect (DisconnectInfo disconnect)
  98. {
  99. if (disconnect == null)
  100. throw new ArgumentNullException ("disconnect");
  101. // Console.WriteLine ("DisconnectInfo.Reason: " + disconnect.Reason);
  102. // FIXME: handle disconnection in practice. So far I see nothing to do.
  103. }
  104. public void Welcome (WelcomeInfo welcome)
  105. {
  106. Console.WriteLine ("##### Welcome message received");
  107. if (WelcomeReceived != null)
  108. WelcomeReceived (welcome);
  109. connect_handle.Set ();
  110. }
  111. public void Refuse (RefuseInfo refuse)
  112. {
  113. // FIXME: it should not probably actually throw an error.
  114. connect_handle.Set ();
  115. throw new InvalidOperationException ("Peer connection was refused");
  116. }
  117. public void LinkUtility (LinkUtilityInfo linkUtility)
  118. {
  119. throw new NotImplementedException ();
  120. }
  121. public void Ping ()
  122. {
  123. throw new NotImplementedException ();
  124. }
  125. public void SendMessage (Message msg)
  126. {
  127. Console.WriteLine ("##### non-connector message received: " + msg.Headers.Action);
  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. ChannelFactory<IPeerConnectorClient> channel_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. if (channel_factory == null) {
  181. var binding = new NetTcpBinding ();
  182. binding.Security.Mode = SecurityMode.None;
  183. channel_factory = new DuplexChannelFactory<IPeerConnectorClient> (conn.Instance, binding);
  184. }
  185. return channel_factory.CreateChannel (new EndpointAddress ("net.p2p://" + node.MeshId + "/"), conn.Address.EndpointAddress.Uri);
  186. }
  187. public override void Send (Message message, TimeSpan timeout)
  188. {
  189. ThrowIfDisposedOrNotOpen ();
  190. DateTime start = DateTime.Now;
  191. // FIXME: give max buffer size
  192. var mb = message.CreateBufferedCopy (0x10000);
  193. foreach (var pc in peers) {
  194. message = mb.CreateMessage ();
  195. if (pc.Status == RemotePeerStatus.None) {
  196. pc.Status = RemotePeerStatus.Error; // prepare for cases that it resulted in an error in the middle.
  197. var inner = CreateInnerClient (pc);
  198. pc.Channel = inner;
  199. inner.Open (timeout - (DateTime.Now - start));
  200. inner.OperationTimeout = timeout - (DateTime.Now - start);
  201. inner.Connect (new ConnectInfo () { Address = local_node_address, NodeId = (uint) node.NodeId });
  202. pc.Instance.WaitForConnectResponse (timeout - (DateTime.Now - start));
  203. pc.Status = RemotePeerStatus.Connected;
  204. }
  205. pc.Channel.OperationTimeout = timeout - (DateTime.Now - start);
  206. // see [MC-PRCH] 3.2.4.1
  207. if (message.Headers.MessageId == null)
  208. message.Headers.MessageId = new UniqueId ();
  209. message.Headers.Add (MessageHeader.CreateHeader ("PeerTo", Constants.NetPeer, RemoteAddress.Uri));
  210. message.Headers.Add (MessageHeader.CreateHeader ("PeerVia", Constants.NetPeer, RemoteAddress.Uri));
  211. message.Headers.Add (MessageHeader.CreateHeader ("FloodMessage", Constants.NetPeer, "PeerFlooder"));
  212. pc.Channel.SendMessage (message);
  213. }
  214. }
  215. internal void EnqueueMessage (Message message)
  216. {
  217. queue.Enqueue (message);
  218. receive_handle.Set ();
  219. }
  220. Queue<Message> queue = new Queue<Message> ();
  221. AutoResetEvent receive_handle = new AutoResetEvent (false);
  222. public override Message Receive (TimeSpan timeout)
  223. {
  224. ThrowIfDisposedOrNotOpen ();
  225. DateTime start = DateTime.Now;
  226. if (queue.Count > 0)
  227. return queue.Dequeue ();
  228. receive_handle.WaitOne ();
  229. return queue.Dequeue ();
  230. }
  231. public override bool WaitForMessage (TimeSpan timeout)
  232. {
  233. ThrowIfDisposedOrNotOpen ();
  234. throw new NotImplementedException ();
  235. }
  236. // CommunicationObject
  237. protected override void OnAbort ()
  238. {
  239. if (client_factory != null) {
  240. client_factory.Abort ();
  241. client_factory = null;
  242. }
  243. OnClose (TimeSpan.Zero);
  244. }
  245. protected override void OnClose (TimeSpan timeout)
  246. {
  247. DateTime start = DateTime.Now;
  248. if (client_factory != null)
  249. client_factory.Close (timeout - (DateTime.Now - start));
  250. peers.Clear ();
  251. resolver.Unregister (node.RegisteredId, timeout - (DateTime.Now - start));
  252. node.SetOffline ();
  253. if (listener_host != null)
  254. listener_host.Close (timeout - (DateTime.Now - start));
  255. node.RegisteredId = null;
  256. }
  257. protected override void OnOpen (TimeSpan timeout)
  258. {
  259. DateTime start = DateTime.Now;
  260. // FIXME: supply maxAddresses
  261. foreach (var a in resolver.Resolve (node.MeshId, 3, timeout))
  262. peers.Add (new RemotePeerConnection (a));
  263. // FIXME: pass more configuration
  264. var binding = new NetTcpBinding ();
  265. binding.Security.Mode = SecurityMode.None;
  266. int port = 0;
  267. var rnd = new Random ();
  268. for (int i = 0; i < 1000; i++) {
  269. if (DateTime.Now - start > timeout)
  270. throw new TimeoutException ();
  271. try {
  272. port = rnd.Next (50000, 51000);
  273. var t = new TcpListener (port);
  274. t.Start ();
  275. t.Stop ();
  276. break;
  277. } catch (SocketException) {
  278. continue;
  279. }
  280. }
  281. string name = Dns.GetHostName ();
  282. var uri = new Uri ("net.tcp://" + name + ":" + port + "/PeerChannelEndpoints/" + Guid.NewGuid ());
  283. var peer_receiver = new LocalPeerReceiver (this);
  284. listener_host = new ServiceHost (peer_receiver);
  285. var sba = listener_host.Description.Behaviors.Find<ServiceBehaviorAttribute> ();
  286. sba.InstanceContextMode = InstanceContextMode.Single;
  287. sba.IncludeExceptionDetailInFaults = true;
  288. var se = listener_host.AddServiceEndpoint (typeof (IPeerConnectorContract).FullName, binding, "net.p2p://" + node.MeshId + "/");
  289. se.ListenUri = uri;
  290. // FIXME: remove debugging code
  291. listener_host.UnknownMessageReceived += delegate (object obj, UnknownMessageReceivedEventArgs earg) { Console.WriteLine ("%%%%% UNKOWN MESSAGE " + earg.Message); };
  292. listener_host.Open (timeout - (DateTime.Now - start));
  293. var nid = (ulong) new Random ().Next (0, int.MaxValue);
  294. var ea = new EndpointAddress (uri);
  295. var pna = new PeerNodeAddress (ea, new ReadOnlyCollection<IPAddress> (Dns.GetHostEntry (name).AddressList));
  296. local_node_address = pna;
  297. node.RegisteredId = resolver.Register (node.MeshId, pna, timeout - (DateTime.Now - start));
  298. node.NodeId = nid;
  299. // Add itself to the local list as well.
  300. // FIXME: it might become unnecessary once it implemented new node registration from peer resolver service.
  301. peers.Add (new RemotePeerConnection (pna));
  302. node.SetOnline ();
  303. }
  304. }
  305. }