PmpNatDevice.cs 8.3 KB

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