2
0

PmpNatDevice.cs 8.2 KB

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