ExternalPortForwarding.cs 10.0 KB

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