PmpNatDevice.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. //
  2. // Authors:
  3. // Ben Motmans <ben.motmans@gmail.com>
  4. //
  5. // Copyright (C) 2007 Ben Motmans
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining
  8. // a copy of this software and associated documentation files (the
  9. // "Software"), to deal in the Software without restriction, including
  10. // without limitation the rights to use, copy, modify, merge, publish,
  11. // distribute, sublicense, and/or sell copies of the Software, and to
  12. // permit persons to whom the Software is furnished to do so, subject to
  13. // the following conditions:
  14. //
  15. // The above copyright notice and this permission notice shall be
  16. // included in all copies or substantial portions of the Software.
  17. //
  18. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  19. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  20. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  21. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  22. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  23. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  24. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  25. //
  26. using System;
  27. using System.IO;
  28. using System.Net;
  29. using System.Net.Sockets;
  30. using System.Threading;
  31. using System.Collections.Generic;
  32. namespace Mono.Nat.Pmp
  33. {
  34. internal sealed class PmpNatDevice : AbstractNatDevice, IEquatable<PmpNatDevice>
  35. {
  36. private AsyncResult externalIpResult;
  37. private bool pendingOp;
  38. private IPAddress localAddress;
  39. private IPAddress publicAddress;
  40. internal PmpNatDevice (IPAddress localAddress, IPAddress publicAddress)
  41. {
  42. this.localAddress = localAddress;
  43. this.publicAddress = publicAddress;
  44. }
  45. public override IPAddress LocalAddress
  46. {
  47. get { return localAddress; }
  48. }
  49. public override IPAddress GetExternalIP ()
  50. {
  51. return publicAddress;
  52. }
  53. public override IAsyncResult BeginCreatePortMap(Mapping mapping, AsyncCallback callback, object asyncState)
  54. {
  55. PortMapAsyncResult pmar = new PortMapAsyncResult (mapping.Protocol, mapping.PublicPort, PmpConstants.DefaultLeaseTime, callback, asyncState);
  56. ThreadPool.QueueUserWorkItem (delegate
  57. {
  58. try
  59. {
  60. CreatePortMap(pmar.Mapping, true);
  61. pmar.Complete();
  62. }
  63. catch (Exception e)
  64. {
  65. pmar.Complete(e);
  66. }
  67. });
  68. return pmar;
  69. }
  70. public override IAsyncResult BeginDeletePortMap (Mapping mapping, AsyncCallback callback, object asyncState)
  71. {
  72. PortMapAsyncResult pmar = new PortMapAsyncResult (mapping, callback, asyncState);
  73. ThreadPool.QueueUserWorkItem (delegate {
  74. try {
  75. CreatePortMap(pmar.Mapping, false);
  76. pmar.Complete();
  77. } catch (Exception e) {
  78. pmar.Complete(e);
  79. }
  80. });
  81. return pmar;
  82. }
  83. public override void EndCreatePortMap (IAsyncResult result)
  84. {
  85. PortMapAsyncResult pmar = result as PortMapAsyncResult;
  86. pmar.AsyncWaitHandle.WaitOne ();
  87. }
  88. public override void EndDeletePortMap (IAsyncResult result)
  89. {
  90. PortMapAsyncResult pmar = result as PortMapAsyncResult;
  91. pmar.AsyncWaitHandle.WaitOne ();
  92. }
  93. public override IAsyncResult BeginGetAllMappings (AsyncCallback callback, object asyncState)
  94. {
  95. //NAT-PMP does not specify a way to get all port mappings
  96. throw new NotSupportedException ();
  97. }
  98. public override IAsyncResult BeginGetExternalIP (AsyncCallback callback, object asyncState)
  99. {
  100. StartOp(ref externalIpResult, callback, asyncState);
  101. AsyncResult result = externalIpResult;
  102. result.Complete();
  103. return result;
  104. }
  105. public override IAsyncResult BeginGetSpecificMapping (Protocol protocol, int port, AsyncCallback callback, object asyncState)
  106. {
  107. //NAT-PMP does not specify a way to get a specific port map
  108. throw new NotSupportedException ();
  109. }
  110. public override Mapping[] EndGetAllMappings (IAsyncResult result)
  111. {
  112. //NAT-PMP does not specify a way to get all port mappings
  113. throw new NotSupportedException ();
  114. }
  115. public override IPAddress EndGetExternalIP (IAsyncResult result)
  116. {
  117. EndOp(result, ref externalIpResult);
  118. return publicAddress;
  119. }
  120. private void StartOp(ref AsyncResult result, AsyncCallback callback, object asyncState)
  121. {
  122. if (pendingOp == true)
  123. throw new InvalidOperationException("Can only have one simultaenous async operation");
  124. pendingOp = true;
  125. result = new AsyncResult(callback, asyncState);
  126. }
  127. private void EndOp(IAsyncResult supplied, ref AsyncResult actual)
  128. {
  129. if (supplied == null)
  130. throw new ArgumentNullException("result");
  131. if (supplied != actual)
  132. throw new ArgumentException("Supplied IAsyncResult does not match the stored result");
  133. if (!supplied.IsCompleted)
  134. supplied.AsyncWaitHandle.WaitOne();
  135. if (actual.StoredException != null)
  136. throw actual.StoredException;
  137. pendingOp = false;
  138. actual = null;
  139. }
  140. public override Mapping EndGetSpecificMapping (IAsyncResult result)
  141. {
  142. //NAT-PMP does not specify a way to get a specific port map
  143. throw new NotSupportedException ();
  144. }
  145. public override bool Equals(object obj)
  146. {
  147. PmpNatDevice device = obj as PmpNatDevice;
  148. return (device == null) ? false : this.Equals(device);
  149. }
  150. public override int GetHashCode ()
  151. {
  152. return this.publicAddress.GetHashCode();
  153. }
  154. public bool Equals (PmpNatDevice other)
  155. {
  156. return (other == null) ? false : this.publicAddress.Equals(other.publicAddress);
  157. }
  158. private Mapping CreatePortMap (Mapping mapping, bool create)
  159. {
  160. List<byte> package = new List<byte> ();
  161. package.Add (PmpConstants.Version);
  162. package.Add (mapping.Protocol == Protocol.Tcp ? PmpConstants.OperationCodeTcp : PmpConstants.OperationCodeUdp);
  163. package.Add ((byte)0); //reserved
  164. package.Add ((byte)0); //reserved
  165. package.AddRange (BitConverter.GetBytes (IPAddress.HostToNetworkOrder((short)mapping.PrivatePort)));
  166. package.AddRange (BitConverter.GetBytes (create ? IPAddress.HostToNetworkOrder((short)mapping.PublicPort) : (short)0));
  167. package.AddRange (BitConverter.GetBytes (IPAddress.HostToNetworkOrder(mapping.Lifetime)));
  168. CreatePortMapAsyncState state = new CreatePortMapAsyncState ();
  169. state.Buffer = package.ToArray ();
  170. state.Mapping = mapping;
  171. ThreadPool.QueueUserWorkItem (new WaitCallback (CreatePortMapAsync), state);
  172. WaitHandle.WaitAll (new WaitHandle[] {state.ResetEvent});
  173. if (!state.Success) {
  174. string type = create ? "create" : "delete";
  175. throw new MappingException (String.Format ("Failed to {0} portmap (protocol={1}, private port={2}", type, mapping.Protocol, mapping.PrivatePort));
  176. }
  177. return state.Mapping;
  178. }
  179. private void CreatePortMapAsync (object obj)
  180. {
  181. CreatePortMapAsyncState state = obj as CreatePortMapAsyncState;
  182. UdpClient udpClient = new UdpClient ();
  183. CreatePortMapListenState listenState = new CreatePortMapListenState (state, udpClient);
  184. int attempt = 0;
  185. int delay = PmpConstants.RetryDelay;
  186. ThreadPool.QueueUserWorkItem (new WaitCallback (CreatePortMapListen), listenState);
  187. while (attempt < PmpConstants.RetryAttempts && !listenState.Success) {
  188. udpClient.Send (state.Buffer, state.Buffer.Length, new IPEndPoint (localAddress, PmpConstants.ServerPort));
  189. listenState.UdpClientReady.Set();
  190. attempt++;
  191. delay *= 2;
  192. Thread.Sleep (delay);
  193. }
  194. state.Success = listenState.Success;
  195. udpClient.Close ();
  196. state.ResetEvent.Set ();
  197. }
  198. private void CreatePortMapListen (object obj)
  199. {
  200. CreatePortMapListenState state = obj as CreatePortMapListenState;
  201. UdpClient udpClient = state.UdpClient;
  202. state.UdpClientReady.WaitOne(); // Evidently UdpClient has some lazy-init Send/Receive race?
  203. IPEndPoint endPoint = new IPEndPoint (localAddress, PmpConstants.ServerPort);
  204. while (!state.Success)
  205. {
  206. byte[] data;
  207. try
  208. {
  209. data = udpClient.Receive(ref endPoint);
  210. }
  211. catch (SocketException)
  212. {
  213. state.Success = false;
  214. return;
  215. }
  216. catch (ObjectDisposedException)
  217. {
  218. state.Success = false;
  219. return;
  220. }
  221. if (data.Length < 16)
  222. continue;
  223. if (data[0] != PmpConstants.Version)
  224. continue;
  225. byte opCode = (byte)(data[1] & (byte)127);
  226. Protocol protocol = Protocol.Tcp;
  227. if (opCode == PmpConstants.OperationCodeUdp)
  228. protocol = Protocol.Udp;
  229. short resultCode = IPAddress.NetworkToHostOrder (BitConverter.ToInt16 (data, 2));
  230. uint epoch = (uint)IPAddress.NetworkToHostOrder (BitConverter.ToInt32 (data, 4));
  231. int privatePort = IPAddress.NetworkToHostOrder (BitConverter.ToInt16 (data, 8));
  232. int publicPort = IPAddress.NetworkToHostOrder (BitConverter.ToInt16 (data, 10));
  233. uint lifetime = (uint)IPAddress.NetworkToHostOrder (BitConverter.ToInt32 (data, 12));
  234. if (publicPort < 0 || privatePort < 0 || resultCode != PmpConstants.ResultCodeSuccess)
  235. {
  236. state.Success = false;
  237. return;
  238. }
  239. if (lifetime == 0)
  240. {
  241. //mapping was deleted
  242. state.Success = true;
  243. state.Mapping = null;
  244. return;
  245. }
  246. else
  247. {
  248. //mapping was created
  249. //TODO: verify that the private port+protocol are a match
  250. Mapping mapping = state.Mapping;
  251. mapping.PublicPort = publicPort;
  252. mapping.Protocol = protocol;
  253. mapping.Expiration = DateTime.Now.AddSeconds (lifetime);
  254. state.Success = true;
  255. }
  256. }
  257. }
  258. /// <summary>
  259. /// Overridden.
  260. /// </summary>
  261. /// <returns></returns>
  262. public override string ToString( )
  263. {
  264. return String.Format( "PmpNatDevice - Local Address: {0}, Public IP: {1}, Last Seen: {2}",
  265. this.localAddress, this.publicAddress, this.LastSeen );
  266. }
  267. private class CreatePortMapAsyncState
  268. {
  269. internal byte[] Buffer;
  270. internal ManualResetEvent ResetEvent = new ManualResetEvent (false);
  271. internal Mapping Mapping;
  272. internal bool Success;
  273. }
  274. private class CreatePortMapListenState
  275. {
  276. internal volatile bool Success;
  277. internal Mapping Mapping;
  278. internal UdpClient UdpClient;
  279. internal ManualResetEvent UdpClientReady;
  280. internal CreatePortMapListenState (CreatePortMapAsyncState state, UdpClient client)
  281. {
  282. Mapping = state.Mapping;
  283. UdpClient = client; UdpClientReady = new ManualResetEvent(false);
  284. }
  285. }
  286. }
  287. }