aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Emby.Dlna/Main/DlnaEntryPoint.cs40
-rw-r--r--Emby.Dlna/PlayTo/PlayToManager.cs10
-rw-r--r--Emby.Server.Implementations/ApplicationHost.cs277
-rw-r--r--Emby.Server.Implementations/Emby.Server.Implementations.csproj1
-rw-r--r--Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs11
-rw-r--r--Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs3
-rw-r--r--Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs24
-rw-r--r--Emby.Server.Implementations/Networking/NetworkManager.cs556
-rw-r--r--Emby.Server.Implementations/Udp/UdpServer.cs2
-rw-r--r--Jellyfin.Api/Controllers/StartupController.cs14
-rw-r--r--Jellyfin.Api/Controllers/SystemController.cs10
-rw-r--r--Jellyfin.Api/Helpers/ClassMigrationHelper.cs70
-rw-r--r--Jellyfin.Networking/Configuration/NetworkConfiguration.cs223
-rw-r--r--Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs21
-rw-r--r--Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs27
-rw-r--r--Jellyfin.Networking/Jellyfin.Networking.csproj30
-rw-r--r--Jellyfin.Networking/Manager/NetworkManager.cs1301
-rw-r--r--Jellyfin.Server/CoreAppHost.cs3
-rw-r--r--Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs5
-rw-r--r--Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs3
-rw-r--r--Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs41
-rw-r--r--Jellyfin.Server/Middleware/LanFilteringMiddleware.cs38
-rw-r--r--Jellyfin.Server/Program.cs66
-rw-r--r--Jellyfin.Server/Startup.cs5
-rw-r--r--MediaBrowser.Common/Net/INetworkManager.cs234
-rw-r--r--MediaBrowser.Common/Net/IPHost.cs444
-rw-r--r--MediaBrowser.Common/Net/IPNetAddress.cs277
-rw-r--r--MediaBrowser.Common/Net/IPObject.cs395
-rw-r--r--MediaBrowser.Common/Net/NetworkExtensions.cs262
-rw-r--r--MediaBrowser.Controller/IServerApplicationHost.cs44
-rw-r--r--MediaBrowser.Model/Configuration/PathSubstitution.cs19
-rw-r--r--MediaBrowser.Model/Configuration/ServerConfiguration.cs404
-rw-r--r--MediaBrowser.sln41
-rw-r--r--RSSDP/RSSDP.csproj1
-rw-r--r--RSSDP/SsdpCommunicationsServer.cs4
-rw-r--r--RSSDP/SsdpDevicePublisher.cs10
-rw-r--r--RSSDP/SsdpRootDevice.cs4
-rw-r--r--tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs3
-rw-r--r--tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj39
-rw-r--r--tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs485
40 files changed, 4276 insertions, 1171 deletions
diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs
index f8a00efac..fb4454a34 100644
--- a/Emby.Dlna/Main/DlnaEntryPoint.cs
+++ b/Emby.Dlna/Main/DlnaEntryPoint.cs
@@ -2,12 +2,14 @@
using System;
using System.Globalization;
+using System.Linq;
using System.Net.Http;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Emby.Dlna.PlayTo;
using Emby.Dlna.Ssdp;
+using Jellyfin.Networking.Manager;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
@@ -134,20 +136,20 @@ namespace Emby.Dlna.Main
{
await ((DlnaManager)_dlnaManager).InitProfilesAsync().ConfigureAwait(false);
- await ReloadComponents().ConfigureAwait(false);
+ ReloadComponents();
_config.NamedConfigurationUpdated += OnNamedConfigurationUpdated;
}
- private async void OnNamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
+ private void OnNamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
{
if (string.Equals(e.Key, "dlna", StringComparison.OrdinalIgnoreCase))
{
- await ReloadComponents().ConfigureAwait(false);
+ ReloadComponents();
}
}
- private async Task ReloadComponents()
+ private void ReloadComponents()
{
var options = _config.GetDlnaConfiguration();
@@ -155,7 +157,7 @@ namespace Emby.Dlna.Main
if (options.EnableServer)
{
- await StartDevicePublisher(options).ConfigureAwait(false);
+ StartDevicePublisher(options);
}
else
{
@@ -225,7 +227,7 @@ namespace Emby.Dlna.Main
}
}
- public async Task StartDevicePublisher(Configuration.DlnaOptions options)
+ public void StartDevicePublisher(Configuration.DlnaOptions options)
{
if (!options.BlastAliveMessages)
{
@@ -245,7 +247,7 @@ namespace Emby.Dlna.Main
SupportPnpRootDevice = false
};
- await RegisterServerEndpoints().ConfigureAwait(false);
+ RegisterServerEndpoints();
_publisher.StartBroadcastingAliveMessages(TimeSpan.FromSeconds(options.BlastAliveMessageIntervalSeconds));
}
@@ -255,14 +257,22 @@ namespace Emby.Dlna.Main
}
}
- private async Task RegisterServerEndpoints()
+ private void RegisterServerEndpoints()
{
- var addresses = await _appHost.GetLocalIpAddresses().ConfigureAwait(false);
-
var udn = CreateUuid(_appHost.SystemId);
var descriptorUri = "/dlna/" + udn + "/description.xml";
- foreach (var address in addresses)
+ var bindAddresses = NetworkManager.CreateCollection(
+ _networkManager.GetInternalBindAddresses()
+ .Where(i => i.AddressFamily == AddressFamily.InterNetwork || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0)));
+
+ if (bindAddresses.Count == 0)
+ {
+ // No interfaces returned, so use loopback.
+ bindAddresses = _networkManager.GetLoopbacks();
+ }
+
+ foreach (IPNetAddress address in bindAddresses)
{
if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
@@ -271,7 +281,7 @@ namespace Emby.Dlna.Main
}
// Limit to LAN addresses only
- if (!_networkManager.IsAddressInSubnets(address, true, true))
+ if (!_networkManager.IsInLocalNetwork(address))
{
continue;
}
@@ -280,14 +290,14 @@ namespace Emby.Dlna.Main
_logger.LogInformation("Registering publisher for {0} on {1}", fullService, address);
- var uri = new Uri(_appHost.GetLocalApiUrl(address) + descriptorUri);
+ var uri = new Uri(_appHost.GetSmartApiUrl(address.Address) + descriptorUri);
var device = new SsdpRootDevice
{
CacheLifetime = TimeSpan.FromSeconds(1800), // How long SSDP clients can cache this info.
Location = uri, // Must point to the URL that serves your devices UPnP description document.
- Address = address,
- SubnetMask = _networkManager.GetLocalIpSubnetMask(address),
+ Address = address.Address,
+ PrefixLength = address.PrefixLength,
FriendlyName = "Jellyfin",
Manufacturer = "Jellyfin",
ModelName = "Jellyfin Server",
diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs
index e93aef304..854b6a1a2 100644
--- a/Emby.Dlna/PlayTo/PlayToManager.cs
+++ b/Emby.Dlna/PlayTo/PlayToManager.cs
@@ -177,15 +177,7 @@ namespace Emby.Dlna.PlayTo
_sessionManager.UpdateDeviceName(sessionInfo.Id, deviceName);
- string serverAddress;
- if (info.LocalIpAddress == null || info.LocalIpAddress.Equals(IPAddress.Any) || info.LocalIpAddress.Equals(IPAddress.IPv6Any))
- {
- serverAddress = await _appHost.GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
- }
- else
- {
- serverAddress = _appHost.GetLocalApiUrl(info.LocalIpAddress);
- }
+ string serverAddress = _appHost.GetSmartApiUrl(info.LocalIpAddress);
controller = new PlayToController(
sessionInfo,
diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs
index aa2ec158f..527b0844a 100644
--- a/Emby.Server.Implementations/ApplicationHost.cs
+++ b/Emby.Server.Implementations/ApplicationHost.cs
@@ -15,6 +15,7 @@ using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
+using System.Xml.Serialization;
using Emby.Dlna;
using Emby.Dlna.Main;
using Emby.Dlna.Ssdp;
@@ -46,6 +47,9 @@ using Emby.Server.Implementations.SyncPlay;
using Emby.Server.Implementations.TV;
using Emby.Server.Implementations.Updates;
using Jellyfin.Api.Helpers;
+using Jellyfin.Api.Migrations;
+using Jellyfin.Networking.Configuration;
+using Jellyfin.Networking.Manager;
using MediaBrowser.Common;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Events;
@@ -98,6 +102,8 @@ using MediaBrowser.Providers.Plugins.TheTvdb;
using MediaBrowser.Providers.Plugins.Tmdb;
using MediaBrowser.Providers.Subtitles;
using MediaBrowser.XbmcMetadata.Providers;
+using Microsoft.AspNetCore.DataProtection.Repositories;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
@@ -118,7 +124,6 @@ namespace Emby.Server.Implementations
private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" };
private readonly IFileSystem _fileSystemManager;
- private readonly INetworkManager _networkManager;
private readonly IXmlSerializer _xmlSerializer;
private readonly IJsonSerializer _jsonSerializer;
private readonly IStartupOptions _startupOptions;
@@ -160,6 +165,11 @@ namespace Emby.Server.Implementations
}
/// <summary>
+ /// Gets the <see cref="INetworkManager"/> singleton instance.
+ /// </summary>
+ public INetworkManager NetManager { get; internal set; }
+
+ /// <summary>
/// Occurs when [has pending restart changed].
/// </summary>
public event EventHandler HasPendingRestartChanged;
@@ -211,7 +221,7 @@ namespace Emby.Server.Implementations
private readonly List<IDisposable> _disposableParts = new List<IDisposable>();
/// <summary>
- /// Gets the configuration manager.
+ /// Gets or sets the configuration manager.
/// </summary>
/// <value>The configuration manager.</value>
protected IConfigurationManager ConfigurationManager { get; set; }
@@ -244,14 +254,12 @@ namespace Emby.Server.Implementations
/// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
/// <param name="options">Instance of the <see cref="IStartupOptions"/> interface.</param>
/// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
- /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
/// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param>
public ApplicationHost(
IServerApplicationPaths applicationPaths,
ILoggerFactory loggerFactory,
IStartupOptions options,
IFileSystem fileSystem,
- INetworkManager networkManager,
IServiceCollection serviceCollection)
{
_xmlSerializer = new MyXmlSerializer();
@@ -259,14 +267,16 @@ namespace Emby.Server.Implementations
ServiceCollection = serviceCollection;
- _networkManager = networkManager;
- networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets;
-
ApplicationPaths = applicationPaths;
LoggerFactory = loggerFactory;
_fileSystemManager = fileSystem;
ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager);
+ MigrateNetworkConfiguration();
+
+ // Have to pre-register the NetworkConfigurationFactory.
+ ConfigurationManager.RegisterConfiguration<NetworkConfigurationFactory>();
+ NetManager = new NetworkManager((IServerConfigurationManager)ConfigurationManager, LoggerFactory.CreateLogger<NetworkManager>());
Logger = LoggerFactory.CreateLogger<ApplicationHost>();
@@ -280,8 +290,6 @@ namespace Emby.Server.Implementations
fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
- _networkManager.NetworkChanged += OnNetworkChanged;
-
CertificateInfo = new CertificateInfo
{
Path = ServerConfigurationManager.Configuration.CertificatePath,
@@ -294,6 +302,18 @@ namespace Emby.Server.Implementations
ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString;
}
+ private void MigrateNetworkConfiguration()
+ {
+ string path = Path.Combine(ConfigurationManager.CommonApplicationPaths.ConfigurationDirectoryPath, "network.xml");
+ if (!File.Exists(path))
+ {
+ var networkSettings = new NetworkConfiguration();
+ ClassMigrationHelper.CopyProperties(ServerConfigurationManager.Configuration, networkSettings);
+ _xmlSerializer.SerializeToFile(networkSettings, path);
+ Logger?.LogDebug("Successfully migrated network settings.");
+ }
+ }
+
public string ExpandVirtualPath(string path)
{
var appPaths = ApplicationPaths;
@@ -310,16 +330,6 @@ namespace Emby.Server.Implementations
.Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
}
- private string[] GetConfiguredLocalSubnets()
- {
- return ServerConfigurationManager.Configuration.LocalNetworkSubnets;
- }
-
- private void OnNetworkChanged(object sender, EventArgs e)
- {
- _validAddressResults.Clear();
- }
-
/// <inheritdoc />
public Version ApplicationVersion { get; }
@@ -486,14 +496,15 @@ namespace Emby.Server.Implementations
/// <inheritdoc/>
public void Init()
{
- HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
- HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
+ var networkConfiguration = ServerConfigurationManager.GetNetworkConfiguration();
+ HttpPort = networkConfiguration.HttpServerPortNumber;
+ HttpsPort = networkConfiguration.HttpsPortNumber;
// Safeguard against invalid configuration
if (HttpPort == HttpsPort)
{
- HttpPort = ServerConfiguration.DefaultHttpPort;
- HttpsPort = ServerConfiguration.DefaultHttpsPort;
+ HttpPort = NetworkConfiguration.DefaultHttpPort;
+ HttpsPort = NetworkConfiguration.DefaultHttpsPort;
}
DiscoverTypes();
@@ -523,7 +534,7 @@ namespace Emby.Server.Implementations
ServiceCollection.AddSingleton<TvdbClientManager>();
ServiceCollection.AddSingleton<TmdbClientManager>();
- ServiceCollection.AddSingleton(_networkManager);
+ ServiceCollection.AddSingleton(NetManager);
ServiceCollection.AddSingleton<IIsoManager, IsoManager>();
@@ -904,9 +915,10 @@ namespace Emby.Server.Implementations
// Don't do anything if these haven't been set yet
if (HttpPort != 0 && HttpsPort != 0)
{
+ var networkConfiguration = ServerConfigurationManager.GetNetworkConfiguration();
// Need to restart if ports have changed
- if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
- ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
+ if (networkConfiguration.HttpServerPortNumber != HttpPort ||
+ networkConfiguration.HttpsPortNumber != HttpsPort)
{
if (ServerConfigurationManager.Configuration.IsPortAuthorized)
{
@@ -1149,6 +1161,9 @@ namespace Emby.Server.Implementations
// Xbmc
yield return typeof(ArtistNfoProvider).Assembly;
+ // Network
+ yield return typeof(NetworkManager).Assembly;
+
foreach (var i in GetAssembliesWithPartsInternal())
{
yield return i;
@@ -1160,13 +1175,10 @@ namespace Emby.Server.Implementations
/// <summary>
/// Gets the system status.
/// </summary>
- /// <param name="cancellationToken">The cancellation token.</param>
+ /// <param name="source">Where this request originated.</param>
/// <returns>SystemInfo.</returns>
- public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
+ public SystemInfo GetSystemInfo(IPAddress source)
{
- var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
- var transcodingTempPath = ConfigurationManager.GetTranscodePath();
-
return new SystemInfo
{
HasPendingRestart = HasPendingRestart,
@@ -1186,9 +1198,9 @@ namespace Emby.Server.Implementations
CanSelfRestart = CanSelfRestart,
CanLaunchWebBrowser = CanLaunchWebBrowser,
HasUpdateAvailable = HasUpdateAvailable,
- TranscodingTempPath = transcodingTempPath,
+ TranscodingTempPath = ConfigurationManager.GetTranscodePath(),
ServerName = FriendlyName,
- LocalAddress = localAddress,
+ LocalAddress = GetSmartApiUrl(source),
SupportsLibraryMonitor = true,
EncoderLocation = _mediaEncoder.EncoderLocation,
SystemArchitecture = RuntimeInformation.OSArchitecture,
@@ -1197,14 +1209,12 @@ namespace Emby.Server.Implementations
}
public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
- => _networkManager.GetMacAddresses()
+ => NetManager.GetMacAddresses()
.Select(i => new WakeOnLanInfo(i))
.ToList();
- public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
+ public PublicSystemInfo GetPublicSystemInfo(IPAddress source)
{
- var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
-
return new PublicSystemInfo
{
Version = ApplicationVersionString,
@@ -1212,193 +1222,98 @@ namespace Emby.Server.Implementations
Id = SystemId,
OperatingSystem = OperatingSystem.Id.ToString(),
ServerName = FriendlyName,
- LocalAddress = localAddress,
+ LocalAddress = GetSmartApiUrl(source),
StartupWizardCompleted = ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted
};
}
/// <inheritdoc/>
- public bool ListenWithHttps => Certificate != null && ServerConfigurationManager.Configuration.EnableHttps;
+ public bool ListenWithHttps => Certificate != null && ServerConfigurationManager.GetNetworkConfiguration().EnableHttps;
/// <inheritdoc/>
- public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken)
+ public string GetSmartApiUrl(IPAddress ipAddress, int? port = null)
{
- try
+ // Published server ends with a /
+ if (_startupOptions.PublishedServerUrl != null)
{
- // Return the first matched address, if found, or the first known local address
- var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
- if (addresses.Count == 0)
- {
- return null;
- }
-
- return GetLocalApiUrl(addresses[0]);
+ // Published server ends with a '/', so we need to remove it.
+ return _startupOptions.PublishedServerUrl.ToString().Trim('/');
}
- catch (Exception ex)
+
+ string smart = NetManager.GetBindInterface(ipAddress, out port);
+ // If the smartAPI doesn't start with http then treat it as a host or ip.
+ if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
- Logger.LogError(ex, "Error getting local Ip address information");
+ return smart.Trim('/');
}
- return null;
+ return GetLocalApiUrl(smart.Trim('/'), null, port);
}
- /// <summary>
- /// Removes the scope id from IPv6 addresses.
- /// </summary>
- /// <param name="address">The IPv6 address.</param>
- /// <returns>The IPv6 address without the scope id.</returns>
- private ReadOnlySpan<char> RemoveScopeId(ReadOnlySpan<char> address)
+ /// <inheritdoc/>
+ public string GetSmartApiUrl(HttpRequest request, int? port = null)
{
- var index = address.IndexOf('%');
- if (index == -1)
+ // Published server ends with a /
+ if (_startupOptions.PublishedServerUrl != null)
{
- return address;
+ // Published server ends with a '/', so we need to remove it.
+ return _startupOptions.PublishedServerUrl.ToString().Trim('/');
}
- return address.Slice(0, index);
- }
-
- /// <inheritdoc />
- public string GetLocalApiUrl(IPAddress ipAddress)
- {
- if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
+ string smart = NetManager.GetBindInterface(request, out port);
+ // If the smartAPI doesn't start with http then treat it as a host or ip.
+ if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
- var str = RemoveScopeId(ipAddress.ToString());
- Span<char> span = new char[str.Length + 2];
- span[0] = '[';
- str.CopyTo(span.Slice(1));
- span[^1] = ']';
-
- return GetLocalApiUrl(span);
+ return smart.Trim('/');
}
- return GetLocalApiUrl(ipAddress.ToString());
+ return GetLocalApiUrl(smart.Trim('/'), request.Scheme, port);
}
/// <inheritdoc/>
- public string GetLoopbackHttpApiUrl()
- {
- return GetLocalApiUrl("127.0.0.1", Uri.UriSchemeHttp, HttpPort);
- }
-
- /// <inheritdoc/>
- public string GetLocalApiUrl(ReadOnlySpan<char> host, string scheme = null, int? port = null)
- {
- // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
- // not. For consistency, always trim the trailing slash.
- return new UriBuilder
- {
- Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp),
- Host = host.ToString(),
- Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort),
- Path = ServerConfigurationManager.Configuration.BaseUrl
- }.ToString().TrimEnd('/');
- }
-
- public Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken)
- {
- return GetLocalIpAddressesInternal(true, 0, cancellationToken);
- }
-
- private async Task<List<IPAddress>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
+ public string GetSmartApiUrl(string hostname, int? port = null)
{
- var addresses = ServerConfigurationManager
- .Configuration
- .LocalNetworkAddresses
- .Select(x => NormalizeConfiguredLocalAddress(x))
- .Where(i => i != null)
- .ToList();
-
- if (addresses.Count == 0)
+ // Published server ends with a /
+ if (_startupOptions.PublishedServerUrl != null)
{
- addresses.AddRange(_networkManager.GetLocalIpAddresses());
+ // Published server ends with a '/', so we need to remove it.
+ return _startupOptions.PublishedServerUrl.ToString().Trim('/');
}
- var resultList = new List<IPAddress>();
+ string smart = NetManager.GetBindInterface(hostname, out port);
- foreach (var address in addresses)
+ // If the smartAPI doesn't start with http then treat it as a host or ip.
+ if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
- if (!allowLoopback)
- {
- if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback))
- {
- continue;
- }
- }
-
- if (await IsLocalIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false))
- {
- resultList.Add(address);
-
- if (limit > 0 && resultList.Count >= limit)
- {
- return resultList;
- }
- }
+ return smart.Trim('/');
}
- return resultList;
+ return GetLocalApiUrl(smart.Trim('/'), null, port);
}
- public IPAddress NormalizeConfiguredLocalAddress(ReadOnlySpan<char> address)
+ /// <inheritdoc/>
+ public string GetLoopbackHttpApiUrl()
{
- var index = address.Trim('/').IndexOf('/');
- if (index != -1)
+ if (NetManager.IsIP6Enabled)
{
- address = address.Slice(index + 1);
+ return GetLocalApiUrl("::1", Uri.UriSchemeHttp, HttpPort);
}
- if (IPAddress.TryParse(address.Trim('/'), out IPAddress result))
- {
- return result;
- }
-
- return null;
+ return GetLocalApiUrl("127.0.0.1", Uri.UriSchemeHttp, HttpPort);
}
- private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
-
- private async Task<bool> IsLocalIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken)
+ /// <inheritdoc/>
+ public string GetLocalApiUrl(string host, string scheme = null, int? port = null)
{
- if (address.Equals(IPAddress.Loopback)
- || address.Equals(IPAddress.IPv6Loopback))
- {
- return true;
- }
-
- var apiUrl = GetLocalApiUrl(address) + "/system/ping";
-
- if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
- {
- return cachedResult;
- }
-
- try
- {
- using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl);
- using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
- .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
-
- await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
- var result = await System.Text.Json.JsonSerializer.DeserializeAsync<string>(stream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false);
- var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
-
- _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
- Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
- return valid;
- }
- catch (OperationCanceledException)
- {
- Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
- throw;
- }
- catch (Exception ex)
+ // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
+ // not. For consistency, always trim the trailing slash.
+ return new UriBuilder
{
- Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
-
- _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
- return false;
- }
+ Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp),
+ Host = host,
+ Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort),
+ Path = ServerConfigurationManager.GetNetworkConfiguration().BaseUrl
+ }.ToString().TrimEnd('/');
}
public string FriendlyName =>
diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj
index d360bb00f..dab4ec5a6 100644
--- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj
+++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj
@@ -22,7 +22,6 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="IPNetwork2" Version="2.5.226" />
<PackageReference Include="Jellyfin.XmlTv" Version="10.6.2" />
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.7" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="2.2.0" />
diff --git a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
index 2e8cc76d2..14201ead2 100644
--- a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
+++ b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
@@ -8,6 +8,7 @@ using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Data.Events;
+using Jellyfin.Networking.Configuration;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Plugins;
@@ -56,7 +57,7 @@ namespace Emby.Server.Implementations.EntryPoints
private string GetConfigIdentifier()
{
const char Separator = '|';
- var config = _config.Configuration;
+ var config = _config.GetNetworkConfiguration();
return new StringBuilder(32)
.Append(config.EnableUPnP).Append(Separator)
@@ -93,7 +94,8 @@ namespace Emby.Server.Implementations.EntryPoints
private void Start()
{
- if (!_config.Configuration.EnableUPnP || !_config.Configuration.EnableRemoteAccess)
+ var config = _config.GetNetworkConfiguration();
+ if (!config.EnableUPnP || !config.EnableRemoteAccess)
{
return;
}
@@ -156,11 +158,12 @@ namespace Emby.Server.Implementations.EntryPoints
private IEnumerable<Task> CreatePortMaps(INatDevice device)
{
- yield return CreatePortMap(device, _appHost.HttpPort, _config.Configuration.PublicPort);
+ var config = _config.GetNetworkConfiguration();
+ yield return CreatePortMap(device, _appHost.HttpPort, config.PublicPort);
if (_appHost.ListenWithHttps)
{
- yield return CreatePortMap(device, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort);
+ yield return CreatePortMap(device, _appHost.HttpsPort, config.PublicHttpsPort);
}
}
diff --git a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs
index 8a0c0043a..3a738fd5d 100644
--- a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs
+++ b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs
@@ -76,7 +76,6 @@ namespace Emby.Server.Implementations.LiveTv
}
var list = sources.ToList();
- var serverUrl = await _appHost.GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
foreach (var source in list)
{
@@ -103,7 +102,7 @@ namespace Emby.Server.Implementations.LiveTv
// Dummy this up so that direct play checks can still run
if (string.IsNullOrEmpty(source.Path) && source.Protocol == MediaProtocol.Http)
{
- source.Path = serverUrl;
+ source.Path = _appHost.GetSmartApiUrl(string.Empty);
}
}
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs
index 858c10030..b092ffd6e 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs
@@ -3,7 +3,9 @@
using System;
using System.Collections.Generic;
using System.IO;
+using System.Linq;
using System.Net;
+using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
@@ -50,6 +52,25 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
EnableStreamSharing = true;
}
+ /// <summary>
+ /// Returns an unused UDP port number in the range specified.
+ /// </summary>
+ /// <param name="range">Upper and Lower boundary of ports to select.</param>
+ /// <returns>System.Int32.</returns>
+ private static int GetUdpPortFromRange((int Min, int Max) range)
+ {
+ var properties = IPGlobalProperties.GetIPGlobalProperties();
+
+ // Get active udp listeners.
+ var udpListenerPorts = properties.GetActiveUdpListeners()
+ .Where(n => n.Port >= range.Min && n.Port <= range.Max)
+ .Select(n => n.Port);
+
+ return Enumerable.Range(range.Min, range.Max)
+ .Where(i => !udpListenerPorts.Contains(i))
+ .FirstOrDefault();
+ }
+
public override async Task Open(CancellationToken openCancellationToken)
{
LiveStreamCancellationTokenSource.Token.ThrowIfCancellationRequested();
@@ -57,7 +78,8 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
var mediaSource = OriginalMediaSource;
var uri = new Uri(mediaSource.Path);
- var localPort = _networkManager.GetRandomUnusedUdpPort();
+ // Temporary Code to reduce PR size.
+ var localPort = GetUdpPortFromRange((49152, 65535));
Directory.CreateDirectory(Path.GetDirectoryName(TempFilePath));
diff --git a/Emby.Server.Implementations/Networking/NetworkManager.cs b/Emby.Server.Implementations/Networking/NetworkManager.cs
deleted file mode 100644
index 089ec30e6..000000000
--- a/Emby.Server.Implementations/Networking/NetworkManager.cs
+++ /dev/null
@@ -1,556 +0,0 @@
-#pragma warning disable CS1591
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Net;
-using System.Net.NetworkInformation;
-using System.Net.Sockets;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.Networking
-{
- /// <summary>
- /// Class to take care of network interface management.
- /// </summary>
- public class NetworkManager : INetworkManager
- {
- private readonly ILogger<NetworkManager> _logger;
-
- private IPAddress[] _localIpAddresses;
- private readonly object _localIpAddressSyncLock = new object();
-
- private readonly object _subnetLookupLock = new object();
- private readonly Dictionary<string, List<string>> _subnetLookup = new Dictionary<string, List<string>>(StringComparer.Ordinal);
-
- private List<PhysicalAddress> _macAddresses;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="NetworkManager"/> class.
- /// </summary>
- /// <param name="logger">Logger to use for messages.</param>
- public NetworkManager(ILogger<NetworkManager> logger)
- {
- _logger = logger;
-
- NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged;
- NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged;
- }
-
- /// <inheritdoc/>
- public event EventHandler NetworkChanged;
-
- /// <inheritdoc/>
- public Func<string[]> LocalSubnetsFn { get; set; }
-
- private void OnNetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
- {
- _logger.LogDebug("NetworkAvailabilityChanged");
- OnNetworkChanged();
- }
-
- private void OnNetworkAddressChanged(object sender, EventArgs e)
- {
- _logger.LogDebug("NetworkAddressChanged");
- OnNetworkChanged();
- }
-
- private void OnNetworkChanged()
- {
- lock (_localIpAddressSyncLock)
- {
- _localIpAddresses = null;
- _macAddresses = null;
- }
-
- NetworkChanged?.Invoke(this, EventArgs.Empty);
- }
-
- /// <inheritdoc/>
- public IPAddress[] GetLocalIpAddresses()
- {
- lock (_localIpAddressSyncLock)
- {
- if (_localIpAddresses == null)
- {
- var addresses = GetLocalIpAddressesInternal().ToArray();
-
- _localIpAddresses = addresses;
- }
-
- return _localIpAddresses;
- }
- }
-
- private List<IPAddress> GetLocalIpAddressesInternal()
- {
- var list = GetIPsDefault().ToList();
-
- if (list.Count == 0)
- {
- list = GetLocalIpAddressesFallback().GetAwaiter().GetResult().ToList();
- }
-
- var listClone = new List<IPAddress>();
-
- var subnets = LocalSubnetsFn();
-
- foreach (var i in list)
- {
- if (i.IsIPv6LinkLocal || i.ToString().StartsWith("169.254.", StringComparison.OrdinalIgnoreCase))
- {
- continue;
- }
-
- if (Array.IndexOf(subnets, $"[{i}]") == -1)
- {
- listClone.Add(i);
- }
- }
-
- return listClone
- .OrderBy(i => i.AddressFamily == AddressFamily.InterNetwork ? 0 : 1)
- // .ThenBy(i => listClone.IndexOf(i))
- .GroupBy(i => i.ToString())
- .Select(x => x.First())
- .ToList();
- }
-
- /// <inheritdoc/>
- public bool IsInPrivateAddressSpace(string endpoint)
- {
- return IsInPrivateAddressSpace(endpoint, true);
- }
-
- // Checks if the address in endpoint is an RFC1918, RFC1122, or RFC3927 address
- private bool IsInPrivateAddressSpace(string endpoint, bool checkSubnets)
- {
- if (string.Equals(endpoint, "::1", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
-
- // IPV6
- if (endpoint.Split('.').Length > 4)
- {
- // Handle ipv4 mapped to ipv6
- var originalEndpoint = endpoint;
- endpoint = endpoint.Replace("::ffff:", string.Empty, StringComparison.OrdinalIgnoreCase);
-
- if (string.Equals(endpoint, originalEndpoint, StringComparison.OrdinalIgnoreCase))
- {
- return false;
- }
- }
-
- // Private address space:
-
- if (string.Equals(endpoint, "localhost", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
-
- if (!IPAddress.TryParse(endpoint, out var ipAddress))
- {
- return false;
- }
-
- byte[] octet = ipAddress.GetAddressBytes();
-
- if ((octet[0] == 10) ||
- (octet[0] == 172 && (octet[1] >= 16 && octet[1] <= 31)) || // RFC1918
- (octet[0] == 192 && octet[1] == 168) || // RFC1918
- (octet[0] == 127) || // RFC1122
- (octet[0] == 169 && octet[1] == 254)) // RFC3927
- {
- return true;
- }
-
- if (checkSubnets && IsInPrivateAddressSpaceAndLocalSubnet(endpoint))
- {
- return true;
- }
-
- return false;
- }
-
- /// <inheritdoc/>
- public bool IsInPrivateAddressSpaceAndLocalSubnet(string endpoint)
- {
- if (endpoint.StartsWith("10.", StringComparison.OrdinalIgnoreCase))
- {
- var endpointFirstPart = endpoint.Split('.')[0];
-
- var subnets = GetSubnets(endpointFirstPart);
-
- foreach (var subnet_Match in subnets)
- {
- // logger.LogDebug("subnet_Match:" + subnet_Match);
-
- if (endpoint.StartsWith(subnet_Match + ".", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- // Gives a list of possible subnets from the system whose interface ip starts with endpointFirstPart
- private List<string> GetSubnets(string endpointFirstPart)
- {
- lock (_subnetLookupLock)
- {
- if (_subnetLookup.TryGetValue(endpointFirstPart, out var subnets))
- {
- return subnets;
- }
-
- subnets = new List<string>();
-
- foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces())
- {
- foreach (var unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses)
- {
- if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork && endpointFirstPart == unicastIPAddressInformation.Address.ToString().Split('.')[0])
- {
- int subnet_Test = 0;
- foreach (string part in unicastIPAddressInformation.IPv4Mask.ToString().Split('.'))
- {
- if (part.Equals("0", StringComparison.Ordinal))
- {
- break;
- }
-
- subnet_Test++;
- }
-
- var subnet_Match = string.Join(".", unicastIPAddressInformation.Address.ToString().Split('.').Take(subnet_Test).ToArray());
-
- // TODO: Is this check necessary?
- if (adapter.OperationalStatus == OperationalStatus.Up)
- {
- subnets.Add(subnet_Match);
- }
- }
- }
- }
-
- _subnetLookup[endpointFirstPart] = subnets;
-
- return subnets;
- }
- }
-
- /// <inheritdoc/>
- public bool IsInLocalNetwork(string endpoint)
- {
- return IsInLocalNetworkInternal(endpoint, true);
- }
-
- /// <inheritdoc/>
- public bool IsAddressInSubnets(string addressString, string[] subnets)
- {
- return IsAddressInSubnets(IPAddress.Parse(addressString), addressString, subnets);
- }
-
- /// <inheritdoc/>
- public bool IsAddressInSubnets(IPAddress address, bool excludeInterfaces, bool excludeRFC)
- {
- byte[] octet = address.GetAddressBytes();
-
- if ((octet[0] == 127) || // RFC1122
- (octet[0] == 169 && octet[1] == 254)) // RFC3927
- {
- // don't use on loopback or 169 interfaces
- return false;
- }
-
- string addressString = address.ToString();
- string excludeAddress = "[" + addressString + "]";
- var subnets = LocalSubnetsFn();
-
- // Include any address if LAN subnets aren't specified
- if (subnets.Length == 0)
- {
- return true;
- }
-
- // Exclude any addresses if they appear in the LAN list in [ ]
- if (Array.IndexOf(subnets, excludeAddress) != -1)
- {
- return false;
- }
-
- return IsAddressInSubnets(address, addressString, subnets);
- }
-
- /// <summary>
- /// Checks if the give address falls within the ranges given in [subnets]. The addresses in subnets can be hosts or subnets in the CIDR format.
- /// </summary>
- /// <param name="address">IPAddress version of the address.</param>
- /// <param name="addressString">The address to check.</param>
- /// <param name="subnets">If true, check against addresses in the LAN settings which have [] arroud and return true if it matches the address give in address.</param>
- /// <returns><c>false</c>if the address isn't in the subnets, <c>true</c> otherwise.</returns>
- private static bool IsAddressInSubnets(IPAddress address, string addressString, string[] subnets)
- {
- foreach (var subnet in subnets)
- {
- var normalizedSubnet = subnet.Trim();
- // Is the subnet a host address and does it match the address being passes?
- if (string.Equals(normalizedSubnet, addressString, StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
-
- // Parse CIDR subnets and see if address falls within it.
- if (normalizedSubnet.Contains('/', StringComparison.Ordinal))
- {
- try
- {
- var ipNetwork = IPNetwork.Parse(normalizedSubnet);
- if (ipNetwork.Contains(address))
- {
- return true;
- }
- }
- catch
- {
- // Ignoring - invalid subnet passed encountered.
- }
- }
- }
-
- return false;
- }
-
- private bool IsInLocalNetworkInternal(string endpoint, bool resolveHost)
- {
- if (string.IsNullOrEmpty(endpoint))
- {
- throw new ArgumentNullException(nameof(endpoint));
- }
-
- if (IPAddress.TryParse(endpoint, out var address))
- {
- var addressString = address.ToString();
-
- var localSubnetsFn = LocalSubnetsFn;
- if (localSubnetsFn != null)
- {
- var localSubnets = localSubnetsFn();
- foreach (var subnet in localSubnets)
- {
- // Only validate if there's at least one valid entry.
- if (!string.IsNullOrWhiteSpace(subnet))
- {
- return IsAddressInSubnets(address, addressString, localSubnets) || IsInPrivateAddressSpace(addressString, false);
- }
- }
- }
-
- int lengthMatch = 100;
- if (address.AddressFamily == AddressFamily.InterNetwork)
- {
- lengthMatch = 4;
- if (IsInPrivateAddressSpace(addressString, true))
- {
- return true;
- }
- }
- else if (address.AddressFamily == AddressFamily.InterNetworkV6)
- {
- lengthMatch = 9;
- if (IsInPrivateAddressSpace(endpoint, true))
- {
- return true;
- }
- }
-
- // Should be even be doing this with ipv6?
- if (addressString.Length >= lengthMatch)
- {
- var prefix = addressString.Substring(0, lengthMatch);
-
- if (GetLocalIpAddresses().Any(i => i.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
- {
- return true;
- }
- }
- }
- else if (resolveHost)
- {
- if (Uri.TryCreate(endpoint, UriKind.RelativeOrAbsolute, out var uri))
- {
- try
- {
- var host = uri.DnsSafeHost;
- _logger.LogDebug("Resolving host {0}", host);
-
- address = GetIpAddresses(host).GetAwaiter().GetResult().FirstOrDefault();
-
- if (address != null)
- {
- _logger.LogDebug("{0} resolved to {1}", host, address);
-
- return IsInLocalNetworkInternal(address.ToString(), false);
- }
- }
- catch (InvalidOperationException)
- {
- // Can happen with reverse proxy or IIS url rewriting?
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error resolving hostname");
- }
- }
- }
-
- return false;
- }
-
- private static Task<IPAddress[]> GetIpAddresses(string hostName)
- {
- return Dns.GetHostAddressesAsync(hostName);
- }
-
- private IEnumerable<IPAddress> GetIPsDefault()
- {
- IEnumerable<NetworkInterface> interfaces;
-
- try
- {
- interfaces = NetworkInterface.GetAllNetworkInterfaces()
- .Where(x => x.OperationalStatus == OperationalStatus.Up
- || x.OperationalStatus == OperationalStatus.Unknown);
- }
- catch (NetworkInformationException ex)
- {
- _logger.LogError(ex, "Error in GetAllNetworkInterfaces");
- return Enumerable.Empty<IPAddress>();
- }
-
- return interfaces.SelectMany(network =>
- {
- var ipProperties = network.GetIPProperties();
-
- // Exclude any addresses if they appear in the LAN list in [ ]
-
- return ipProperties.UnicastAddresses
- .Select(i => i.Address)
- .Where(i => i.AddressFamily == AddressFamily.InterNetwork || i.AddressFamily == AddressFamily.InterNetworkV6);
- }).GroupBy(i => i.ToString())
- .Select(x => x.First());
- }
-
- private static async Task<IEnumerable<IPAddress>> GetLocalIpAddressesFallback()
- {
- var host = await Dns.GetHostEntryAsync(Dns.GetHostName()).ConfigureAwait(false);
-
- // Reverse them because the last one is usually the correct one
- // It's not fool-proof so ultimately the consumer will have to examine them and decide
- return host.AddressList
- .Where(i => i.AddressFamily == AddressFamily.InterNetwork || i.AddressFamily == AddressFamily.InterNetworkV6)
- .Reverse();
- }
-
- /// <summary>
- /// Gets a random port number that is currently available.
- /// </summary>
- /// <returns>System.Int32.</returns>
- public int GetRandomUnusedTcpPort()
- {
- var listener = new TcpListener(IPAddress.Any, 0);
- listener.Start();
- var port = ((IPEndPoint)listener.LocalEndpoint).Port;
- listener.Stop();
- return port;
- }
-
- /// <inheritdoc/>
- public int GetRandomUnusedUdpPort()
- {
- var localEndPoint = new IPEndPoint(IPAddress.Any, 0);
- using (var udpClient = new UdpClient(localEndPoint))
- {
- return ((IPEndPoint)udpClient.Client.LocalEndPoint).Port;
- }
- }
-
- /// <inheritdoc/>
- public List<PhysicalAddress> GetMacAddresses()
- {
- return _macAddresses ??= GetMacAddressesInternal().ToList();
- }
-
- private static IEnumerable<PhysicalAddress> GetMacAddressesInternal()
- => NetworkInterface.GetAllNetworkInterfaces()
- .Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback)
- .Select(x => x.GetPhysicalAddress())
- .Where(x => !x.Equals(PhysicalAddress.None));
-
- /// <inheritdoc/>
- public bool IsInSameSubnet(IPAddress address1, IPAddress address2, IPAddress subnetMask)
- {
- IPAddress network1 = GetNetworkAddress(address1, subnetMask);
- IPAddress network2 = GetNetworkAddress(address2, subnetMask);
- return network1.Equals(network2);
- }
-
- private IPAddress GetNetworkAddress(IPAddress address, IPAddress subnetMask)
- {
- byte[] ipAdressBytes = address.GetAddressBytes();
- byte[] subnetMaskBytes = subnetMask.GetAddressBytes();
-
- if (ipAdressBytes.Length != subnetMaskBytes.Length)
- {
- throw new ArgumentException("Lengths of IP address and subnet mask do not match.");
- }
-
- byte[] broadcastAddress = new byte[ipAdressBytes.Length];
- for (int i = 0; i < broadcastAddress.Length; i++)
- {
- broadcastAddress[i] = (byte)(ipAdressBytes[i] & subnetMaskBytes[i]);
- }
-
- return new IPAddress(broadcastAddress);
- }
-
- /// <inheritdoc/>
- public IPAddress GetLocalIpSubnetMask(IPAddress address)
- {
- NetworkInterface[] interfaces;
-
- try
- {
- var validStatuses = new[] { OperationalStatus.Up, OperationalStatus.Unknown };
-
- interfaces = NetworkInterface.GetAllNetworkInterfaces()
- .Where(i => validStatuses.Contains(i.OperationalStatus))
- .ToArray();
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error in GetAllNetworkInterfaces");
- return null;
- }
-
- foreach (NetworkInterface ni in interfaces)
- {
- foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
- {
- if (ip.Address.Equals(address) && ip.IPv4Mask != null)
- {
- return ip.IPv4Mask;
- }
- }
- }
-
- return null;
- }
- }
-}
diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs
index b7a59cee2..4fd7ac0c1 100644
--- a/Emby.Server.Implementations/Udp/UdpServer.cs
+++ b/Emby.Server.Implementations/Udp/UdpServer.cs
@@ -49,7 +49,7 @@ namespace Emby.Server.Implementations.Udp
{
string localUrl = !string.IsNullOrEmpty(_config[AddressOverrideConfigKey])
? _config[AddressOverrideConfigKey]
- : await _appHost.GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
+ : _appHost.GetSmartApiUrl(((IPEndPoint)endpoint).Address);
if (!string.IsNullOrEmpty(localUrl))
{
diff --git a/Jellyfin.Api/Controllers/StartupController.cs b/Jellyfin.Api/Controllers/StartupController.cs
index 9c259cc19..d9cb34557 100644
--- a/Jellyfin.Api/Controllers/StartupController.cs
+++ b/Jellyfin.Api/Controllers/StartupController.cs
@@ -3,6 +3,7 @@ using System.Linq;
using System.Threading.Tasks;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Models.StartupDtos;
+using Jellyfin.Networking.Configuration;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Library;
using Microsoft.AspNetCore.Authorization;
@@ -72,9 +73,9 @@ namespace Jellyfin.Api.Controllers
[ProducesResponseType(StatusCodes.Status204NoContent)]
public ActionResult UpdateInitialConfiguration([FromBody, Required] StartupConfigurationDto startupConfiguration)
{
- _config.Configuration.UICulture = startupConfiguration.UICulture;
- _config.Configuration.MetadataCountryCode = startupConfiguration.MetadataCountryCode;
- _config.Configuration.PreferredMetadataLanguage = startupConfiguration.PreferredMetadataLanguage;
+ _config.Configuration.UICulture = startupConfiguration.UICulture ?? string.Empty;
+ _config.Configuration.MetadataCountryCode = startupConfiguration.MetadataCountryCode ?? string.Empty;
+ _config.Configuration.PreferredMetadataLanguage = startupConfiguration.PreferredMetadataLanguage ?? string.Empty;
_config.SaveConfiguration();
return NoContent();
}
@@ -89,9 +90,10 @@ namespace Jellyfin.Api.Controllers
[ProducesResponseType(StatusCodes.Status204NoContent)]
public ActionResult SetRemoteAccess([FromBody, Required] StartupRemoteAccessDto startupRemoteAccessDto)
{
- _config.Configuration.EnableRemoteAccess = startupRemoteAccessDto.EnableRemoteAccess;
- _config.Configuration.EnableUPnP = startupRemoteAccessDto.EnableAutomaticPortMapping;
- _config.SaveConfiguration();
+ NetworkConfiguration settings = _config.GetNetworkConfiguration();
+ settings.EnableRemoteAccess = startupRemoteAccessDto.EnableRemoteAccess;
+ settings.EnableUPnP = startupRemoteAccessDto.EnableAutomaticPortMapping;
+ _config.SaveConfiguration("network", settings);
return NoContent();
}
diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs
index 4cb1984a2..7784e8a11 100644
--- a/Jellyfin.Api/Controllers/SystemController.cs
+++ b/Jellyfin.Api/Controllers/SystemController.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
@@ -64,9 +64,9 @@ namespace Jellyfin.Api.Controllers
[HttpGet("Info")]
[Authorize(Policy = Policies.FirstTimeSetupOrIgnoreParentalControl)]
[ProducesResponseType(StatusCodes.Status200OK)]
- public async Task<ActionResult<SystemInfo>> GetSystemInfo()
+ public ActionResult<SystemInfo> GetSystemInfo()
{
- return await _appHost.GetSystemInfo(CancellationToken.None).ConfigureAwait(false);
+ return _appHost.GetSystemInfo(Request.HttpContext.Connection.RemoteIpAddress);
}
/// <summary>
@@ -76,9 +76,9 @@ namespace Jellyfin.Api.Controllers
/// <returns>A <see cref="PublicSystemInfo"/> with public info about the system.</returns>
[HttpGet("Info/Public")]
[ProducesResponseType(StatusCodes.Status200OK)]
- public async Task<ActionResult<PublicSystemInfo>> GetPublicSystemInfo()
+ public ActionResult<PublicSystemInfo> GetPublicSystemInfo()
{
- return await _appHost.GetPublicSystemInfo(CancellationToken.None).ConfigureAwait(false);
+ return _appHost.GetPublicSystemInfo(Request.HttpContext.Connection.RemoteIpAddress);
}
/// <summary>
diff --git a/Jellyfin.Api/Helpers/ClassMigrationHelper.cs b/Jellyfin.Api/Helpers/ClassMigrationHelper.cs
new file mode 100644
index 000000000..123fd012d
--- /dev/null
+++ b/Jellyfin.Api/Helpers/ClassMigrationHelper.cs
@@ -0,0 +1,70 @@
+using System;
+using System.Reflection;
+
+namespace Jellyfin.Api.Migrations
+{
+ /// <summary>
+ /// A static class for reflection type functions. Temporary until web changed.
+ /// </summary>
+ public static class ClassMigrationHelper
+ {
+ /// <summary>
+ /// Extension for 'Object' that copies the properties to a destination object.
+ /// </summary>
+ /// <param name="source">The source.</param>
+ /// <param name="destination">The destination.</param>
+ public static void CopyProperties(this object source, object destination)
+ {
+ // If any this null throw an exception
+ if (source == null || destination == null)
+ {
+ throw new Exception("Source or/and Destination Objects are null");
+ }
+
+ // Getting the Types of the objects
+ Type typeDest = destination.GetType();
+ Type typeSrc = source.GetType();
+
+ // Iterate the Properties of the source instance and populate them from their desination counterparts.
+ PropertyInfo[] srcProps = typeSrc.GetProperties();
+ foreach (PropertyInfo srcProp in srcProps)
+ {
+ if (!srcProp.CanRead)
+ {
+ continue;
+ }
+
+ var targetProperty = typeDest.GetProperty(srcProp.Name);
+ if (targetProperty == null)
+ {
+ continue;
+ }
+
+ if (!targetProperty.CanWrite)
+ {
+ continue;
+ }
+
+ var obj = targetProperty.GetSetMethod(true);
+ if (obj != null && obj.IsPrivate)
+ {
+ continue;
+ }
+
+ var target = targetProperty.GetSetMethod();
+ if (target != null && (target.Attributes & MethodAttributes.Static) != 0)
+ {
+ continue;
+ }
+
+ if (!targetProperty.PropertyType.IsAssignableFrom(srcProp.PropertyType))
+ {
+ continue;
+ }
+
+ // Passed all tests, lets set the value
+ targetProperty.SetValue(destination, srcProp.GetValue(source, null), null);
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs
new file mode 100644
index 000000000..e710eb3c7
--- /dev/null
+++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs
@@ -0,0 +1,223 @@
+#pragma warning disable CA1819 // Properties should not return arrays
+
+using System;
+using MediaBrowser.Model.Configuration;
+
+namespace Jellyfin.Networking.Configuration
+{
+ /// <summary>
+ /// Defines the <see cref="NetworkConfiguration" />.
+ /// </summary>
+ public class NetworkConfiguration
+ {
+ /// <summary>
+ /// The default value for <see cref="HttpServerPortNumber"/>.
+ /// </summary>
+ public const int DefaultHttpPort = 8096;
+
+ /// <summary>
+ /// The default value for <see cref="PublicHttpsPort"/> and <see cref="HttpsPortNumber"/>.
+ /// </summary>
+ public const int DefaultHttpsPort = 8920;
+
+ private string _baseUrl = string.Empty;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the server should force connections over HTTPS.
+ /// </summary>
+ public bool RequireHttps { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value used to specify the URL prefix that your Jellyfin instance can be accessed at.
+ /// </summary>
+ public string BaseUrl
+ {
+ get => _baseUrl;
+ set
+ {
+ // Normalize the start of the string
+ if (string.IsNullOrWhiteSpace(value))
+ {
+ // If baseUrl is empty, set an empty prefix string
+ _baseUrl = string.Empty;
+ return;
+ }
+
+ if (value[0] != '/')
+ {
+ // If baseUrl was not configured with a leading slash, append one for consistency
+ value = "/" + value;
+ }
+
+ // Normalize the end of the string
+ if (value[^1] == '/')
+ {
+ // If baseUrl was configured with a trailing slash, remove it for consistency
+ value = value.Remove(value.Length - 1);
+ }
+
+ _baseUrl = value;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the public HTTPS port.
+ /// </summary>
+ /// <value>The public HTTPS port.</value>
+ public int PublicHttpsPort { get; set; } = DefaultHttpsPort;
+
+ /// <summary>
+ /// Gets or sets the HTTP server port number.
+ /// </summary>
+ /// <value>The HTTP server port number.</value>
+ public int HttpServerPortNumber { get; set; } = DefaultHttpPort;
+
+ /// <summary>
+ /// Gets or sets the HTTPS server port number.
+ /// </summary>
+ /// <value>The HTTPS server port number.</value>
+ public int HttpsPortNumber { get; set; } = DefaultHttpsPort;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to use HTTPS.
+ /// </summary>
+ /// <remarks>
+ /// In order for HTTPS to be used, in addition to setting this to true, valid values must also be
+ /// provided for <see cref="ServerConfiguration.CertificatePath"/> and <see cref="ServerConfiguration.CertificatePassword"/>.
+ /// </remarks>
+ public bool EnableHttps { get; set; }
+
+ /// <summary>
+ /// Gets or sets the public mapped port.
+ /// </summary>
+ /// <value>The public mapped port.</value>
+ public int PublicPort { get; set; } = DefaultHttpPort;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding.
+ /// </summary>
+ public bool UPnPCreateHttpPortMap { get; set; }
+
+ /// <summary>
+ /// Gets or sets the UDPPortRange
+ /// Gets or sets client udp port range.
+ /// </summary>
+ public string UDPPortRange { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether gets or sets IPV6 capability.
+ /// </summary>
+ public bool EnableIPV6 { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether gets or sets IPV4 capability.
+ /// </summary>
+ public bool EnableIPV4 { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether detailed ssdp logs are sent to the console/log.
+ /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to work.
+ /// </summary>
+ public bool EnableSSDPTracing { get; set; }
+
+ /// <summary>
+ /// Gets or sets the SSDPTracingFilter
+ /// Gets or sets a value indicating whether an IP address is to be used to filter the detailed ssdp logs that are being sent to the console/log.
+ /// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work.
+ /// </summary>
+ public string SSDPTracingFilter { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the number of times SSDP UDP messages are sent.
+ /// </summary>
+ public int UDPSendCount { get; set; } = 2;
+
+ /// <summary>
+ /// Gets or sets the delay between each groups of SSDP messages (in ms).
+ /// </summary>
+ public int UDPSendDelay { get; set; } = 100;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether address names that match <see cref="VirtualInterfaceNames"/> should be Ignore for the purposes of binding.
+ /// </summary>
+ public bool IgnoreVirtualInterfaces { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets the VirtualInterfaceNames
+ /// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. <seealso cref="IgnoreVirtualInterfaces"/>.
+ /// </summary>
+ public string VirtualInterfaceNames { get; set; } = "vEthernet*";
+
+ /// <summary>
+ /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor.
+ /// </summary>
+ public int GatewayMonitorPeriod { get; set; } = 60;
+
+ /// <summary>
+ /// Gets a value indicating whether multi-socket binding is available.
+ /// </summary>
+ public bool EnableMultiSocketBinding { get; } = true;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether all IPv6 interfaces should be treated as on the internal network.
+ /// Depending on the address range implemented ULA ranges might not be used.
+ /// </summary>
+ public bool TrustAllIP6Interfaces { get; set; }
+
+ /// <summary>
+ /// Gets or sets the ports that HDHomerun uses.
+ /// </summary>
+ public string HDHomerunPortRange { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the PublishedServerUriBySubnet
+ /// Gets or sets PublishedServerUri to advertise for specific subnets.
+ /// </summary>
+ public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets a value indicating whether Autodiscovery tracing is enabled.
+ /// </summary>
+ public bool AutoDiscoveryTracing { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether Autodiscovery is enabled.
+ /// </summary>
+ public bool AutoDiscovery { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets the filter for remote IP connectivity. Used in conjuntion with <seealso cref="IsRemoteIPFilterBlacklist"/>.
+ /// </summary>
+ public string[] RemoteIPFilter { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets a value indicating whether <seealso cref="RemoteIPFilter"/> contains a blacklist or a whitelist. Default is a whitelist.
+ /// </summary>
+ public bool IsRemoteIPFilterBlacklist { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to enable automatic port forwarding.
+ /// </summary>
+ public bool EnableUPnP { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether access outside of the LAN is permitted.
+ /// </summary>
+ public bool EnableRemoteAccess { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets the subnets that are deemed to make up the LAN.
+ /// </summary>
+ public string[] LocalNetworkSubnets { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used.
+ /// </summary>
+ public string[] LocalNetworkAddresses { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets the known proxies.
+ /// </summary>
+ public string[] KnownProxies { get; set; } = Array.Empty<string>();
+ }
+}
diff --git a/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs b/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs
new file mode 100644
index 000000000..e77b17ba9
--- /dev/null
+++ b/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs
@@ -0,0 +1,21 @@
+using Jellyfin.Networking.Configuration;
+using MediaBrowser.Common.Configuration;
+
+namespace Jellyfin.Networking.Configuration
+{
+ /// <summary>
+ /// Defines the <see cref="NetworkConfigurationExtensions" />.
+ /// </summary>
+ public static class NetworkConfigurationExtensions
+ {
+ /// <summary>
+ /// Retrieves the network configuration.
+ /// </summary>
+ /// <param name="config">The <see cref="IConfigurationManager"/>.</param>
+ /// <returns>The <see cref="NetworkConfiguration"/>.</returns>
+ public static NetworkConfiguration GetNetworkConfiguration(this IConfigurationManager config)
+ {
+ return config.GetConfiguration<NetworkConfiguration>("network");
+ }
+ }
+}
diff --git a/Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs b/Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs
new file mode 100644
index 000000000..ac0485d87
--- /dev/null
+++ b/Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs
@@ -0,0 +1,27 @@
+using System.Collections.Generic;
+using MediaBrowser.Common.Configuration;
+
+namespace Jellyfin.Networking.Configuration
+{
+ /// <summary>
+ /// Defines the <see cref="NetworkConfigurationFactory" />.
+ /// </summary>
+ public class NetworkConfigurationFactory : IConfigurationFactory
+ {
+ /// <summary>
+ /// The GetConfigurations.
+ /// </summary>
+ /// <returns>The <see cref="IEnumerable{ConfigurationStore}"/>.</returns>
+ public IEnumerable<ConfigurationStore> GetConfigurations()
+ {
+ return new[]
+ {
+ new ConfigurationStore
+ {
+ Key = "network",
+ ConfigurationType = typeof(NetworkConfiguration)
+ }
+ };
+ }
+ }
+}
diff --git a/Jellyfin.Networking/Jellyfin.Networking.csproj b/Jellyfin.Networking/Jellyfin.Networking.csproj
new file mode 100644
index 000000000..cbda74361
--- /dev/null
+++ b/Jellyfin.Networking/Jellyfin.Networking.csproj
@@ -0,0 +1,30 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>net5.0</TargetFramework>
+ <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
+ <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
+ <Nullable>enable</Nullable>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <Compile Include="..\SharedVersion.cs" />
+ </ItemGroup>
+
+ <!-- Code Analyzers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8" PrivateAssets="All" />
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+
+ <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <CodeAnalysisRuleSet>../jellyfin.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
+ <ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />
+ </ItemGroup>
+</Project>
diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs
new file mode 100644
index 000000000..00711f162
--- /dev/null
+++ b/Jellyfin.Networking/Manager/NetworkManager.cs
@@ -0,0 +1,1301 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Globalization;
+using System.Linq;
+using System.Net;
+using System.Net.NetworkInformation;
+using System.Net.Sockets;
+using System.Threading.Tasks;
+using Jellyfin.Networking.Configuration;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Net;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Networking.Manager
+{
+ /// <summary>
+ /// Class to take care of network interface management.
+ /// Note: The normal collection methods and properties will not work with Collection{IPObject}. <see cref="MediaBrowser.Common.Net.NetworkExtensions"/>.
+ /// </summary>
+ public class NetworkManager : INetworkManager, IDisposable
+ {
+ /// <summary>
+ /// Contains the description of the interface along with its index.
+ /// </summary>
+ private readonly Dictionary<string, int> _interfaceNames;
+
+ /// <summary>
+ /// Threading lock for network properties.
+ /// </summary>
+ private readonly object _intLock = new object();
+
+ /// <summary>
+ /// List of all interface addresses and masks.
+ /// </summary>
+ private readonly Collection<IPObject> _interfaceAddresses;
+
+ /// <summary>
+ /// List of all interface MAC addresses.
+ /// </summary>
+ private readonly List<PhysicalAddress> _macAddresses;
+
+ private readonly ILogger<NetworkManager> _logger;
+
+ private readonly IConfigurationManager _configurationManager;
+
+ private readonly object _eventFireLock;
+
+ /// <summary>
+ /// Holds the bind address overrides.
+ /// </summary>
+ private readonly Dictionary<IPNetAddress, string> _publishedServerUrls;
+
+ /// <summary>
+ /// Used to stop "event-racing conditions".
+ /// </summary>
+ private bool _eventfire;
+
+ /// <summary>
+ /// Unfiltered user defined LAN subnets. (<see cref="NetworkConfiguration.LocalNetworkSubnets"/>)
+ /// or internal interface network subnets if undefined by user.
+ /// </summary>
+ private Collection<IPObject> _lanSubnets;
+
+ /// <summary>
+ /// User defined list of subnets to excluded from the LAN.
+ /// </summary>
+ private Collection<IPObject> _excludedSubnets;
+
+ /// <summary>
+ /// List of interface addresses to bind the WS.
+ /// </summary>
+ private Collection<IPObject> _bindAddresses;
+
+ /// <summary>
+ /// List of interface addresses to exclude from bind.
+ /// </summary>
+ private Collection<IPObject> _bindExclusions;
+
+ /// <summary>
+ /// Caches list of all internal filtered interface addresses and masks.
+ /// </summary>
+ private Collection<IPObject> _internalInterfaces;
+
+ /// <summary>
+ /// Flag set when no custom LAN has been defined in the config.
+ /// </summary>
+ private bool _usingPrivateAddresses;
+
+ /// <summary>
+ /// True if this object is disposed.
+ /// </summary>
+ private bool _disposed;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="NetworkManager"/> class.
+ /// </summary>
+ /// <param name="configurationManager">IServerConfigurationManager instance.</param>
+ /// <param name="logger">Logger to use for messages.</param>
+#pragma warning disable CS8618 // Non-nullable field is uninitialized. : Values are set in UpdateSettings function. Compiler doesn't yet recognise this.
+ public NetworkManager(IConfigurationManager configurationManager, ILogger<NetworkManager> logger)
+ {
+ _logger = logger ?? throw new ArgumentNullException(nameof(logger));
+ _configurationManager = configurationManager ?? throw new ArgumentNullException(nameof(configurationManager));
+
+ _interfaceAddresses = new Collection<IPObject>();
+ _macAddresses = new List<PhysicalAddress>();
+ _interfaceNames = new Dictionary<string, int>();
+ _publishedServerUrls = new Dictionary<IPNetAddress, string>();
+ _eventFireLock = new object();
+
+ UpdateSettings(_configurationManager.GetNetworkConfiguration());
+
+ NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged;
+ NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged;
+
+ _configurationManager.NamedConfigurationUpdated += ConfigurationUpdated;
+ }
+#pragma warning restore CS8618 // Non-nullable field is uninitialized.
+
+ /// <summary>
+ /// Event triggered on network changes.
+ /// </summary>
+ public event EventHandler? NetworkChanged;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether testing is taking place.
+ /// </summary>
+ public static string MockNetworkSettings { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether IP6 is enabled.
+ /// </summary>
+ public bool IsIP6Enabled { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether IP4 is enabled.
+ /// </summary>
+ public bool IsIP4Enabled { get; set; }
+
+ /// <inheritdoc/>
+ public Collection<IPObject> RemoteAddressFilter { get; private set; }
+
+ /// <summary>
+ /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal.
+ /// </summary>
+ public bool TrustAllIP6Interfaces { get; internal set; }
+
+ /// <summary>
+ /// Gets the Published server override list.
+ /// </summary>
+ public Dictionary<IPNetAddress, string> PublishedServerUrls => _publishedServerUrls;
+
+ /// <summary>
+ /// Creates a new network collection.
+ /// </summary>
+ /// <param name="source">Items to assign the collection, or null.</param>
+ /// <returns>The collection created.</returns>
+ public static Collection<IPObject> CreateCollection(IEnumerable<IPObject>? source = null)
+ {
+ var result = new Collection<IPObject>();
+ if (source != null)
+ {
+ foreach (var item in source)
+ {
+ result.AddItem(item);
+ }
+ }
+
+ return result;
+ }
+
+ /// <inheritdoc/>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <inheritdoc/>
+ public IReadOnlyCollection<PhysicalAddress> GetMacAddresses()
+ {
+ // Populated in construction - so always has values.
+ return _macAddresses.AsReadOnly();
+ }
+
+ /// <inheritdoc/>
+ public bool IsGatewayInterface(IPObject? addressObj)
+ {
+ var address = addressObj?.Address ?? IPAddress.None;
+ return _internalInterfaces.Any(i => i.Address.Equals(address) && i.Tag < 0);
+ }
+
+ /// <inheritdoc/>
+ public bool IsGatewayInterface(IPAddress? addressObj)
+ {
+ return _internalInterfaces.Any(i => i.Address.Equals(addressObj ?? IPAddress.None) && i.Tag < 0);
+ }
+
+ /// <inheritdoc/>
+ public Collection<IPObject> GetLoopbacks()
+ {
+ Collection<IPObject> nc = new Collection<IPObject>();
+ if (IsIP4Enabled)
+ {
+ nc.AddItem(IPAddress.Loopback);
+ }
+
+ if (IsIP6Enabled)
+ {
+ nc.AddItem(IPAddress.IPv6Loopback);
+ }
+
+ return nc;
+ }
+
+ /// <inheritdoc/>
+ public bool IsExcluded(IPAddress ip)
+ {
+ return _excludedSubnets.ContainsAddress(ip);
+ }
+
+ /// <inheritdoc/>
+ public bool IsExcluded(EndPoint ip)
+ {
+ return ip != null && IsExcluded(((IPEndPoint)ip).Address);
+ }
+
+ /// <inheritdoc/>
+ public Collection<IPObject> CreateIPCollection(string[] values, bool bracketed = false)
+ {
+ Collection<IPObject> col = new Collection<IPObject>();
+ if (values == null)
+ {
+ return col;
+ }
+
+ for (int a = 0; a < values.Length; a++)
+ {
+ string v = values[a].Trim();
+
+ try
+ {
+ if (v.StartsWith('[') && v.EndsWith(']'))
+ {
+ if (bracketed)
+ {
+ AddToCollection(col, v[1..^1]);
+ }
+ }
+ else if (v.StartsWith('!'))
+ {
+ if (bracketed)
+ {
+ AddToCollection(col, v[1..]);
+ }
+ }
+ else if (!bracketed)
+ {
+ AddToCollection(col, v);
+ }
+ }
+ catch (ArgumentException e)
+ {
+ _logger.LogWarning(e, "Ignoring LAN value {value}.", v);
+ }
+ }
+
+ return col;
+ }
+
+ /// <inheritdoc/>
+ public Collection<IPObject> GetAllBindInterfaces(bool individualInterfaces = false)
+ {
+ int count = _bindAddresses.Count;
+
+ if (count == 0)
+ {
+ if (_bindExclusions.Count > 0)
+ {
+ // Return all the interfaces except the ones specifically excluded.
+ return _interfaceAddresses.Exclude(_bindExclusions);
+ }
+
+ if (individualInterfaces)
+ {
+ return new Collection<IPObject>(_interfaceAddresses);
+ }
+
+ // No bind address and no exclusions, so listen on all interfaces.
+ Collection<IPObject> result = new Collection<IPObject>();
+
+ if (IsIP4Enabled)
+ {
+ result.AddItem(IPAddress.Any);
+ }
+
+ if (IsIP6Enabled)
+ {
+ result.AddItem(IPAddress.IPv6Any);
+ }
+
+ return result;
+ }
+
+ // Remove any excluded bind interfaces.
+ return _bindAddresses.Exclude(_bindExclusions);
+ }
+
+ /// <inheritdoc/>
+ public string GetBindInterface(string source, out int? port)
+ {
+ if (!string.IsNullOrEmpty(source) && IPHost.TryParse(source, out IPHost host))
+ {
+ return GetBindInterface(host, out port);
+ }
+
+ return GetBindInterface(IPHost.None, out port);
+ }
+
+ /// <inheritdoc/>
+ public string GetBindInterface(IPAddress source, out int? port)
+ {
+ return GetBindInterface(new IPNetAddress(source), out port);
+ }
+
+ /// <inheritdoc/>
+ public string GetBindInterface(HttpRequest source, out int? port)
+ {
+ string result;
+
+ if (source != null && IPHost.TryParse(source.Host.Host, out IPHost host))
+ {
+ result = GetBindInterface(host, out port);
+ port ??= source.Host.Port;
+ }
+ else
+ {
+ result = GetBindInterface(IPNetAddress.None, out port);
+ port ??= source?.Host.Port;
+ }
+
+ return result;
+ }
+
+ /// <inheritdoc/>
+ public string GetBindInterface(IPObject source, out int? port)
+ {
+ port = null;
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+
+ // Do we have a source?
+ bool haveSource = !source.Address.Equals(IPAddress.None);
+ bool isExternal = false;
+
+ if (haveSource)
+ {
+ if (!IsIP6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ _logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected.");
+ }
+
+ if (!IsIP4Enabled && source.AddressFamily == AddressFamily.InterNetwork)
+ {
+ _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected.");
+ }
+
+ isExternal = !IsInLocalNetwork(source);
+
+ if (MatchesPublishedServerUrl(source, isExternal, out string res, out port))
+ {
+ _logger.LogInformation("{Source}: Using BindAddress {Address}:{Port}", source, res, port);
+ return res;
+ }
+ }
+
+ _logger.LogDebug("GetBindInterface: Source: {0}, External: {1}:", haveSource, isExternal);
+
+ // No preference given, so move on to bind addresses.
+ if (MatchesBindInterface(source, isExternal, out string result))
+ {
+ return result;
+ }
+
+ if (isExternal && MatchesExternalInterface(source, out result))
+ {
+ return result;
+ }
+
+ // Get the first LAN interface address that isn't a loopback.
+ var interfaces = CreateCollection(_interfaceAddresses
+ .Exclude(_bindExclusions)
+ .Where(p => IsInLocalNetwork(p))
+ .OrderBy(p => p.Tag));
+
+ if (interfaces.Count > 0)
+ {
+ if (haveSource)
+ {
+ // Does the request originate in one of the interface subnets?
+ // (For systems with multiple internal network cards, and multiple subnets)
+ foreach (var intf in interfaces)
+ {
+ if (intf.Contains(source))
+ {
+ result = FormatIP6String(intf.Address);
+ _logger.LogDebug("{0}: GetBindInterface: Has source, matched best internal interface on range. {1}", source, result);
+ return result;
+ }
+ }
+ }
+
+ result = FormatIP6String(interfaces.First().Address);
+ _logger.LogDebug("{0}: GetBindInterface: Matched first internal interface. {1}", source, result);
+ return result;
+ }
+
+ // There isn't any others, so we'll use the loopback.
+ result = IsIP6Enabled ? "::" : "127.0.0.1";
+ _logger.LogWarning("{0}: GetBindInterface: Loopback return.", source, result);
+ return result;
+ }
+
+ /// <inheritdoc/>
+ public Collection<IPObject> GetInternalBindAddresses()
+ {
+ int count = _bindAddresses.Count;
+
+ if (count == 0)
+ {
+ if (_bindExclusions.Count > 0)
+ {
+ // Return all the internal interfaces except the ones excluded.
+ return CreateCollection(_internalInterfaces.Where(p => !_bindExclusions.ContainsAddress(p)));
+ }
+
+ // No bind address, so return all internal interfaces.
+ return CreateCollection(_internalInterfaces.Where(p => !p.IsLoopback()));
+ }
+
+ return new Collection<IPObject>(_bindAddresses);
+ }
+
+ /// <inheritdoc/>
+ public bool IsInLocalNetwork(IPObject address)
+ {
+ if (address == null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ if (address.Equals(IPAddress.None))
+ {
+ return false;
+ }
+
+ // See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
+ if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ return true;
+ }
+
+ // As private addresses can be redefined by Configuration.LocalNetworkAddresses
+ return _lanSubnets.ContainsAddress(address) && !_excludedSubnets.ContainsAddress(address);
+ }
+
+ /// <inheritdoc/>
+ public bool IsInLocalNetwork(string address)
+ {
+ if (IPHost.TryParse(address, out IPHost ep))
+ {
+ return _lanSubnets.ContainsAddress(ep) && !_excludedSubnets.ContainsAddress(ep);
+ }
+
+ return false;
+ }
+
+ /// <inheritdoc/>
+ public bool IsInLocalNetwork(IPAddress address)
+ {
+ if (address == null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ // See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
+ if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ return true;
+ }
+
+ // As private addresses can be redefined by Configuration.LocalNetworkAddresses
+ return _lanSubnets.ContainsAddress(address) && !_excludedSubnets.ContainsAddress(address);
+ }
+
+ /// <inheritdoc/>
+ public bool IsPrivateAddressRange(IPObject address)
+ {
+ if (address == null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ // See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
+ if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ return true;
+ }
+ else
+ {
+ return address.IsPrivateAddressRange();
+ }
+ }
+
+ /// <inheritdoc/>
+ public bool IsExcludedInterface(IPAddress address)
+ {
+ return _bindExclusions.ContainsAddress(address);
+ }
+
+ /// <inheritdoc/>
+ public Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null)
+ {
+ if (filter == null)
+ {
+ return _lanSubnets.Exclude(_excludedSubnets).AsNetworks();
+ }
+
+ return _lanSubnets.Exclude(filter);
+ }
+
+ /// <inheritdoc/>
+ public bool IsValidInterfaceAddress(IPAddress address)
+ {
+ return _interfaceAddresses.ContainsAddress(address);
+ }
+
+ /// <inheritdoc/>
+ public bool TryParseInterface(string token, out Collection<IPObject>? result)
+ {
+ result = null;
+ if (string.IsNullOrEmpty(token))
+ {
+ return false;
+ }
+
+ if (_interfaceNames != null && _interfaceNames.TryGetValue(token.ToLower(CultureInfo.InvariantCulture), out int index))
+ {
+ result = new Collection<IPObject>();
+
+ _logger.LogInformation("Interface {0} used in settings. Using its interface addresses.", token);
+
+ // Replace interface tags with the interface IP's.
+ foreach (IPNetAddress iface in _interfaceAddresses)
+ {
+ if (Math.Abs(iface.Tag) == index
+ && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork)
+ || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)))
+ {
+ result.AddItem(iface);
+ }
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Reloads all settings and re-initialises the instance.
+ /// </summary>
+ /// <param name="configuration">The <see cref="NetworkConfiguration"/> to use.</param>
+ public void UpdateSettings(NetworkConfiguration configuration)
+ {
+ NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration));
+
+ IsIP4Enabled = Socket.OSSupportsIPv4 && config.EnableIPV4;
+ IsIP6Enabled = Socket.OSSupportsIPv6 && config.EnableIPV6;
+
+ if (!IsIP6Enabled && !IsIP4Enabled)
+ {
+ _logger.LogError("IPv4 and IPv6 cannot both be disabled.");
+ IsIP4Enabled = true;
+ }
+
+ TrustAllIP6Interfaces = config.TrustAllIP6Interfaces;
+ // UdpHelper.EnableMultiSocketBinding = config.EnableMultiSocketBinding;
+
+ if (string.IsNullOrEmpty(MockNetworkSettings))
+ {
+ InitialiseInterfaces();
+ }
+ else // Used in testing only.
+ {
+ // Format is <IPAddress>,<Index>,<Name>: <next interface>. Set index to -ve to simulate a gateway.
+ var interfaceList = MockNetworkSettings.Split(':');
+ foreach (var details in interfaceList)
+ {
+ var parts = details.Split(',');
+ var address = IPNetAddress.Parse(parts[0]);
+ var index = int.Parse(parts[1], CultureInfo.InvariantCulture);
+ address.Tag = index;
+ _interfaceAddresses.AddItem(address);
+ _interfaceNames.Add(parts[2], Math.Abs(index));
+ }
+ }
+
+ InitialiseLAN(config);
+ InitialiseBind(config);
+ InitialiseRemote(config);
+ InitialiseOverrides(config);
+ }
+
+ /// <summary>
+ /// Protected implementation of Dispose pattern.
+ /// </summary>
+ /// <param name="disposing"><c>True</c> to dispose the managed state.</param>
+ protected virtual void Dispose(bool disposing)
+ {
+ if (!_disposed)
+ {
+ if (disposing)
+ {
+ _configurationManager.NamedConfigurationUpdated -= ConfigurationUpdated;
+ NetworkChange.NetworkAddressChanged -= OnNetworkAddressChanged;
+ NetworkChange.NetworkAvailabilityChanged -= OnNetworkAvailabilityChanged;
+ }
+
+ _disposed = true;
+ }
+ }
+
+ /// <summary>
+ /// Tries to identify the string and return an object of that class.
+ /// </summary>
+ /// <param name="addr">String to parse.</param>
+ /// <param name="result">IPObject to return.</param>
+ /// <returns><c>true</c> if the value parsed successfully, <c>false</c> otherwise.</returns>
+ private static bool TryParse(string addr, out IPObject result)
+ {
+ if (!string.IsNullOrEmpty(addr))
+ {
+ // Is it an IP address
+ if (IPNetAddress.TryParse(addr, out IPNetAddress nw))
+ {
+ result = nw;
+ return true;
+ }
+
+ if (IPHost.TryParse(addr, out IPHost h))
+ {
+ result = h;
+ return true;
+ }
+ }
+
+ result = IPNetAddress.None;
+ return false;
+ }
+
+ /// <summary>
+ /// Converts an IPAddress into a string.
+ /// Ipv6 addresses are returned in [ ], with their scope removed.
+ /// </summary>
+ /// <param name="address">Address to convert.</param>
+ /// <returns>URI safe conversion of the address.</returns>
+ private static string FormatIP6String(IPAddress address)
+ {
+ var str = address.ToString();
+ if (address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ int i = str.IndexOf("%", StringComparison.OrdinalIgnoreCase);
+
+ if (i != -1)
+ {
+ str = str.Substring(0, i);
+ }
+
+ return $"[{str}]";
+ }
+
+ return str;
+ }
+
+ private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt)
+ {
+ if (evt.Key.Equals("network", StringComparison.Ordinal))
+ {
+ UpdateSettings((NetworkConfiguration)evt.NewConfiguration);
+ }
+ }
+
+ /// <summary>
+ /// Checks the string to see if it matches any interface names.
+ /// </summary>
+ /// <param name="token">String to check.</param>
+ /// <param name="index">Interface index number.</param>
+ /// <returns><c>true</c> if an interface name matches the token, <c>False</c> otherwise.</returns>
+ private bool IsInterface(string token, out int index)
+ {
+ index = -1;
+
+ // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1.
+ // Null check required here for automated testing.
+ if (_interfaceNames != null && token.Length > 1)
+ {
+ bool partial = token[^1] == '*';
+ if (partial)
+ {
+ token = token[0..^1];
+ }
+
+ foreach ((string interfc, int interfcIndex) in _interfaceNames)
+ {
+ if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase))
+ || (partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture)))
+ {
+ index = interfcIndex;
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Parses a string and adds it into the the collection, replacing any interface references.
+ /// </summary>
+ /// <param name="col"><see cref="Collection{IPObject}"/>Collection.</param>
+ /// <param name="token">String value to parse.</param>
+ private void AddToCollection(Collection<IPObject> col, string token)
+ {
+ // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1.
+ // Null check required here for automated testing.
+ if (IsInterface(token, out int index))
+ {
+ _logger.LogInformation("Interface {0} used in settings. Using its interface addresses.", token);
+
+ // Replace interface tags with the interface IP's.
+ foreach (IPNetAddress iface in _interfaceAddresses)
+ {
+ if (Math.Abs(iface.Tag) == index
+ && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork)
+ || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)))
+ {
+ col.AddItem(iface);
+ }
+ }
+ }
+ else if (TryParse(token, out IPObject obj))
+ {
+ if (!IsIP6Enabled)
+ {
+ // Remove IP6 addresses from multi-homed IPHosts.
+ obj.Remove(AddressFamily.InterNetworkV6);
+ if (!obj.IsIP6())
+ {
+ col.AddItem(obj);
+ }
+ }
+ else if (!IsIP4Enabled)
+ {
+ // Remove IP4 addresses from multi-homed IPHosts.
+ obj.Remove(AddressFamily.InterNetwork);
+ if (obj.IsIP6())
+ {
+ col.AddItem(obj);
+ }
+ }
+ else
+ {
+ col.AddItem(obj);
+ }
+ }
+ else
+ {
+ _logger.LogDebug("Invalid or unknown network {0}.", token);
+ }
+ }
+
+ /// <summary>
+ /// Handler for network change events.
+ /// </summary>
+ /// <param name="sender">Sender.</param>
+ /// <param name="e">A <see cref="NetworkAvailabilityEventArgs"/> containing network availability information.</param>
+ private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e)
+ {
+ _logger.LogDebug("Network availability changed.");
+ OnNetworkChanged();
+ }
+
+ /// <summary>
+ /// Handler for network change events.
+ /// </summary>
+ /// <param name="sender">Sender.</param>
+ /// <param name="e">An <see cref="EventArgs"/>.</param>
+ private void OnNetworkAddressChanged(object? sender, EventArgs e)
+ {
+ _logger.LogDebug("Network address change detected.");
+ OnNetworkChanged();
+ }
+
+ /// <summary>
+ /// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession.
+ /// </summary>
+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
+ private async Task OnNetworkChangeAsync()
+ {
+ try
+ {
+ await Task.Delay(2000).ConfigureAwait(false);
+ InitialiseInterfaces();
+ // Recalculate LAN caches.
+ InitialiseLAN(_configurationManager.GetNetworkConfiguration());
+
+ NetworkChanged?.Invoke(this, EventArgs.Empty);
+ }
+ finally
+ {
+ _eventfire = false;
+ }
+ }
+
+ /// <summary>
+ /// Triggers our event, and re-loads interface information.
+ /// </summary>
+ private void OnNetworkChanged()
+ {
+ lock (_eventFireLock)
+ {
+ if (!_eventfire)
+ {
+ _logger.LogDebug("Network Address Change Event.");
+ // As network events tend to fire one after the other only fire once every second.
+ _eventfire = true;
+ OnNetworkChangeAsync().GetAwaiter().GetResult();
+ }
+ }
+ }
+
+ /// <summary>
+ /// Parses the user defined overrides into the dictionary object.
+ /// Overrides are the equivalent of localised publishedServerUrl, enabling
+ /// different addresses to be advertised over different subnets.
+ /// format is subnet=ipaddress|host|uri
+ /// when subnet = 0.0.0.0, any external address matches.
+ /// </summary>
+ private void InitialiseOverrides(NetworkConfiguration config)
+ {
+ lock (_intLock)
+ {
+ _publishedServerUrls.Clear();
+ string[] overrides = config.PublishedServerUriBySubnet;
+ if (overrides == null)
+ {
+ return;
+ }
+
+ foreach (var entry in overrides)
+ {
+ var parts = entry.Split('=');
+ if (parts.Length != 2)
+ {
+ _logger.LogError("Unable to parse bind override. {0}", entry);
+ }
+ else
+ {
+ var replacement = parts[1].Trim();
+ if (string.Equals(parts[0], "remaining", StringComparison.OrdinalIgnoreCase))
+ {
+ _publishedServerUrls[new IPNetAddress(IPAddress.Broadcast)] = replacement;
+ }
+ else if (string.Equals(parts[0], "external", StringComparison.OrdinalIgnoreCase))
+ {
+ _publishedServerUrls[new IPNetAddress(IPAddress.Any)] = replacement;
+ }
+ else if (TryParseInterface(parts[0], out Collection<IPObject>? addresses) && addresses != null)
+ {
+ foreach (IPNetAddress na in addresses)
+ {
+ _publishedServerUrls[na] = replacement;
+ }
+ }
+ else if (IPNetAddress.TryParse(parts[0], out IPNetAddress result))
+ {
+ _publishedServerUrls[result] = replacement;
+ }
+ else
+ {
+ _logger.LogError("Unable to parse bind ip address. {0}", parts[1]);
+ }
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Initialises the network bind addresses.
+ /// </summary>
+ private void InitialiseBind(NetworkConfiguration config)
+ {
+ string[] lanAddresses = config.LocalNetworkAddresses;
+
+ // TODO: remove when bug fixed: https://github.com/jellyfin/jellyfin-web/issues/1334
+
+ if (lanAddresses.Length == 1 && lanAddresses[0].IndexOf(',', StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ lanAddresses = lanAddresses[0].Split(',');
+ }
+
+ // TODO: end fix: https://github.com/jellyfin/jellyfin-web/issues/1334
+
+ // Add virtual machine interface names to the list of bind exclusions, so that they are auto-excluded.
+ if (config.IgnoreVirtualInterfaces)
+ {
+ var newList = lanAddresses.ToList();
+ newList.AddRange(config.VirtualInterfaceNames.Split(',').ToList());
+ lanAddresses = newList.ToArray();
+ }
+
+ // Read and parse bind addresses and exclusions, removing ones that don't exist.
+ _bindAddresses = CreateIPCollection(lanAddresses).Union(_interfaceAddresses);
+ _bindExclusions = CreateIPCollection(lanAddresses, true).Union(_interfaceAddresses);
+ _logger.LogInformation("Using bind addresses: {0}", _bindAddresses.AsString());
+ _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions.AsString());
+ }
+
+ /// <summary>
+ /// Initialises the remote address values.
+ /// </summary>
+ private void InitialiseRemote(NetworkConfiguration config)
+ {
+ RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter);
+ }
+
+ /// <summary>
+ /// Initialises internal LAN cache settings.
+ /// </summary>
+ private void InitialiseLAN(NetworkConfiguration config)
+ {
+ lock (_intLock)
+ {
+ _logger.LogDebug("Refreshing LAN information.");
+
+ // Get config options.
+ string[] subnets = config.LocalNetworkSubnets;
+
+ // Create lists from user settings.
+
+ _lanSubnets = CreateIPCollection(subnets);
+ _excludedSubnets = CreateIPCollection(subnets, true).AsNetworks();
+
+ // If no LAN addresses are specified - all private subnets are deemed to be the LAN
+ _usingPrivateAddresses = _lanSubnets.Count == 0;
+
+ // NOTE: The order of the commands in this statement matters.
+ if (_usingPrivateAddresses)
+ {
+ _logger.LogDebug("Using LAN interface addresses as user provided no LAN details.");
+ // Internal interfaces must be private and not excluded.
+ _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.ContainsAddress(i)));
+
+ // Subnets are the same as the calculated internal interface.
+ _lanSubnets = new Collection<IPObject>();
+
+ // We must listen on loopback for LiveTV to function regardless of the settings.
+ if (IsIP6Enabled)
+ {
+ _lanSubnets.AddItem(IPNetAddress.IP6Loopback);
+ _lanSubnets.AddItem(IPNetAddress.Parse("fc00::/7")); // ULA
+ _lanSubnets.AddItem(IPNetAddress.Parse("fe80::/10")); // Site local
+ }
+
+ if (IsIP4Enabled)
+ {
+ _lanSubnets.AddItem(IPNetAddress.IP4Loopback);
+ _lanSubnets.AddItem(IPNetAddress.Parse("10.0.0.0/8"));
+ _lanSubnets.AddItem(IPNetAddress.Parse("172.16.0.0/12"));
+ _lanSubnets.AddItem(IPNetAddress.Parse("192.168.0.0/16"));
+ }
+ }
+ else
+ {
+ // We must listen on loopback for LiveTV to function regardless of the settings.
+ if (IsIP6Enabled)
+ {
+ _lanSubnets.AddItem(IPNetAddress.IP6Loopback);
+ }
+
+ if (IsIP4Enabled)
+ {
+ _lanSubnets.AddItem(IPNetAddress.IP4Loopback);
+ }
+
+ // Internal interfaces must be private, not excluded and part of the LocalNetworkSubnet.
+ _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsInLocalNetwork(i)));
+ }
+
+ _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets.AsString());
+ _logger.LogInformation("Defined LAN exclusions : {0}", _excludedSubnets.AsString());
+ _logger.LogInformation("Using LAN addresses: {0}", _lanSubnets.Exclude(_excludedSubnets).AsNetworks().AsString());
+ }
+ }
+
+ /// <summary>
+ /// Generate a list of all the interface ip addresses and submasks where that are in the active/unknown state.
+ /// Generate a list of all active mac addresses that aren't loopback addresses.
+ /// </summary>
+ private void InitialiseInterfaces()
+ {
+ lock (_intLock)
+ {
+ _logger.LogDebug("Refreshing interfaces.");
+
+ _interfaceNames.Clear();
+ _interfaceAddresses.Clear();
+
+ try
+ {
+ IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces()
+ .Where(i => i.SupportsMulticast && i.OperationalStatus == OperationalStatus.Up);
+
+ foreach (NetworkInterface adapter in nics)
+ {
+ try
+ {
+ IPInterfaceProperties ipProperties = adapter.GetIPProperties();
+ PhysicalAddress mac = adapter.GetPhysicalAddress();
+
+ // populate mac list
+ if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && mac != null && mac != PhysicalAddress.None)
+ {
+ _macAddresses.Add(mac);
+ }
+
+ // populate interface address list
+ foreach (UnicastIPAddressInformation info in ipProperties.UnicastAddresses)
+ {
+ if (IsIP4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork)
+ {
+ IPNetAddress nw = new IPNetAddress(info.Address, IPObject.MaskToCidr(info.IPv4Mask))
+ {
+ // Keep the number of gateways on this interface, along with its index.
+ Tag = ipProperties.GetIPv4Properties().Index
+ };
+
+ int tag = nw.Tag;
+ if ((ipProperties.GatewayAddresses.Count > 0) && !nw.IsLoopback())
+ {
+ // -ve Tags signify the interface has a gateway.
+ nw.Tag *= -1;
+ }
+
+ _interfaceAddresses.AddItem(nw);
+
+ // Store interface name so we can use the name in Collections.
+ _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag;
+ _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag;
+ }
+ else if (IsIP6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ IPNetAddress nw = new IPNetAddress(info.Address, (byte)info.PrefixLength)
+ {
+ // Keep the number of gateways on this interface, along with its index.
+ Tag = ipProperties.GetIPv6Properties().Index
+ };
+
+ int tag = nw.Tag;
+ if ((ipProperties.GatewayAddresses.Count > 0) && !nw.IsLoopback())
+ {
+ // -ve Tags signify the interface has a gateway.
+ nw.Tag *= -1;
+ }
+
+ _interfaceAddresses.AddItem(nw);
+
+ // Store interface name so we can use the name in Collections.
+ _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag;
+ _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag;
+ }
+ }
+ }
+#pragma warning disable CA1031 // Do not catch general exception types
+ catch
+ {
+ // Ignore error, and attempt to continue.
+ }
+#pragma warning restore CA1031 // Do not catch general exception types
+ }
+
+ _logger.LogDebug("Discovered {0} interfaces.", _interfaceAddresses.Count);
+ _logger.LogDebug("Interfaces addresses : {0}", _interfaceAddresses.AsString());
+
+ // If for some reason we don't have an interface info, resolve our DNS name.
+ if (_interfaceAddresses.Count == 0)
+ {
+ _logger.LogWarning("No interfaces information available. Using loopback.");
+
+ IPHost host = new IPHost(Dns.GetHostName());
+ foreach (var a in host.GetAddresses())
+ {
+ _interfaceAddresses.AddItem(a);
+ }
+
+ if (_interfaceAddresses.Count == 0)
+ {
+ _logger.LogError("No interfaces information available. Resolving DNS name.");
+ // Last ditch attempt - use loopback address.
+ _interfaceAddresses.AddItem(IPNetAddress.IP4Loopback);
+ if (IsIP6Enabled)
+ {
+ _interfaceAddresses.AddItem(IPNetAddress.IP6Loopback);
+ }
+ }
+ }
+ }
+ catch (NetworkInformationException ex)
+ {
+ _logger.LogError(ex, "Error in InitialiseInterfaces.");
+ }
+ }
+ }
+
+ /// <summary>
+ /// Attempts to match the source against a user defined bind interface.
+ /// </summary>
+ /// <param name="source">IP source address to use.</param>
+ /// <param name="isExternal">True if the source is in the external subnet.</param>
+ /// <param name="bindPreference">The published server url that matches the source address.</param>
+ /// <param name="port">The resultant port, if one exists.</param>
+ /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns>
+ private bool MatchesPublishedServerUrl(IPObject source, bool isExternal, out string bindPreference, out int? port)
+ {
+ bindPreference = string.Empty;
+ port = null;
+
+ // Check for user override.
+ foreach (var addr in _publishedServerUrls)
+ {
+ // Remaining. Match anything.
+ if (addr.Key.Equals(IPAddress.Broadcast))
+ {
+ bindPreference = addr.Value;
+ break;
+ }
+ else if ((addr.Key.Equals(IPAddress.Any) || addr.Key.Equals(IPAddress.IPv6Any)) && isExternal)
+ {
+ // External.
+ bindPreference = addr.Value;
+ break;
+ }
+ else if (addr.Key.Contains(source))
+ {
+ // Match ip address.
+ bindPreference = addr.Value;
+ break;
+ }
+ }
+
+ if (!string.IsNullOrEmpty(bindPreference))
+ {
+ // Has it got a port defined?
+ var parts = bindPreference.Split(':');
+ if (parts.Length > 1)
+ {
+ if (int.TryParse(parts[1], out int p))
+ {
+ bindPreference = parts[0];
+ port = p;
+ }
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Attempts to match the source against a user defined bind interface.
+ /// </summary>
+ /// <param name="source">IP source address to use.</param>
+ /// <param name="isExternal">True if the source is in the external subnet.</param>
+ /// <param name="result">The result, if a match is found.</param>
+ /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns>
+ private bool MatchesBindInterface(IPObject source, bool isExternal, out string result)
+ {
+ result = string.Empty;
+ var nc = _bindAddresses.Exclude(_bindExclusions);
+
+ int count = nc.Count;
+ if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses[0].Equals(IPAddress.IPv6Any)))
+ {
+ // Ignore IPAny addresses.
+ count = 0;
+ }
+
+ if (count != 0)
+ {
+ // Check to see if any of the bind interfaces are in the same subnet.
+
+ Collection<IPObject> bindResult;
+ IPAddress? defaultGateway = null;
+ IPAddress? bindAddress;
+
+ if (isExternal)
+ {
+ // Find all external bind addresses. Store the default gateway, but check to see if there is a better match first.
+ bindResult = CreateCollection(nc
+ .Where(p => !IsInLocalNetwork(p))
+ .OrderBy(p => p.Tag));
+ defaultGateway = bindResult.FirstOrDefault()?.Address;
+ bindAddress = bindResult
+ .Where(p => p.Contains(source))
+ .OrderBy(p => p.Tag)
+ .FirstOrDefault()?.Address;
+ }
+ else
+ {
+ // Look for the best internal address.
+ bindAddress = nc
+ .Where(p => IsInLocalNetwork(p) && (p.Contains(source) || p.Equals(IPAddress.None)))
+ .OrderBy(p => p.Tag)
+ .FirstOrDefault()?.Address;
+ }
+
+ if (bindAddress != null)
+ {
+ result = FormatIP6String(bindAddress);
+ _logger.LogDebug("{0}: GetBindInterface: Has source, found a match bind interface subnets. {1}", source, result);
+ return true;
+ }
+
+ if (isExternal && defaultGateway != null)
+ {
+ result = FormatIP6String(defaultGateway);
+ _logger.LogDebug("{0}: GetBindInterface: Using first user defined external interface. {1}", source, result);
+ return true;
+ }
+
+ result = FormatIP6String(nc.First().Address);
+ _logger.LogDebug("{0}: GetBindInterface: Selected first user defined interface. {1}", source, result);
+
+ if (isExternal)
+ {
+ _logger.LogWarning("{0}: External request received, however, only an internal interface bind found.", source);
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Attempts to match the source against an external interface.
+ /// </summary>
+ /// <param name="source">IP source address to use.</param>
+ /// <param name="result">The result, if a match is found.</param>
+ /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns>
+ private bool MatchesExternalInterface(IPObject source, out string result)
+ {
+ result = string.Empty;
+ // Get the first WAN interface address that isn't a loopback.
+ var extResult = CreateCollection(_interfaceAddresses
+ .Exclude(_bindExclusions)
+ .Where(p => !IsInLocalNetwork(p))
+ .OrderBy(p => p.Tag));
+
+ if (extResult.Count > 0)
+ {
+ // Does the request originate in one of the interface subnets?
+ // (For systems with multiple internal network cards, and multiple subnets)
+ foreach (var intf in extResult)
+ {
+ if (!IsInLocalNetwork(intf) && intf.Contains(source))
+ {
+ result = FormatIP6String(intf.Address);
+ _logger.LogDebug("{0}: GetBindInterface: Selected best external on interface on range. {1}", source, result);
+ return true;
+ }
+ }
+
+ result = FormatIP6String(extResult.First().Address);
+ _logger.LogDebug("{0}: GetBindInterface: Selected first external interface. {0}", source, result);
+ return true;
+ }
+
+ // Have to return something, so return an internal address
+
+ _logger.LogWarning("{0}: External request received, however, no WAN interface found.", source);
+ return false;
+ }
+ }
+}
diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs
index cb8ae91f5..78f596a5c 100644
--- a/Jellyfin.Server/CoreAppHost.cs
+++ b/Jellyfin.Server/CoreAppHost.cs
@@ -38,21 +38,18 @@ namespace Jellyfin.Server
/// <param name="loggerFactory">The <see cref="ILoggerFactory" /> to be used by the <see cref="CoreAppHost" />.</param>
/// <param name="options">The <see cref="StartupOptions" /> to be used by the <see cref="CoreAppHost" />.</param>
/// <param name="fileSystem">The <see cref="IFileSystem" /> to be used by the <see cref="CoreAppHost" />.</param>
- /// <param name="networkManager">The <see cref="INetworkManager" /> to be used by the <see cref="CoreAppHost" />.</param>
/// <param name="collection">The <see cref="IServiceCollection"/> to be used by the <see cref="CoreAppHost"/>.</param>
public CoreAppHost(
IServerApplicationPaths applicationPaths,
ILoggerFactory loggerFactory,
IStartupOptions options,
IFileSystem fileSystem,
- INetworkManager networkManager,
IServiceCollection collection)
: base(
applicationPaths,
loggerFactory,
options,
fileSystem,
- networkManager,
collection)
{
}
diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs
index c7fbfa4d0..6bf6f383f 100644
--- a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs
+++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs
@@ -1,4 +1,5 @@
using System.Collections.Generic;
+using Jellyfin.Networking.Configuration;
using Jellyfin.Server.Middleware;
using MediaBrowser.Controller.Configuration;
using Microsoft.AspNetCore.Builder;
@@ -24,8 +25,8 @@ namespace Jellyfin.Server.Extensions
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
- var baseUrl = serverConfigurationManager.Configuration.BaseUrl.Trim('/');
- var apiDocBaseUrl = serverConfigurationManager.Configuration.BaseUrl;
+ var baseUrl = serverConfigurationManager.GetNetworkConfiguration().BaseUrl.Trim('/');
+ var apiDocBaseUrl = serverConfigurationManager.GetNetworkConfiguration().BaseUrl;
if (!string.IsNullOrEmpty(baseUrl))
{
baseUrl += '/';
diff --git a/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs b/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs
index 9316737bd..c23da2fd6 100644
--- a/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs
+++ b/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs
@@ -1,5 +1,6 @@
using System;
using System.Threading.Tasks;
+using Jellyfin.Networking.Configuration;
using MediaBrowser.Controller.Configuration;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
@@ -42,7 +43,7 @@ namespace Jellyfin.Server.Middleware
public async Task Invoke(HttpContext httpContext, IServerConfigurationManager serverConfigurationManager)
{
var localPath = httpContext.Request.Path.ToString();
- var baseUrlPrefix = serverConfigurationManager.Configuration.BaseUrl;
+ var baseUrlPrefix = serverConfigurationManager.GetNetworkConfiguration().BaseUrl;
if (string.Equals(localPath, baseUrlPrefix + "/", StringComparison.OrdinalIgnoreCase)
|| string.Equals(localPath, baseUrlPrefix, StringComparison.OrdinalIgnoreCase)
diff --git a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs
index 4bda8f273..525cd9ffe 100644
--- a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs
+++ b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs
@@ -1,5 +1,6 @@
-using System.Linq;
+using System.Net;
using System.Threading.Tasks;
+using Jellyfin.Networking.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
@@ -34,40 +35,40 @@ namespace Jellyfin.Server.Middleware
{
if (httpContext.IsLocal())
{
+ // Running locally.
await _next(httpContext).ConfigureAwait(false);
return;
}
- var remoteIp = httpContext.GetNormalizedRemoteIp();
+ var remoteIp = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback;
- if (serverConfigurationManager.Configuration.EnableRemoteAccess)
+ if (serverConfigurationManager.GetNetworkConfiguration().EnableRemoteAccess)
{
- var addressFilter = serverConfigurationManager.Configuration.RemoteIPFilter.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
+ // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely.
+ // If left blank, all remote addresses will be allowed.
+ var remoteAddressFilter = networkManager.RemoteAddressFilter;
- if (addressFilter.Length > 0 && !networkManager.IsInLocalNetwork(remoteIp))
+ if (remoteAddressFilter.Count > 0 && !networkManager.IsInLocalNetwork(remoteIp))
{
- if (serverConfigurationManager.Configuration.IsRemoteIPFilterBlacklist)
+ // remoteAddressFilter is a whitelist or blacklist.
+ bool isListed = remoteAddressFilter.ContainsAddress(remoteIp);
+ if (!serverConfigurationManager.GetNetworkConfiguration().IsRemoteIPFilterBlacklist)
{
- if (networkManager.IsAddressInSubnets(remoteIp, addressFilter))
- {
- return;
- }
+ // Black list, so flip over.
+ isListed = !isListed;
}
- else
+
+ if (!isListed)
{
- if (!networkManager.IsAddressInSubnets(remoteIp, addressFilter))
- {
- return;
- }
+ // If your name isn't on the list, you arn't coming in.
+ return;
}
}
}
- else
+ else if (!networkManager.IsInLocalNetwork(remoteIp))
{
- if (!networkManager.IsInLocalNetwork(remoteIp))
- {
- return;
- }
+ // Remote not enabled. So everyone should be LAN.
+ return;
}
await _next(httpContext).ConfigureAwait(false);
diff --git a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs
index 9d795145a..8065054a1 100644
--- a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs
+++ b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs
@@ -1,6 +1,9 @@
using System;
using System.Linq;
+using System.Net;
using System.Threading.Tasks;
+using Jellyfin.Networking.Configuration;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using Microsoft.AspNetCore.Http;
@@ -32,45 +35,14 @@ namespace Jellyfin.Server.Middleware
/// <returns>The async task.</returns>
public async Task Invoke(HttpContext httpContext, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager)
{
- var currentHost = httpContext.Request.Host.ToString();
- var hosts = serverConfigurationManager
- .Configuration
- .LocalNetworkAddresses
- .Select(NormalizeConfiguredLocalAddress)
- .ToList();
+ var host = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback;
- if (hosts.Count == 0)
+ if (!networkManager.IsInLocalNetwork(host) && !serverConfigurationManager.GetNetworkConfiguration().EnableRemoteAccess)
{
- await _next(httpContext).ConfigureAwait(false);
return;
}
- currentHost ??= string.Empty;
-
- if (networkManager.IsInPrivateAddressSpace(currentHost))
- {
- hosts.Add("localhost");
- hosts.Add("127.0.0.1");
-
- if (hosts.All(i => currentHost.IndexOf(i, StringComparison.OrdinalIgnoreCase) == -1))
- {
- return;
- }
- }
-
await _next(httpContext).ConfigureAwait(false);
}
-
- private static string NormalizeConfiguredLocalAddress(string address)
- {
- var add = address.AsSpan().Trim('/');
- int index = add.IndexOf('/');
- if (index != -1)
- {
- add = add.Slice(index + 1);
- }
-
- return add.TrimStart('/').ToString();
- }
}
}
diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs
index 97a51c202..db67f6470 100644
--- a/Jellyfin.Server/Program.cs
+++ b/Jellyfin.Server/Program.cs
@@ -12,9 +12,9 @@ using System.Threading.Tasks;
using CommandLine;
using Emby.Server.Implementations;
using Emby.Server.Implementations.IO;
-using Emby.Server.Implementations.Networking;
using Jellyfin.Api.Controllers;
using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Extensions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
@@ -161,7 +161,6 @@ namespace Jellyfin.Server
_loggerFactory,
options,
new ManagedFileSystem(_loggerFactory.CreateLogger<ManagedFileSystem>(), appPaths),
- new NetworkManager(_loggerFactory.CreateLogger<NetworkManager>()),
serviceCollection);
try
@@ -272,53 +271,17 @@ namespace Jellyfin.Server
return builder
.UseKestrel((builderContext, options) =>
{
- var addresses = appHost.ServerConfigurationManager
- .Configuration
- .LocalNetworkAddresses
- .Select(x => appHost.NormalizeConfiguredLocalAddress(x))
- .Where(i => i != null)
- .ToHashSet();
- if (addresses.Count > 0 && !addresses.Contains(IPAddress.Any))
- {
- if (!addresses.Contains(IPAddress.Loopback))
- {
- // we must listen on loopback for LiveTV to function regardless of the settings
- addresses.Add(IPAddress.Loopback);
- }
+ var addresses = appHost.NetManager.GetAllBindInterfaces();
- foreach (var address in addresses)
- {
- _logger.LogInformation("Kestrel listening on {IpAddress}", address);
- options.Listen(address, appHost.HttpPort);
-
- if (appHost.ListenWithHttps)
- {
- options.Listen(
- address,
- appHost.HttpsPort,
- listenOptions => listenOptions.UseHttps(appHost.Certificate));
- }
- else if (builderContext.HostingEnvironment.IsDevelopment())
- {
- try
- {
- options.Listen(address, appHost.HttpsPort, listenOptions => listenOptions.UseHttps());
- }
- catch (InvalidOperationException ex)
- {
- _logger.LogError(ex, "Failed to listen to HTTPS using the ASP.NET Core HTTPS development certificate. Please ensure it has been installed and set as trusted.");
- }
- }
- }
- }
- else
+ bool flagged = false;
+ foreach (IPObject netAdd in addresses)
{
- _logger.LogInformation("Kestrel listening on all interfaces");
- options.ListenAnyIP(appHost.HttpPort);
-
+ _logger.LogInformation("Kestrel listening on {0}", netAdd);
+ options.Listen(netAdd.Address, appHost.HttpPort);
if (appHost.ListenWithHttps)
{
- options.ListenAnyIP(
+ options.Listen(
+ netAdd.Address,
appHost.HttpsPort,
listenOptions => listenOptions.UseHttps(appHost.Certificate));
}
@@ -326,11 +289,18 @@ namespace Jellyfin.Server
{
try
{
- options.ListenAnyIP(appHost.HttpsPort, listenOptions => listenOptions.UseHttps());
+ options.Listen(
+ netAdd.Address,
+ appHost.HttpsPort,
+ listenOptions => listenOptions.UseHttps());
}
- catch (InvalidOperationException ex)
+ catch (InvalidOperationException)
{
- _logger.LogError(ex, "Failed to listen to HTTPS using the ASP.NET Core HTTPS development certificate. Please ensure it has been installed and set as trusted.");
+ if (!flagged)
+ {
+ _logger.LogWarning("Failed to listen to HTTPS using the ASP.NET Core HTTPS development certificate. Please ensure it has been installed and set as trusted.");
+ flagged = true;
+ }
}
}
}
diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs
index 62ffe174c..d84f658bf 100644
--- a/Jellyfin.Server/Startup.cs
+++ b/Jellyfin.Server/Startup.cs
@@ -3,6 +3,7 @@ using System.ComponentModel;
using System.Net.Http.Headers;
using System.Net.Mime;
using Jellyfin.Api.TypeConverters;
+using Jellyfin.Networking.Configuration;
using Jellyfin.Server.Extensions;
using Jellyfin.Server.Implementations;
using Jellyfin.Server.Middleware;
@@ -54,7 +55,7 @@ namespace Jellyfin.Server
{
options.HttpsPort = _serverApplicationHost.HttpsPort;
});
- services.AddJellyfinApi(_serverApplicationHost.GetApiPluginAssemblies(), _serverConfigurationManager.Configuration.KnownProxies);
+ services.AddJellyfinApi(_serverApplicationHost.GetApiPluginAssemblies(), _serverConfigurationManager.GetNetworkConfiguration().KnownProxies);
services.AddJellyfinApiSwagger();
@@ -98,7 +99,7 @@ namespace Jellyfin.Server
app.UseBaseUrlRedirection();
// Wrap rest of configuration so everything only listens on BaseUrl.
- app.Map(_serverConfigurationManager.Configuration.BaseUrl, mainApp =>
+ app.Map(_serverConfigurationManager.GetNetworkConfiguration().BaseUrl, mainApp =>
{
if (env.IsDevelopment())
{
diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs
index a0330afef..43562afe3 100644
--- a/MediaBrowser.Common/Net/INetworkManager.cs
+++ b/MediaBrowser.Common/Net/INetworkManager.cs
@@ -1,97 +1,233 @@
-#pragma warning disable CS1591
-
+#nullable enable
using System;
using System.Collections.Generic;
+using System.Collections.ObjectModel;
using System.Net;
using System.Net.NetworkInformation;
+using MediaBrowser.Common.Net;
+using Microsoft.AspNetCore.Http;
namespace MediaBrowser.Common.Net
{
+ /// <summary>
+ /// Interface for the NetworkManager class.
+ /// </summary>
public interface INetworkManager
{
+ /// <summary>
+ /// Event triggered on network changes.
+ /// </summary>
event EventHandler NetworkChanged;
/// <summary>
- /// Gets or sets a function to return the list of user defined LAN addresses.
+ /// Gets the published server urls list.
+ /// </summary>
+ Dictionary<IPNetAddress, string> PublishedServerUrls { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal.
+ /// </summary>
+ bool TrustAllIP6Interfaces { get; }
+
+ /// <summary>
+ /// Gets the remote address filter.
+ /// </summary>
+ Collection<IPObject> RemoteAddressFilter { get; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether iP6 is enabled.
+ /// </summary>
+ bool IsIP6Enabled { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether iP4 is enabled.
+ /// </summary>
+ bool IsIP4Enabled { get; set; }
+
+ /// <summary>
+ /// Calculates the list of interfaces to use for Kestrel.
+ /// </summary>
+ /// <returns>A Collection{IPObject} object containing all the interfaces to bind.
+ /// If all the interfaces are specified, and none are excluded, it returns zero items
+ /// to represent any address.</returns>
+ /// <param name="individualInterfaces">When false, return <see cref="IPAddress.Any"/> or <see cref="IPAddress.IPv6Any"/> for all interfaces.</param>
+ Collection<IPObject> GetAllBindInterfaces(bool individualInterfaces = false);
+
+ /// <summary>
+ /// Returns a collection containing the loopback interfaces.
+ /// </summary>
+ /// <returns>Collection{IPObject}.</returns>
+ Collection<IPObject> GetLoopbacks();
+
+ /// <summary>
+ /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
+ /// If no bind addresses are specified, an internal interface address is selected.
+ /// The priority of selection is as follows:-
+ ///
+ /// The value contained in the startup parameter --published-server-url.
+ ///
+ /// If the user specified custom subnet overrides, the correct subnet for the source address.
+ ///
+ /// If the user specified bind interfaces to use:-
+ /// The bind interface that contains the source subnet.
+ /// The first bind interface specified that suits best first the source's endpoint. eg. external or internal.
+ ///
+ /// If the source is from a public subnet address range and the user hasn't specified any bind addresses:-
+ /// The first public interface that isn't a loopback and contains the source subnet.
+ /// The first public interface that isn't a loopback. Priority is given to interfaces with gateways.
+ /// An internal interface if there are no public ip addresses.
+ ///
+ /// If the source is from a private subnet address range and the user hasn't specified any bind addresses:-
+ /// The first private interface that contains the source subnet.
+ /// The first private interface that isn't a loopback. Priority is given to interfaces with gateways.
+ ///
+ /// If no interfaces meet any of these criteria, then a loopback address is returned.
+ ///
+ /// Interface that have been specifically excluded from binding are not used in any of the calculations.
+ /// </summary>
+ /// <param name="source">Source of the request.</param>
+ /// <param name="port">Optional port returned, if it's part of an override.</param>
+ /// <returns>IP Address to use, or loopback address if all else fails.</returns>
+ string GetBindInterface(IPObject source, out int? port);
+
+ /// <summary>
+ /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
+ /// If no bind addresses are specified, an internal interface address is selected.
+ /// (See <see cref="GetBindInterface(IPObject, out int?)"/>.
+ /// </summary>
+ /// <param name="source">Source of the request.</param>
+ /// <param name="port">Optional port returned, if it's part of an override.</param>
+ /// <returns>IP Address to use, or loopback address if all else fails.</returns>
+ string GetBindInterface(HttpRequest source, out int? port);
+
+ /// <summary>
+ /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
+ /// If no bind addresses are specified, an internal interface address is selected.
+ /// (See <see cref="GetBindInterface(IPObject, out int?)"/>.
+ /// </summary>
+ /// <param name="source">IP address of the request.</param>
+ /// <param name="port">Optional port returned, if it's part of an override.</param>
+ /// <returns>IP Address to use, or loopback address if all else fails.</returns>
+ string GetBindInterface(IPAddress source, out int? port);
+
+ /// <summary>
+ /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
+ /// If no bind addresses are specified, an internal interface address is selected.
+ /// (See <see cref="GetBindInterface(IPObject, out int?)"/>.
+ /// </summary>
+ /// <param name="source">Source of the request.</param>
+ /// <param name="port">Optional port returned, if it's part of an override.</param>
+ /// <returns>IP Address to use, or loopback address if all else fails.</returns>
+ string GetBindInterface(string source, out int? port);
+
+ /// <summary>
+ /// Checks to see if the ip address is specifically excluded in LocalNetworkAddresses.
+ /// </summary>
+ /// <param name="address">IP address to check.</param>
+ /// <returns>True if it is.</returns>
+ bool IsExcludedInterface(IPAddress address);
+
+ /// <summary>
+ /// Get a list of all the MAC addresses associated with active interfaces.
+ /// </summary>
+ /// <returns>List of MAC addresses.</returns>
+ IReadOnlyCollection<PhysicalAddress> GetMacAddresses();
+
+ /// <summary>
+ /// Checks to see if the IP Address provided matches an interface that has a gateway.
+ /// </summary>
+ /// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param>
+ /// <returns>Result of the check.</returns>
+ bool IsGatewayInterface(IPObject? addressObj);
+
+ /// <summary>
+ /// Checks to see if the IP Address provided matches an interface that has a gateway.
/// </summary>
- Func<string[]> LocalSubnetsFn { get; set; }
+ /// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param>
+ /// <returns>Result of the check.</returns>
+ bool IsGatewayInterface(IPAddress? addressObj);
/// <summary>
- /// Gets a random port TCP number that is currently available.
+ /// Returns true if the address is a private address.
+ /// The config option TrustIP6Interfaces overrides this functions behaviour.
/// </summary>
- /// <returns>System.Int32.</returns>
- int GetRandomUnusedTcpPort();
+ /// <param name="address">Address to check.</param>
+ /// <returns>True or False.</returns>
+ bool IsPrivateAddressRange(IPObject address);
/// <summary>
- /// Gets a random port UDP number that is currently available.
+ /// Returns true if the address is part of the user defined LAN.
+ /// The config option TrustIP6Interfaces overrides this functions behaviour.
/// </summary>
- /// <returns>System.Int32.</returns>
- int GetRandomUnusedUdpPort();
+ /// <param name="address">IP to check.</param>
+ /// <returns>True if endpoint is within the LAN range.</returns>
+ bool IsInLocalNetwork(string address);
/// <summary>
- /// Returns the MAC Address from first Network Card in Computer.
+ /// Returns true if the address is part of the user defined LAN.
+ /// The config option TrustIP6Interfaces overrides this functions behaviour.
/// </summary>
- /// <returns>The MAC Address.</returns>
- List<PhysicalAddress> GetMacAddresses();
+ /// <param name="address">IP to check.</param>
+ /// <returns>True if endpoint is within the LAN range.</returns>
+ bool IsInLocalNetwork(IPObject address);
/// <summary>
- /// Determines whether [is in private address space] [the specified endpoint].
+ /// Returns true if the address is part of the user defined LAN.
+ /// The config option TrustIP6Interfaces overrides this functions behaviour.
/// </summary>
- /// <param name="endpoint">The endpoint.</param>
- /// <returns><c>true</c> if [is in private address space] [the specified endpoint]; otherwise, <c>false</c>.</returns>
- bool IsInPrivateAddressSpace(string endpoint);
+ /// <param name="address">IP to check.</param>
+ /// <returns>True if endpoint is within the LAN range.</returns>
+ bool IsInLocalNetwork(IPAddress address);
/// <summary>
- /// Determines whether [is in private address space 10.x.x.x] [the specified endpoint] and exists in the subnets returned by GetSubnets().
+ /// Attempts to convert the token to an IP address, permitting for interface descriptions and indexes.
+ /// eg. "eth1", or "TP-LINK Wireless USB Adapter".
/// </summary>
- /// <param name="endpoint">The endpoint.</param>
- /// <returns><c>true</c> if [is in private address space 10.x.x.x] [the specified endpoint]; otherwise, <c>false</c>.</returns>
- bool IsInPrivateAddressSpaceAndLocalSubnet(string endpoint);
+ /// <param name="token">Token to parse.</param>
+ /// <param name="result">Resultant object's ip addresses, if successful.</param>
+ /// <returns>Success of the operation.</returns>
+ bool TryParseInterface(string token, out Collection<IPObject>? result);
/// <summary>
- /// Determines whether [is in local network] [the specified endpoint].
+ /// Parses an array of strings into a Collection{IPObject}.
/// </summary>
- /// <param name="endpoint">The endpoint.</param>
- /// <returns><c>true</c> if [is in local network] [the specified endpoint]; otherwise, <c>false</c>.</returns>
- bool IsInLocalNetwork(string endpoint);
+ /// <param name="values">Values to parse.</param>
+ /// <param name="bracketed">When true, only include values in []. When false, ignore bracketed values.</param>
+ /// <returns>IPCollection object containing the value strings.</returns>
+ Collection<IPObject> CreateIPCollection(string[] values, bool bracketed = false);
/// <summary>
- /// Investigates an caches a list of interface addresses, excluding local link and LAN excluded addresses.
+ /// Returns all the internal Bind interface addresses.
/// </summary>
- /// <returns>The list of ipaddresses.</returns>
- IPAddress[] GetLocalIpAddresses();
+ /// <returns>An internal list of interfaces addresses.</returns>
+ Collection<IPObject> GetInternalBindAddresses();
/// <summary>
- /// Checks if the given address falls within the ranges given in [subnets]. The addresses in subnets can be hosts or subnets in the CIDR format.
+ /// Checks to see if an IP address is still a valid interface address.
/// </summary>
- /// <param name="addressString">The address to check.</param>
- /// <param name="subnets">If true, check against addresses in the LAN settings surrounded by brackets ([]).</param>
- /// <returns><c>true</c>if the address is in at least one of the given subnets, <c>false</c> otherwise.</returns>
- bool IsAddressInSubnets(string addressString, string[] subnets);
+ /// <param name="address">IP address to check.</param>
+ /// <returns>True if it is.</returns>
+ bool IsValidInterfaceAddress(IPAddress address);
/// <summary>
- /// Returns true if address is in the LAN list in the config file.
+ /// Returns true if the IP address is in the excluded list.
/// </summary>
- /// <param name="address">The address to check.</param>
- /// <param name="excludeInterfaces">If true, check against addresses in the LAN settings which have [] arroud and return true if it matches the address give in address.</param>
- /// <param name="excludeRFC">If true, returns false if address is in the 127.x.x.x or 169.128.x.x range.</param>
- /// <returns><c>false</c>if the address isn't in the LAN list, <c>true</c> if the address has been defined as a LAN address.</returns>
- bool IsAddressInSubnets(IPAddress address, bool excludeInterfaces, bool excludeRFC);
+ /// <param name="ip">IP to check.</param>
+ /// <returns>True if excluded.</returns>
+ bool IsExcluded(IPAddress ip);
/// <summary>
- /// Checks if address is in the LAN list in the config file.
+ /// Returns true if the IP address is in the excluded list.
/// </summary>
- /// <param name="address1">Source address to check.</param>
- /// <param name="address2">Destination address to check against.</param>
- /// <param name="subnetMask">Destination subnet to check against.</param>
- /// <returns><c>true/false</c>depending on whether address1 is in the same subnet as IPAddress2 with subnetMask.</returns>
- bool IsInSameSubnet(IPAddress address1, IPAddress address2, IPAddress subnetMask);
+ /// <param name="ip">IP to check.</param>
+ /// <returns>True if excluded.</returns>
+ bool IsExcluded(EndPoint ip);
/// <summary>
- /// Returns the subnet mask of an interface with the given address.
+ /// Gets the filtered LAN ip addresses.
/// </summary>
- /// <param name="address">The address to check.</param>
- /// <returns>Returns the subnet mask of an interface with the given address, or null if an interface match cannot be found.</returns>
- IPAddress GetLocalIpSubnetMask(IPAddress address);
+ /// <param name="filter">Optional filter for the list.</param>
+ /// <returns>Returns a filtered list of LAN addresses.</returns>
+ Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null);
}
}
diff --git a/MediaBrowser.Common/Net/IPHost.cs b/MediaBrowser.Common/Net/IPHost.cs
new file mode 100644
index 000000000..f9e1568ef
--- /dev/null
+++ b/MediaBrowser.Common/Net/IPHost.cs
@@ -0,0 +1,444 @@
+#nullable enable
+using System;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+
+namespace MediaBrowser.Common.Net
+{
+ /// <summary>
+ /// Object that holds a host name.
+ /// </summary>
+ public class IPHost : IPObject
+ {
+ /// <summary>
+ /// Represents an IPHost that has no value.
+ /// </summary>
+ public static readonly IPHost None = new IPHost(string.Empty, IPAddress.None);
+
+ /// <summary>
+ /// Time when last resolved in ticks.
+ /// </summary>
+ private long _lastResolved;
+
+ /// <summary>
+ /// Gets the IP Addresses, attempting to resolve the name, if there are none.
+ /// </summary>
+ private IPAddress[] _addresses;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="IPHost"/> class.
+ /// </summary>
+ /// <param name="name">Host name to assign.</param>
+ public IPHost(string name)
+ {
+ HostName = name ?? throw new ArgumentNullException(nameof(name));
+ _addresses = Array.Empty<IPAddress>();
+ Resolved = false;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="IPHost"/> class.
+ /// </summary>
+ /// <param name="name">Host name to assign.</param>
+ /// <param name="address">Address to assign.</param>
+ private IPHost(string name, IPAddress address)
+ {
+ HostName = name ?? throw new ArgumentNullException(nameof(name));
+ _addresses = new IPAddress[] { address ?? throw new ArgumentNullException(nameof(address)) };
+ Resolved = !address.Equals(IPAddress.None);
+ }
+
+ /// <summary>
+ /// Gets or sets the object's first IP address.
+ /// </summary>
+ public override IPAddress Address
+ {
+ get
+ {
+ return ResolveHost() ? this[0] : IPAddress.None;
+ }
+
+ set
+ {
+ // Not implemented, as a host's address is determined by DNS.
+ throw new NotImplementedException("The address of a host is determined by DNS.");
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the object's first IP's subnet prefix.
+ /// The setter does nothing, but shouldn't raise an exception.
+ /// </summary>
+ public override byte PrefixLength
+ {
+ get
+ {
+ return (byte)(ResolveHost() ? 128 : 32);
+ }
+
+ set
+ {
+ // Not implemented, as a host object can only have a prefix length of 128 (IPv6) or 32 (IPv4) prefix length,
+ // which is automatically determined by it's IP type. Anything else is meaningless.
+ throw new NotImplementedException("The prefix length on a host cannot be set.");
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets timeout value before resolve required, in minutes.
+ /// </summary>
+ public byte Timeout { get; set; } = 30;
+
+ /// <summary>
+ /// Gets a value indicating whether the address has a value.
+ /// </summary>
+ public bool HasAddress => _addresses.Length != 0;
+
+ /// <summary>
+ /// Gets the host name of this object.
+ /// </summary>
+ public string HostName { get; }
+
+ /// <summary>
+ /// Gets a value indicating whether this host has attempted to be resolved.
+ /// </summary>
+ public bool Resolved { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the IP Addresses associated with this object.
+ /// </summary>
+ /// <param name="index">Index of address.</param>
+ public IPAddress this[int index]
+ {
+ get
+ {
+ ResolveHost();
+ return index >= 0 && index < _addresses.Length ? _addresses[index] : IPAddress.None;
+ }
+ }
+
+ /// <summary>
+ /// Attempts to parse the host string.
+ /// </summary>
+ /// <param name="host">Host name to parse.</param>
+ /// <param name="hostObj">Object representing the string, if it has successfully been parsed.</param>
+ /// <returns><c>true</c> if the parsing is successful, <c>false</c> if not.</returns>
+ public static bool TryParse(string host, out IPHost hostObj)
+ {
+ if (!string.IsNullOrEmpty(host))
+ {
+ // See if it's an IPv6 with port address e.g. [::1]:120.
+ int i = host.IndexOf("]:", StringComparison.OrdinalIgnoreCase);
+ if (i != -1)
+ {
+ return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj);
+ }
+ else
+ {
+ // See if it's an IPv6 in [] with no port.
+ i = host.IndexOf(']', StringComparison.OrdinalIgnoreCase);
+ if (i != -1)
+ {
+ return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj);
+ }
+
+ // Is it a host or IPv4 with port?
+ string[] hosts = host.Split(':');
+
+ if (hosts.Length > 2)
+ {
+ hostObj = new IPHost(string.Empty, IPAddress.None);
+ return false;
+ }
+
+ // Remove port from IPv4 if it exists.
+ host = hosts[0];
+
+ if (string.Equals("localhost", host, StringComparison.OrdinalIgnoreCase))
+ {
+ hostObj = new IPHost(host, new IPAddress(Ipv4Loopback));
+ return true;
+ }
+
+ if (IPNetAddress.TryParse(host, out IPNetAddress netIP))
+ {
+ // Host name is an ip address, so fake resolve.
+ hostObj = new IPHost(host, netIP.Address);
+ return true;
+ }
+ }
+
+ // Only thing left is to see if it's a host string.
+ if (!string.IsNullOrEmpty(host))
+ {
+ // Use regular expression as CheckHostName isn't RFC5892 compliant.
+ // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation
+ Regex re = new Regex(@"^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)$", RegexOptions.IgnoreCase | RegexOptions.Multiline);
+ if (re.Match(host).Success)
+ {
+ hostObj = new IPHost(host);
+ return true;
+ }
+ }
+ }
+
+ hostObj = IPHost.None;
+ return false;
+ }
+
+ /// <summary>
+ /// Attempts to parse the host string.
+ /// </summary>
+ /// <param name="host">Host name to parse.</param>
+ /// <returns>Object representing the string, if it has successfully been parsed.</returns>
+ public static IPHost Parse(string host)
+ {
+ if (!string.IsNullOrEmpty(host) && IPHost.TryParse(host, out IPHost res))
+ {
+ return res;
+ }
+
+ throw new InvalidCastException("Host does not contain a valid value. {host}");
+ }
+
+ /// <summary>
+ /// Attempts to parse the host string, ensuring that it resolves only to a specific IP type.
+ /// </summary>
+ /// <param name="host">Host name to parse.</param>
+ /// <param name="family">Addressfamily filter.</param>
+ /// <returns>Object representing the string, if it has successfully been parsed.</returns>
+ public static IPHost Parse(string host, AddressFamily family)
+ {
+ if (!string.IsNullOrEmpty(host) && IPHost.TryParse(host, out IPHost res))
+ {
+ if (family == AddressFamily.InterNetwork)
+ {
+ res.Remove(AddressFamily.InterNetworkV6);
+ }
+ else
+ {
+ res.Remove(AddressFamily.InterNetwork);
+ }
+
+ return res;
+ }
+
+ throw new InvalidCastException("Host does not contain a valid value. {host}");
+ }
+
+ /// <summary>
+ /// Returns the Addresses that this item resolved to.
+ /// </summary>
+ /// <returns>IPAddress Array.</returns>
+ public IPAddress[] GetAddresses()
+ {
+ ResolveHost();
+ return _addresses;
+ }
+
+ /// <inheritdoc/>
+ public override bool Contains(IPAddress address)
+ {
+ if (address != null && !Address.Equals(IPAddress.None))
+ {
+ if (address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ foreach (var addr in GetAddresses())
+ {
+ if (address.Equals(addr))
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /// <inheritdoc/>
+ public override bool Equals(IPObject? other)
+ {
+ if (other is IPHost otherObj)
+ {
+ // Do we have the name Hostname?
+ if (string.Equals(otherObj.HostName, HostName, StringComparison.OrdinalIgnoreCase))
+ {
+ return true;
+ }
+
+ if (!ResolveHost() || !otherObj.ResolveHost())
+ {
+ return false;
+ }
+
+ // Do any of our IP addresses match?
+ foreach (IPAddress addr in _addresses)
+ {
+ foreach (IPAddress otherAddress in otherObj._addresses)
+ {
+ if (addr.Equals(otherAddress))
+ {
+ return true;
+ }
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /// <inheritdoc/>
+ public override bool IsIP6()
+ {
+ // Returns true if interfaces are only IP6.
+ if (ResolveHost())
+ {
+ foreach (IPAddress i in _addresses)
+ {
+ if (i.AddressFamily != AddressFamily.InterNetworkV6)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <inheritdoc/>
+ public override string ToString()
+ {
+ // StringBuilder not optimum here.
+ string output = string.Empty;
+ if (_addresses.Length > 0)
+ {
+ bool moreThanOne = _addresses.Length > 1;
+ if (moreThanOne)
+ {
+ output = "[";
+ }
+
+ foreach (var i in _addresses)
+ {
+ if (Address.Equals(IPAddress.None) && Address.AddressFamily == AddressFamily.Unspecified)
+ {
+ output += HostName + ",";
+ }
+ else if (i.Equals(IPAddress.Any))
+ {
+ output += "Any IP4 Address,";
+ }
+ else if (Address.Equals(IPAddress.IPv6Any))
+ {
+ output += "Any IP6 Address,";
+ }
+ else if (i.Equals(IPAddress.Broadcast))
+ {
+ output += "Any Address,";
+ }
+ else
+ {
+ output += $"{i}/32,";
+ }
+ }
+
+ output = output[0..^1];
+
+ if (moreThanOne)
+ {
+ output += "]";
+ }
+ }
+ else
+ {
+ output = HostName;
+ }
+
+ return output;
+ }
+
+ /// <inheritdoc/>
+ public override void Remove(AddressFamily family)
+ {
+ if (ResolveHost())
+ {
+ _addresses = _addresses.Where(p => p.AddressFamily != family).ToArray();
+ }
+ }
+
+ /// <inheritdoc/>
+ public override bool Contains(IPObject address)
+ {
+ // An IPHost cannot contain another IPObject, it can only be equal.
+ return Equals(address);
+ }
+
+ /// <inheritdoc/>
+ protected override IPObject CalculateNetworkAddress()
+ {
+ var netAddr = NetworkAddressOf(this[0], PrefixLength);
+ return new IPNetAddress(netAddr.Address, netAddr.PrefixLength);
+ }
+
+ /// <summary>
+ /// Attempt to resolve the ip address of a host.
+ /// </summary>
+ /// <returns><c>true</c> if any addresses have been resolved, otherwise <c>false</c>.</returns>
+ private bool ResolveHost()
+ {
+ // When was the last time we resolved?
+ if (_lastResolved == 0)
+ {
+ _lastResolved = DateTime.UtcNow.Ticks;
+ }
+
+ // If we haven't resolved before, or out timer has run out...
+ if ((_addresses.Length == 0 && !Resolved) || (TimeSpan.FromTicks(DateTime.UtcNow.Ticks - _lastResolved).TotalMinutes > Timeout))
+ {
+ _lastResolved = DateTime.UtcNow.Ticks;
+ ResolveHostInternal().GetAwaiter().GetResult();
+ Resolved = true;
+ }
+
+ return _addresses.Length > 0;
+ }
+
+ /// <summary>
+ /// Task that looks up a Host name and returns its IP addresses.
+ /// </summary>
+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
+ private async Task ResolveHostInternal()
+ {
+ if (!string.IsNullOrEmpty(HostName))
+ {
+ // Resolves the host name - so save a DNS lookup.
+ if (string.Equals(HostName, "localhost", StringComparison.OrdinalIgnoreCase))
+ {
+ _addresses = new IPAddress[] { new IPAddress(Ipv4Loopback), new IPAddress(Ipv6Loopback) };
+ return;
+ }
+
+ if (Uri.CheckHostName(HostName).Equals(UriHostNameType.Dns))
+ {
+ try
+ {
+ IPHostEntry ip = await Dns.GetHostEntryAsync(HostName).ConfigureAwait(false);
+ _addresses = ip.AddressList;
+ }
+ catch (SocketException)
+ {
+ // Ignore socket errors, as the result value will just be an empty array.
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Net/IPNetAddress.cs b/MediaBrowser.Common/Net/IPNetAddress.cs
new file mode 100644
index 000000000..0d28c35cb
--- /dev/null
+++ b/MediaBrowser.Common/Net/IPNetAddress.cs
@@ -0,0 +1,277 @@
+#nullable enable
+using System;
+using System.Net;
+using System.Net.Sockets;
+
+namespace MediaBrowser.Common.Net
+{
+ /// <summary>
+ /// An object that holds and IP address and subnet mask.
+ /// </summary>
+ public class IPNetAddress : IPObject
+ {
+ /// <summary>
+ /// Represents an IPNetAddress that has no value.
+ /// </summary>
+ public static readonly IPNetAddress None = new IPNetAddress(IPAddress.None);
+
+ /// <summary>
+ /// IPv4 multicast address.
+ /// </summary>
+ public static readonly IPAddress MulticastIPv4 = IPAddress.Parse("239.255.255.250");
+
+ /// <summary>
+ /// IPv6 local link multicast address.
+ /// </summary>
+ public static readonly IPAddress MulticastIPv6LinkLocal = IPAddress.Parse("ff02::C");
+
+ /// <summary>
+ /// IPv6 site local multicast address.
+ /// </summary>
+ public static readonly IPAddress MulticastIPv6SiteLocal = IPAddress.Parse("ff05::C");
+
+ /// <summary>
+ /// IP4Loopback address host.
+ /// </summary>
+ public static readonly IPNetAddress IP4Loopback = IPNetAddress.Parse("127.0.0.1/32");
+
+ /// <summary>
+ /// IP6Loopback address host.
+ /// </summary>
+ public static readonly IPNetAddress IP6Loopback = IPNetAddress.Parse("::1");
+
+ /// <summary>
+ /// Object's IP address.
+ /// </summary>
+ private IPAddress _address;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="IPNetAddress"/> class.
+ /// </summary>
+ /// <param name="address">Address to assign.</param>
+ public IPNetAddress(IPAddress address)
+ {
+ _address = address ?? throw new ArgumentNullException(nameof(address));
+ PrefixLength = (byte)(address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="IPNetAddress"/> class.
+ /// </summary>
+ /// <param name="address">IP Address.</param>
+ /// <param name="prefixLength">Mask as a CIDR.</param>
+ public IPNetAddress(IPAddress address, byte prefixLength)
+ {
+ if (address?.IsIPv4MappedToIPv6 ?? throw new ArgumentNullException(nameof(address)))
+ {
+ _address = address.MapToIPv4();
+ }
+ else
+ {
+ _address = address;
+ }
+
+ PrefixLength = prefixLength;
+ }
+
+ /// <summary>
+ /// Gets or sets the object's IP address.
+ /// </summary>
+ public override IPAddress Address
+ {
+ get
+ {
+ return _address;
+ }
+
+ set
+ {
+ _address = value ?? IPAddress.None;
+ }
+ }
+
+ /// <inheritdoc/>
+ public override byte PrefixLength { get; set; }
+
+ /// <summary>
+ /// Try to parse the address and subnet strings into an IPNetAddress object.
+ /// </summary>
+ /// <param name="addr">IP address to parse. Can be CIDR or X.X.X.X notation.</param>
+ /// <param name="ip">Resultant object.</param>
+ /// <returns>True if the values parsed successfully. False if not, resulting in the IP being null.</returns>
+ public static bool TryParse(string addr, out IPNetAddress ip)
+ {
+ if (!string.IsNullOrEmpty(addr))
+ {
+ addr = addr.Trim();
+
+ // Try to parse it as is.
+ if (IPAddress.TryParse(addr, out IPAddress? res))
+ {
+ ip = new IPNetAddress(res);
+ return true;
+ }
+
+ // Is it a network?
+ string[] tokens = addr.Split("/");
+
+ if (tokens.Length == 2)
+ {
+ tokens[0] = tokens[0].TrimEnd();
+ tokens[1] = tokens[1].TrimStart();
+
+ if (IPAddress.TryParse(tokens[0], out res))
+ {
+ // Is the subnet part a cidr?
+ if (byte.TryParse(tokens[1], out byte cidr))
+ {
+ ip = new IPNetAddress(res, cidr);
+ return true;
+ }
+
+ // Is the subnet in x.y.a.b form?
+ if (IPAddress.TryParse(tokens[1], out IPAddress? mask))
+ {
+ ip = new IPNetAddress(res, MaskToCidr(mask));
+ return true;
+ }
+ }
+ }
+ }
+
+ ip = None;
+ return false;
+ }
+
+ /// <summary>
+ /// Parses the string provided, throwing an exception if it is badly formed.
+ /// </summary>
+ /// <param name="addr">String to parse.</param>
+ /// <returns>IPNetAddress object.</returns>
+ public static IPNetAddress Parse(string addr)
+ {
+ if (TryParse(addr, out IPNetAddress o))
+ {
+ return o;
+ }
+
+ throw new ArgumentException("Unable to recognise object :" + addr);
+ }
+
+ /// <inheritdoc/>
+ public override bool Contains(IPAddress address)
+ {
+ if (address == null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ if (address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ var altAddress = NetworkAddressOf(address, PrefixLength);
+ return NetworkAddress.Address.Equals(altAddress.Address) && NetworkAddress.PrefixLength >= altAddress.PrefixLength;
+ }
+
+ /// <inheritdoc/>
+ public override bool Contains(IPObject address)
+ {
+ if (address is IPHost addressObj && addressObj.HasAddress)
+ {
+ foreach (IPAddress addr in addressObj.GetAddresses())
+ {
+ if (Contains(addr))
+ {
+ return true;
+ }
+ }
+ }
+ else if (address is IPNetAddress netaddrObj)
+ {
+ // Have the same network address, but different subnets?
+ if (NetworkAddress.Address.Equals(netaddrObj.NetworkAddress.Address))
+ {
+ return NetworkAddress.PrefixLength <= netaddrObj.PrefixLength;
+ }
+
+ var altAddress = NetworkAddressOf(netaddrObj.Address, PrefixLength);
+ return NetworkAddress.Address.Equals(altAddress.Address);
+ }
+
+ return false;
+ }
+
+ /// <inheritdoc/>
+ public override bool Equals(IPObject? other)
+ {
+ if (other is IPNetAddress otherObj && !Address.Equals(IPAddress.None) && !otherObj.Address.Equals(IPAddress.None))
+ {
+ return Address.Equals(otherObj.Address) &&
+ PrefixLength == otherObj.PrefixLength;
+ }
+
+ return false;
+ }
+
+ /// <inheritdoc/>
+ public override bool Equals(IPAddress address)
+ {
+ if (address != null && !address.Equals(IPAddress.None) && !Address.Equals(IPAddress.None))
+ {
+ return address.Equals(Address);
+ }
+
+ return false;
+ }
+
+ /// <inheritdoc/>
+ public override string ToString()
+ {
+ return ToString(false);
+ }
+
+ /// <summary>
+ /// Returns a textual representation of this object.
+ /// </summary>
+ /// <param name="shortVersion">Set to true, if the subnet is to be included as part of the address.</param>
+ /// <returns>String representation of this object.</returns>
+ public string ToString(bool shortVersion)
+ {
+ if (!Address.Equals(IPAddress.None))
+ {
+ if (Address.Equals(IPAddress.Any))
+ {
+ return "Any IP4 Address";
+ }
+
+ if (Address.Equals(IPAddress.IPv6Any))
+ {
+ return "Any IP6 Address";
+ }
+
+ if (Address.Equals(IPAddress.Broadcast))
+ {
+ return "Any Address";
+ }
+
+ if (shortVersion)
+ {
+ return Address.ToString();
+ }
+
+ return $"{Address}/{PrefixLength}";
+ }
+
+ return string.Empty;
+ }
+
+ /// <inheritdoc/>
+ protected override IPObject CalculateNetworkAddress()
+ {
+ var value = NetworkAddressOf(_address, PrefixLength);
+ return new IPNetAddress(value.Address, value.PrefixLength);
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Net/IPObject.cs b/MediaBrowser.Common/Net/IPObject.cs
new file mode 100644
index 000000000..d18ac9893
--- /dev/null
+++ b/MediaBrowser.Common/Net/IPObject.cs
@@ -0,0 +1,395 @@
+#nullable enable
+using System;
+using System.Net;
+using System.Net.Sockets;
+
+namespace MediaBrowser.Common.Net
+{
+ /// <summary>
+ /// Base network object class.
+ /// </summary>
+ public abstract class IPObject : IEquatable<IPObject>
+ {
+ /// <summary>
+ /// IPv6 Loopback address.
+ /// </summary>
+ protected static readonly byte[] Ipv6Loopback = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
+
+ /// <summary>
+ /// IPv4 Loopback address.
+ /// </summary>
+ protected static readonly byte[] Ipv4Loopback = { 127, 0, 0, 1 };
+
+ /// <summary>
+ /// The network address of this object.
+ /// </summary>
+ private IPObject? _networkAddress;
+
+ /// <summary>
+ /// Gets or sets a user defined value that is associated with this object.
+ /// </summary>
+ public int Tag { get; set; }
+
+ /// <summary>
+ /// Gets or sets the object's IP address.
+ /// </summary>
+ public abstract IPAddress Address { get; set; }
+
+ /// <summary>
+ /// Gets the object's network address.
+ /// </summary>
+ public IPObject NetworkAddress => _networkAddress ??= CalculateNetworkAddress();
+
+ /// <summary>
+ /// Gets or sets the object's IP address.
+ /// </summary>
+ public abstract byte PrefixLength { get; set; }
+
+ /// <summary>
+ /// Gets the AddressFamily of this object.
+ /// </summary>
+ public AddressFamily AddressFamily
+ {
+ get
+ {
+ // Keep terms separate as Address performs other functions in inherited objects.
+ IPAddress address = Address;
+ return address.Equals(IPAddress.None) ? AddressFamily.Unspecified : address.AddressFamily;
+ }
+ }
+
+ /// <summary>
+ /// Returns the network address of an object.
+ /// </summary>
+ /// <param name="address">IP Address to convert.</param>
+ /// <param name="prefixLength">Subnet prefix.</param>
+ /// <returns>IPAddress.</returns>
+ public static (IPAddress Address, byte PrefixLength) NetworkAddressOf(IPAddress address, byte prefixLength)
+ {
+ if (address == null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ if (address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ if (IsLoopback(address))
+ {
+ return (Address: address, PrefixLength: prefixLength);
+ }
+
+ // An ip address is just a list of bytes, each one representing a segment on the network.
+ // This separates the IP address into octets and calculates how many octets will need to be altered or set to zero dependant upon the
+ // prefix length value. eg. /16 on a 4 octet ip4 address (192.168.2.240) will result in the 2 and the 240 being zeroed out.
+ // Where there is not an exact boundary (eg /23), mod is used to calculate how many bits of this value are to be kept.
+
+ byte[] addressBytes = address.GetAddressBytes();
+
+ int div = prefixLength / 8;
+ int mod = prefixLength % 8;
+ if (mod != 0)
+ {
+ // Prefix length is counted right to left, so subtract 8 so we know how many bits to clear.
+ mod = 8 - mod;
+
+ // Shift out the bits from the octet that we don't want, by moving right then back left.
+ addressBytes[div] = (byte)((int)addressBytes[div] >> mod << mod);
+ // Move on the next byte.
+ div++;
+ }
+
+ // Blank out the remaining octets from mod + 1 to the end of the byte array. (192.168.2.240/16 becomes 192.168.0.0)
+ for (int octet = div; octet < addressBytes.Length; octet++)
+ {
+ addressBytes[octet] = 0;
+ }
+
+ // Return the network address for the prefix.
+ return (Address: new IPAddress(addressBytes), PrefixLength: prefixLength);
+ }
+
+ /// <summary>
+ /// Tests to see if the ip address is a Loopback address.
+ /// </summary>
+ /// <param name="address">Value to test.</param>
+ /// <returns>True if it is.</returns>
+ public static bool IsLoopback(IPAddress address)
+ {
+ if (address == null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ if (!address.Equals(IPAddress.None))
+ {
+ if (address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ return address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback);
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Tests to see if the ip address is an IP6 address.
+ /// </summary>
+ /// <param name="address">Value to test.</param>
+ /// <returns>True if it is.</returns>
+ public static bool IsIP6(IPAddress address)
+ {
+ if (address == null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ if (address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ return !address.Equals(IPAddress.None) && (address.AddressFamily == AddressFamily.InterNetworkV6);
+ }
+
+ /// <summary>
+ /// Tests to see if the address in the private address range.
+ /// </summary>
+ /// <param name="address">Object to test.</param>
+ /// <returns>True if it contains a private address.</returns>
+ public static bool IsPrivateAddressRange(IPAddress address)
+ {
+ if (address == null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ if (!address.Equals(IPAddress.None))
+ {
+ if (address.AddressFamily == AddressFamily.InterNetwork)
+ {
+ if (address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ byte[] octet = address.GetAddressBytes();
+
+ return (octet[0] == 10)
+ || (octet[0] == 172 && octet[1] >= 16 && octet[1] <= 31) // RFC1918
+ || (octet[0] == 192 && octet[1] == 168) // RFC1918
+ || (octet[0] == 127); // RFC1122
+ }
+ else
+ {
+ byte[] octet = address.GetAddressBytes();
+ uint word = (uint)(octet[0] << 8) + octet[1];
+
+ return (word >= 0xfe80 && word <= 0xfebf) // fe80::/10 :Local link.
+ || (word >= 0xfc00 && word <= 0xfdff); // fc00::/7 :Unique local address.
+ }
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Returns true if the IPAddress contains an IP6 Local link address.
+ /// </summary>
+ /// <param name="address">IPAddress object to check.</param>
+ /// <returns>True if it is a local link address.</returns>
+ /// <remarks>
+ /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress
+ /// it appears that the IPAddress.IsIPv6LinkLocal is out of date.
+ /// </remarks>
+ public static bool IsIPv6LinkLocal(IPAddress address)
+ {
+ if (address == null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ if (address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ if (address.AddressFamily != AddressFamily.InterNetworkV6)
+ {
+ return false;
+ }
+
+ byte[] octet = address.GetAddressBytes();
+ uint word = (uint)(octet[0] << 8) + octet[1];
+
+ return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link.
+ }
+
+ /// <summary>
+ /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only.
+ /// </summary>
+ /// <param name="cidr">Subnet mask in CIDR notation.</param>
+ /// <param name="family">IPv4 or IPv6 family.</param>
+ /// <returns>String value of the subnet mask in dotted decimal notation.</returns>
+ public static IPAddress CidrToMask(byte cidr, AddressFamily family)
+ {
+ uint addr = 0xFFFFFFFF << (family == AddressFamily.InterNetwork ? 32 : 128 - cidr);
+ addr = ((addr & 0xff000000) >> 24)
+ | ((addr & 0x00ff0000) >> 8)
+ | ((addr & 0x0000ff00) << 8)
+ | ((addr & 0x000000ff) << 24);
+ return new IPAddress(addr);
+ }
+
+ /// <summary>
+ /// Convert a mask to a CIDR. IPv4 only.
+ /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask.
+ /// </summary>
+ /// <param name="mask">Subnet mask.</param>
+ /// <returns>Byte CIDR representing the mask.</returns>
+ public static byte MaskToCidr(IPAddress mask)
+ {
+ if (mask == null)
+ {
+ throw new ArgumentNullException(nameof(mask));
+ }
+
+ byte cidrnet = 0;
+ if (!mask.Equals(IPAddress.Any))
+ {
+ byte[] bytes = mask.GetAddressBytes();
+
+ var zeroed = false;
+ for (var i = 0; i < bytes.Length; i++)
+ {
+ for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1)
+ {
+ if (zeroed)
+ {
+ // Invalid netmask.
+ return (byte)~cidrnet;
+ }
+
+ if ((v & 0x80) == 0)
+ {
+ zeroed = true;
+ }
+ else
+ {
+ cidrnet++;
+ }
+ }
+ }
+ }
+
+ return cidrnet;
+ }
+
+ /// <summary>
+ /// Tests to see if this object is a Loopback address.
+ /// </summary>
+ /// <returns>True if it is.</returns>
+ public virtual bool IsLoopback()
+ {
+ return IsLoopback(Address);
+ }
+
+ /// <summary>
+ /// Removes all addresses of a specific type from this object.
+ /// </summary>
+ /// <param name="family">Type of address to remove.</param>
+ public virtual void Remove(AddressFamily family)
+ {
+ // This method only performs a function in the IPHost implementation of IPObject.
+ }
+
+ /// <summary>
+ /// Tests to see if this object is an IPv6 address.
+ /// </summary>
+ /// <returns>True if it is.</returns>
+ public virtual bool IsIP6()
+ {
+ return IsIP6(Address);
+ }
+
+ /// <summary>
+ /// Returns true if this IP address is in the RFC private address range.
+ /// </summary>
+ /// <returns>True this object has a private address.</returns>
+ public virtual bool IsPrivateAddressRange()
+ {
+ return IsPrivateAddressRange(Address);
+ }
+
+ /// <summary>
+ /// Compares this to the object passed as a parameter.
+ /// </summary>
+ /// <param name="ip">Object to compare to.</param>
+ /// <returns>Equality result.</returns>
+ public virtual bool Equals(IPAddress ip)
+ {
+ if (ip != null)
+ {
+ if (ip.IsIPv4MappedToIPv6)
+ {
+ ip = ip.MapToIPv4();
+ }
+
+ return !Address.Equals(IPAddress.None) && Address.Equals(ip);
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Compares this to the object passed as a parameter.
+ /// </summary>
+ /// <param name="other">Object to compare to.</param>
+ /// <returns>Equality result.</returns>
+ public virtual bool Equals(IPObject? other)
+ {
+ if (other != null)
+ {
+ return !Address.Equals(IPAddress.None) && Address.Equals(other.Address);
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Compares the address in this object and the address in the object passed as a parameter.
+ /// </summary>
+ /// <param name="address">Object's IP address to compare to.</param>
+ /// <returns>Comparison result.</returns>
+ public abstract bool Contains(IPObject address);
+
+ /// <summary>
+ /// Compares the address in this object and the address in the object passed as a parameter.
+ /// </summary>
+ /// <param name="address">Object's IP address to compare to.</param>
+ /// <returns>Comparison result.</returns>
+ public abstract bool Contains(IPAddress address);
+
+ /// <inheritdoc/>
+ public override int GetHashCode()
+ {
+ return Address.GetHashCode();
+ }
+
+ /// <inheritdoc/>
+ public override bool Equals(object? obj)
+ {
+ return Equals(obj as IPObject);
+ }
+
+ /// <summary>
+ /// Calculates the network address of this object.
+ /// </summary>
+ /// <returns>Returns the network address of this object.</returns>
+ protected abstract IPObject CalculateNetworkAddress();
+ }
+}
diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs
new file mode 100644
index 000000000..d07bba249
--- /dev/null
+++ b/MediaBrowser.Common/Net/NetworkExtensions.cs
@@ -0,0 +1,262 @@
+#pragma warning disable CA1062 // Validate arguments of public methods
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Net;
+using System.Runtime.CompilerServices;
+using System.Text;
+
+namespace MediaBrowser.Common.Net
+{
+ /// <summary>
+ /// Defines the <see cref="NetworkExtensions" />.
+ /// </summary>
+ public static class NetworkExtensions
+ {
+ /// <summary>
+ /// Add an address to the collection.
+ /// </summary>
+ /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
+ /// <param name="ip">Item to add.</param>
+ public static void AddItem(this Collection<IPObject> source, IPAddress ip)
+ {
+ if (!source.ContainsAddress(ip))
+ {
+ source.Add(new IPNetAddress(ip, 32));
+ }
+ }
+
+ /// <summary>
+ /// Adds a network to the collection.
+ /// </summary>
+ /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
+ /// <param name="item">Item to add.</param>
+ public static void AddItem(this Collection<IPObject> source, IPObject item)
+ {
+ if (!source.ContainsAddress(item))
+ {
+ source.Add(item);
+ }
+ }
+
+ /// <summary>
+ /// Converts this object to a string.
+ /// </summary>
+ /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
+ /// <returns>Returns a string representation of this object.</returns>
+ public static string AsString(this Collection<IPObject> source)
+ {
+ return $"[{string.Join(',', source)}]";
+ }
+
+ /// <summary>
+ /// Returns true if the collection contains an item with the ip address,
+ /// or the ip address falls within any of the collection's network ranges.
+ /// </summary>
+ /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
+ /// <param name="item">The item to look for.</param>
+ /// <returns>True if the collection contains the item.</returns>
+ public static bool ContainsAddress(this Collection<IPObject> source, IPAddress item)
+ {
+ if (source.Count == 0)
+ {
+ return false;
+ }
+
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+
+ if (item.IsIPv4MappedToIPv6)
+ {
+ item = item.MapToIPv4();
+ }
+
+ foreach (var i in source)
+ {
+ if (i.Contains(item))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Returns true if the collection contains an item with the ip address,
+ /// or the ip address falls within any of the collection's network ranges.
+ /// </summary>
+ /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
+ /// <param name="item">The item to look for.</param>
+ /// <returns>True if the collection contains the item.</returns>
+ public static bool ContainsAddress(this Collection<IPObject> source, IPObject item)
+ {
+ if (source.Count == 0)
+ {
+ return false;
+ }
+
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+
+ foreach (var i in source)
+ {
+ if (i.Contains(item))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Compares two Collection{IPObject} objects. The order is ignored.
+ /// </summary>
+ /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
+ /// <param name="dest">Item to compare to.</param>
+ /// <returns>True if both are equal.</returns>
+ public static bool Compare(this Collection<IPObject> source, Collection<IPObject> dest)
+ {
+ if (dest == null || source.Count != dest.Count)
+ {
+ return false;
+ }
+
+ foreach (var sourceItem in source)
+ {
+ bool found = false;
+ foreach (var destItem in dest)
+ {
+ if (sourceItem.Equals(destItem))
+ {
+ found = true;
+ break;
+ }
+ }
+
+ if (!found)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Returns a collection containing the subnets of this collection given.
+ /// </summary>
+ /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
+ /// <returns>Collection{IPObject} object containing the subnets.</returns>
+ public static Collection<IPObject> AsNetworks(this Collection<IPObject> source)
+ {
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+
+ Collection<IPObject> res = new Collection<IPObject>();
+
+ foreach (IPObject i in source)
+ {
+ if (i is IPNetAddress nw)
+ {
+ // Add the subnet calculated from the interface address/mask.
+ var na = nw.NetworkAddress;
+ na.Tag = i.Tag;
+ res.AddItem(na);
+ }
+ else if (i is IPHost ipHost)
+ {
+ // Flatten out IPHost and add all its ip addresses.
+ foreach (var addr in ipHost.GetAddresses())
+ {
+ IPNetAddress host = new IPNetAddress(addr)
+ {
+ Tag = i.Tag
+ };
+
+ res.AddItem(host);
+ }
+ }
+ }
+
+ return res;
+ }
+
+ /// <summary>
+ /// Excludes all the items from this list that are found in excludeList.
+ /// </summary>
+ /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
+ /// <param name="excludeList">Items to exclude.</param>
+ /// <returns>A new collection, with the items excluded.</returns>
+ public static Collection<IPObject> Exclude(this Collection<IPObject> source, Collection<IPObject> excludeList)
+ {
+ if (source.Count == 0 || excludeList == null)
+ {
+ return new Collection<IPObject>(source);
+ }
+
+ Collection<IPObject> results = new Collection<IPObject>();
+
+ bool found;
+ foreach (var outer in source)
+ {
+ found = false;
+
+ foreach (var inner in excludeList)
+ {
+ if (outer.Equals(inner))
+ {
+ found = true;
+ break;
+ }
+ }
+
+ if (!found)
+ {
+ results.AddItem(outer);
+ }
+ }
+
+ return results;
+ }
+
+ /// <summary>
+ /// Returns all items that co-exist in this object and target.
+ /// </summary>
+ /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
+ /// <param name="target">Collection to compare with.</param>
+ /// <returns>A collection containing all the matches.</returns>
+ public static Collection<IPObject> Union(this Collection<IPObject> source, Collection<IPObject> target)
+ {
+ if (source.Count == 0)
+ {
+ return new Collection<IPObject>();
+ }
+
+ if (target == null)
+ {
+ throw new ArgumentNullException(nameof(target));
+ }
+
+ Collection<IPObject> nc = new Collection<IPObject>();
+
+ foreach (IPObject i in source)
+ {
+ if (target.ContainsAddress(i))
+ {
+ nc.AddItem(i);
+ }
+ }
+
+ return nc;
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs
index ffbb147b0..2456da826 100644
--- a/MediaBrowser.Controller/IServerApplicationHost.cs
+++ b/MediaBrowser.Controller/IServerApplicationHost.cs
@@ -8,6 +8,7 @@ using System.Threading.Tasks;
using MediaBrowser.Common;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Model.System;
+using Microsoft.AspNetCore.Http;
namespace MediaBrowser.Controller
{
@@ -56,41 +57,42 @@ namespace MediaBrowser.Controller
/// <summary>
/// Gets the system info.
/// </summary>
- /// <param name="cancellationToken">A cancellation token that can be used to cancel the task.</param>
+ /// <param name="source">The originator of the request.</param>
/// <returns>SystemInfo.</returns>
- Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken = default);
+ SystemInfo GetSystemInfo(IPAddress source);
- Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken = default);
+ PublicSystemInfo GetPublicSystemInfo(IPAddress address);
/// <summary>
- /// Gets all the local IP addresses of this API instance. Each address is validated by sending a 'ping' request
- /// to the API that should exist at the address.
+ /// Gets a URL specific for the request.
/// </summary>
- /// <param name="cancellationToken">A cancellation token that can be used to cancel the task.</param>
- /// <returns>A list containing all the local IP addresses of the server.</returns>
- Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken = default);
+ /// <param name="request">The <see cref="HttpRequest"/> instance.</param>
+ /// <param name="port">Optional port number.</param>
+ /// <returns>An accessible URL.</returns>
+ string GetSmartApiUrl(HttpRequest request, int? port = null);
/// <summary>
- /// Gets a local (LAN) URL that can be used to access the API. The hostname used is the first valid configured
- /// IP address that can be found via <see cref="GetLocalIpAddresses"/>. HTTPS will be preferred when available.
+ /// Gets a URL specific for the request.
/// </summary>
- /// <param name="cancellationToken">A cancellation token that can be used to cancel the task.</param>
- /// <returns>The server URL.</returns>
- Task<string> GetLocalApiUrl(CancellationToken cancellationToken = default);
+ /// <param name="remoteAddr">The remote <see cref="IPAddress"/> of the connection.</param>
+ /// <param name="port">Optional port number.</param>
+ /// <returns>An accessible URL.</returns>
+ string GetSmartApiUrl(IPAddress remoteAddr, int? port = null);
/// <summary>
- /// Gets a localhost URL that can be used to access the API using the loop-back IP address (127.0.0.1)
- /// over HTTP (not HTTPS).
+ /// Gets a URL specific for the request.
/// </summary>
- /// <returns>The API URL.</returns>
- string GetLoopbackHttpApiUrl();
+ /// <param name="hostname">The hostname used in the connection.</param>
+ /// <param name="port">Optional port number.</param>
+ /// <returns>An accessible URL.</returns>
+ string GetSmartApiUrl(string hostname, int? port = null);
/// <summary>
- /// Gets a local (LAN) URL that can be used to access the API. HTTPS will be preferred when available.
+ /// Gets a localhost URL that can be used to access the API using the loop-back IP address.
+ /// over HTTP (not HTTPS).
/// </summary>
- /// <param name="address">The IP address to use as the hostname in the URL.</param>
/// <returns>The API URL.</returns>
- string GetLocalApiUrl(IPAddress address);
+ string GetLoopbackHttpApiUrl();
/// <summary>
/// Gets a local (LAN) URL that can be used to access the API.
@@ -106,7 +108,7 @@ namespace MediaBrowser.Controller
/// preferring the HTTPS port, if available.
/// </param>
/// <returns>The API URL.</returns>
- string GetLocalApiUrl(ReadOnlySpan<char> hostname, string scheme = null, int? port = null);
+ string GetLocalApiUrl(string hostname, string scheme = null, int? port = null);
/// <summary>
/// Open a URL in an external browser window.
diff --git a/MediaBrowser.Model/Configuration/PathSubstitution.cs b/MediaBrowser.Model/Configuration/PathSubstitution.cs
new file mode 100644
index 000000000..a066886e2
--- /dev/null
+++ b/MediaBrowser.Model/Configuration/PathSubstitution.cs
@@ -0,0 +1,19 @@
+#nullable enable
+#pragma warning disable CS1591
+#pragma warning disable CA1819
+
+using System;
+using System.Collections.Generic;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Updates;
+
+namespace MediaBrowser.Model.Configuration
+{
+
+ public class PathSubstitution
+ {
+ public string From { get; set; } = string.Empty;
+
+ public string To { get; set; } = string.Empty;
+ }
+}
diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs
index 23a5201f7..08bda14ba 100644
--- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs
+++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs
@@ -1,5 +1,5 @@
-#nullable disable
#pragma warning disable CS1591
+#pragma warning disable CA1819
using System;
using System.Collections.Generic;
@@ -15,41 +15,184 @@ namespace MediaBrowser.Model.Configuration
{
public const int DefaultHttpPort = 8096;
public const int DefaultHttpsPort = 8920;
- private string _baseUrl;
+ private string _baseUrl = string.Empty;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ServerConfiguration" /> class.
+ /// </summary>
+ public ServerConfiguration()
+ {
+ MetadataOptions = new[]
+ {
+ new MetadataOptions()
+ {
+ ItemType = "Book"
+ },
+ new MetadataOptions()
+ {
+ ItemType = "Movie"
+ },
+ new MetadataOptions
+ {
+ ItemType = "MusicVideo",
+ DisabledMetadataFetchers = new[] { "The Open Movie Database" },
+ DisabledImageFetchers = new[] { "The Open Movie Database" }
+ },
+ new MetadataOptions
+ {
+ ItemType = "Series",
+ DisabledMetadataFetchers = new[] { "TheMovieDb" },
+ DisabledImageFetchers = new[] { "TheMovieDb" }
+ },
+ new MetadataOptions
+ {
+ ItemType = "MusicAlbum",
+ DisabledMetadataFetchers = new[] { "TheAudioDB" }
+ },
+ new MetadataOptions
+ {
+ ItemType = "MusicArtist",
+ DisabledMetadataFetchers = new[] { "TheAudioDB" }
+ },
+ new MetadataOptions
+ {
+ ItemType = "BoxSet"
+ },
+ new MetadataOptions
+ {
+ ItemType = "Season",
+ DisabledMetadataFetchers = new[] { "TheMovieDb" },
+ },
+ new MetadataOptions
+ {
+ ItemType = "Episode",
+ DisabledMetadataFetchers = new[] { "The Open Movie Database", "TheMovieDb" },
+ DisabledImageFetchers = new[] { "The Open Movie Database", "TheMovieDb" }
+ }
+ };
+ }
/// <summary>
/// Gets or sets a value indicating whether to enable automatic port forwarding.
/// </summary>
- public bool EnableUPnP { get; set; }
+ public bool EnableUPnP { get; set; } = false;
/// <summary>
/// Gets or sets a value indicating whether to enable prometheus metrics exporting.
/// </summary>
- public bool EnableMetrics { get; set; }
+ public bool EnableMetrics { get; set; } = false;
/// <summary>
/// Gets or sets the public mapped port.
/// </summary>
/// <value>The public mapped port.</value>
- public int PublicPort { get; set; }
+ public int PublicPort { get; set; } = DefaultHttpPort;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding.
+ /// </summary>
+ public bool UPnPCreateHttpPortMap { get; set; } = false;
+
+ /// <summary>
+ /// Gets or sets client udp port range.
+ /// </summary>
+ public string UDPPortRange { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether IPV6 capability is enabled.
+ /// </summary>
+ public bool EnableIPV6 { get; set; } = false;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether IPV4 capability is enabled.
+ /// </summary>
+ public bool EnableIPV4 { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether detailed ssdp logs are sent to the console/log.
+ /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to work.
+ /// </summary>
+ public bool EnableSSDPTracing { get; set; } = false;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether an IP address is to be used to filter the detailed ssdp logs that are being sent to the console/log.
+ /// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work.
+ /// </summary>
+ public string SSDPTracingFilter { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the number of times SSDP UDP messages are sent.
+ /// </summary>
+ public int UDPSendCount { get; set; } = 2;
+
+ /// <summary>
+ /// Gets or sets the delay between each groups of SSDP messages (in ms).
+ /// </summary>
+ public int UDPSendDelay { get; set; } = 100;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether address names that match <see cref="VirtualInterfaceNames"/> should be Ignore for the purposes of binding.
+ /// </summary>
+ public bool IgnoreVirtualInterfaces { get; set; } = true;
+
+ /// <summary>
+ /// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. <seealso cref="IgnoreVirtualInterfaces"/>.
+ /// </summary>
+ public string VirtualInterfaceNames { get; set; } = "vEthernet*";
+
+ /// <summary>
+ /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor.
+ /// </summary>
+ public int GatewayMonitorPeriod { get; set; } = 60;
+
+ /// <summary>
+ /// Gets a value indicating whether multi-socket binding is available.
+ /// </summary>
+ public bool EnableMultiSocketBinding { get; } = true;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether all IPv6 interfaces should be treated as on the internal network.
+ /// Depending on the address range implemented ULA ranges might not be used.
+ /// </summary>
+ public bool TrustAllIP6Interfaces { get; set; } = false;
+
+ /// <summary>
+ /// Gets or sets the ports that HDHomerun uses.
+ /// </summary>
+ public string HDHomerunPortRange { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets PublishedServerUri to advertise for specific subnets.
+ /// </summary>
+ public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Gets or sets a value indicating whether Autodiscovery tracing is enabled.
+ /// </summary>
+ public bool AutoDiscoveryTracing { get; set; } = false;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether Autodiscovery is enabled.
+ /// </summary>
+ public bool AutoDiscovery { get; set; } = true;
/// <summary>
/// Gets or sets the public HTTPS port.
/// </summary>
/// <value>The public HTTPS port.</value>
- public int PublicHttpsPort { get; set; }
+ public int PublicHttpsPort { get; set; } = DefaultHttpsPort;
/// <summary>
/// Gets or sets the HTTP server port number.
/// </summary>
/// <value>The HTTP server port number.</value>
- public int HttpServerPortNumber { get; set; }
+ public int HttpServerPortNumber { get; set; } = DefaultHttpPort;
/// <summary>
/// Gets or sets the HTTPS server port number.
/// </summary>
/// <value>The HTTPS server port number.</value>
- public int HttpsPortNumber { get; set; }
+ public int HttpsPortNumber { get; set; } = DefaultHttpsPort;
/// <summary>
/// Gets or sets a value indicating whether to use HTTPS.
@@ -58,19 +201,19 @@ namespace MediaBrowser.Model.Configuration
/// In order for HTTPS to be used, in addition to setting this to true, valid values must also be
/// provided for <see cref="CertificatePath"/> and <see cref="CertificatePassword"/>.
/// </remarks>
- public bool EnableHttps { get; set; }
+ public bool EnableHttps { get; set; } = false;
- public bool EnableNormalizedItemByNameIds { get; set; }
+ public bool EnableNormalizedItemByNameIds { get; set; } = true;
/// <summary>
/// Gets or sets the filesystem path of an X.509 certificate to use for SSL.
/// </summary>
- public string CertificatePath { get; set; }
+ public string CertificatePath { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the password required to access the X.509 certificate data in the file specified by <see cref="CertificatePath"/>.
/// </summary>
- public string CertificatePassword { get; set; }
+ public string CertificatePassword { get; set; } = string.Empty;
/// <summary>
/// Gets or sets a value indicating whether this instance is port authorized.
@@ -79,90 +222,93 @@ namespace MediaBrowser.Model.Configuration
public bool IsPortAuthorized { get; set; }
/// <summary>
- /// Gets or sets if quick connect is available for use on this server.
+ /// Gets or sets a value indicating whether quick connect is available for use on this server.
/// </summary>
- public bool QuickConnectAvailable { get; set; }
-
- public bool EnableRemoteAccess { get; set; }
+ public bool QuickConnectAvailable { get; set; } = false;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether access outside of the LAN is permitted.
+ /// </summary>
+ public bool EnableRemoteAccess { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether [enable case sensitive item ids].
/// </summary>
/// <value><c>true</c> if [enable case sensitive item ids]; otherwise, <c>false</c>.</value>
- public bool EnableCaseSensitiveItemIds { get; set; }
+ public bool EnableCaseSensitiveItemIds { get; set; } = true;
- public bool DisableLiveTvChannelUserDataName { get; set; }
+ public bool DisableLiveTvChannelUserDataName { get; set; } = true;
/// <summary>
/// Gets or sets the metadata path.
/// </summary>
/// <value>The metadata path.</value>
- public string MetadataPath { get; set; }
+ public string MetadataPath { get; set; } = string.Empty;
- public string MetadataNetworkPath { get; set; }
+ public string MetadataNetworkPath { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the preferred metadata language.
/// </summary>
/// <value>The preferred metadata language.</value>
- public string PreferredMetadataLanguage { get; set; }
+ public string PreferredMetadataLanguage { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the metadata country code.
/// </summary>
/// <value>The metadata country code.</value>
- public string MetadataCountryCode { get; set; }
+ public string MetadataCountryCode { get; set; } = "US";
/// <summary>
- /// Characters to be replaced with a ' ' in strings to create a sort name.
+ /// Gets or sets characters to be replaced with a ' ' in strings to create a sort name.
/// </summary>
/// <value>The sort replace characters.</value>
- public string[] SortReplaceCharacters { get; set; }
+ public string[] SortReplaceCharacters { get; set; } = new[] { ".", "+", "%" };
/// <summary>
- /// Characters to be removed from strings to create a sort name.
+ /// Gets or sets characters to be removed from strings to create a sort name.
/// </summary>
/// <value>The sort remove characters.</value>
- public string[] SortRemoveCharacters { get; set; }
+ public string[] SortRemoveCharacters { get; set; } = new[] { ",", "&", "-", "{", "}", "'" };
/// <summary>
- /// Words to be removed from strings to create a sort name.
+ /// Gets or sets words to be removed from strings to create a sort name.
/// </summary>
/// <value>The sort remove words.</value>
- public string[] SortRemoveWords { get; set; }
+ public string[] SortRemoveWords { get; set; } = new[] { "the", "a", "an" };
/// <summary>
/// Gets or sets the minimum percentage of an item that must be played in order for playstate to be updated.
/// </summary>
/// <value>The min resume PCT.</value>
- public int MinResumePct { get; set; }
+ public int MinResumePct { get; set; } = 5;
/// <summary>
/// Gets or sets the maximum percentage of an item that can be played while still saving playstate. If this percentage is crossed playstate will be reset to the beginning and the item will be marked watched.
/// </summary>
/// <value>The max resume PCT.</value>
- public int MaxResumePct { get; set; }
+ public int MaxResumePct { get; set; } = 90;
/// <summary>
/// Gets or sets the minimum duration that an item must have in order to be eligible for playstate updates..
/// </summary>
/// <value>The min resume duration seconds.</value>
- public int MinResumeDurationSeconds { get; set; }
+ public int MinResumeDurationSeconds { get; set; } = 300;
/// <summary>
- /// The delay in seconds that we will wait after a file system change to try and discover what has been added/removed
+ /// Gets or sets the delay in seconds that we will wait after a file system change to try and discover what has been added/removed
/// Some delay is necessary with some items because their creation is not atomic. It involves the creation of several
/// different directories and files.
/// </summary>
/// <value>The file watcher delay.</value>
- public int LibraryMonitorDelay { get; set; }
+ public int LibraryMonitorDelay { get; set; } = 60;
/// <summary>
/// Gets or sets a value indicating whether [enable dashboard response caching].
/// Allows potential contributors without visual studio to modify production dashboard code and test changes.
/// </summary>
/// <value><c>true</c> if [enable dashboard response caching]; otherwise, <c>false</c>.</value>
- public bool EnableDashboardResponseCaching { get; set; }
+ public bool EnableDashboardResponseCaching { get; set; } = true;
/// <summary>
/// Gets or sets the image saving convention.
@@ -172,9 +318,9 @@ namespace MediaBrowser.Model.Configuration
public MetadataOptions[] MetadataOptions { get; set; }
- public bool SkipDeserializationForBasicTypes { get; set; }
+ public bool SkipDeserializationForBasicTypes { get; set; } = true;
- public string ServerName { get; set; }
+ public string ServerName { get; set; } = string.Empty;
public string BaseUrl
{
@@ -206,194 +352,84 @@ namespace MediaBrowser.Model.Configuration
}
}
- public string UICulture { get; set; }
-
- public bool SaveMetadataHidden { get; set; }
+ public string UICulture { get; set; } = "en-US";
- public NameValuePair[] ContentTypes { get; set; }
+ public bool SaveMetadataHidden { get; set; } = false;
- public int RemoteClientBitrateLimit { get; set; }
+ public NameValuePair[] ContentTypes { get; set; } = Array.Empty<NameValuePair>();
- public bool EnableFolderView { get; set; }
+ public int RemoteClientBitrateLimit { get; set; } = 0;
- public bool EnableGroupingIntoCollections { get; set; }
+ public bool EnableFolderView { get; set; } = false;
- public bool DisplaySpecialsWithinSeasons { get; set; }
+ public bool EnableGroupingIntoCollections { get; set; } = false;
- public string[] LocalNetworkSubnets { get; set; }
+ public bool DisplaySpecialsWithinSeasons { get; set; } = true;
- public string[] LocalNetworkAddresses { get; set; }
+ /// <summary>
+ /// Gets or sets the subnets that are deemed to make up the LAN.
+ /// </summary>
+ public string[] LocalNetworkSubnets { get; set; } = Array.Empty<string>();
- public string[] CodecsUsed { get; set; }
+ /// <summary>
+ /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used.
+ /// </summary>
+ public string[] LocalNetworkAddresses { get; set; } = Array.Empty<string>();
- public List<RepositoryInfo> PluginRepositories { get; set; }
+ public string[] CodecsUsed { get; set; } = Array.Empty<string>();
- public bool IgnoreVirtualInterfaces { get; set; }
+ public List<RepositoryInfo> PluginRepositories { get; set; } = new List<RepositoryInfo>();
- public bool EnableExternalContentInSuggestions { get; set; }
+ public bool EnableExternalContentInSuggestions { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether the server should force connections over HTTPS.
/// </summary>
- public bool RequireHttps { get; set; }
+ public bool RequireHttps { get; set; } = false;
- public bool EnableNewOmdbSupport { get; set; }
+ public bool EnableNewOmdbSupport { get; set; } = true;
- public string[] RemoteIPFilter { get; set; }
+ /// <summary>
+ /// Gets or sets the filter for remote IP connectivity. Used in conjuntion with <seealso cref="IsRemoteIPFilterBlacklist"/>.
+ /// </summary>
+ public string[] RemoteIPFilter { get; set; } = Array.Empty<string>();
- public bool IsRemoteIPFilterBlacklist { get; set; }
+ /// <summary>
+ /// Gets or sets a value indicating whether <seealso cref="RemoteIPFilter"/> contains a blacklist or a whitelist. Default is a whitelist.
+ /// </summary>
+ public bool IsRemoteIPFilterBlacklist { get; set; } = false;
- public int ImageExtractionTimeoutMs { get; set; }
+ public int ImageExtractionTimeoutMs { get; set; } = 0;
- public PathSubstitution[] PathSubstitutions { get; set; }
+ public PathSubstitution[] PathSubstitutions { get; set; } = Array.Empty<PathSubstitution>();
- public bool EnableSimpleArtistDetection { get; set; }
+ public bool EnableSimpleArtistDetection { get; set; } = false;
- public string[] UninstalledPlugins { get; set; }
+ public string[] UninstalledPlugins { get; set; } = Array.Empty<string>();
/// <summary>
/// Gets or sets a value indicating whether slow server responses should be logged as a warning.
/// </summary>
- public bool EnableSlowResponseWarning { get; set; }
+ public bool EnableSlowResponseWarning { get; set; } = true;
/// <summary>
/// Gets or sets the threshold for the slow response time warning in ms.
/// </summary>
- public long SlowResponseThresholdMs { get; set; }
+ public long SlowResponseThresholdMs { get; set; } = 500;
/// <summary>
/// Gets or sets the cors hosts.
/// </summary>
- public string[] CorsHosts { get; set; }
+ public string[] CorsHosts { get; set; } = new[] { "*" };
/// <summary>
/// Gets or sets the known proxies.
/// </summary>
- public string[] KnownProxies { get; set; }
+ public string[] KnownProxies { get; set; } = Array.Empty<string>();
/// <summary>
/// Gets or sets the number of days we should retain activity logs.
/// </summary>
- public int? ActivityLogRetentionDays { get; set; }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ServerConfiguration" /> class.
- /// </summary>
- public ServerConfiguration()
- {
- UninstalledPlugins = Array.Empty<string>();
- RemoteIPFilter = Array.Empty<string>();
- LocalNetworkSubnets = Array.Empty<string>();
- LocalNetworkAddresses = Array.Empty<string>();
- CodecsUsed = Array.Empty<string>();
- PathSubstitutions = Array.Empty<PathSubstitution>();
- IgnoreVirtualInterfaces = false;
- EnableSimpleArtistDetection = false;
- SkipDeserializationForBasicTypes = true;
-
- PluginRepositories = new List<RepositoryInfo>();
-
- DisplaySpecialsWithinSeasons = true;
- EnableExternalContentInSuggestions = true;
-
- ImageSavingConvention = ImageSavingConvention.Compatible;
- PublicPort = DefaultHttpPort;
- PublicHttpsPort = DefaultHttpsPort;
- HttpServerPortNumber = DefaultHttpPort;
- HttpsPortNumber = DefaultHttpsPort;
- EnableMetrics = false;
- EnableHttps = false;
- EnableDashboardResponseCaching = true;
- EnableCaseSensitiveItemIds = true;
- EnableNormalizedItemByNameIds = true;
- DisableLiveTvChannelUserDataName = true;
- EnableNewOmdbSupport = true;
-
- EnableRemoteAccess = true;
- QuickConnectAvailable = false;
-
- EnableUPnP = false;
- MinResumePct = 5;
- MaxResumePct = 90;
-
- // 5 minutes
- MinResumeDurationSeconds = 300;
-
- LibraryMonitorDelay = 60;
-
- ContentTypes = Array.Empty<NameValuePair>();
-
- PreferredMetadataLanguage = "en";
- MetadataCountryCode = "US";
-
- SortReplaceCharacters = new[] { ".", "+", "%" };
- SortRemoveCharacters = new[] { ",", "&", "-", "{", "}", "'" };
- SortRemoveWords = new[] { "the", "a", "an" };
-
- BaseUrl = string.Empty;
- UICulture = "en-US";
-
- MetadataOptions = new[]
- {
- new MetadataOptions()
- {
- ItemType = "Book"
- },
- new MetadataOptions()
- {
- ItemType = "Movie"
- },
- new MetadataOptions
- {
- ItemType = "MusicVideo",
- DisabledMetadataFetchers = new[] { "The Open Movie Database" },
- DisabledImageFetchers = new[] { "The Open Movie Database" }
- },
- new MetadataOptions
- {
- ItemType = "Series",
- DisabledMetadataFetchers = new[] { "TheMovieDb" },
- DisabledImageFetchers = new[] { "TheMovieDb" }
- },
- new MetadataOptions
- {
- ItemType = "MusicAlbum",
- DisabledMetadataFetchers = new[] { "TheAudioDB" }
- },
- new MetadataOptions
- {
- ItemType = "MusicArtist",
- DisabledMetadataFetchers = new[] { "TheAudioDB" }
- },
- new MetadataOptions
- {
- ItemType = "BoxSet"
- },
- new MetadataOptions
- {
- ItemType = "Season",
- DisabledMetadataFetchers = new[] { "TheMovieDb" },
- },
- new MetadataOptions
- {
- ItemType = "Episode",
- DisabledMetadataFetchers = new[] { "The Open Movie Database", "TheMovieDb" },
- DisabledImageFetchers = new[] { "The Open Movie Database", "TheMovieDb" }
- }
- };
-
- EnableSlowResponseWarning = true;
- SlowResponseThresholdMs = 500;
- CorsHosts = new[] { "*" };
- KnownProxies = Array.Empty<string>();
- ActivityLogRetentionDays = 30;
- }
- }
-
- public class PathSubstitution
- {
- public string From { get; set; }
-
- public string To { get; set; }
+ public int? ActivityLogRetentionDays { get; set; } = 30;
}
-}
+} \ No newline at end of file
diff --git a/MediaBrowser.sln b/MediaBrowser.sln
index 25402aee1..cb204137b 100644
--- a/MediaBrowser.sln
+++ b/MediaBrowser.sln
@@ -1,6 +1,6 @@
Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 15
-VisualStudioVersion = 15.0.26730.3
+# Visual Studio Version 16
+VisualStudioVersion = 16.0.30503.244
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server", "Jellyfin.Server\Jellyfin.Server.csproj", "{07E39F42-A2C6-4B32-AF8C-725F957A73FF}"
EndProject
@@ -66,12 +66,20 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Data", "Jellyfin.D
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server.Implementations", "Jellyfin.Server.Implementations\Jellyfin.Server.Implementations.csproj", "{DAE48069-6D86-4BA6-B148-D1D49B6DDA52}"
EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking", "Jellyfin.Networking\Jellyfin.Networking.csproj", "{0A3FCC4D-C714-4072-B90F-E374A15F9FF9}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking.Tests", "tests\Jellyfin.Networking.Tests\NetworkTesting\Jellyfin.Networking.Tests.csproj", "{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.Build.0 = Release|Any CPU
{17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -132,10 +140,6 @@ Global
{960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Any CPU.Build.0 = Debug|Any CPU
{960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Any CPU.ActiveCfg = Release|Any CPU
{960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Any CPU.Build.0 = Release|Any CPU
- {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.Build.0 = Release|Any CPU
{154872D9-6C12-4007-96E3-8F70A58386CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{154872D9-6C12-4007-96E3-8F70A58386CE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{154872D9-6C12-4007-96E3-8F70A58386CE}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -176,10 +180,27 @@ Global
{DAE48069-6D86-4BA6-B148-D1D49B6DDA52}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DAE48069-6D86-4BA6-B148-D1D49B6DDA52}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DAE48069-6D86-4BA6-B148-D1D49B6DDA52}.Release|Any CPU.Build.0 = Release|Any CPU
+ {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Release|Any CPU.Build.0 = Release|Any CPU
+ {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
+ GlobalSection(NestedProjects) = preSolution
+ {DF194677-DFD3-42AF-9F75-D44D5A416478} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {28464062-0939-4AA7-9F7B-24DDDA61A7C0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {3998657B-1CCC-49DD-A19F-275DC8495F57} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {462584F7-5023-4019-9EAC-B98CA458C0A0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
+ EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3448830C-EBDC-426C-85CD-7BBB9651A7FE}
EndGlobalSection
@@ -201,12 +222,4 @@ Global
$0.DotNetNamingPolicy = $2
$2.DirectoryNamespaceAssociation = PrefixedHierarchical
EndGlobalSection
- GlobalSection(NestedProjects) = preSolution
- {DF194677-DFD3-42AF-9F75-D44D5A416478} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
- {28464062-0939-4AA7-9F7B-24DDDA61A7C0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
- {3998657B-1CCC-49DD-A19F-275DC8495F57} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
- {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
- {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
- {462584F7-5023-4019-9EAC-B98CA458C0A0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6}
- EndGlobalSection
EndGlobal
diff --git a/RSSDP/RSSDP.csproj b/RSSDP/RSSDP.csproj
index d0962e82c..c64ee9389 100644
--- a/RSSDP/RSSDP.csproj
+++ b/RSSDP/RSSDP.csproj
@@ -6,6 +6,7 @@
</PropertyGroup>
<ItemGroup>
+ <ProjectReference Include="..\Jellyfin.Networking\Jellyfin.Networking.csproj" />
<ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
</ItemGroup>
diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs
index a4be32e7d..8f1f0fa61 100644
--- a/RSSDP/SsdpCommunicationsServer.cs
+++ b/RSSDP/SsdpCommunicationsServer.cs
@@ -352,7 +352,7 @@ namespace Rssdp.Infrastructure
if (_enableMultiSocketBinding)
{
- foreach (var address in _networkManager.GetLocalIpAddresses())
+ foreach (var address in _networkManager.GetInternalBindAddresses())
{
if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
@@ -362,7 +362,7 @@ namespace Rssdp.Infrastructure
try
{
- sockets.Add(_SocketFactory.CreateSsdpUdpSocket(address, _LocalPort));
+ sockets.Add(_SocketFactory.CreateSsdpUdpSocket(address.Address, _LocalPort));
}
catch (Exception ex)
{
diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs
index 1a8577d8d..3e89d7f60 100644
--- a/RSSDP/SsdpDevicePublisher.cs
+++ b/RSSDP/SsdpDevicePublisher.cs
@@ -300,17 +300,15 @@ namespace Rssdp.Infrastructure
foreach (var device in deviceList)
{
- if (!_sendOnlyMatchedHost ||
- _networkManager.IsInSameSubnet(device.ToRootDevice().Address, remoteEndPoint.Address, device.ToRootDevice().SubnetMask))
+ var root = device.ToRootDevice();
+ var source = new IPNetAddress(root.Address, root.PrefixLength);
+ var destination = new IPNetAddress(remoteEndPoint.Address, root.PrefixLength);
+ if (!_sendOnlyMatchedHost || source.NetworkAddress.Equals(destination.NetworkAddress))
{
SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIpAddress, cancellationToken);
}
}
}
- else
- {
- // WriteTrace(String.Format("Sending 0 search responses."));
- }
});
}
diff --git a/RSSDP/SsdpRootDevice.cs b/RSSDP/SsdpRootDevice.cs
index 8937ec331..d5abe4a4c 100644
--- a/RSSDP/SsdpRootDevice.cs
+++ b/RSSDP/SsdpRootDevice.cs
@@ -45,9 +45,9 @@ namespace Rssdp
public IPAddress Address { get; set; }
/// <summary>
- /// Gets or sets the SubnetMask used to check if the received message from same interface with this device/tree. Required.
+ /// Gets or sets the prefix length used to check if the received message from same interface with this device/tree. Required.
/// </summary>
- public IPAddress SubnetMask { get; set; }
+ public byte PrefixLength { get; set; }
/// <summary>
/// The base URL to use for all relative url's provided in other propertise (and those of child devices). Optional.
diff --git a/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs b/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs
index bd3d35687..54f8eb225 100644
--- a/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs
+++ b/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs
@@ -3,8 +3,6 @@ using System.Collections.Concurrent;
using System.IO;
using Emby.Server.Implementations;
using Emby.Server.Implementations.IO;
-using Emby.Server.Implementations.Networking;
-using Jellyfin.Drawing.Skia;
using Jellyfin.Server;
using MediaBrowser.Common;
using Microsoft.AspNetCore.Hosting;
@@ -80,7 +78,6 @@ namespace Jellyfin.Api.Tests
loggerFactory,
commandLineOpts,
new ManagedFileSystem(loggerFactory.CreateLogger<ManagedFileSystem>(), appPaths),
- new NetworkManager(loggerFactory.CreateLogger<NetworkManager>()),
serviceCollection);
_disposableComponents.Add(appHost);
appHost.Init();
diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj
new file mode 100644
index 000000000..703d43210
--- /dev/null
+++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj
@@ -0,0 +1,39 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
+ <PropertyGroup>
+ <ProjectGuid>{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}</ProjectGuid>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <TargetFramework>net5.0</TargetFramework>
+ <IsPackable>false</IsPackable>
+ <Nullable>enable</Nullable>
+ <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" />
+ <PackageReference Include="xunit" Version="2.4.1" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" />
+ <PackageReference Include="coverlet.collector" Version="1.3.0" />
+ <PackageReference Include="Moq" Version="4.14.5" />
+ </ItemGroup>
+
+ <!-- Code Analyzers-->
+ <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8" PrivateAssets="All" />
+ <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
+ <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\..\..\Emby.Server.Implementations\Emby.Server.Implementations.csproj" />
+ <ProjectReference Include="..\..\..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
+ </ItemGroup>
+ <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <CodeAnalysisRuleSet>../../jellyfin-tests.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
+ <DefineConstants>DEBUG</DefineConstants>
+ </PropertyGroup>
+</Project>
diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs
new file mode 100644
index 000000000..03b733a9a
--- /dev/null
+++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs
@@ -0,0 +1,485 @@
+using System;
+using System.Net;
+using Emby.Dlna.PlayTo;
+using Jellyfin.Networking.Configuration;
+using Jellyfin.Networking.Manager;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Net;
+using Moq;
+using Microsoft.Extensions.Logging.Abstractions;
+using Xunit;
+using NetCollection = System.Collections.ObjectModel.Collection<MediaBrowser.Common.Net.IPObject>;
+using XMLProperties = System.Collections.Generic.Dictionary<string, string>;
+
+namespace NetworkTesting
+{
+ public class NetTesting
+ {
+ /// <summary>
+ /// Trys to identify the string and return an object of that class.
+ /// </summary>
+ /// <param name="addr">String to parse.</param>
+ /// <param name="result">IPObject to return.</param>
+ /// <returns>True if the value parsed successfully.</returns>
+ private static bool TryParse(string addr, out IPObject result)
+ {
+ if (!string.IsNullOrEmpty(addr))
+ {
+ // Is it an IP address
+ if (IPNetAddress.TryParse(addr, out IPNetAddress nw))
+ {
+ result = nw;
+ return true;
+ }
+
+ if (IPHost.TryParse(addr, out IPHost h))
+ {
+ result = h;
+ return true;
+ }
+ }
+
+ result = IPNetAddress.None;
+ return false;
+ }
+
+ private static IConfigurationManager GetMockConfig(NetworkConfiguration conf)
+ {
+ var configManager = new Mock<IConfigurationManager>
+ {
+ CallBase = true
+ };
+ configManager.Setup(x => x.GetConfiguration(It.IsAny<string>())).Returns(conf);
+ return (IConfigurationManager)configManager.Object;
+ }
+
+ [Theory]
+ [InlineData("192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.0/24", "[192.168.1.208/24,200.200.200.200/24]")]
+ [InlineData("192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")]
+ [InlineData("192.168.1.208/24,-16,vEthernet1:192.168.1.208/24,-16,vEthernet212;200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")]
+ public void IgnoreVirtualInterfaces(string interfaces, string lan, string value)
+ {
+ var conf = new NetworkConfiguration()
+ {
+ EnableIPV6 = true,
+ EnableIPV4 = true,
+ LocalNetworkSubnets = lan?.Split(';') ?? throw new ArgumentNullException(nameof(lan))
+ };
+
+ NetworkManager.MockNetworkSettings = interfaces;
+ using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
+ NetworkManager.MockNetworkSettings = string.Empty;
+
+ Assert.True(string.Equals(nm.GetInternalBindAddresses().AsString(), value, StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData("192.168.10.0/24, !192.168.10.60/32", "192.168.10.60")]
+ public void TextIsInNetwork(string network, string value)
+ {
+ if (network == null)
+ {
+ throw new ArgumentNullException(nameof(network));
+ }
+
+ var conf = new NetworkConfiguration()
+ {
+ EnableIPV6 = true,
+ EnableIPV4 = true,
+ LocalNetworkSubnets = network.Split(',')
+ };
+
+ using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
+
+ Assert.True(!nm.IsInLocalNetwork(value));
+ }
+
+ [Theory]
+ [InlineData("127.0.0.1")]
+ [InlineData("127.0.0.1:123")]
+ [InlineData("localhost")]
+ [InlineData("localhost:1345")]
+ [InlineData("www.google.co.uk")]
+ [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517")]
+ [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517/56")]
+ [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517]:124")]
+ [InlineData("fe80::7add:12ff:febb:c67b%16")]
+ [InlineData("[fe80::7add:12ff:febb:c67b%16]:123")]
+ [InlineData("192.168.1.2/255.255.255.0")]
+ [InlineData("192.168.1.2/24")]
+
+ public void TestCollectionCreation(string address)
+ {
+ Assert.True(TryParse(address, out _));
+ }
+
+ [Theory]
+ [InlineData("256.128.0.0.0.1")]
+ [InlineData("127.0.0.1#")]
+ [InlineData("localhost!")]
+ [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517:1231")]
+ public void TestInvalidCollectionCreation(string address)
+ {
+ Assert.False(TryParse(address, out _));
+ }
+
+ [Theory]
+ // Src, IncIP6, incIP4, exIP6, ecIP4, net
+ [InlineData("127.0.0.1#",
+ "[]",
+ "[]",
+ "[]",
+ "[]",
+ "[]")]
+ [InlineData("[127.0.0.1]",
+ "[]",
+ "[]",
+ "[127.0.0.1/32]",
+ "[127.0.0.1/32]",
+ "[]")]
+ [InlineData("",
+ "[]",
+ "[]",
+ "[]",
+ "[]",
+ "[]")]
+ [InlineData("192.158.1.2/255.255.0.0,192.169.1.2/8",
+ "[192.158.1.2/16,192.169.1.2/8]",
+ "[192.158.1.2/16,192.169.1.2/8]",
+ "[]",
+ "[]",
+ "[192.158.0.0/16,192.0.0.0/8]")]
+ [InlineData("192.158.1.2/16, localhost, fd23:184f:2029:0:3139:7386:67d7:d517, [10.10.10.10]",
+ "[192.158.1.2/16,127.0.0.1/32,fd23:184f:2029:0:3139:7386:67d7:d517/128]",
+ "[192.158.1.2/16,127.0.0.1/32]",
+ "[10.10.10.10/32]",
+ "[10.10.10.10/32]",
+ "[192.158.0.0/16,127.0.0.1/32,fd23:184f:2029:0:3139:7386:67d7:d517/128]")]
+ public void TestCollections(string settings, string result1, string result2, string result3, string result4, string result5)
+ {
+ if (settings == null)
+ {
+ throw new ArgumentNullException(nameof(settings));
+ }
+
+ var conf = new NetworkConfiguration()
+ {
+ EnableIPV6 = true,
+ EnableIPV4 = true,
+ };
+
+ using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
+
+ // Test included, IP6.
+ NetCollection nc = nm.CreateIPCollection(settings.Split(","), false);
+ Assert.True(string.Equals(nc?.AsString(), result1, System.StringComparison.OrdinalIgnoreCase));
+
+ // Text excluded, non IP6.
+ nc = nm.CreateIPCollection(settings.Split(","), true);
+ Assert.True(string.Equals(nc?.AsString(), result3, System.StringComparison.OrdinalIgnoreCase));
+
+ conf.EnableIPV6 = false;
+ nm.UpdateSettings(conf);
+
+ // Test included, non IP6.
+ nc = nm.CreateIPCollection(settings.Split(","), false);
+ Assert.True(string.Equals(nc?.AsString(), result2, System.StringComparison.OrdinalIgnoreCase));
+
+ // Test excluded, including IPv6.
+ nc = nm.CreateIPCollection(settings.Split(","), true);
+ Assert.True(string.Equals(nc?.AsString(), result4, System.StringComparison.OrdinalIgnoreCase));
+
+ conf.EnableIPV6 = true;
+ nm.UpdateSettings(conf);
+
+ // Test network addresses of collection.
+ nc = nm.CreateIPCollection(settings.Split(","), false);
+ nc = nc.AsNetworks();
+ Assert.True(string.Equals(nc?.AsString(), result5, System.StringComparison.OrdinalIgnoreCase));
+ }
+
+ [Theory]
+ [InlineData("127.0.0.1", "fd23:184f:2029:0:3139:7386:67d7:d517/64,fd23:184f:2029:0:c0f0:8a8a:7605:fffa/128,fe80::3139:7386:67d7:d517%16/64,192.168.1.208/24,::1/128,127.0.0.1/8", "[127.0.0.1/32]")]
+ [InlineData("127.0.0.1", "127.0.0.1/8", "[127.0.0.1/32]")]
+ public void UnionCheck(string settings, string compare, string result)
+ {
+ if (settings == null)
+ {
+ throw new ArgumentNullException(nameof(settings));
+ }
+
+ if (compare == null)
+ {
+ throw new ArgumentNullException(nameof(compare));
+ }
+
+ if (result == null)
+ {
+ throw new ArgumentNullException(nameof(result));
+ }
+
+
+ var conf = new NetworkConfiguration()
+ {
+ EnableIPV6 = true,
+ EnableIPV4 = true,
+ };
+
+ using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
+
+ NetCollection nc1 = nm.CreateIPCollection(settings.Split(","), false);
+ NetCollection nc2 = nm.CreateIPCollection(compare.Split(","), false);
+
+ Assert.True(nc1.Union(nc2).AsString() == result);
+ }
+
+ [Theory]
+ [InlineData("192.168.5.85/24", "192.168.5.1")]
+ [InlineData("192.168.5.85/24", "192.168.5.254")]
+ [InlineData("10.128.240.50/30", "10.128.240.48")]
+ [InlineData("10.128.240.50/30", "10.128.240.49")]
+ [InlineData("10.128.240.50/30", "10.128.240.50")]
+ [InlineData("10.128.240.50/30", "10.128.240.51")]
+ [InlineData("127.0.0.1/8", "127.0.0.1")]
+ public void IpV4SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress)
+ {
+ var ipAddressObj = IPNetAddress.Parse(netMask);
+ Assert.True(ipAddressObj.Contains(IPAddress.Parse(ipAddress)));
+ }
+
+ [Theory]
+ [InlineData("192.168.5.85/24", "192.168.4.254")]
+ [InlineData("192.168.5.85/24", "191.168.5.254")]
+ [InlineData("10.128.240.50/30", "10.128.240.47")]
+ [InlineData("10.128.240.50/30", "10.128.240.52")]
+ [InlineData("10.128.240.50/30", "10.128.239.50")]
+ [InlineData("10.128.240.50/30", "10.127.240.51")]
+ public void IpV4SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress)
+ {
+ var ipAddressObj = IPNetAddress.Parse(netMask);
+ Assert.False(ipAddressObj.Contains(IPAddress.Parse(ipAddress)));
+ }
+
+ [Theory]
+ [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")]
+ [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:FFFF:FFFF:FFFF:FFFF")]
+ [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:0001:0000:0000:0000")]
+ [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:FFFF:FFFF:FFFF:FFF0")]
+ [InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")]
+ public void IpV6SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress)
+ {
+ var ipAddressObj = IPNetAddress.Parse(netMask);
+ Assert.True(ipAddressObj.Contains(IPAddress.Parse(ipAddress)));
+ }
+
+ [Theory]
+ [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0011:FFFF:FFFF:FFFF:FFFF")]
+ [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0013:0000:0000:0000:0000")]
+ [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0013:0001:0000:0000:0000")]
+ [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0011:FFFF:FFFF:FFFF:FFF0")]
+ [InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0001")]
+ public void IpV6SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress)
+ {
+ var ipAddressObj = IPNetAddress.Parse(netMask);
+ Assert.False(ipAddressObj.Contains(IPAddress.Parse(ipAddress)));
+ }
+
+ [Theory]
+ [InlineData("10.0.0.0/255.0.0.0", "10.10.10.1/32")]
+ [InlineData("10.0.0.0/8", "10.10.10.1/32")]
+ [InlineData("10.0.0.0/255.0.0.0", "10.10.10.1")]
+
+ [InlineData("10.10.0.0/255.255.0.0", "10.10.10.1/32")]
+ [InlineData("10.10.0.0/16", "10.10.10.1/32")]
+ [InlineData("10.10.0.0/255.255.0.0", "10.10.10.1")]
+
+ [InlineData("10.10.10.0/255.255.255.0", "10.10.10.1/32")]
+ [InlineData("10.10.10.0/24", "10.10.10.1/32")]
+ [InlineData("10.10.10.0/255.255.255.0", "10.10.10.1")]
+
+ public void TestSubnets(string network, string ip)
+ {
+ Assert.True(TryParse(network, out IPObject? networkObj));
+ Assert.True(TryParse(ip, out IPObject? ipObj));
+ Assert.True(networkObj.Contains(ipObj));
+ }
+
+ [Theory]
+ [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "172.168.1.2/24", "172.168.1.2/24")]
+ [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "172.168.1.2/24, 10.10.10.1", "172.168.1.2/24,10.10.10.1/24")]
+ [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "192.168.1.2/255.255.255.0, 10.10.10.1", "192.168.1.2/24,10.10.10.1/24")]
+ [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "192.168.1.2/24, 100.10.10.1", "192.168.1.2/24")]
+ [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "194.168.1.2/24, 100.10.10.1", "")]
+
+ public void TestMatches(string source, string dest, string result)
+ {
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+
+ if (dest == null)
+ {
+ throw new ArgumentNullException(nameof(dest));
+ }
+
+ if (result == null)
+ {
+ throw new ArgumentNullException(nameof(result));
+ }
+
+ var conf = new NetworkConfiguration()
+ {
+ EnableIPV6 = true,
+ EnableIPV4 = true
+ };
+
+ using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
+
+ // Test included, IP6.
+ NetCollection ncSource = nm.CreateIPCollection(source.Split(","));
+ NetCollection ncDest = nm.CreateIPCollection(dest.Split(","));
+ NetCollection ncResult = ncSource.Union(ncDest);
+ NetCollection resultCollection = nm.CreateIPCollection(result.Split(","));
+ Assert.True(ncResult.Compare(resultCollection));
+ }
+
+
+ [Theory]
+ [InlineData("10.1.1.1/32", "10.1.1.1")]
+ [InlineData("192.168.1.254/32", "192.168.1.254/255.255.255.255")]
+
+ public void TestEquals(string source, string dest)
+ {
+ Assert.True(IPNetAddress.Parse(source).Equals(IPNetAddress.Parse(dest)));
+ Assert.True(IPNetAddress.Parse(dest).Equals(IPNetAddress.Parse(source)));
+ }
+
+ [Theory]
+
+ // Testing bind interfaces. These are set for my system so won't work elsewhere.
+ // On my system eth16 is internal, eth11 external (Windows defines the indexes).
+ //
+ // This test is to replicate how DNLA requests work throughout the system.
+
+ // User on internal network, we're bound internal and external - so result is internal.
+ [InlineData("192.168.1.1", "eth16,eth11", false, "eth16")]
+ // User on external network, we're bound internal and external - so result is external.
+ [InlineData("8.8.8.8", "eth16,eth11", false, "eth11")]
+ // User on internal network, we're bound internal only - so result is internal.
+ [InlineData("10.10.10.10", "eth16", false, "eth16")]
+ // User on internal network, no binding specified - so result is the 1st internal.
+ [InlineData("192.168.1.1", "", false, "eth16")]
+ // User on external network, internal binding only - so result is the 1st internal.
+ [InlineData("jellyfin.org", "eth16", false, "eth16")]
+ // User on external network, no binding - so result is the 1st external.
+ [InlineData("jellyfin.org", "", false, "eth11")]
+ // User assumed to be internal, no binding - so result is the 1st internal.
+ [InlineData("", "", false, "eth16")]
+ public void TestBindInterfaces(string source, string bindAddresses, bool ipv6enabled, string result)
+ {
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+
+ if (bindAddresses == null)
+ {
+ throw new ArgumentNullException(nameof(bindAddresses));
+ }
+
+ if (result == null)
+ {
+ throw new ArgumentNullException(nameof(result));
+ }
+
+ var conf = new NetworkConfiguration()
+ {
+ LocalNetworkAddresses = bindAddresses.Split(','),
+ EnableIPV6 = ipv6enabled,
+ EnableIPV4 = true
+ };
+
+ NetworkManager.MockNetworkSettings = "192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11";
+ using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
+ NetworkManager.MockNetworkSettings = string.Empty;
+
+ _ = nm.TryParseInterface(result, out NetCollection? resultObj);
+
+ if (resultObj != null)
+ {
+ result = ((IPNetAddress)resultObj[0]).ToString(true);
+ var intf = nm.GetBindInterface(source, out int? _);
+
+ Assert.True(string.Equals(intf, result, System.StringComparison.OrdinalIgnoreCase));
+ }
+ }
+
+ [Theory]
+
+ // Testing bind interfaces. These are set for my system so won't work elsewhere.
+ // On my system eth16 is internal, eth11 external (Windows defines the indexes).
+ //
+ // This test is to replicate how subnet bound ServerPublisherUri work throughout the system.
+
+ // User on internal network, we're bound internal and external - so result is internal override.
+ [InlineData("192.168.1.1", "192.168.1.0/24", "eth16,eth11", false, "192.168.1.0/24=internal.jellyfin", "internal.jellyfin")]
+
+ // User on external network, we're bound internal and external - so result is override.
+ [InlineData("8.8.8.8", "192.168.1.0/24", "eth16,eth11", false, "0.0.0.0=http://helloworld.com", "http://helloworld.com")]
+
+ // User on internal network, we're bound internal only, but the address isn't in the LAN - so return the override.
+ [InlineData("10.10.10.10", "192.168.1.0/24", "eth16", false, "0.0.0.0=http://internalButNotDefinedAsLan.com", "http://internalButNotDefinedAsLan.com")]
+
+ // User on internal network, no binding specified - so result is the 1st internal.
+ [InlineData("192.168.1.1", "192.168.1.0/24", "", false, "0.0.0.0=http://helloworld.com", "eth16")]
+
+ // User on external network, internal binding only - so asumption is a proxy forward, return external override.
+ [InlineData("jellyfin.org", "192.168.1.0/24", "eth16", false, "0.0.0.0=http://helloworld.com", "http://helloworld.com")]
+
+ // User on external network, no binding - so result is the 1st external which is overriden.
+ [InlineData("jellyfin.org", "192.168.1.0/24", "", false, "0.0.0.0 = http://helloworld.com", "http://helloworld.com")]
+
+ // User assumed to be internal, no binding - so result is the 1st internal.
+ [InlineData("", "192.168.1.0/24", "", false, "0.0.0.0=http://helloworld.com", "eth16")]
+
+ // User is internal, no binding - so result is the 1st internal, which is then overridden.
+ [InlineData("192.168.1.1", "192.168.1.0/24", "", false, "eth16=http://helloworld.com", "http://helloworld.com")]
+
+ public void TestBindInterfaceOverrides(string source, string lan, string bindAddresses, bool ipv6enabled, string publishedServers, string result)
+ {
+ if (lan == null)
+ {
+ throw new ArgumentNullException(nameof(lan));
+ }
+
+ if (bindAddresses == null)
+ {
+ throw new ArgumentNullException(nameof(bindAddresses));
+ }
+
+ var conf = new NetworkConfiguration()
+ {
+ LocalNetworkSubnets = lan.Split(','),
+ LocalNetworkAddresses = bindAddresses.Split(','),
+ EnableIPV6 = ipv6enabled,
+ EnableIPV4 = true,
+ PublishedServerUriBySubnet = new string[] { publishedServers }
+ };
+
+ NetworkManager.MockNetworkSettings = "192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11";
+ using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
+ NetworkManager.MockNetworkSettings = string.Empty;
+
+ if (nm.TryParseInterface(result, out NetCollection? resultObj) && resultObj != null)
+ {
+ // Parse out IPAddresses so we can do a string comparison. (Ignore subnet masks).
+ result = ((IPNetAddress)resultObj[0]).ToString(true);
+ }
+
+ var intf = nm.GetBindInterface(source, out int? _);
+
+ Assert.True(string.Equals(intf, result, System.StringComparison.OrdinalIgnoreCase));
+ }
+ }
+}