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

258 lines
9.1 KiB
C#
Raw Normal View History

2015-04-19 15:54:20 +00:00
using MediaBrowser.Controller;
2014-02-26 04:38:21 +00:00
using MediaBrowser.Controller.Configuration;
2015-04-29 18:48:34 +00:00
using MediaBrowser.Controller.Dlna;
2014-02-26 04:38:21 +00:00
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.Logging;
2016-04-04 19:07:43 +00:00
using Mono.Nat;
2014-02-26 04:38: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 MediaBrowser.Common.Threading;
2014-02-26 04:38:21 +00:00
namespace MediaBrowser.Server.Implementations.EntryPoints
{
public class ExternalPortForwarding : IServerEntryPoint
{
private readonly IServerApplicationHost _appHost;
private readonly ILogger _logger;
private readonly IServerConfigurationManager _config;
2015-04-29 18:48:34 +00:00
private readonly ISsdpHandler _ssdp;
2016-04-04 19:07:43 +00:00
private PeriodicTimer _timer;
private bool _isStarted;
2014-08-21 15:55:35 +00:00
2015-04-29 18:48:34 +00:00
public ExternalPortForwarding(ILogManager logmanager, IServerApplicationHost appHost, IServerConfigurationManager config, ISsdpHandler ssdp)
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;
2015-04-29 18:48:34 +00:00
_ssdp = ssdp;
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.ToString());
values.Add(_appHost.EnableHttps.ToString());
return string.Join("|", values.ToArray());
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-04-04 19:07:43 +00:00
//NatUtility.Logger = new LogWriter(_logger);
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
// it is hard to say what one should do when an unhandled exception is raised
// because there isn't anything one can do about it. Probably save a log or ignored it.
NatUtility.UnhandledException += NatUtility_UnhandledException;
NatUtility.StartDiscovery();
2016-06-11 15:56:15 +00:00
_timer = new PeriodicTimer(ClearCreatedRules, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
2016-04-04 19:07:43 +00:00
_ssdp.MessageReceived += _ssdp_MessageReceived;
_lastConfigIdentifier = GetConfigIdentifier();
_isStarted = true;
}
2016-06-11 15:56:15 +00:00
private void ClearCreatedRules(object state)
{
_createdRules = new List<string>();
_usnsHandled = new List<string>();
}
2016-04-04 19:07:43 +00:00
void _ssdp_MessageReceived(object sender, SsdpMessageEventArgs e)
{
var endpoint = e.EndPoint as IPEndPoint;
2014-02-26 04:38:21 +00:00
2016-06-11 15:56:15 +00:00
if (endpoint == null || e.LocalEndPoint == null)
2016-04-04 19:07:43 +00:00
{
2016-06-11 15:56:15 +00:00
return;
}
string usn;
if (!e.Headers.TryGetValue("USN", out usn)) usn = string.Empty;
string nt;
if (!e.Headers.TryGetValue("NT", out nt)) nt = string.Empty;
// 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;
if (!_usnsHandled.Contains(identifier))
{
_usnsHandled.Add(identifier);
_logger.Debug("Calling Nat.Handle on " + identifier);
2016-04-04 19:07:43 +00:00
NatUtility.Handle(e.LocalEndPoint.Address, e.Message, endpoint, NatProtocol.Upnp);
2014-02-26 04:38:21 +00:00
}
2016-04-04 19:07:43 +00:00
}
void NatUtility_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var ex = e.ExceptionObject as Exception;
if (ex == null)
2014-02-26 04:38:21 +00:00
{
2016-04-04 19:07:43 +00:00
//_logger.Error("Unidentified error reported by Mono.Nat");
2014-02-26 04:38:21 +00:00
}
2016-04-04 19:07:43 +00:00
else
2014-08-21 15:55:35 +00:00
{
2016-04-04 19:07:43 +00:00
// Seeing some blank exceptions coming through here
//_logger.ErrorException("Error reported by Mono.Nat: ", ex);
2014-08-21 15:55:35 +00:00
}
2016-04-04 19:07:43 +00:00
}
2014-02-26 04:38:21 +00:00
2016-04-04 19:07:43 +00:00
void NatUtility_DeviceFound(object sender, DeviceEventArgs e)
{
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>();
2016-04-04 19:07:43 +00:00
private void CreateRules(INatDevice device)
{
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();
if (!_createdRules.Contains(address))
{
_createdRules.Add(address);
CreatePortMap(device, _appHost.HttpPort, _config.Configuration.PublicPort);
CreatePortMap(device, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort);
}
2014-02-26 04:38:21 +00:00
}
2016-04-04 19:07:43 +00:00
private void 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-04-04 19:07:43 +00:00
device.CreatePortMap(new Mapping(Protocol.Tcp, privatePort, publicPort)
2014-02-26 04:38:21 +00:00
{
2016-04-04 19:07:43 +00:00
Description = _appHost.Name
});
}
// 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
}
2016-03-31 18:46:03 +00:00
public void Dispose()
2014-02-26 04:38:21 +00:00
{
2016-03-31 18:46:03 +00:00
DisposeNat();
}
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;
}
_ssdp.MessageReceived -= _ssdp_MessageReceived;
try
{
// This is not a significant improvement
NatUtility.StopDiscovery();
NatUtility.DeviceFound -= NatUtility_DeviceFound;
NatUtility.DeviceLost -= NatUtility_DeviceLost;
NatUtility.UnhandledException -= NatUtility_UnhandledException;
}
// 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
}