PmpSearcher.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. //
  2. // Authors:
  3. // Alan McGovern alan.mcgovern@gmail.com
  4. // Ben Motmans <ben.motmans@gmail.com>
  5. // Nicholas Terry <nick.i.terry@gmail.com>
  6. //
  7. // Copyright (C) 2006 Alan McGovern
  8. // Copyright (C) 2007 Ben Motmans
  9. // Copyright (C) 2014 Nicholas Terry
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System;
  31. using System.Collections.Generic;
  32. using System.Text;
  33. using System.Net;
  34. using Mono.Nat.Pmp;
  35. using System.Net.NetworkInformation;
  36. using System.Net.Sockets;
  37. using System.Threading.Tasks;
  38. using Microsoft.Extensions.Logging;
  39. using System.Linq;
  40. namespace Mono.Nat
  41. {
  42. internal class PmpSearcher : ISearcher, IDisposable
  43. {
  44. private ILogger _logger;
  45. private int timeout = 250;
  46. private DateTime nextSearch;
  47. public event EventHandler<DeviceEventArgs> DeviceFound;
  48. public PmpSearcher(ILogger logger)
  49. {
  50. _logger = logger;
  51. CreateSocketsAndAddGateways();
  52. }
  53. public void Dispose()
  54. {
  55. var list = sockets.ToList();
  56. sockets.Clear();
  57. foreach (var s in list)
  58. {
  59. using (s)
  60. {
  61. s.Close();
  62. }
  63. }
  64. }
  65. private List<UdpClient> sockets;
  66. private Dictionary<UdpClient, List<IPEndPoint>> gatewayLists;
  67. private void CreateSocketsAndAddGateways()
  68. {
  69. sockets = new List<UdpClient>();
  70. gatewayLists = new Dictionary<UdpClient, List<IPEndPoint>>();
  71. try
  72. {
  73. foreach (var n in NetworkInterface.GetAllNetworkInterfaces())
  74. {
  75. if (n.OperationalStatus != OperationalStatus.Up && n.OperationalStatus != OperationalStatus.Unknown)
  76. continue;
  77. IPInterfaceProperties properties = n.GetIPProperties();
  78. var gatewayList = new List<IPEndPoint>();
  79. foreach (GatewayIPAddressInformation gateway in properties.GatewayAddresses)
  80. {
  81. if (gateway.Address.AddressFamily == AddressFamily.InterNetwork)
  82. {
  83. gatewayList.Add(new IPEndPoint(gateway.Address, PmpConstants.ServerPort));
  84. }
  85. }
  86. if (gatewayList.Count == 0)
  87. {
  88. /* Mono on OSX doesn't give any gateway addresses, so check DNS entries */
  89. foreach (var gw2 in properties.DnsAddresses)
  90. {
  91. if (gw2.AddressFamily == AddressFamily.InterNetwork)
  92. {
  93. gatewayList.Add(new IPEndPoint(gw2, PmpConstants.ServerPort));
  94. }
  95. }
  96. foreach (UnicastIPAddressInformation unicast in properties.UnicastAddresses)
  97. {
  98. if (/*unicast.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred
  99. && unicast.AddressPreferredLifetime != UInt32.MaxValue
  100. && */unicast.Address.AddressFamily == AddressFamily.InterNetwork)
  101. {
  102. var bytes = unicast.Address.GetAddressBytes();
  103. bytes[3] = 1;
  104. gatewayList.Add(new IPEndPoint(new IPAddress(bytes), PmpConstants.ServerPort));
  105. }
  106. }
  107. }
  108. if (gatewayList.Count > 0)
  109. {
  110. foreach (var address in properties.UnicastAddresses)
  111. {
  112. if (address.Address.AddressFamily == AddressFamily.InterNetwork)
  113. {
  114. UdpClient client;
  115. try
  116. {
  117. client = new UdpClient(new IPEndPoint(address.Address, 0));
  118. }
  119. catch (SocketException)
  120. {
  121. continue; // Move on to the next address.
  122. }
  123. gatewayLists.Add(client, gatewayList);
  124. sockets.Add(client);
  125. }
  126. }
  127. }
  128. }
  129. }
  130. catch (Exception)
  131. {
  132. // NAT-PMP does not use multicast, so there isn't really a good fallback.
  133. }
  134. }
  135. public async void Search()
  136. {
  137. foreach (UdpClient s in sockets)
  138. {
  139. try
  140. {
  141. await Search(s).ConfigureAwait(false);
  142. }
  143. catch
  144. {
  145. // Ignore any search errors
  146. }
  147. }
  148. }
  149. async Task Search(UdpClient client)
  150. {
  151. // Sort out the time for the next search first. The spec says the
  152. // timeout should double after each attempt. Once it reaches 64 seconds
  153. // (and that attempt fails), assume no devices available
  154. nextSearch = DateTime.Now.AddMilliseconds(timeout);
  155. timeout *= 2;
  156. // We've tried 9 times as per spec, try searching again in 5 minutes
  157. if (timeout == 128 * 1000)
  158. {
  159. timeout = 250;
  160. nextSearch = DateTime.Now.AddMinutes(10);
  161. return;
  162. }
  163. // The nat-pmp search message. Must be sent to GatewayIP:53531
  164. byte[] buffer = new byte[] { PmpConstants.Version, PmpConstants.OperationCode };
  165. foreach (IPEndPoint gatewayEndpoint in gatewayLists[client])
  166. {
  167. await client.SendAsync(buffer, buffer.Length, gatewayEndpoint).ConfigureAwait(false);
  168. }
  169. }
  170. bool IsSearchAddress(IPAddress address)
  171. {
  172. foreach (var gatewayList in gatewayLists.Values)
  173. foreach (var gatewayEndpoint in gatewayList)
  174. if (gatewayEndpoint.Address.Equals(address))
  175. return true;
  176. return false;
  177. }
  178. public void Handle(IPAddress localAddress, byte[] response, IPEndPoint endpoint)
  179. {
  180. if (!IsSearchAddress(endpoint.Address))
  181. return;
  182. if (response.Length != 12)
  183. return;
  184. if (response[0] != PmpConstants.Version)
  185. return;
  186. if (response[1] != PmpConstants.ServerNoop)
  187. return;
  188. int errorcode = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(response, 2));
  189. if (errorcode != 0)
  190. _logger.LogDebug("Non zero error: {0}", errorcode);
  191. var publicIp = new IPAddress(new byte[] { response[8], response[9], response[10], response[11] });
  192. nextSearch = DateTime.Now.AddMinutes(5);
  193. timeout = 250;
  194. OnDeviceFound(new DeviceEventArgs(new PmpNatDevice(endpoint.Address, publicIp, _logger)));
  195. }
  196. public DateTime NextSearch
  197. {
  198. get { return nextSearch; }
  199. }
  200. private void OnDeviceFound(DeviceEventArgs args)
  201. {
  202. if (DeviceFound != null)
  203. DeviceFound(this, args);
  204. }
  205. public NatProtocol Protocol
  206. {
  207. get { return NatProtocol.Pmp; }
  208. }
  209. }
  210. }