jellyfin/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs

337 lines
11 KiB
C#
Raw Normal View History

2016-11-11 04:25:21 +00:00
using System;
2014-08-21 15:55:35 +00:00
using System.Collections.Generic;
2015-01-19 04:29:57 +00:00
using System.Globalization;
2015-04-29 18:48:34 +00:00
using System.Net;
using System.Threading.Tasks;
2016-10-28 01:07:40 +00:00
using MediaBrowser.Common.Net;
2016-11-11 04:25:21 +00:00
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Plugins;
2016-10-29 18:46:56 +00:00
using MediaBrowser.Model.Dlna;
2016-09-11 07:33:53 +00:00
using MediaBrowser.Model.Events;
2016-11-11 04:25:21 +00:00
using MediaBrowser.Model.Logging;
2016-11-03 22:53:02 +00:00
using MediaBrowser.Model.Threading;
2016-11-11 04:25:21 +00:00
using Mono.Nat;
using MediaBrowser.Model.Extensions;
2017-11-23 15:46:16 +00:00
using System.Threading;
2014-02-26 04:38:21 +00:00
namespace Emby.Server.Implementations.EntryPoints
2014-02-26 04:38:21 +00:00
{
public class ExternalPortForwarding : IServerEntryPoint
{
private readonly IServerApplicationHost _appHost;
private readonly ILogger _logger;
2016-10-28 01:07:40 +00:00
private readonly IHttpClient _httpClient;
2014-02-26 04:38:21 +00:00
private readonly IServerConfigurationManager _config;
2016-09-11 07:33:53 +00:00
private readonly IDeviceDiscovery _deviceDiscovery;
2016-04-04 19:07:43 +00:00
2016-11-03 22:53:02 +00:00
private ITimer _timer;
2016-04-04 19:07:43 +00:00
private bool _isStarted;
2016-11-03 22:53:02 +00:00
private readonly ITimerFactory _timerFactory;
2014-08-21 15:55:35 +00:00
2016-11-03 22:53:02 +00:00
public ExternalPortForwarding(ILogManager logmanager, IServerApplicationHost appHost, IServerConfigurationManager config, IDeviceDiscovery deviceDiscovery, IHttpClient httpClient, ITimerFactory timerFactory)
2014-02-26 04:38:21 +00:00
{
2014-05-02 02:54:33 +00:00
_logger = logmanager.GetLogger("PortMapper");
2014-02-26 04:38:21 +00:00
_appHost = appHost;
_config = config;
2016-09-11 07:33:53 +00:00
_deviceDiscovery = deviceDiscovery;
2016-10-28 01:07:40 +00:00
_httpClient = httpClient;
2016-11-03 22:53:02 +00:00
_timerFactory = timerFactory;
2016-04-04 19:07:43 +00:00
}
2016-03-31 19:22:07 +00:00
2016-04-04 19:07:43 +00:00
private string _lastConfigIdentifier;
private string GetConfigIdentifier()
{
var values = new List<string>();
var config = _config.Configuration;
values.Add(config.EnableUPnP.ToString());
values.Add(config.PublicPort.ToString(CultureInfo.InvariantCulture));
values.Add(_appHost.HttpPort.ToString(CultureInfo.InvariantCulture));
values.Add(_appHost.HttpsPort.ToString(CultureInfo.InvariantCulture));
values.Add((config.EnableHttps || config.RequireHttps).ToString());
2016-04-04 19:07:43 +00:00
values.Add(_appHost.EnableHttps.ToString());
return string.Join("|", values.ToArray(values.Count));
2015-01-19 04:29:57 +00:00
}
2014-02-26 04:38:21 +00:00
2016-04-04 19:07:43 +00:00
void _config_ConfigurationUpdated(object sender, EventArgs e)
2014-02-26 04:38:21 +00:00
{
2016-04-04 19:07:43 +00:00
if (!string.Equals(_lastConfigIdentifier, GetConfigIdentifier(), StringComparison.OrdinalIgnoreCase))
{
if (_isStarted)
{
DisposeNat();
}
Run();
}
2016-03-31 19:22:07 +00:00
}
2014-08-21 15:55:35 +00:00
2016-03-31 19:22:07 +00:00
public void Run()
{
2016-09-11 07:33:53 +00:00
NatUtility.Logger = _logger;
2016-10-28 01:07:40 +00:00
NatUtility.HttpClient = _httpClient;
2016-04-04 19:07:43 +00:00
if (_config.Configuration.EnableUPnP)
{
Start();
}
_config.ConfigurationUpdated -= _config_ConfigurationUpdated;
_config.ConfigurationUpdated += _config_ConfigurationUpdated;
2014-02-26 04:38:21 +00:00
}
2016-04-04 19:07:43 +00:00
private void Start()
2014-02-26 04:38:21 +00:00
{
2016-04-04 19:07:43 +00:00
_logger.Debug("Starting NAT discovery");
NatUtility.EnabledProtocols = new List<NatProtocol>
2016-03-31 19:22:07 +00:00
{
2016-04-04 19:07:43 +00:00
NatProtocol.Pmp
};
NatUtility.DeviceFound += NatUtility_DeviceFound;
2016-03-31 19:22:07 +00:00
2016-04-04 19:07:43 +00:00
// Mono.Nat does never rise this event. The event is there however it is useless.
// You could remove it with no risk.
NatUtility.DeviceLost += NatUtility_DeviceLost;
2015-04-29 18:48:34 +00:00
2015-01-19 04:29:57 +00:00
2016-04-04 19:07:43 +00:00
NatUtility.StartDiscovery();
_timer = _timerFactory.Create(ClearCreatedRules, null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));
2016-04-04 19:07:43 +00:00
2016-09-11 07:33:53 +00:00
_deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered;
2016-04-04 19:07:43 +00:00
_lastConfigIdentifier = GetConfigIdentifier();
_isStarted = true;
}
2016-09-11 07:33:53 +00:00
private async void _deviceDiscovery_DeviceDiscovered(object sender, GenericEventArgs<UpnpDeviceInfo> e)
2016-04-04 19:07:43 +00:00
{
2017-01-02 19:36:54 +00:00
if (_disposed)
{
return;
}
2016-09-11 07:33:53 +00:00
var info = e.Argument;
2016-06-11 15:56:15 +00:00
string usn;
2016-09-11 07:33:53 +00:00
if (!info.Headers.TryGetValue("USN", out usn)) usn = string.Empty;
2016-06-11 15:56:15 +00:00
string nt;
2016-09-11 07:33:53 +00:00
if (!info.Headers.TryGetValue("NT", out nt)) nt = string.Empty;
2016-06-11 15:56:15 +00:00
// Filter device type
if (usn.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
nt.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
usn.IndexOf("WANPPPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
nt.IndexOf("WANPPPConnection:", StringComparison.OrdinalIgnoreCase) == -1)
{
return;
}
var identifier = string.IsNullOrWhiteSpace(usn) ? nt : usn;
2016-10-14 16:22:04 +00:00
if (info.Location == null)
2016-06-11 15:56:15 +00:00
{
2016-10-14 16:22:04 +00:00
return;
}
lock (_usnsHandled)
{
if (_usnsHandled.Contains(identifier))
{
return;
}
2016-06-11 15:56:15 +00:00
_usnsHandled.Add(identifier);
2016-10-14 16:22:04 +00:00
}
2016-06-11 15:56:15 +00:00
2016-10-28 01:07:40 +00:00
_logger.Debug("Found NAT device: " + identifier);
2016-09-11 07:33:53 +00:00
2016-10-14 16:22:04 +00:00
IPAddress address;
if (IPAddress.TryParse(info.Location.Host, out address))
{
// The Handle method doesn't need the port
var endpoint = new IPEndPoint(address, info.Location.Port);
2016-09-11 07:33:53 +00:00
2016-10-14 16:22:04 +00:00
IPAddress localAddress = null;
2016-09-11 07:33:53 +00:00
2016-10-14 16:22:04 +00:00
try
{
2017-11-23 15:46:16 +00:00
var localAddressString = await _appHost.GetLocalApiUrl(CancellationToken.None).ConfigureAwait(false);
2016-09-11 07:33:53 +00:00
2016-10-28 01:07:40 +00:00
Uri uri;
if (Uri.TryCreate(localAddressString, UriKind.Absolute, out uri))
2016-09-11 07:33:53 +00:00
{
2016-10-28 01:07:40 +00:00
localAddressString = uri.Host;
if (!IPAddress.TryParse(localAddressString, out localAddress))
{
return;
}
2016-09-11 07:33:53 +00:00
}
}
2016-10-28 01:07:40 +00:00
catch (Exception ex)
2016-10-14 16:22:04 +00:00
{
return;
}
2017-01-02 19:36:54 +00:00
if (_disposed)
{
return;
}
2016-10-28 01:07:40 +00:00
_logger.Debug("Calling Nat.Handle on " + identifier);
2016-10-14 16:22:04 +00:00
NatUtility.Handle(localAddress, info, endpoint, NatProtocol.Upnp);
2014-02-26 04:38:21 +00:00
}
2016-04-04 19:07:43 +00:00
}
2016-09-11 07:33:53 +00:00
private void ClearCreatedRules(object state)
{
2017-02-22 20:58:02 +00:00
lock (_createdRules)
{
_createdRules.Clear();
}
2016-10-14 16:22:04 +00:00
lock (_usnsHandled)
{
_usnsHandled.Clear();
}
2016-09-11 07:33:53 +00:00
}
2016-04-04 19:07:43 +00:00
void NatUtility_DeviceFound(object sender, DeviceEventArgs e)
{
2017-01-02 19:36:54 +00:00
if (_disposed)
{
return;
}
2016-04-04 19:07:43 +00:00
try
2014-02-26 04:38:21 +00:00
{
2016-04-04 19:07:43 +00:00
var device = e.Device;
_logger.Debug("NAT device found: {0}", device.LocalAddress.ToString());
CreateRules(device);
}
catch
2016-04-04 19:07:43 +00:00
{
// I think it could be a good idea to log the exception because
// you are using permanent portmapping here (never expire) and that means that next time
// CreatePortMap is invoked it can fails with a 718-ConflictInMappingEntry or not. That depends
// on the router's upnp implementation (specs says it should fail however some routers don't do it)
// It also can fail with others like 727-ExternalPortOnlySupportsWildcard, 728-NoPortMapsAvailable
// and those errors (upnp errors) could be useful for diagnosting.
// Commenting out because users are reporting problems out of our control
//_logger.ErrorException("Error creating port forwarding rules", ex);
2016-03-31 18:46:03 +00:00
}
2014-02-26 04:38:21 +00:00
}
2016-04-04 19:07:43 +00:00
private List<string> _createdRules = new List<string>();
2016-06-11 15:56:15 +00:00
private List<string> _usnsHandled = new List<string>();
2017-01-24 19:54:18 +00:00
private async void CreateRules(INatDevice device)
{
2017-01-02 19:36:54 +00:00
if (_disposed)
{
throw new ObjectDisposedException("PortMapper");
}
2016-03-31 18:46:03 +00:00
// On some systems the device discovered event seems to fire repeatedly
// This check will help ensure we're not trying to port map the same device over and over
2014-02-26 04:38:21 +00:00
2016-04-04 19:07:43 +00:00
var address = device.LocalAddress.ToString();
2017-02-22 20:58:02 +00:00
lock (_createdRules)
2016-04-04 19:07:43 +00:00
{
2017-02-22 20:58:02 +00:00
if (!_createdRules.Contains(address))
2017-01-24 19:54:18 +00:00
{
2017-02-22 20:58:02 +00:00
_createdRules.Add(address);
2017-01-24 19:54:18 +00:00
}
2017-02-22 20:58:02 +00:00
else
{
return;
}
}
var success = await CreatePortMap(device, _appHost.HttpPort, _config.Configuration.PublicPort).ConfigureAwait(false);
if (success)
{
await CreatePortMap(device, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort).ConfigureAwait(false);
2016-04-04 19:07:43 +00:00
}
2014-02-26 04:38:21 +00:00
}
2017-01-24 19:54:18 +00:00
private async Task<bool> CreatePortMap(INatDevice device, int privatePort, int publicPort)
2014-02-26 04:38:21 +00:00
{
2016-03-31 18:46:03 +00:00
_logger.Debug("Creating port map on port {0}", privatePort);
2016-10-28 01:07:40 +00:00
try
2014-02-26 04:38:21 +00:00
{
2016-10-28 01:07:40 +00:00
await device.CreatePortMap(new Mapping(Protocol.Tcp, privatePort, publicPort)
{
Description = _appHost.Name
2016-10-28 01:07:40 +00:00
}).ConfigureAwait(false);
2017-01-24 19:54:18 +00:00
return true;
2016-10-28 01:07:40 +00:00
}
catch (Exception ex)
{
2016-12-17 20:52:05 +00:00
_logger.Error("Error creating port map: " + ex.Message);
2017-01-24 19:54:18 +00:00
return false;
2016-10-28 01:07:40 +00:00
}
2016-04-04 19:07:43 +00:00
}
// As I said before, this method will be never invoked. You can remove it.
void NatUtility_DeviceLost(object sender, DeviceEventArgs e)
{
var device = e.Device;
_logger.Debug("NAT device lost: {0}", device.LocalAddress.ToString());
2014-02-26 04:38:21 +00:00
}
2017-01-02 19:36:54 +00:00
private bool _disposed = false;
2016-03-31 18:46:03 +00:00
public void Dispose()
2014-02-26 04:38:21 +00:00
{
2017-01-02 19:36:54 +00:00
_disposed = true;
2016-03-31 18:46:03 +00:00
DisposeNat();
2017-09-05 19:49:02 +00:00
GC.SuppressFinalize(this);
2016-03-31 18:46:03 +00:00
}
2014-02-26 04:38:21 +00:00
2016-03-31 18:46:03 +00:00
private void DisposeNat()
{
2016-04-04 19:07:43 +00:00
_logger.Debug("Stopping NAT discovery");
if (_timer != null)
2014-02-26 04:38:21 +00:00
{
2016-04-04 19:07:43 +00:00
_timer.Dispose();
_timer = null;
}
2016-09-11 07:33:53 +00:00
_deviceDiscovery.DeviceDiscovered -= _deviceDiscovery_DeviceDiscovered;
2016-04-04 19:07:43 +00:00
try
{
// This is not a significant improvement
NatUtility.StopDiscovery();
NatUtility.DeviceFound -= NatUtility_DeviceFound;
NatUtility.DeviceLost -= NatUtility_DeviceLost;
}
// Statements in try-block will no fail because StopDiscovery is a one-line
// method that was no chances to fail.
// public static void StopDiscovery ()
// {
// searching.Reset();
// }
// IMO you could remove the catch-block
catch (Exception ex)
{
_logger.ErrorException("Error stopping NAT Discovery", ex);
}
finally
{
_isStarted = false;
2014-02-26 04:38:21 +00:00
}
}
}
2016-04-04 19:07:43 +00:00
}