ExternalPortForwarding.cs 10 KB

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