PmpSearcher.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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.Linq;
  38. using System.Threading.Tasks;
  39. namespace Mono.Nat
  40. {
  41. internal class PmpSearcher : ISearcher
  42. {
  43. static PmpSearcher instance = new PmpSearcher();
  44. public static PmpSearcher Instance
  45. {
  46. get { return instance; }
  47. }
  48. private int timeout;
  49. private DateTime nextSearch;
  50. public event EventHandler<DeviceEventArgs> DeviceFound;
  51. public event EventHandler<DeviceEventArgs> DeviceLost;
  52. static PmpSearcher()
  53. {
  54. CreateSocketsAndAddGateways();
  55. }
  56. public static List<UdpClient> sockets;
  57. protected static Dictionary<UdpClient, List<IPEndPoint>> gatewayLists;
  58. internal static void CreateSocketsAndAddGateways()
  59. {
  60. sockets = new List<UdpClient>();
  61. gatewayLists = new Dictionary<UdpClient, List<IPEndPoint>>();
  62. try
  63. {
  64. foreach (NetworkInterface n in NetworkInterface.GetAllNetworkInterfaces())
  65. {
  66. if (n.OperationalStatus != OperationalStatus.Up && n.OperationalStatus != OperationalStatus.Unknown)
  67. continue;
  68. IPInterfaceProperties properties = n.GetIPProperties();
  69. List<IPEndPoint> gatewayList = new List<IPEndPoint>();
  70. foreach (GatewayIPAddressInformation gateway in properties.GatewayAddresses)
  71. {
  72. if (gateway.Address.AddressFamily == AddressFamily.InterNetwork)
  73. {
  74. gatewayList.Add(new IPEndPoint(gateway.Address, PmpConstants.ServerPort));
  75. }
  76. }
  77. if (gatewayList.Count == 0)
  78. {
  79. /* Mono on OSX doesn't give any gateway addresses, so check DNS entries */
  80. foreach (var gw2 in properties.DnsAddresses)
  81. {
  82. if (gw2.AddressFamily == AddressFamily.InterNetwork)
  83. {
  84. gatewayList.Add(new IPEndPoint(gw2, PmpConstants.ServerPort));
  85. }
  86. }
  87. foreach (var unicast in properties.UnicastAddresses)
  88. {
  89. if (/*unicast.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred
  90. && unicast.AddressPreferredLifetime != UInt32.MaxValue
  91. && */unicast.Address.AddressFamily == AddressFamily.InterNetwork)
  92. {
  93. var bytes = unicast.Address.GetAddressBytes();
  94. bytes[3] = 1;
  95. gatewayList.Add(new IPEndPoint(new IPAddress(bytes), PmpConstants.ServerPort));
  96. }
  97. }
  98. }
  99. if (gatewayList.Count > 0)
  100. {
  101. foreach (UnicastIPAddressInformation address in properties.UnicastAddresses)
  102. {
  103. if (address.Address.AddressFamily == AddressFamily.InterNetwork)
  104. {
  105. UdpClient client;
  106. try
  107. {
  108. client = new UdpClient(new IPEndPoint(address.Address, 0));
  109. }
  110. catch (SocketException)
  111. {
  112. continue; // Move on to the next address.
  113. }
  114. gatewayLists.Add(client, gatewayList);
  115. sockets.Add(client);
  116. }
  117. }
  118. }
  119. }
  120. }
  121. catch (Exception)
  122. {
  123. // NAT-PMP does not use multicast, so there isn't really a good fallback.
  124. }
  125. }
  126. PmpSearcher()
  127. {
  128. timeout = 250;
  129. }
  130. public async void Search()
  131. {
  132. foreach (UdpClient s in sockets)
  133. {
  134. try
  135. {
  136. await Search(s).ConfigureAwait(false);
  137. }
  138. catch
  139. {
  140. // Ignore any search errors
  141. }
  142. }
  143. }
  144. async Task Search (UdpClient client)
  145. {
  146. // Sort out the time for the next search first. The spec says the
  147. // timeout should double after each attempt. Once it reaches 64 seconds
  148. // (and that attempt fails), assume no devices available
  149. nextSearch = DateTime.Now.AddMilliseconds(timeout);
  150. timeout *= 2;
  151. // We've tried 9 times as per spec, try searching again in 5 minutes
  152. if (timeout == 128 * 1000)
  153. {
  154. timeout = 250;
  155. nextSearch = DateTime.Now.AddMinutes(10);
  156. return;
  157. }
  158. // The nat-pmp search message. Must be sent to GatewayIP:53531
  159. byte[] buffer = new byte[] { PmpConstants.Version, PmpConstants.OperationCode };
  160. foreach (IPEndPoint gatewayEndpoint in gatewayLists[client])
  161. {
  162. await client.SendAsync(buffer, buffer.Length, gatewayEndpoint).ConfigureAwait(false);
  163. }
  164. }
  165. bool IsSearchAddress(IPAddress address)
  166. {
  167. foreach (List<IPEndPoint> gatewayList in gatewayLists.Values)
  168. foreach (IPEndPoint gatewayEndpoint in gatewayList)
  169. if (gatewayEndpoint.Address.Equals(address))
  170. return true;
  171. return false;
  172. }
  173. public void Handle(IPAddress localAddress, byte[] response, IPEndPoint endpoint)
  174. {
  175. if (!IsSearchAddress(endpoint.Address))
  176. return;
  177. if (response.Length != 12)
  178. return;
  179. if (response[0] != PmpConstants.Version)
  180. return;
  181. if (response[1] != PmpConstants.ServerNoop)
  182. return;
  183. int errorcode = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(response, 2));
  184. if (errorcode != 0)
  185. NatUtility.Log("Non zero error: {0}", errorcode);
  186. IPAddress publicIp = new IPAddress(new byte[] { response[8], response[9], response[10], response[11] });
  187. nextSearch = DateTime.Now.AddMinutes(5);
  188. timeout = 250;
  189. OnDeviceFound(new DeviceEventArgs(new PmpNatDevice(endpoint.Address, publicIp)));
  190. }
  191. public DateTime NextSearch
  192. {
  193. get { return nextSearch; }
  194. }
  195. private void OnDeviceFound(DeviceEventArgs args)
  196. {
  197. if (DeviceFound != null)
  198. DeviceFound(this, args);
  199. }
  200. public NatProtocol Protocol
  201. {
  202. get { return NatProtocol.Pmp; }
  203. }
  204. }
  205. }