ExternalPortForwarding.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. using MediaBrowser.Controller;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Dlna;
  4. using MediaBrowser.Controller.Plugins;
  5. using MediaBrowser.Model.Logging;
  6. using Mono.Nat;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Globalization;
  10. using System.Net;
  11. using MediaBrowser.Common.Net;
  12. using MediaBrowser.Model.Events;
  13. using MediaBrowser.Server.Implementations.Threading;
  14. namespace MediaBrowser.Server.Implementations.EntryPoints
  15. {
  16. public class ExternalPortForwarding : IServerEntryPoint
  17. {
  18. private readonly IServerApplicationHost _appHost;
  19. private readonly ILogger _logger;
  20. private readonly IHttpClient _httpClient;
  21. private readonly IServerConfigurationManager _config;
  22. private readonly IDeviceDiscovery _deviceDiscovery;
  23. private PeriodicTimer _timer;
  24. private bool _isStarted;
  25. public ExternalPortForwarding(ILogManager logmanager, IServerApplicationHost appHost, IServerConfigurationManager config, IDeviceDiscovery deviceDiscovery, IHttpClient httpClient)
  26. {
  27. _logger = logmanager.GetLogger("PortMapper");
  28. _appHost = appHost;
  29. _config = config;
  30. _deviceDiscovery = deviceDiscovery;
  31. _httpClient = httpClient;
  32. }
  33. private string _lastConfigIdentifier;
  34. private string GetConfigIdentifier()
  35. {
  36. var values = new List<string>();
  37. var config = _config.Configuration;
  38. values.Add(config.EnableUPnP.ToString());
  39. values.Add(config.PublicPort.ToString(CultureInfo.InvariantCulture));
  40. values.Add(_appHost.HttpPort.ToString(CultureInfo.InvariantCulture));
  41. values.Add(_appHost.HttpsPort.ToString(CultureInfo.InvariantCulture));
  42. values.Add(config.EnableHttps.ToString());
  43. values.Add(_appHost.EnableHttps.ToString());
  44. return string.Join("|", values.ToArray());
  45. }
  46. void _config_ConfigurationUpdated(object sender, EventArgs e)
  47. {
  48. if (!string.Equals(_lastConfigIdentifier, GetConfigIdentifier(), StringComparison.OrdinalIgnoreCase))
  49. {
  50. if (_isStarted)
  51. {
  52. DisposeNat();
  53. }
  54. Run();
  55. }
  56. }
  57. public void Run()
  58. {
  59. NatUtility.Logger = _logger;
  60. NatUtility.HttpClient = _httpClient;
  61. if (_config.Configuration.EnableUPnP)
  62. {
  63. Start();
  64. }
  65. _config.ConfigurationUpdated -= _config_ConfigurationUpdated;
  66. _config.ConfigurationUpdated += _config_ConfigurationUpdated;
  67. }
  68. private void Start()
  69. {
  70. _logger.Debug("Starting NAT discovery");
  71. NatUtility.EnabledProtocols = new List<NatProtocol>
  72. {
  73. NatProtocol.Pmp
  74. };
  75. NatUtility.DeviceFound += NatUtility_DeviceFound;
  76. // Mono.Nat does never rise this event. The event is there however it is useless.
  77. // You could remove it with no risk.
  78. NatUtility.DeviceLost += NatUtility_DeviceLost;
  79. NatUtility.StartDiscovery();
  80. _timer = new PeriodicTimer(ClearCreatedRules, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
  81. _deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered;
  82. _lastConfigIdentifier = GetConfigIdentifier();
  83. _isStarted = true;
  84. }
  85. private async void _deviceDiscovery_DeviceDiscovered(object sender, GenericEventArgs<UpnpDeviceInfo> e)
  86. {
  87. var info = e.Argument;
  88. string usn;
  89. if (!info.Headers.TryGetValue("USN", out usn)) usn = string.Empty;
  90. string nt;
  91. if (!info.Headers.TryGetValue("NT", out nt)) nt = string.Empty;
  92. // Filter device type
  93. if (usn.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
  94. nt.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
  95. usn.IndexOf("WANPPPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
  96. nt.IndexOf("WANPPPConnection:", StringComparison.OrdinalIgnoreCase) == -1)
  97. {
  98. return;
  99. }
  100. var identifier = string.IsNullOrWhiteSpace(usn) ? nt : usn;
  101. if (info.Location == null)
  102. {
  103. return;
  104. }
  105. lock (_usnsHandled)
  106. {
  107. if (_usnsHandled.Contains(identifier))
  108. {
  109. return;
  110. }
  111. _usnsHandled.Add(identifier);
  112. }
  113. _logger.Debug("Found NAT device: " + identifier);
  114. IPAddress address;
  115. if (IPAddress.TryParse(info.Location.Host, out address))
  116. {
  117. // The Handle method doesn't need the port
  118. var endpoint = new IPEndPoint(address, info.Location.Port);
  119. IPAddress localAddress = null;
  120. try
  121. {
  122. var localAddressString = await _appHost.GetLocalApiUrl().ConfigureAwait(false);
  123. Uri uri;
  124. if (Uri.TryCreate(localAddressString, UriKind.Absolute, out uri))
  125. {
  126. localAddressString = uri.Host;
  127. if (!IPAddress.TryParse(localAddressString, out localAddress))
  128. {
  129. return;
  130. }
  131. }
  132. }
  133. catch (Exception ex)
  134. {
  135. return;
  136. }
  137. _logger.Debug("Calling Nat.Handle on " + identifier);
  138. NatUtility.Handle(localAddress, info, endpoint, NatProtocol.Upnp);
  139. }
  140. }
  141. private void ClearCreatedRules(object state)
  142. {
  143. _createdRules = new List<string>();
  144. lock (_usnsHandled)
  145. {
  146. _usnsHandled.Clear();
  147. }
  148. }
  149. void NatUtility_DeviceFound(object sender, DeviceEventArgs e)
  150. {
  151. try
  152. {
  153. var device = e.Device;
  154. _logger.Debug("NAT device found: {0}", device.LocalAddress.ToString());
  155. CreateRules(device);
  156. }
  157. catch
  158. {
  159. // I think it could be a good idea to log the exception because
  160. // you are using permanent portmapping here (never expire) and that means that next time
  161. // CreatePortMap is invoked it can fails with a 718-ConflictInMappingEntry or not. That depends
  162. // on the router's upnp implementation (specs says it should fail however some routers don't do it)
  163. // It also can fail with others like 727-ExternalPortOnlySupportsWildcard, 728-NoPortMapsAvailable
  164. // and those errors (upnp errors) could be useful for diagnosting.
  165. // Commenting out because users are reporting problems out of our control
  166. //_logger.ErrorException("Error creating port forwarding rules", ex);
  167. }
  168. }
  169. private List<string> _createdRules = new List<string>();
  170. private List<string> _usnsHandled = new List<string>();
  171. private void CreateRules(INatDevice device)
  172. {
  173. // On some systems the device discovered event seems to fire repeatedly
  174. // This check will help ensure we're not trying to port map the same device over and over
  175. var address = device.LocalAddress.ToString();
  176. if (!_createdRules.Contains(address))
  177. {
  178. _createdRules.Add(address);
  179. CreatePortMap(device, _appHost.HttpPort, _config.Configuration.PublicPort);
  180. CreatePortMap(device, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort);
  181. }
  182. }
  183. private async void CreatePortMap(INatDevice device, int privatePort, int publicPort)
  184. {
  185. _logger.Debug("Creating port map on port {0}", privatePort);
  186. try
  187. {
  188. await device.CreatePortMap(new Mapping(Protocol.Tcp, privatePort, publicPort)
  189. {
  190. Description = _appHost.Name
  191. }).ConfigureAwait(false);
  192. }
  193. catch (Exception ex)
  194. {
  195. _logger.ErrorException("Error creating port map", ex);
  196. }
  197. }
  198. // As I said before, this method will be never invoked. You can remove it.
  199. void NatUtility_DeviceLost(object sender, DeviceEventArgs e)
  200. {
  201. var device = e.Device;
  202. _logger.Debug("NAT device lost: {0}", device.LocalAddress.ToString());
  203. }
  204. public void Dispose()
  205. {
  206. DisposeNat();
  207. }
  208. private void DisposeNat()
  209. {
  210. _logger.Debug("Stopping NAT discovery");
  211. if (_timer != null)
  212. {
  213. _timer.Dispose();
  214. _timer = null;
  215. }
  216. _deviceDiscovery.DeviceDiscovered -= _deviceDiscovery_DeviceDiscovered;
  217. try
  218. {
  219. // This is not a significant improvement
  220. NatUtility.StopDiscovery();
  221. NatUtility.DeviceFound -= NatUtility_DeviceFound;
  222. NatUtility.DeviceLost -= NatUtility_DeviceLost;
  223. }
  224. // Statements in try-block will no fail because StopDiscovery is a one-line
  225. // method that was no chances to fail.
  226. // public static void StopDiscovery ()
  227. // {
  228. // searching.Reset();
  229. // }
  230. // IMO you could remove the catch-block
  231. catch (Exception ex)
  232. {
  233. _logger.ErrorException("Error stopping NAT Discovery", ex);
  234. }
  235. finally
  236. {
  237. _isStarted = false;
  238. }
  239. }
  240. }
  241. }