PmpNatDevice.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. using System.Threading.Tasks;
  33. namespace Mono.Nat.Pmp
  34. {
  35. internal sealed class PmpNatDevice : AbstractNatDevice, IEquatable<PmpNatDevice>
  36. {
  37. private IPAddress localAddress;
  38. private IPAddress publicAddress;
  39. internal PmpNatDevice(IPAddress localAddress, IPAddress publicAddress)
  40. {
  41. this.localAddress = localAddress;
  42. this.publicAddress = publicAddress;
  43. }
  44. public override IPAddress LocalAddress
  45. {
  46. get { return localAddress; }
  47. }
  48. public override Task CreatePortMap(Mapping mapping)
  49. {
  50. return InternalCreatePortMapAsync(mapping, true);
  51. }
  52. public override bool Equals(object obj)
  53. {
  54. PmpNatDevice device = obj as PmpNatDevice;
  55. return (device == null) ? false : this.Equals(device);
  56. }
  57. public override int GetHashCode()
  58. {
  59. return this.publicAddress.GetHashCode();
  60. }
  61. public bool Equals(PmpNatDevice other)
  62. {
  63. return (other == null) ? false : this.publicAddress.Equals(other.publicAddress);
  64. }
  65. private async Task<Mapping> InternalCreatePortMapAsync(Mapping mapping, bool create)
  66. {
  67. var package = new List<byte>();
  68. package.Add(PmpConstants.Version);
  69. package.Add(mapping.Protocol == Protocol.Tcp ? PmpConstants.OperationCodeTcp : PmpConstants.OperationCodeUdp);
  70. package.Add(0); //reserved
  71. package.Add(0); //reserved
  72. package.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)mapping.PrivatePort)));
  73. package.AddRange(
  74. BitConverter.GetBytes(create ? IPAddress.HostToNetworkOrder((short)mapping.PublicPort) : (short)0));
  75. package.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(mapping.Lifetime)));
  76. try
  77. {
  78. byte[] buffer = package.ToArray();
  79. int attempt = 0;
  80. int delay = PmpConstants.RetryDelay;
  81. using (var udpClient = new UdpClient())
  82. {
  83. var cancellationTokenSource = new CancellationTokenSource();
  84. while (attempt < PmpConstants.RetryAttempts)
  85. {
  86. await udpClient.SendAsync(buffer, buffer.Length,
  87. new IPEndPoint(LocalAddress, PmpConstants.ServerPort));
  88. if (attempt == 0)
  89. {
  90. Task.Run(() => CreatePortMapListen(udpClient, mapping, cancellationTokenSource.Token));
  91. }
  92. attempt++;
  93. delay *= 2;
  94. await Task.Delay(delay).ConfigureAwait(false);
  95. }
  96. cancellationTokenSource.Cancel();
  97. }
  98. }
  99. catch (OperationCanceledException)
  100. {
  101. }
  102. catch (Exception e)
  103. {
  104. string type = create ? "create" : "delete";
  105. string message = String.Format("Failed to {0} portmap (protocol={1}, private port={2}) {3}",
  106. type,
  107. mapping.Protocol,
  108. mapping.PrivatePort,
  109. e.Message);
  110. NatUtility.Log(message);
  111. var pmpException = e as MappingException;
  112. throw new MappingException(message, pmpException);
  113. }
  114. return mapping;
  115. }
  116. private async void CreatePortMapListen(UdpClient udpClient, Mapping mapping, CancellationToken cancellationToken)
  117. {
  118. while (!cancellationToken.IsCancellationRequested)
  119. {
  120. try
  121. {
  122. var result = await udpClient.ReceiveAsync().ConfigureAwait(false);
  123. var endPoint = result.RemoteEndPoint;
  124. byte[] data = data = result.Buffer;
  125. if (data.Length < 16)
  126. continue;
  127. if (data[0] != PmpConstants.Version)
  128. continue;
  129. var opCode = (byte)(data[1] & 127);
  130. var protocol = Protocol.Tcp;
  131. if (opCode == PmpConstants.OperationCodeUdp)
  132. protocol = Protocol.Udp;
  133. short resultCode = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 2));
  134. int epoch = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(data, 4));
  135. short privatePort = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 8));
  136. short publicPort = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data, 10));
  137. var lifetime = (uint)IPAddress.NetworkToHostOrder(BitConverter.ToInt32(data, 12));
  138. if (privatePort < 0 || publicPort < 0 || resultCode != PmpConstants.ResultCodeSuccess)
  139. {
  140. var errors = new[]
  141. {
  142. "Success",
  143. "Unsupported Version",
  144. "Not Authorized/Refused (e.g. box supports mapping, but user has turned feature off)"
  145. ,
  146. "Network Failure (e.g. NAT box itself has not obtained a DHCP lease)",
  147. "Out of resources (NAT box cannot create any more mappings at this time)",
  148. "Unsupported opcode"
  149. };
  150. var errorMsg = errors[resultCode];
  151. NatUtility.Log("Error in CreatePortMapListen: " + errorMsg);
  152. return;
  153. }
  154. if (lifetime == 0) return; //mapping was deleted
  155. //mapping was created
  156. //TODO: verify that the private port+protocol are a match
  157. mapping.PublicPort = publicPort;
  158. mapping.Protocol = protocol;
  159. mapping.Expiration = DateTime.Now.AddSeconds(lifetime);
  160. return;
  161. }
  162. catch (Exception ex)
  163. {
  164. NatUtility.Logger.ErrorException("Error in CreatePortMapListen", ex);
  165. return;
  166. }
  167. }
  168. }
  169. /// <summary>
  170. /// Overridden.
  171. /// </summary>
  172. /// <returns></returns>
  173. public override string ToString()
  174. {
  175. return String.Format("PmpNatDevice - Local Address: {0}, Public IP: {1}, Last Seen: {2}",
  176. this.localAddress, this.publicAddress, this.LastSeen);
  177. }
  178. }
  179. }