From 24d99bdc3e45ea1b94c9d6285de5784ec6565e93 Mon Sep 17 00:00:00 2001 From: h1dden-da3m0n <33120068+h1dden-da3m0n@users.noreply.github.com> Date: Sun, 20 Jun 2021 19:21:14 +0200 Subject: [PATCH 001/358] add auto-bump_version workflow --- .github/workflows/auto-bump_version.yml | 96 +++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 .github/workflows/auto-bump_version.yml diff --git a/.github/workflows/auto-bump_version.yml b/.github/workflows/auto-bump_version.yml new file mode 100644 index 0000000000..67f2e60643 --- /dev/null +++ b/.github/workflows/auto-bump_version.yml @@ -0,0 +1,96 @@ +name: Auto bump_version + +on: + release: + types: + - published + workflow_dispatch: + inputs: + TAG_BRANCH: + required: true + description: release-x.y.z + NEXT_VERSION: + required: true + description: x.y.z + +jobs: + auto_bump_version: + runs-on: ubuntu-latest + if: ${{ github.event_name == 'release' && !contains(github.event.release.tag_name, 'rc') }} + env: + TAG_BRANCH: ${{ github.event.release.target_commitish }} + steps: + - name: Wait for deploy checks to finish + uses: jitterbit/await-check-suites@v1 + with: + ref: ${{ env.TAG_BRANCH }} + intervalSeconds: 60 + timeoutSeconds: 3600 + + - name: Setup YQ + uses: chrisdickinson/setup-yq@latest + with: + yq-version: v4.9.6 + + - name: Checkout Repository + uses: actions/checkout@v2 + with: + ref: ${{ env.TAG_BRANCH }} + + - name: Setup EnvVars + run: |- + CURRENT_VERSION=$(yq e '.version' build.yaml) + CURRENT_MAJOR_MINOR=${CURRENT_VERSION%.*} + CURRENT_PATCH=${CURRENT_VERSION##*.} + echo "CURRENT_VERSION=${CURRENT_VERSION}" >> $GITHUB_ENV + echo "CURRENT_MAJOR_MINOR=${CURRENT_MAJOR_MINOR}" >> $GITHUB_ENV + echo "CURRENT_PATCH=${CURRENT_PATCH}" >> $GITHUB_ENV + echo "NEXT_VERSION=${CURRENT_MAJOR_MINOR}.$(($CURRENT_PATCH + 1))" >> $GITHUB_ENV + + - name: Run bump_version + run: ./bump_version ${{ env.NEXT_VERSION }} + + - name: Commit Changes + run: |- + git config user.name "jellyfin-bot" + git config user.email "team@jellyfin.org" + git checkout ${{ env.TAG_BRANCH }} + git commit -am "Bump version to ${{ env.NEXT_VERSION }}" + git push origin ${{ env.TAG_BRANCH }} + + manual_bump_version: + runs-on: ubuntu-latest + if: ${{ github.event_name == 'workflow_dispatch' }} + env: + TAG_BRANCH: ${{ github.event.inputs.TAG_BRANCH }} + steps: + - name: Setup YQ + uses: chrisdickinson/setup-yq@latest + with: + yq-version: v4.9.6 + + - name: Checkout Repository + uses: actions/checkout@v2 + with: + ref: ${{ env.TAG_BRANCH }} + + - name: Setup EnvVars + run: |- + CURRENT_VERSION=$(yq e '.version' build.yaml) + CURRENT_MAJOR_MINOR=${CURRENT_VERSION%.*} + CURRENT_PATCH=${CURRENT_VERSION##*.} + echo "CURRENT_VERSION=${CURRENT_VERSION}" >> $GITHUB_ENV + echo "CURRENT_MAJOR_MINOR=${CURRENT_MAJOR_MINOR}" >> $GITHUB_ENV + echo "CURRENT_PATCH=${CURRENT_PATCH}" >> $GITHUB_ENV + echo "NEXT_VERSION=${{ github.event.inputs.NEXT_VERSION }}" >> $GITHUB_ENV + + - name: Run bump_version + run: ./bump_version ${{ env.NEXT_VERSION }} + + - name: Commit Changes + run: |- + git config user.name "jellyfin-bot" + git config user.email "team@jellyfin.org" + git checkout ${{ env.TAG_BRANCH }} + git commit -am "Bump version to ${{ env.NEXT_VERSION }}" + git push origin ${{ env.TAG_BRANCH }} From 9923ea6151282df1204089289d59a158b6eaaf67 Mon Sep 17 00:00:00 2001 From: h1dden-da3m0n <33120068+h1dden-da3m0n@users.noreply.github.com> Date: Sun, 27 Jun 2021 13:20:54 +0200 Subject: [PATCH 002/358] change to address review feedback --- .github/workflows/auto-bump_version.yml | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/.github/workflows/auto-bump_version.yml b/.github/workflows/auto-bump_version.yml index 67f2e60643..dc0adb96b0 100644 --- a/.github/workflows/auto-bump_version.yml +++ b/.github/workflows/auto-bump_version.yml @@ -63,27 +63,13 @@ jobs: if: ${{ github.event_name == 'workflow_dispatch' }} env: TAG_BRANCH: ${{ github.event.inputs.TAG_BRANCH }} + NEXT_VERSION: ${{ github.event.inputs.NEXT_VERSION }} steps: - - name: Setup YQ - uses: chrisdickinson/setup-yq@latest - with: - yq-version: v4.9.6 - - name: Checkout Repository uses: actions/checkout@v2 with: ref: ${{ env.TAG_BRANCH }} - - name: Setup EnvVars - run: |- - CURRENT_VERSION=$(yq e '.version' build.yaml) - CURRENT_MAJOR_MINOR=${CURRENT_VERSION%.*} - CURRENT_PATCH=${CURRENT_VERSION##*.} - echo "CURRENT_VERSION=${CURRENT_VERSION}" >> $GITHUB_ENV - echo "CURRENT_MAJOR_MINOR=${CURRENT_MAJOR_MINOR}" >> $GITHUB_ENV - echo "CURRENT_PATCH=${CURRENT_PATCH}" >> $GITHUB_ENV - echo "NEXT_VERSION=${{ github.event.inputs.NEXT_VERSION }}" >> $GITHUB_ENV - - name: Run bump_version run: ./bump_version ${{ env.NEXT_VERSION }} From 25fc8a1c934706d1a0cf8c424f379e6e708a3283 Mon Sep 17 00:00:00 2001 From: h1dden-da3m0n <33120068+h1dden-da3m0n@users.noreply.github.com> Date: Sun, 12 Sep 2021 21:52:14 +0200 Subject: [PATCH 003/358] ci: unify name to web equivalent workflow see jellyfin/jellyfin-web#2897 for reference --- .../{auto-bump_version.yml => repo-bump-version.yaml} | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename .github/workflows/{auto-bump_version.yml => repo-bump-version.yaml} (97%) diff --git a/.github/workflows/auto-bump_version.yml b/.github/workflows/repo-bump-version.yaml similarity index 97% rename from .github/workflows/auto-bump_version.yml rename to .github/workflows/repo-bump-version.yaml index dc0adb96b0..351e24576f 100644 --- a/.github/workflows/auto-bump_version.yml +++ b/.github/workflows/repo-bump-version.yaml @@ -1,4 +1,4 @@ -name: Auto bump_version +name: '🆙 Auto bump_version' on: release: @@ -30,7 +30,7 @@ jobs: - name: Setup YQ uses: chrisdickinson/setup-yq@latest with: - yq-version: v4.9.6 + yq-version: v4.9.8 - name: Checkout Repository uses: actions/checkout@v2 From 066db8ac7fcece0ab3420b6b6c03e420d22c7306 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Tue, 19 Jul 2022 21:28:04 +0200 Subject: [PATCH 004/358] Migrate NetworkManager and Tests to native .NET IP objects --- Emby.Dlna/Main/DlnaEntryPoint.cs | 19 +- .../ApplicationHost.cs | 4 +- .../Configuration/NetworkConfiguration.cs | 10 +- Jellyfin.Networking/Manager/NetworkManager.cs | 1500 ++++++++--------- .../ApiServiceCollectionExtensions.cs | 8 +- .../CreateNetworkConfiguration.cs | 4 +- Jellyfin.Server/Program.cs | 6 +- MediaBrowser.Common/Net/INetworkManager.cs | 128 +- MediaBrowser.Common/Net/IPData.cs | 76 + MediaBrowser.Common/Net/IPHost.cs | 441 ----- MediaBrowser.Common/Net/IPNetAddress.cs | 276 --- MediaBrowser.Common/Net/IPObject.cs | 370 ---- MediaBrowser.Common/Net/NetworkExtensions.cs | 309 ++-- .../IServerApplicationHost.cs | 5 +- RSSDP/SsdpDevicePublisher.cs | 7 +- .../IPNetAddressTests.cs | 49 - ...HostTests.cs => NetworkExtensionsTests.cs} | 10 +- .../NetworkParseTests.cs | 253 +-- 18 files changed, 964 insertions(+), 2511 deletions(-) create mode 100644 MediaBrowser.Common/Net/IPData.cs delete mode 100644 MediaBrowser.Common/Net/IPHost.cs delete mode 100644 MediaBrowser.Common/Net/IPNetAddress.cs delete mode 100644 MediaBrowser.Common/Net/IPObject.cs delete mode 100644 tests/Jellyfin.Networking.Tests/IPNetAddressTests.cs rename tests/Jellyfin.Networking.Tests/{IPHostTests.cs => NetworkExtensionsTests.cs} (80%) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 15021c19d6..01a9def0bf 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -3,15 +3,16 @@ #pragma warning disable CS1591 using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Net; using System.Net.Http; using System.Net.Sockets; using System.Threading.Tasks; using Emby.Dlna.PlayTo; using Emby.Dlna.Ssdp; using Jellyfin.Networking.Configuration; -using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; @@ -285,9 +286,11 @@ namespace Emby.Dlna.Main var udn = CreateUuid(_appHost.SystemId); var descriptorUri = "/dlna/" + udn + "/description.xml"; - var bindAddresses = NetworkManager.CreateCollection( - _networkManager.GetInternalBindAddresses() - .Where(i => i.AddressFamily == AddressFamily.InterNetwork || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0))); + var bindAddresses = _networkManager + .GetInternalBindAddresses() + .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork + || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0)) + .ToList(); if (bindAddresses.Count == 0) { @@ -295,7 +298,7 @@ namespace Emby.Dlna.Main bindAddresses = _networkManager.GetLoopbacks(); } - foreach (IPNetAddress address in bindAddresses) + foreach (var address in bindAddresses) { if (address.AddressFamily == AddressFamily.InterNetworkV6) { @@ -304,7 +307,7 @@ namespace Emby.Dlna.Main } // Limit to LAN addresses only - if (!_networkManager.IsInLocalNetwork(address)) + if (!_networkManager.IsInLocalNetwork(address.Address)) { continue; } @@ -313,14 +316,14 @@ namespace Emby.Dlna.Main _logger.LogInformation("Registering publisher for {ResourceName} on {DeviceAddress}", fullService, address); - var uri = new UriBuilder(_appHost.GetApiUrlForLocalAccess(address, false) + descriptorUri); + var uri = new UriBuilder(_appHost.GetApiUrlForLocalAccess(address.Address, false) + descriptorUri); var device = new SsdpRootDevice { CacheLifetime = TimeSpan.FromSeconds(1800), // How long SSDP clients can cache this info. Location = uri.Uri, // Must point to the URL that serves your devices UPnP description document. Address = address.Address, - PrefixLength = address.PrefixLength, + PrefixLength = NetworkExtensions.MaskToCidr(address.Subnet.Prefix), FriendlyName = "Jellyfin", Manufacturer = "Jellyfin", ModelName = "Jellyfin Server", diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 32289625fe..a0ad4a9ab5 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1114,10 +1114,10 @@ namespace Emby.Server.Implementations } /// - public string GetApiUrlForLocalAccess(IPObject hostname = null, bool allowHttps = true) + public string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true) { // With an empty source, the port will be null - var smart = NetManager.GetBindInterface(hostname ?? IPHost.None, out _); + var smart = NetManager.GetBindInterface(ipAddress, out _); var scheme = !allowHttps ? Uri.UriSchemeHttp : null; int? port = !allowHttps ? HttpPort : null; return GetLocalApiUrl(smart, scheme, port); diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index 61db223d92..0ac55c986e 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -113,12 +113,12 @@ namespace Jellyfin.Networking.Configuration public string UDPPortRange { get; set; } = string.Empty; /// - /// Gets or sets a value indicating whether gets or sets IPV6 capability. + /// Gets or sets a value indicating whether IPv6 is enabled or not. /// public bool EnableIPV6 { get; set; } /// - /// Gets or sets a value indicating whether gets or sets IPV4 capability. + /// Gets or sets a value indicating whether IPv6 is enabled or not. /// public bool EnableIPV4 { get; set; } = true; @@ -165,12 +165,6 @@ namespace Jellyfin.Networking.Configuration /// public bool EnableMultiSocketBinding { get; } = true; - /// - /// 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. - /// - public bool TrustAllIP6Interfaces { get; set; } - /// /// Gets or sets the ports that HDHomerun uses. /// diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 4b7b87814c..f51fd85dd5 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net; @@ -12,30 +11,25 @@ using Jellyfin.Networking.Configuration; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Logging; namespace Jellyfin.Networking.Manager { /// /// Class to take care of network interface management. - /// Note: The normal collection methods and properties will not work with Collection{IPObject}. . /// public class NetworkManager : INetworkManager, IDisposable { - /// - /// Contains the description of the interface along with its index. - /// - private readonly Dictionary _interfaceNames; - /// /// Threading lock for network properties. /// - private readonly object _intLock = new object(); + private readonly object _initLock; /// - /// List of all interface addresses and masks. + /// Dictionary containing interface addresses and their subnets. /// - private readonly Collection _interfaceAddresses; + private readonly List _interfaces; /// /// List of all interface MAC addresses. @@ -49,9 +43,11 @@ namespace Jellyfin.Networking.Manager private readonly object _eventFireLock; /// - /// Holds the bind address overrides. + /// Holds the published server URLs and the IPs to use them on. /// - private readonly Dictionary _publishedServerUrls; + private readonly Dictionary _publishedServerUrls; + + private Collection _remoteAddressFilter; /// /// Used to stop "event-racing conditions". @@ -59,35 +55,25 @@ namespace Jellyfin.Networking.Manager private bool _eventfire; /// - /// Unfiltered user defined LAN subnets. () + /// Unfiltered user defined LAN subnets () /// or internal interface network subnets if undefined by user. /// - private Collection _lanSubnets; + private Collection _lanSubnets; /// /// User defined list of subnets to excluded from the LAN. /// - private Collection _excludedSubnets; + private Collection _excludedSubnets; /// - /// List of interface addresses to bind the WS. + /// List of interfaces to bind to. /// - private Collection _bindAddresses; + private List _bindAddresses; /// /// List of interface addresses to exclude from bind. /// - private Collection _bindExclusions; - - /// - /// Caches list of all internal filtered interface addresses and masks. - /// - private Collection _internalInterfaces; - - /// - /// Flag set when no custom LAN has been defined in the configuration. - /// - private bool _usingPrivateAddresses; + private List _bindExclusions; /// /// True if this object is disposed. @@ -104,12 +90,12 @@ namespace Jellyfin.Networking.Manager { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _configurationManager = configurationManager ?? throw new ArgumentNullException(nameof(configurationManager)); - - _interfaceAddresses = new Collection(); + _initLock = new(); + _interfaces = new List(); _macAddresses = new List(); - _interfaceNames = new Dictionary(); - _publishedServerUrls = new Dictionary(); + _publishedServerUrls = new Dictionary(); _eventFireLock = new object(); + _remoteAddressFilter = new Collection(); UpdateSettings(_configurationManager.GetNetworkConfiguration()); @@ -131,46 +117,24 @@ namespace Jellyfin.Networking.Manager public static string MockNetworkSettings { get; set; } = string.Empty; /// - /// Gets or sets a value indicating whether IP6 is enabled. + /// Gets a value indicating whether IP4 is enabled. /// - public bool IsIP6Enabled { get; set; } + public bool IsIpv4Enabled => _configurationManager.GetNetworkConfiguration().EnableIPV4; /// - /// Gets or sets a value indicating whether IP4 is enabled. + /// Gets a value indicating whether IP6 is enabled. /// - public bool IsIP4Enabled { get; set; } - - /// - public Collection RemoteAddressFilter { get; private set; } + public bool IsIpv6Enabled => _configurationManager.GetNetworkConfiguration().EnableIPV6; /// /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. /// - public bool TrustAllIP6Interfaces { get; internal set; } + public bool TrustAllIpv6Interfaces { get; private set; } /// /// Gets the Published server override list. /// - public Dictionary PublishedServerUrls => _publishedServerUrls; - - /// - /// Creates a new network collection. - /// - /// Items to assign the collection, or null. - /// The collection created. - public static Collection CreateCollection(IEnumerable? source = null) - { - var result = new Collection(); - if (source != null) - { - foreach (var item in source) - { - result.AddItem(item, false); - } - } - - return result; - } + public Dictionary PublishedServerUrls => _publishedServerUrls; /// public void Dispose() @@ -179,418 +143,363 @@ namespace Jellyfin.Networking.Manager GC.SuppressFinalize(this); } - /// - public IReadOnlyCollection GetMacAddresses() + /// + /// Handler for network change events. + /// + /// Sender. + /// A containing network availability information. + private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e) { - // Populated in construction - so always has values. - return _macAddresses; + _logger.LogDebug("Network availability changed."); + OnNetworkChanged(); } - /// - public bool IsGatewayInterface(IPObject? addressObj) + /// + /// Handler for network change events. + /// + /// Sender. + /// An . + private void OnNetworkAddressChanged(object? sender, EventArgs e) { - var address = addressObj?.Address ?? IPAddress.None; - return _internalInterfaces.Any(i => i.Address.Equals(address) && i.Tag < 0); + _logger.LogDebug("Network address change detected."); + OnNetworkChanged(); } - /// - public bool IsGatewayInterface(IPAddress? addressObj) + /// + /// Triggers our event, and re-loads interface information. + /// + private void OnNetworkChanged() { - return _internalInterfaces.Any(i => i.Address.Equals(addressObj ?? IPAddress.None) && i.Tag < 0); + 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(); + } + } } - /// - public Collection GetLoopbacks() + /// + /// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession. + /// + /// A representing the asynchronous operation. + private async Task OnNetworkChangeAsync() { - Collection nc = new Collection(); - if (IsIP4Enabled) + try { - nc.AddItem(IPAddress.Loopback); - } + await Task.Delay(2000).ConfigureAwait(false); + InitialiseInterfaces(); + // Recalculate LAN caches. + InitialiseLan(_configurationManager.GetNetworkConfiguration()); - if (IsIP6Enabled) + NetworkChanged?.Invoke(this, EventArgs.Empty); + } + finally { - nc.AddItem(IPAddress.IPv6Loopback); + _eventfire = false; } - - return nc; - } - - /// - public bool IsExcluded(IPAddress ip) - { - return _excludedSubnets.ContainsAddress(ip); - } - - /// - public bool IsExcluded(EndPoint ip) - { - return ip != null && IsExcluded(((IPEndPoint)ip).Address); } - /// - public Collection CreateIPCollection(string[] values, bool negated = false) + /// + /// 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. + /// + private void InitialiseInterfaces() { - Collection col = new Collection(); - if (values == null) + lock (_initLock) { - return col; - } + _logger.LogDebug("Refreshing interfaces."); - for (int a = 0; a < values.Length; a++) - { - string v = values[a].Trim(); + _interfaces.Clear(); + _macAddresses.Clear(); try { - if (v.StartsWith('!')) + IEnumerable nics = NetworkInterface.GetAllNetworkInterfaces() + .Where(i => i.SupportsMulticast && i.OperationalStatus == OperationalStatus.Up); + + foreach (NetworkInterface adapter in nics) { - if (negated) + try + { + IPInterfaceProperties ipProperties = adapter.GetIPProperties(); + PhysicalAddress mac = adapter.GetPhysicalAddress(); + + // Populate MAC list + if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && PhysicalAddress.None.Equals(mac)) + { + _macAddresses.Add(mac); + } + + // Populate interface list + foreach (UnicastIPAddressInformation info in ipProperties.UnicastAddresses) + { + if (IsIpv4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork) + { + var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength), adapter.Name); + interfaceObject.Index = ipProperties.GetIPv4Properties().Index; + interfaceObject.Name = adapter.Name.ToLower(CultureInfo.InvariantCulture); + + _interfaces.Add(interfaceObject); + } + else if (IsIpv6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6) + { + var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength), adapter.Name); + interfaceObject.Index = ipProperties.GetIPv6Properties().Index; + interfaceObject.Name = adapter.Name.ToLower(CultureInfo.InvariantCulture); + + _interfaces.Add(interfaceObject); + } + } + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception ex) +#pragma warning restore CA1031 // Do not catch general exception types { - AddToCollection(col, v[1..]); + // Ignore error, and attempt to continue. + _logger.LogError(ex, "Error encountered parsing interfaces."); } } - else if (!negated) - { - AddToCollection(col, v); - } } - catch (ArgumentException e) +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception ex) +#pragma warning restore CA1031 // Do not catch general exception types { - _logger.LogWarning(e, "Ignoring LAN value {Value}.", v); + _logger.LogError(ex, "Error obtaining interfaces."); } - } - - return col; - } - - /// - public Collection GetAllBindInterfaces(bool individualInterfaces = false) - { - int count = _bindAddresses.Count; - if (count == 0) - { - if (_bindExclusions.Count > 0) + // If for some reason we don't have an interface info, resolve the DNS name. + if (_interfaces.Count == 0) { - // Return all the interfaces except the ones specifically excluded. - return _interfaceAddresses.Exclude(_bindExclusions, false); - } + _logger.LogError("No interfaces information available. Resolving DNS name."); + var hostName = Dns.GetHostName(); + if (Uri.CheckHostName(hostName).Equals(UriHostNameType.Dns)) + { + try + { + IPHostEntry hip = Dns.GetHostEntry(hostName); + foreach (var address in hip.AddressList) + { + _interfaces.Add(new IPData(address, null)); + } + } + catch (SocketException ex) + { + // Log and then ignore socket errors, as the result value will just be an empty array. + _logger.LogWarning("GetHostEntryAsync failed with {Message}.", ex.Message); + } + } - if (individualInterfaces) - { - return new Collection(_interfaceAddresses); + if (_interfaces.Count == 0) + { + _logger.LogWarning("No interfaces information available. Using loopback."); + } } - // No bind address and no exclusions, so listen on all interfaces. - Collection result = new Collection(); - - if (IsIP6Enabled && IsIP4Enabled) - { - // Kestrel source code shows it uses Sockets.DualMode - so this also covers IPAddress.Any - result.AddItem(IPAddress.IPv6Any); - } - else if (IsIP4Enabled) + if (IsIpv4Enabled && !IsIpv6Enabled) { - result.AddItem(IPAddress.Any); + _interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); } - else if (IsIP6Enabled) + + if (!IsIpv4Enabled && IsIpv6Enabled) { - // Cannot use IPv6Any as Kestrel will bind to IPv4 addresses. - foreach (var iface in _interfaceAddresses) - { - if (iface.AddressFamily == AddressFamily.InterNetworkV6) - { - result.AddItem(iface.Address); - } - } + _interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); } - return result; + _logger.LogDebug("Discovered {0} interfaces.", _interfaces.Count); + _logger.LogDebug("Interfaces addresses : {0}", _interfaces.Select(s => s.Address).ToString()); } - - // Remove any excluded bind interfaces. - return _bindAddresses.Exclude(_bindExclusions, false); } - /// - public string GetBindInterface(string source, out int? port) + /// + /// Initialises internal LAN cache. + /// + private void InitialiseLan(NetworkConfiguration config) { - if (!string.IsNullOrEmpty(source) && IPHost.TryParse(source, out IPHost host)) + lock (_initLock) { - return GetBindInterface(host, out port); - } + _logger.LogDebug("Refreshing LAN information."); - return GetBindInterface(IPHost.None, out port); - } + // Get configuration options + string[] subnets = config.LocalNetworkSubnets; - /// - public string GetBindInterface(IPAddress source, out int? port) - { - return GetBindInterface(new IPNetAddress(source), out port); - } + _ = TryParseSubnets(subnets, out _lanSubnets, false); + _ = TryParseSubnets(subnets, out _excludedSubnets, true); - /// - public string GetBindInterface(HttpRequest source, out int? port) - { - string result; + if (_lanSubnets.Count == 0) + { + // If no LAN addresses are specified, all private subnets are deemed to be the LAN + _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); - 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; - } + if (IsIpv6Enabled) + { + _lanSubnets.Add(new IPNetwork(IPAddress.Parse("fc00::"), 7)); // ULA + _lanSubnets.Add(new IPNetwork(IPAddress.Parse("fe80::"), 10)); // Site local + } - return result; - } + if (IsIpv4Enabled) + { + _lanSubnets.Add(new IPNetwork(IPAddress.Parse("10.0.0.0"), 8)); + _lanSubnets.Add(new IPNetwork(IPAddress.Parse("172.16.0.0"), 12)); + _lanSubnets.Add(new IPNetwork(IPAddress.Parse("192.168.0.0"), 16)); + } + } - /// - public string GetBindInterface(IPObject source, out int? port) - { - port = null; - if (source == null) - { - throw new ArgumentNullException(nameof(source)); + _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets.Select(s => s.Prefix + "/" + s.PrefixLength)); + _logger.LogInformation("Defined LAN exclusions : {0}", _excludedSubnets.Select(s => s.Prefix + "/" + s.PrefixLength)); + _logger.LogInformation("Using LAN addresses: {0}", _lanSubnets.Where(s => !_excludedSubnets.Contains(s)).Select(s => s.Prefix + "/" + s.PrefixLength)); } + } - // Do we have a source? - bool haveSource = !source.Address.Equals(IPAddress.None); - bool isExternal = false; - - if (haveSource) + /// + /// Initialises the network bind addresses. + /// + private void InitialiseBind(NetworkConfiguration config) + { + lock (_initLock) { - if (!IsIP6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6) + // Use explicit bind addresses + if (config.LocalNetworkAddresses.Length > 0) { - _logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); + _bindAddresses = config.LocalNetworkAddresses.Select(p => IPAddress.TryParse(p, out var address) + ? address + : (_interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase)).Select(x => x.Address).FirstOrDefault() ?? IPAddress.None)).ToList(); + _bindAddresses.RemoveAll(x => x == IPAddress.None); } - - if (!IsIP4Enabled && source.AddressFamily == AddressFamily.InterNetwork) + else { - _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); + // Use all addresses from all interfaces + _bindAddresses = _interfaces.Select(x => x.Address).ToList(); } - isExternal = !IsInLocalNetwork(source); + _bindExclusions = new List(); - if (MatchesPublishedServerUrl(source, isExternal, out string res, out port)) + // Add all interfaces matching any virtual machine interface prefix to _bindExclusions + if (config.IgnoreVirtualInterfaces) { - _logger.LogInformation("{Source}: Using BindAddress {Address}:{Port}", source, res, port); - return res; - } - } + // Remove potentially exisiting * and split config string into prefixes + var virtualInterfacePrefixes = config.VirtualInterfaceNames.Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase).ToLower().Split(','); - _logger.LogDebug("GetBindInterface: Source: {HaveSource}, External: {IsExternal}:", haveSource, isExternal); + // Check all interfaces for matches against the prefixes and add the interface IPs to _bindExclusions + if (_bindAddresses.Count > 0 && virtualInterfacePrefixes.Length > 0) + { + var localInterfaces = _interfaces.ToList(); + foreach (var virtualInterfacePrefix in virtualInterfacePrefixes) + { + var excludedInterfaceIps = localInterfaces.Where(intf => intf.Name.StartsWith(virtualInterfacePrefix, StringComparison.OrdinalIgnoreCase)) + .Select(intf => intf.Address); + foreach (var interfaceIp in excludedInterfaceIps) + { + _bindExclusions.Add(interfaceIp); + } + } + } + } - // No preference given, so move on to bind addresses. - if (MatchesBindInterface(source, isExternal, out string result)) - { - return result; - } + // Remove all excluded addresses from _bindAddresses + _bindAddresses.RemoveAll(x => _bindExclusions.Contains(x)); - if (isExternal && MatchesExternalInterface(source, out result)) - { - return result; + _logger.LogInformation("Using bind addresses: {0}", _bindAddresses); + _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions); } + } - // Get the first LAN interface address that isn't a loopback. - var interfaces = CreateCollection( - _interfaceAddresses - .Exclude(_bindExclusions, false) - .Where(IsInLocalNetwork) - .OrderBy(p => p.Tag)); - - if (interfaces.Count > 0) + /// + /// Initialises the remote address values. + /// + private void InitialiseRemote(NetworkConfiguration config) + { + lock (_initLock) { - if (haveSource) + // Parse config values into filter collection + var remoteIPFilter = config.RemoteIPFilter; + if (remoteIPFilter.Any() && !string.IsNullOrWhiteSpace(remoteIPFilter.First())) { - foreach (var intf in interfaces) - { - if (intf.Address.Equals(source.Address)) - { - result = FormatIP6String(intf.Address); - _logger.LogDebug("{Source}: GetBindInterface: Has found matching interface. {Result}", source, result); - return result; - } - } + // Parse all IPs with netmask to a subnet + _ = TryParseSubnets(remoteIPFilter.Where(x => x.Contains("/", StringComparison.OrdinalIgnoreCase)).ToArray(), out _remoteAddressFilter, false); - // 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) + // Parse everything else as an IP and construct subnet with a single IP + var ips = remoteIPFilter.Where(x => !x.Contains("/", StringComparison.OrdinalIgnoreCase)); + foreach (var ip in ips) { - if (intf.Contains(source)) + if (IPAddress.TryParse(ip, out var ipp)) { - result = FormatIP6String(intf.Address); - _logger.LogDebug("{Source}: GetBindInterface: Has source, matched best internal interface on range. {Result}", source, result); - return result; + _remoteAddressFilter.Add(new IPNetwork(ipp, ipp.AddressFamily == AddressFamily.InterNetwork ? 32 : 128)); } } } - - result = FormatIP6String(interfaces.First().Address); - _logger.LogDebug("{Source}: GetBindInterface: Matched first internal interface. {Result}", source, result); - return result; } - - // There isn't any others, so we'll use the loopback. - result = IsIP6Enabled ? "::1" : "127.0.0.1"; - _logger.LogWarning("{Source}: GetBindInterface: Loopback {Result} returned.", source, result); - return result; } - /// - public Collection 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); - } - - return new Collection(_bindAddresses.Where(a => IsInLocalNetwork(a)).ToArray()); - } - - /// - public bool IsInLocalNetwork(IPObject address) - { - return IsInLocalNetwork(address.Address); - } - - /// - public bool IsInLocalNetwork(string address) - { - return IPHost.TryParse(address, out IPHost ipHost) && IsInLocalNetwork(ipHost); - } - - /// - public bool IsInLocalNetwork(IPAddress 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 IPAddress.IsLoopback(address) || (_lanSubnets.ContainsAddress(address) && !_excludedSubnets.ContainsAddress(address)); - } - - /// - 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(); - } - } - - /// - public bool IsExcludedInterface(IPAddress address) - { - return _bindExclusions.ContainsAddress(address); - } - - /// - public Collection GetFilteredLANSubnets(Collection? filter = null) - { - if (filter == null) - { - return _lanSubnets.Exclude(_excludedSubnets, true).AsNetworks(); - } - - return _lanSubnets.Exclude(filter, true); - } - - /// - public bool IsValidInterfaceAddress(IPAddress address) - { - return _interfaceAddresses.ContainsAddress(address); - } - - /// - public bool TryParseInterface(string token, out Collection? result) + /// + /// 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. + /// + private void InitialiseOverrides(NetworkConfiguration config) { - result = null; - if (string.IsNullOrEmpty(token)) + lock (_initLock) { - return false; - } - - if (_interfaceNames != null && _interfaceNames.TryGetValue(token.ToLower(CultureInfo.InvariantCulture), out int index)) - { - result = new Collection(); - - _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token); + _publishedServerUrls.Clear(); + string[] overrides = config.PublishedServerUriBySubnet; - // Replace interface tags with the interface IP's. - foreach (IPNetAddress iface in _interfaceAddresses) + foreach (var entry in overrides) { - if (Math.Abs(iface.Tag) == index - && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) - || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) + var parts = entry.Split('='); + if (parts.Length != 2) { - result.AddItem(iface, false); + _logger.LogError("Unable to parse bind override: {Entry}", entry); } - } + else + { + var replacement = parts[1].Trim(); + var ipParts = parts[0].Split("/"); + if (string.Equals(parts[0], "all", StringComparison.OrdinalIgnoreCase)) + { + _publishedServerUrls[new IPData(IPAddress.Broadcast, null)] = replacement; + } + else if (string.Equals(parts[0], "external", StringComparison.OrdinalIgnoreCase)) + { + _publishedServerUrls[new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))] = replacement; + _publishedServerUrls[new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))] = replacement; + } + else if (IPAddress.TryParse(ipParts[0], out IPAddress? result)) + { + var data = new IPData(result, null); + if (ipParts.Length > 1 && int.TryParse(ipParts[1], out var netmask)) + { + data.Subnet = new IPNetwork(result, netmask); + } - return true; + _publishedServerUrls[data] = replacement; + } + else if (TryParseInterface(parts[0], out var ifaces)) + { + foreach (var iface in ifaces) + { + _publishedServerUrls[iface] = replacement; + } + } + else + { + _logger.LogError("Unable to parse bind ip address. {Parts}", parts[1]); + } + } + } } - - return false; } - /// - public bool HasRemoteAccess(IPAddress remoteIp) + private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt) { - var config = _configurationManager.GetNetworkConfiguration(); - if (config.EnableRemoteAccess) + if (evt.Key.Equals("network", StringComparison.Ordinal)) { - // 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. - if (RemoteAddressFilter.Count > 0 && !IsInLocalNetwork(remoteIp)) - { - // remoteAddressFilter is a whitelist or blacklist. - return RemoteAddressFilter.ContainsAddress(remoteIp) == !config.IsRemoteIPFilterBlacklist; - } - } - else if (!IsInLocalNetwork(remoteIp)) - { - // Remote not enabled. So everyone should be LAN. - return false; + UpdateSettings((NetworkConfiguration)evt.NewConfiguration); } - - return true; } /// @@ -601,17 +510,6 @@ namespace Jellyfin.Networking.Manager { 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; - if (string.IsNullOrEmpty(MockNetworkSettings)) { InitialiseInterfaces(); @@ -623,15 +521,22 @@ namespace Jellyfin.Networking.Manager foreach (var details in interfaceList) { var parts = details.Split(','); - var address = IPNetAddress.Parse(parts[0]); + var split = parts[0].Split("/"); + var address = IPAddress.Parse(split[0]); + var network = new IPNetwork(address, int.Parse(split[1], CultureInfo.InvariantCulture)); var index = int.Parse(parts[1], CultureInfo.InvariantCulture); - address.Tag = index; - _interfaceAddresses.AddItem(address, false); - _interfaceNames[parts[2]] = Math.Abs(index); + if (address.AddressFamily == AddressFamily.InterNetwork) + { + _interfaces.Add(new IPData(address, network, parts[2])); + } + else if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + _interfaces.Add(new IPData(address, network, parts[2])); + } } } - InitialiseLAN(config); + InitialiseLan(config); InitialiseBind(config); InitialiseRemote(config); InitialiseOverrides(config); @@ -656,540 +561,467 @@ namespace Jellyfin.Networking.Manager } } - /// - /// Tries to identify the string and return an object of that class. - /// - /// String to parse. - /// IPObject to return. - /// true if the value parsed successfully, false otherwise. - private static bool TryParse(string addr, out IPObject result) + /// + public bool TryParseInterface(string intf, out Collection result) { - if (!string.IsNullOrEmpty(addr)) + result = new Collection(); + if (string.IsNullOrEmpty(intf)) { - // Is it an IP address - if (IPNetAddress.TryParse(addr, out IPNetAddress nw)) - { - result = nw; - return true; - } + return false; + } - if (IPHost.TryParse(addr, out IPHost h)) + if (_interfaces != null) + { + // Match all interfaces starting with names starting with token + var matchedInterfaces = _interfaces.Where(s => s.Name.Equals(intf.ToLower(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase)); + if (matchedInterfaces.Any()) { - result = h; + _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", intf); + + // Use interface IP instead of name + foreach (IPData iface in matchedInterfaces) + { + if ((IsIpv4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) + || (IsIpv6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)) + { + result.Add(iface); + } + } + return true; } } - result = IPNetAddress.None; return false; } /// - /// Converts an IPAddress into a string. - /// Ipv6 addresses are returned in [ ], with their scope removed. + /// Try parsing an array of strings into subnets, respecting exclusions. /// - /// Address to convert. - /// URI safe conversion of the address. - private static string FormatIP6String(IPAddress address) + /// Input string to be parsed. + /// Collection of . + /// Boolean signaling if negated or not negated values should be parsed. + /// True if parsing was successful. + public bool TryParseSubnets(string[] values, out Collection result, bool negated = false) { - 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}]"; - } + result = new Collection(); - return str; - } - - private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt) - { - if (evt.Key.Equals(NetworkConfigurationStore.StoreKey, StringComparison.Ordinal)) + if (values == null || values.Length == 0) { - UpdateSettings((NetworkConfiguration)evt.NewConfiguration); + return false; } - } - - /// - /// Checks the string to see if it matches any interface names. - /// - /// String to check. - /// Interface index numbers that match. - /// true if an interface name matches the token, False otherwise. - private bool TryGetInterfaces(string token, [NotNullWhen(true)] out List? index) - { - index = null; - // 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) + for (int a = 0; a < values.Length; a++) { - bool partial = token[^1] == '*'; - if (partial) - { - token = token[..^1]; - } + string[] v = values[a].Trim().Split("/"); - foreach ((string interfc, int interfcIndex) in _interfaceNames) + try { - if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase)) - || (partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture))) + var address = IPAddress.None; + if (negated && v[0].StartsWith('!')) { - index ??= new List(); - index.Add(interfcIndex); + _ = IPAddress.TryParse(v[0][1..], out address); } - } - } - - return index != null; - } - - /// - /// Parses a string and adds it into the collection, replacing any interface references. - /// - /// Collection. - /// String value to parse. - private void AddToCollection(Collection 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 (TryGetInterfaces(token, out var indices)) - { - _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token); - - // Replace all the interface tags with the interface IP's. - foreach (IPNetAddress iface in _interfaceAddresses) - { - if (indices.Contains(Math.Abs(iface.Tag)) - && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) - || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) + else if (!negated) { - col.AddItem(iface); + _ = IPAddress.TryParse(v[0][0..], out address); } - } - } - else if (TryParse(token, out IPObject obj)) - { - // Expand if the ip address is "any". - if ((obj.Address.Equals(IPAddress.Any) && IsIP4Enabled) - || (obj.Address.Equals(IPAddress.IPv6Any) && IsIP6Enabled)) - { - foreach (IPNetAddress iface in _interfaceAddresses) + + if (address != IPAddress.None && address != null) { - if (obj.AddressFamily == iface.AddressFamily) + if (int.TryParse(v[1], out var netmask)) + { + result.Add(new IPNetwork(address, netmask)); + } + else if (address.AddressFamily == AddressFamily.InterNetwork) { - col.AddItem(iface); + result.Add(new IPNetwork(address, 32)); + } + else if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + result.Add(new IPNetwork(address, 128)); } } } - else if (!IsIP6Enabled) + catch (ArgumentException e) { - // Remove IP6 addresses from multi-homed IPHosts. - obj.Remove(AddressFamily.InterNetworkV6); - if (!obj.IsIP6()) - { - col.AddItem(obj); - } + _logger.LogWarning(e, "Ignoring LAN value {Value}.", v); } - else if (!IsIP4Enabled) + } + + if (result.Count > 0) + { + return true; + } + + return false; + } + + /// + public bool HasRemoteAccess(IPAddress remoteIp) + { + var config = _configurationManager.GetNetworkConfiguration(); + if (config.EnableRemoteAccess) + { + // 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. + if (_remoteAddressFilter.Any() && !_lanSubnets.Any(x => x.Contains(remoteIp))) { - // Remove IP4 addresses from multi-homed IPHosts. - obj.Remove(AddressFamily.InterNetwork); - if (obj.IsIP6()) + // remoteAddressFilter is a whitelist or blacklist. + var matches = _remoteAddressFilter.Count(remoteNetwork => remoteNetwork.Contains(remoteIp)); + if ((!config.IsRemoteIPFilterBlacklist && matches > 0) + || (config.IsRemoteIPFilterBlacklist && matches == 0)) { - col.AddItem(obj); + return true; } - } - else - { - col.AddItem(obj); + + return false; } } - else + else if (!_lanSubnets.Where(x => x.Contains(remoteIp)).Any()) { - _logger.LogDebug("Invalid or unknown object {Token}.", token); + // Remote not enabled. So everyone should be LAN. + return false; } - } - /// - /// Handler for network change events. - /// - /// Sender. - /// A containing network availability information. - private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e) - { - _logger.LogDebug("Network availability changed."); - OnNetworkChanged(); + return true; } - /// - /// Handler for network change events. - /// - /// Sender. - /// An . - private void OnNetworkAddressChanged(object? sender, EventArgs e) + /// + public IReadOnlyCollection GetMacAddresses() { - _logger.LogDebug("Network address change detected."); - OnNetworkChanged(); + // Populated in construction - so always has values. + return _macAddresses; } - /// - /// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession. - /// - /// A representing the asynchronous operation. - private async Task OnNetworkChangeAsync() + /// + public List GetLoopbacks() { - try + var loopbackNetworks = new List(); + if (IsIpv4Enabled) { - await Task.Delay(2000).ConfigureAwait(false); - InitialiseInterfaces(); - // Recalculate LAN caches. - InitialiseLAN(_configurationManager.GetNetworkConfiguration()); - - NetworkChanged?.Invoke(this, EventArgs.Empty); - } - finally - { - _eventfire = false; + loopbackNetworks.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); } - } - - /// - /// Triggers our event, and re-loads interface information. - /// - private void OnNetworkChanged() - { - lock (_eventFireLock) + + if (IsIpv6Enabled) { - 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(); - } + loopbackNetworks.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); } + + return loopbackNetworks; } - /// - /// 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. - /// - private void InitialiseOverrides(NetworkConfiguration config) + /// + public List GetAllBindInterfaces(bool individualInterfaces = false) { - lock (_intLock) + if (_bindAddresses.Count == 0) { - _publishedServerUrls.Clear(); - string[] overrides = config.PublishedServerUriBySubnet; - if (overrides == null) + if (_bindExclusions.Count > 0) { - return; + foreach (var exclusion in _bindExclusions) + { + // Return all the interfaces except the ones specifically excluded. + _interfaces.RemoveAll(intf => intf.Address == exclusion); + } + + return _interfaces; } - foreach (var entry in overrides) + // No bind address and no exclusions, so listen on all interfaces. + var result = new List(); + + if (individualInterfaces) { - var parts = entry.Split('='); - if (parts.Length != 2) + foreach (var iface in _interfaces) { - _logger.LogError("Unable to parse bind override: {Entry}", entry); + result.Add(iface); } - else + + return result; + } + + if (IsIpv4Enabled && IsIpv6Enabled) + { + // Kestrel source code shows it uses Sockets.DualMode - so this also covers IPAddress.Any by default + result.Add(new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))); + } + else if (IsIpv4Enabled) + { + result.Add(new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))); + } + else if (IsIpv6Enabled) + { + // Cannot use IPv6Any as Kestrel will bind to IPv4 addresses too. + foreach (var iface in _interfaces) { - var replacement = parts[1].Trim(); - if (string.Equals(parts[0], "all", 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? addresses) && addresses != null) - { - foreach (IPNetAddress na in addresses) - { - _publishedServerUrls[na] = replacement; - } - } - else if (IPNetAddress.TryParse(parts[0], out IPNetAddress result)) - { - _publishedServerUrls[result] = replacement; - } - else + if (iface.AddressFamily == AddressFamily.InterNetworkV6) { - _logger.LogError("Unable to parse bind ip address. {Parts}", parts[1]); + result.Add(iface); } } } + + return result; } - } - /// - /// Initialises the network bind addresses. - /// - private void InitialiseBind(NetworkConfiguration config) - { - lock (_intLock) + // Remove any excluded bind interfaces. + foreach (var exclusion in _bindExclusions) { - string[] lanAddresses = config.LocalNetworkAddresses; + // Return all the interfaces except the ones specifically excluded. + _bindAddresses.Remove(exclusion); + } - // Add virtual machine interface names to the list of bind exclusions, so that they are auto-excluded. - if (config.IgnoreVirtualInterfaces) - { - // each virtual interface name must be pre-pended with the exclusion symbol ! - var virtualInterfaceNames = config.VirtualInterfaceNames.Split(',').Select(p => "!" + p).ToArray(); - if (lanAddresses.Length > 0) - { - var newList = new string[lanAddresses.Length + virtualInterfaceNames.Length]; - Array.Copy(lanAddresses, newList, lanAddresses.Length); - Array.Copy(virtualInterfaceNames, 0, newList, lanAddresses.Length, virtualInterfaceNames.Length); - lanAddresses = newList; - } - else - { - lanAddresses = virtualInterfaceNames; - } - } + return _bindAddresses.Select(s => new IPData(s, null)).ToList(); + } - // Read and parse bind addresses and exclusions, removing ones that don't exist. - _bindAddresses = CreateIPCollection(lanAddresses).ThatAreContainedInNetworks(_interfaceAddresses); - _bindExclusions = CreateIPCollection(lanAddresses, true).ThatAreContainedInNetworks(_interfaceAddresses); - _logger.LogInformation("Using bind addresses: {0}", _bindAddresses.AsString()); - _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions.AsString()); - } + /// + public string GetBindInterface(string source, out int? port) + { + _ = NetworkExtensions.TryParseHost(source, out var address, IsIpv4Enabled, IsIpv6Enabled); + var result = GetBindInterface(address.FirstOrDefault(), out port); + return result; } - /// - /// Initialises the remote address values. - /// - private void InitialiseRemote(NetworkConfiguration config) + /// + public string GetBindInterface(HttpRequest source, out int? port) { - lock (_intLock) - { - RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter); - } + string result; + _ = NetworkExtensions.TryParseHost(source.Host.Host, out var addresses, IsIpv4Enabled, IsIpv6Enabled); + result = GetBindInterface(addresses.FirstOrDefault(), out port); + port ??= source.Host.Port; + + return result; } - /// - /// Initialises internal LAN cache settings. - /// - private void InitialiseLAN(NetworkConfiguration config) + /// + public string GetBindInterface(IPAddress? source, out int? port) { - lock (_intLock) + port = null; + + string result; + + if (source != null) { - _logger.LogDebug("Refreshing LAN information."); + if (IsIpv4Enabled && source.AddressFamily == AddressFamily.InterNetworkV6) + { + _logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); + } - // Get configuration options. - string[] subnets = config.LocalNetworkSubnets; + if (IsIpv6Enabled && source.AddressFamily == AddressFamily.InterNetwork) + { + _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); + } - // Create lists from user settings. + bool isExternal = !_lanSubnets.Any(network => network.Contains(source)); + _logger.LogDebug("GetBindInterface with source. External: {IsExternal}:", isExternal); - _lanSubnets = CreateIPCollection(subnets); - _excludedSubnets = CreateIPCollection(subnets, true).AsNetworks(); + if (MatchesPublishedServerUrl(source, isExternal, out string res, out port)) + { + _logger.LogInformation("{Source}: Using BindAddress {Address}:{Port}", source, res, port); + return res; + } - // If no LAN addresses are specified - all private subnets are deemed to be the LAN - _usingPrivateAddresses = _lanSubnets.Count == 0; + // No preference given, so move on to bind addresses. + if (MatchesBindInterface(source, isExternal, out result)) + { + return result; + } - // NOTE: The order of the commands generating the collection in this statement matters. - // Altering the order will cause the collections to be created incorrectly. - if (_usingPrivateAddresses) + if (isExternal && MatchesExternalInterface(source, out result)) { - _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))); + return result; + } + } - // Subnets are the same as the calculated internal interface. - _lanSubnets = new Collection(); + // Get the first LAN interface address that's not excluded and not a loopback address. + var availableInterfaces = _interfaces.Where(x => !IPAddress.IsLoopback(x.Address)) + .OrderByDescending(x => _bindAddresses.Contains(x.Address)) + .ThenByDescending(x => IsInLocalNetwork(x.Address)) + .ThenBy(x => x.Index); - if (IsIP6Enabled) + if (availableInterfaces.Any()) + { + if (source != null) + { + foreach (var intf in availableInterfaces) { - _lanSubnets.AddItem(IPNetAddress.Parse("fc00::/7")); // ULA - _lanSubnets.AddItem(IPNetAddress.Parse("fe80::/10")); // Site local + if (intf.Address.Equals(source)) + { + result = NetworkExtensions.FormatIpString(intf.Address); + _logger.LogDebug("{Source}: GetBindInterface: Has found matching interface. {Result}", source, result); + return result; + } } - if (IsIP4Enabled) + // Does the request originate in one of the interface subnets? + // (For systems with multiple internal network cards, and multiple subnets) + foreach (var intf in availableInterfaces) { - _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")); + if (intf.Subnet.Contains(source)) + { + result = NetworkExtensions.FormatIpString(intf.Address); + _logger.LogDebug("{Source}: GetBindInterface: Has source, matched best internal interface on range. {Result}", source, result); + return result; + } } } - else + + result = NetworkExtensions.FormatIpString(availableInterfaces.First().Address); + _logger.LogDebug("{Source}: GetBindInterface: Matched first internal interface. {Result}", source, result); + return result; + } + + // There isn't any others, so we'll use the loopback. + result = IsIpv4Enabled && !IsIpv6Enabled ? "127.0.0.1" : "::1"; + _logger.LogWarning("{Source}: GetBindInterface: Loopback {Result} returned.", source, result); + return result; + } + + /// + public List GetInternalBindAddresses() + { + if (_bindAddresses.Count == 0) + { + if (_bindExclusions.Count > 0) { - // Internal interfaces must be private, not excluded and part of the LocalNetworkSubnet. - _internalInterfaces = CreateCollection(_interfaceAddresses.Where(IsInLocalNetwork)); + // Return all the internal interfaces except the ones excluded. + return _interfaces.Where(p => !_bindExclusions.Contains(p.Address)).ToList(); } - _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, true).AsNetworks().AsString()); + // No bind address, so return all internal interfaces. + return _interfaces; } + + // Select all local bind addresses + return _interfaces.Where(x => _bindAddresses.Contains(x.Address)) + .Where(x => IsInLocalNetwork(x.Address)) + .OrderBy(x => x.Index).ToList(); } - /// - /// 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. - /// - private void InitialiseInterfaces() + /// + public bool IsInLocalNetwork(string address) { - lock (_intLock) + if (IPAddress.TryParse(address, out var ep)) { - _logger.LogDebug("Refreshing interfaces."); - - _interfaceNames.Clear(); - _interfaceAddresses.Clear(); - _macAddresses.Clear(); + return IPAddress.IsLoopback(ep) || (_lanSubnets.Any(x => x.Contains(ep)) && !_excludedSubnets.Any(x => x.Contains(ep))); + } - try + if (NetworkExtensions.TryParseHost(address, out var addresses, IsIpv4Enabled, IsIpv6Enabled)) + { + bool match = false; + foreach (var ept in addresses) { - IEnumerable nics = NetworkInterface.GetAllNetworkInterfaces() - .Where(i => i.SupportsMulticast && i.OperationalStatus == OperationalStatus.Up); + match |= IPAddress.IsLoopback(ept) || (_lanSubnets.Any(x => x.Contains(ept)) && !_excludedSubnets.Any(x => x.Contains(ept))); + } - foreach (NetworkInterface adapter in nics) - { - try - { - IPInterfaceProperties ipProperties = adapter.GetIPProperties(); - PhysicalAddress mac = adapter.GetPhysicalAddress(); + return match; + } - // populate mac list - if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && mac != null && mac != PhysicalAddress.None) - { - _macAddresses.Add(mac); - } + return false; + } - // 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, false); - - // 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, false); - - // 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 (Exception ex) - { - // Ignore error, and attempt to continue. - _logger.LogError(ex, "Error encountered parsing interfaces."); - } -#pragma warning restore CA1031 // Do not catch general exception types - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Error in InitialiseInterfaces."); - } + /// + public bool IsInLocalNetwork(IPAddress address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } - // If for some reason we don't have an interface info, resolve our DNS name. - if (_interfaceAddresses.Count == 0) - { - _logger.LogError("No interfaces information available. Resolving DNS name."); - IPHost host = new IPHost(Dns.GetHostName()); - foreach (var a in host.GetAddresses()) - { - _interfaceAddresses.AddItem(a); - } + // See conversation at https://github.com/jellyfin/jellyfin/pull/3515. + if (TrustAllIpv6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) + { + return true; + } - if (_interfaceAddresses.Count == 0) - { - _logger.LogWarning("No interfaces information available. Using loopback."); - } - } + // As private addresses can be redefined by Configuration.LocalNetworkAddresses + var match = CheckIfLanAndNotExcluded(address); - if (IsIP4Enabled) - { - _interfaceAddresses.AddItem(IPNetAddress.IP4Loopback); - } + return address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback) || match; + } + + private IPData? FindInterfaceForIp(IPAddress address, bool localNetwork = false) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } - if (IsIP6Enabled) + var interfaces = _interfaces; + + if (localNetwork) + { + interfaces = interfaces.Where(x => IsInLocalNetwork(x.Address)).ToList(); + } + + foreach (var intf in _interfaces) + { + if (intf.Subnet.Contains(address)) { - _interfaceAddresses.AddItem(IPNetAddress.IP6Loopback); + return intf; } + } + + return null; + } - _logger.LogDebug("Discovered {0} interfaces.", _interfaceAddresses.Count); - _logger.LogDebug("Interfaces addresses : {0}", _interfaceAddresses.AsString()); + private bool CheckIfLanAndNotExcluded(IPAddress address) + { + bool match = false; + foreach (var lanSubnet in _lanSubnets) + { + match |= lanSubnet.Contains(address); + } + + foreach (var excludedSubnet in _excludedSubnets) + { + match &= !excludedSubnet.Contains(address); } + + NetworkExtensions.IsIPv6LinkLocal(address); + return match; } /// - /// Attempts to match the source against a user defined bind interface. + /// Attempts to match the source against the published server URL overrides. /// /// IP source address to use. - /// True if the source is in the external subnet. - /// The published server url that matches the source address. + /// True if the source is in an external subnet. + /// The published server URL that matches the source address. /// The resultant port, if one exists. /// true if a match is found, false otherwise. - private bool MatchesPublishedServerUrl(IPObject source, bool isInExternalSubnet, out string bindPreference, out int? port) + private bool MatchesPublishedServerUrl(IPAddress source, bool isInExternalSubnet, out string bindPreference, out int? port) { bindPreference = string.Empty; port = null; + var validPublishedServerUrls = _publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.Any)).ToList(); + validPublishedServerUrls.AddRange(_publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.IPv6Any))); + validPublishedServerUrls.AddRange(_publishedServerUrls.Where(x => x.Key.Subnet.Contains(source))); + validPublishedServerUrls.Distinct(); + // Check for user override. - foreach (var addr in _publishedServerUrls) + foreach (var data in validPublishedServerUrls) { + // Get address interface + var intf = _interfaces.FirstOrDefault(s => s.Subnet.Contains(data.Key.Address)); + // Remaining. Match anything. - if (addr.Key.Address.Equals(IPAddress.Broadcast)) + if (data.Key.Address.Equals(IPAddress.Broadcast)) { - bindPreference = addr.Value; + bindPreference = data.Value; break; } - else if ((addr.Key.Address.Equals(IPAddress.Any) || addr.Key.Address.Equals(IPAddress.IPv6Any)) && isInExternalSubnet) + else if ((data.Key.Address.Equals(IPAddress.Any) || data.Key.Address.Equals(IPAddress.IPv6Any)) && isInExternalSubnet) { // External. - bindPreference = addr.Value; + bindPreference = data.Value; break; } - else if (addr.Key.Contains(source)) + else if (intf?.Address != null) { // Match ip address. - bindPreference = addr.Value; + bindPreference = data.Value; break; } } @@ -1220,12 +1052,11 @@ namespace Jellyfin.Networking.Manager /// True if the source is in the external subnet. /// The result, if a match is found. /// true if a match is found, false otherwise. - private bool MatchesBindInterface(IPObject source, bool isInExternalSubnet, out string result) + private bool MatchesBindInterface(IPAddress source, bool isInExternalSubnet, out string result) { result = string.Empty; - var addresses = _bindAddresses.Exclude(_bindExclusions, false); - int count = addresses.Count; + int count = _bindAddresses.Count; if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses[0].Equals(IPAddress.IPv6Any))) { // Ignore IPAny addresses. @@ -1234,24 +1065,25 @@ namespace Jellyfin.Networking.Manager if (count != 0) { - // Check to see if any of the bind interfaces are in the same subnet. - + // Check to see if any of the bind interfaces are in the same subnet as the source. IPAddress? defaultGateway = null; IPAddress? bindAddress = null; if (isInExternalSubnet) { // Find all external bind addresses. Store the default gateway, but check to see if there is a better match first. - foreach (var addr in addresses.OrderBy(p => p.Tag)) + foreach (var addr in _bindAddresses) { if (defaultGateway == null && !IsInLocalNetwork(addr)) { - defaultGateway = addr.Address; + defaultGateway = addr; } - if (bindAddress == null && addr.Contains(source)) + var intf = _interfaces.Where(x => x.Subnet.Contains(addr)).FirstOrDefault(); + + if (bindAddress == null && intf != null && intf.Subnet.Contains(source)) { - bindAddress = addr.Address; + bindAddress = intf.Address; } if (defaultGateway != null && bindAddress != null) @@ -1263,32 +1095,37 @@ namespace Jellyfin.Networking.Manager else { // Look for the best internal address. - bindAddress = addresses - .Where(p => IsInLocalNetwork(p) && (p.Contains(source) || p.Equals(IPAddress.None))) - .OrderBy(p => p.Tag) - .FirstOrDefault()?.Address; + foreach (var bA in _bindAddresses.Where(x => IsInLocalNetwork(x))) + { + var intf = FindInterfaceForIp(source, true); + if (intf != null) + { + bindAddress = intf.Address; + break; + } + } } if (bindAddress != null) { - result = FormatIP6String(bindAddress); - _logger.LogDebug("{Source}: GetBindInterface: Has source, found a match bind interface subnets. {Result}", source, result); + result = NetworkExtensions.FormatIpString(bindAddress); + _logger.LogDebug("{Source}: GetBindInterface: Has source, found a matching bind interface subnet. {Result}", source, result); return true; } if (isInExternalSubnet && defaultGateway != null) { - result = FormatIP6String(defaultGateway); + result = NetworkExtensions.FormatIpString(defaultGateway); _logger.LogDebug("{Source}: GetBindInterface: Using first user defined external interface. {Result}", source, result); return true; } - result = FormatIP6String(addresses[0].Address); + result = NetworkExtensions.FormatIpString(_bindAddresses[0]); _logger.LogDebug("{Source}: GetBindInterface: Selected first user defined interface. {Result}", source, result); if (isInExternalSubnet) { - _logger.LogWarning("{Source}: External request received, however, only an internal interface bind found.", source); + _logger.LogWarning("{Source}: External request received, only an internal interface bind found.", source); } return true; @@ -1303,30 +1140,29 @@ namespace Jellyfin.Networking.Manager /// IP source address to use. /// The result, if a match is found. /// true if a match is found, false otherwise. - private bool MatchesExternalInterface(IPObject source, out string result) + private bool MatchesExternalInterface(IPAddress source, out string result) { result = string.Empty; // Get the first WAN interface address that isn't a loopback. - var extResult = _interfaceAddresses - .Exclude(_bindExclusions, false) - .Where(p => !IsInLocalNetwork(p)) - .OrderBy(p => p.Tag); + var extResult = _interfaces.Where(p => !IsInLocalNetwork(p.Address)); - if (extResult.Any()) + IPAddress? hasResult = null; + // 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) { - // 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) + hasResult ??= intf.Address; + if (!IsInLocalNetwork(intf.Address) && intf.Subnet.Contains(source)) { - if (!IsInLocalNetwork(intf) && intf.Contains(source)) - { - result = FormatIP6String(intf.Address); - _logger.LogDebug("{Source}: GetBindInterface: Selected best external on interface on range. {Result}", source, result); - return true; - } + result = NetworkExtensions.FormatIpString(intf.Address); + _logger.LogDebug("{Source}: GetBindInterface: Selected best external on interface on range. {Result}", source, result); + return true; } + } - result = FormatIP6String(extResult.First().Address); + if (hasResult != null) + { + result = NetworkExtensions.FormatIpString(hasResult); _logger.LogDebug("{Source}: GetBindInterface: Selected first external interface. {Result}", source, result); return true; } diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 66fa3bc31b..7030b726cd 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -344,13 +344,13 @@ namespace Jellyfin.Server.Extensions { for (var i = 0; i < allowedProxies.Length; i++) { - if (IPNetAddress.TryParse(allowedProxies[i], out var addr)) + if (IPAddress.TryParse(allowedProxies[i], out var addr)) { - AddIpAddress(config, options, addr.Address, addr.PrefixLength); + AddIpAddress(config, options, addr, addr.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); } - else if (IPHost.TryParse(allowedProxies[i], out var host)) + else if (NetworkExtensions.TryParseHost(allowedProxies[i], out var host)) { - foreach (var address in host.GetAddresses()) + foreach (var address in host) { AddIpAddress(config, options, address, address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); } diff --git a/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs b/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs index 5e601ca847..ceeaa26e62 100644 --- a/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs +++ b/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs @@ -114,9 +114,7 @@ public class CreateNetworkConfiguration : IMigrationRoutine public bool IgnoreVirtualInterfaces { get; set; } = true; - public string VirtualInterfaceNames { get; set; } = "vEthernet*"; - - public bool TrustAllIP6Interfaces { get; set; } + public string VirtualInterfaceNames { get; set; } = "veth*"; public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty(); diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 2bda8d2905..63055a61d4 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -300,7 +300,7 @@ namespace Jellyfin.Server var addresses = appHost.NetManager.GetAllBindInterfaces(); bool flagged = false; - foreach (IPObject netAdd in addresses) + foreach (IPData netAdd in addresses) { _logger.LogInformation("Kestrel listening on {Address}", netAdd.Address == IPAddress.IPv6Any ? "All Addresses" : netAdd); options.Listen(netAdd.Address, appHost.HttpPort); @@ -689,10 +689,10 @@ namespace Jellyfin.Server if (!string.IsNullOrEmpty(socketPerms)) { - #pragma warning disable SA1300 // Entrypoint is case sensitive. +#pragma warning disable SA1300 // Entrypoint is case sensitive. [DllImport("libc")] static extern int chmod(string pathname, int mode); - #pragma warning restore SA1300 +#pragma warning restore SA1300 var exitCode = chmod(socketPath, Convert.ToInt32(socketPerms, 8)); diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index b939397301..fdf42bdbce 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -18,44 +18,29 @@ namespace MediaBrowser.Common.Net event EventHandler NetworkChanged; /// - /// Gets the published server urls list. + /// Gets a value indicating whether iP6 is enabled. /// - Dictionary PublishedServerUrls { get; } + bool IsIpv6Enabled { get; } /// - /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. + /// Gets a value indicating whether iP4 is enabled. /// - bool TrustAllIP6Interfaces { get; } - - /// - /// Gets the remote address filter. - /// - Collection RemoteAddressFilter { get; } - - /// - /// Gets or sets a value indicating whether iP6 is enabled. - /// - bool IsIP6Enabled { get; set; } - - /// - /// Gets or sets a value indicating whether iP4 is enabled. - /// - bool IsIP4Enabled { get; set; } + bool IsIpv4Enabled { get; } /// /// Calculates the list of interfaces to use for Kestrel. /// - /// A Collection{IPObject} object containing all the interfaces to bind. + /// A List{IPData} 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. /// When false, return or for all interfaces. - Collection GetAllBindInterfaces(bool individualInterfaces = false); + List GetAllBindInterfaces(bool individualInterfaces = false); /// /// Returns a collection containing the loopback interfaces. /// - /// Collection{IPObject}. - Collection GetLoopbacks(); + /// List{IPData}. + List GetLoopbacks(); /// /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) @@ -86,22 +71,12 @@ namespace MediaBrowser.Common.Net /// Source of the request. /// Optional port returned, if it's part of an override. /// IP Address to use, or loopback address if all else fails. - string GetBindInterface(IPObject source, out int? port); - - /// - /// 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 . - /// - /// Source of the request. - /// Optional port returned, if it's part of an override. - /// IP Address to use, or loopback address if all else fails. string GetBindInterface(HttpRequest source, out int? port); /// /// 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 . /// /// IP address of the request. /// Optional port returned, if it's part of an override. @@ -111,48 +86,19 @@ namespace MediaBrowser.Common.Net /// /// 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 . /// /// Source of the request. /// Optional port returned, if it's part of an override. /// IP Address to use, or loopback address if all else fails. string GetBindInterface(string source, out int? port); - /// - /// Checks to see if the ip address is specifically excluded in LocalNetworkAddresses. - /// - /// IP address to check. - /// True if it is. - bool IsExcludedInterface(IPAddress address); - /// /// Get a list of all the MAC addresses associated with active interfaces. /// /// List of MAC addresses. IReadOnlyCollection GetMacAddresses(); - /// - /// Checks to see if the IP Address provided matches an interface that has a gateway. - /// - /// IP to check. Can be an IPAddress or an IPObject. - /// Result of the check. - bool IsGatewayInterface(IPObject? addressObj); - - /// - /// Checks to see if the IP Address provided matches an interface that has a gateway. - /// - /// IP to check. Can be an IPAddress or an IPObject. - /// Result of the check. - bool IsGatewayInterface(IPAddress? addressObj); - - /// - /// Returns true if the address is a private address. - /// The configuration option TrustIP6Interfaces overrides this functions behaviour. - /// - /// Address to check. - /// True or False. - bool IsPrivateAddressRange(IPObject address); - /// /// Returns true if the address is part of the user defined LAN. /// The configuration option TrustIP6Interfaces overrides this functions behaviour. @@ -161,14 +107,6 @@ namespace MediaBrowser.Common.Net /// True if endpoint is within the LAN range. bool IsInLocalNetwork(string address); - /// - /// Returns true if the address is part of the user defined LAN. - /// The configuration option TrustIP6Interfaces overrides this functions behaviour. - /// - /// IP to check. - /// True if endpoint is within the LAN range. - bool IsInLocalNetwork(IPObject address); - /// /// Returns true if the address is part of the user defined LAN. /// The configuration option TrustIP6Interfaces overrides this functions behaviour. @@ -178,55 +116,19 @@ namespace MediaBrowser.Common.Net bool IsInLocalNetwork(IPAddress address); /// - /// Attempts to convert the token to an IP address, permitting for interface descriptions and indexes. - /// eg. "eth1", or "TP-LINK Wireless USB Adapter". + /// Attempts to convert the interface name to an IP address. + /// eg. "eth1", or "enp3s5". /// - /// Token to parse. + /// Interface name. /// Resultant object's ip addresses, if successful. /// Success of the operation. - bool TryParseInterface(string token, out Collection? result); - - /// - /// Parses an array of strings into a Collection{IPObject}. - /// - /// Values to parse. - /// When true, only include values beginning with !. When false, ignore ! values. - /// IPCollection object containing the value strings. - Collection CreateIPCollection(string[] values, bool negated = false); + bool TryParseInterface(string intf, out Collection? result); /// /// Returns all the internal Bind interface addresses. /// /// An internal list of interfaces addresses. - Collection GetInternalBindAddresses(); - - /// - /// Checks to see if an IP address is still a valid interface address. - /// - /// IP address to check. - /// True if it is. - bool IsValidInterfaceAddress(IPAddress address); - - /// - /// Returns true if the IP address is in the excluded list. - /// - /// IP to check. - /// True if excluded. - bool IsExcluded(IPAddress ip); - - /// - /// Returns true if the IP address is in the excluded list. - /// - /// IP to check. - /// True if excluded. - bool IsExcluded(EndPoint ip); - - /// - /// Gets the filtered LAN ip addresses. - /// - /// Optional filter for the list. - /// Returns a filtered list of LAN addresses. - Collection GetFilteredLANSubnets(Collection? filter = null); + List GetInternalBindAddresses(); /// /// Checks to see if has access. diff --git a/MediaBrowser.Common/Net/IPData.cs b/MediaBrowser.Common/Net/IPData.cs new file mode 100644 index 0000000000..3c6adc7e86 --- /dev/null +++ b/MediaBrowser.Common/Net/IPData.cs @@ -0,0 +1,76 @@ +using System.Net; +using System.Net.Sockets; +using Microsoft.AspNetCore.HttpOverrides; + +namespace MediaBrowser.Common.Net +{ + /// + /// Base network object class. + /// + public class IPData + { + /// + /// Initializes a new instance of the class. + /// + /// An . + /// The . + public IPData( + IPAddress address, + IPNetwork? subnet) + { + Address = address; + Subnet = subnet ?? (address.AddressFamily == AddressFamily.InterNetwork ? new IPNetwork(address, 32) : new IPNetwork(address, 128)); + Name = string.Empty; + } + + /// + /// Initializes a new instance of the class. + /// + /// An . + /// The . + /// The object's name. + public IPData( + IPAddress address, + IPNetwork? subnet, + string name) + { + Address = address; + Subnet = subnet ?? (address.AddressFamily == AddressFamily.InterNetwork ? new IPNetwork(address, 32) : new IPNetwork(address, 128)); + Name = name; + } + + /// + /// Gets or sets the object's IP address. + /// + public IPAddress Address { get; set; } + + /// + /// Gets or sets the object's IP address. + /// + public IPNetwork Subnet { get; set; } + + /// + /// Gets or sets the interface index. + /// + public int Index { get; set; } + + /// + /// Gets or sets the interface name. + /// + public string Name { get; set; } + + /// + /// Gets the AddressFamily of this object. + /// + public AddressFamily AddressFamily + { + get + { + return Address.Equals(IPAddress.None) + ? (Subnet.Prefix.AddressFamily.Equals(IPAddress.None) + ? AddressFamily.Unspecified : Subnet.Prefix.AddressFamily) + : Address.AddressFamily; + } + } + } +} diff --git a/MediaBrowser.Common/Net/IPHost.cs b/MediaBrowser.Common/Net/IPHost.cs deleted file mode 100644 index 1f125f2b1d..0000000000 --- a/MediaBrowser.Common/Net/IPHost.cs +++ /dev/null @@ -1,441 +0,0 @@ -using System; -using System.Diagnostics; -using System.Linq; -using System.Net; -using System.Net.Sockets; -using System.Text.RegularExpressions; - -namespace MediaBrowser.Common.Net -{ - /// - /// Object that holds a host name. - /// - public class IPHost : IPObject - { - /// - /// Gets or sets timeout value before resolve required, in minutes. - /// - public const int Timeout = 30; - - /// - /// Represents an IPHost that has no value. - /// - public static readonly IPHost None = new IPHost(string.Empty, IPAddress.None); - - /// - /// Time when last resolved in ticks. - /// - private DateTime? _lastResolved = null; - - /// - /// Gets the IP Addresses, attempting to resolve the name, if there are none. - /// - private IPAddress[] _addresses; - - /// - /// Initializes a new instance of the class. - /// - /// Host name to assign. - public IPHost(string name) - { - HostName = name ?? throw new ArgumentNullException(nameof(name)); - _addresses = Array.Empty(); - Resolved = false; - } - - /// - /// Initializes a new instance of the class. - /// - /// Host name to assign. - /// Address to assign. - 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); - } - - /// - /// Gets or sets the object's first IP address. - /// - 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."); - } - } - - /// - /// Gets or sets the object's first IP's subnet prefix. - /// The setter does nothing, but shouldn't raise an exception. - /// - public override byte PrefixLength - { - get => (byte)(ResolveHost() ? 128 : 32); - - // 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. - set => throw new NotImplementedException(); - } - - /// - /// Gets a value indicating whether the address has a value. - /// - public bool HasAddress => _addresses.Length != 0; - - /// - /// Gets the host name of this object. - /// - public string HostName { get; } - - /// - /// Gets a value indicating whether this host has attempted to be resolved. - /// - public bool Resolved { get; private set; } - - /// - /// Gets or sets the IP Addresses associated with this object. - /// - /// Index of address. - public IPAddress this[int index] - { - get - { - ResolveHost(); - return index >= 0 && index < _addresses.Length ? _addresses[index] : IPAddress.None; - } - } - - /// - /// Attempts to parse the host string. - /// - /// Host name to parse. - /// Object representing the string, if it has successfully been parsed. - /// true if the parsing is successful, false if not. - public static bool TryParse(string host, out IPHost hostObj) - { - if (string.IsNullOrWhiteSpace(host)) - { - hostObj = IPHost.None; - return false; - } - - // See if it's an IPv6 with port address e.g. [::1] or [::1]:120. - int i = host.IndexOf(']', StringComparison.Ordinal); - if (i != -1) - { - return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj); - } - - if (IPNetAddress.TryParse(host, out var netAddress)) - { - // Host name is an ip address, so fake resolve. - hostObj = new IPHost(host, netAddress.Address); - return true; - } - - // Is it a host, IPv4/6 with/out port? - string[] hosts = host.Split(':'); - - if (hosts.Length <= 2) - { - // This is either a hostname: port, or an IP4:port. - host = hosts[0]; - - if (string.Equals("localhost", host, StringComparison.OrdinalIgnoreCase)) - { - hostObj = new IPHost(host); - return true; - } - - if (IPAddress.TryParse(host, out var netIP)) - { - // Host name is an ip address, so fake resolve. - hostObj = new IPHost(host, netIP); - return true; - } - } - else - { - // Invalid host name, as it cannot contain : - hostObj = new IPHost(string.Empty, IPAddress.None); - return false; - } - - // 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 - string pattern = @"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)$"; - - if (Regex.IsMatch(host, pattern)) - { - hostObj = new IPHost(host); - return true; - } - - hostObj = IPHost.None; - return false; - } - - /// - /// Attempts to parse the host string. - /// - /// Host name to parse. - /// Object representing the string, if it has successfully been parsed. - 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}"); - } - - /// - /// Attempts to parse the host string, ensuring that it resolves only to a specific IP type. - /// - /// Host name to parse. - /// Addressfamily filter. - /// Object representing the string, if it has successfully been parsed. - 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}"); - } - - /// - /// Returns the Addresses that this item resolved to. - /// - /// IPAddress Array. - public IPAddress[] GetAddresses() - { - ResolveHost(); - return _addresses; - } - - /// - 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; - } - - /// - 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; - } - - /// - 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; - } - - /// - 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 if (i.AddressFamily == AddressFamily.InterNetwork) - { - output += $"{i}/32,"; - } - else - { - output += $"{i}/128,"; - } - } - - output = output[..^1]; - - if (moreThanOne) - { - output += "]"; - } - } - else - { - output = HostName; - } - - return output; - } - - /// - public override void Remove(AddressFamily family) - { - if (ResolveHost()) - { - _addresses = _addresses.Where(p => p.AddressFamily != family).ToArray(); - } - } - - /// - public override bool Contains(IPObject address) - { - // An IPHost cannot contain another IPObject, it can only be equal. - return Equals(address); - } - - /// - protected override IPObject CalculateNetworkAddress() - { - var (address, prefixLength) = NetworkAddressOf(this[0], PrefixLength); - return new IPNetAddress(address, prefixLength); - } - - /// - /// Attempt to resolve the ip address of a host. - /// - /// true if any addresses have been resolved, otherwise false. - private bool ResolveHost() - { - // When was the last time we resolved? - _lastResolved ??= DateTime.UtcNow; - - // If we haven't resolved before, or our timer has run out... - if ((_addresses.Length == 0 && !Resolved) || (DateTime.UtcNow > _lastResolved.Value.AddMinutes(Timeout))) - { - _lastResolved = DateTime.UtcNow; - ResolveHostInternal(); - Resolved = true; - } - - return _addresses.Length > 0; - } - - /// - /// Task that looks up a Host name and returns its IP addresses. - /// - private void ResolveHostInternal() - { - var hostName = HostName; - if (string.IsNullOrEmpty(hostName)) - { - return; - } - - // Resolves the host name - so save a DNS lookup. - if (string.Equals(hostName, "localhost", StringComparison.OrdinalIgnoreCase)) - { - _addresses = new IPAddress[] { IPAddress.Loopback, IPAddress.IPv6Loopback }; - return; - } - - if (Uri.CheckHostName(hostName) == UriHostNameType.Dns) - { - try - { - _addresses = Dns.GetHostEntry(hostName).AddressList; - } - catch (SocketException ex) - { - // Log and then ignore socket errors, as the result value will just be an empty array. - Debug.WriteLine("GetHostAddresses failed with {Message}.", ex.Message); - } - } - } - } -} diff --git a/MediaBrowser.Common/Net/IPNetAddress.cs b/MediaBrowser.Common/Net/IPNetAddress.cs deleted file mode 100644 index f1428d4bef..0000000000 --- a/MediaBrowser.Common/Net/IPNetAddress.cs +++ /dev/null @@ -1,276 +0,0 @@ -using System; -using System.Net; -using System.Net.Sockets; - -namespace MediaBrowser.Common.Net -{ - /// - /// An object that holds and IP address and subnet mask. - /// - public class IPNetAddress : IPObject - { - /// - /// Represents an IPNetAddress that has no value. - /// - public static readonly IPNetAddress None = new IPNetAddress(IPAddress.None); - - /// - /// IPv4 multicast address. - /// - public static readonly IPAddress SSDPMulticastIPv4 = IPAddress.Parse("239.255.255.250"); - - /// - /// IPv6 local link multicast address. - /// - public static readonly IPAddress SSDPMulticastIPv6LinkLocal = IPAddress.Parse("ff02::C"); - - /// - /// IPv6 site local multicast address. - /// - public static readonly IPAddress SSDPMulticastIPv6SiteLocal = IPAddress.Parse("ff05::C"); - - /// - /// IP4Loopback address host. - /// - public static readonly IPNetAddress IP4Loopback = IPNetAddress.Parse("127.0.0.1/8"); - - /// - /// IP6Loopback address host. - /// - public static readonly IPNetAddress IP6Loopback = new IPNetAddress(IPAddress.IPv6Loopback); - - /// - /// Object's IP address. - /// - private IPAddress _address; - - /// - /// Initializes a new instance of the class. - /// - /// Address to assign. - public IPNetAddress(IPAddress address) - { - _address = address ?? throw new ArgumentNullException(nameof(address)); - PrefixLength = (byte)(address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); - } - - /// - /// Initializes a new instance of the class. - /// - /// IP Address. - /// Mask as a CIDR. - public IPNetAddress(IPAddress address, byte prefixLength) - { - if (address?.IsIPv4MappedToIPv6 ?? throw new ArgumentNullException(nameof(address))) - { - _address = address.MapToIPv4(); - } - else - { - _address = address; - } - - PrefixLength = prefixLength; - } - - /// - /// Gets or sets the object's IP address. - /// - public override IPAddress Address - { - get - { - return _address; - } - - set - { - _address = value ?? IPAddress.None; - } - } - - /// - public override byte PrefixLength { get; set; } - - /// - /// Try to parse the address and subnet strings into an IPNetAddress object. - /// - /// IP address to parse. Can be CIDR or X.X.X.X notation. - /// Resultant object. - /// True if the values parsed successfully. False if not, resulting in the IP being null. - 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; - } - - /// - /// Parses the string provided, throwing an exception if it is badly formed. - /// - /// String to parse. - /// IPNetAddress object. - public static IPNetAddress Parse(string addr) - { - if (TryParse(addr, out IPNetAddress o)) - { - return o; - } - - throw new ArgumentException("Unable to recognise object :" + addr); - } - - /// - public override bool Contains(IPAddress address) - { - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } - - if (address.IsIPv4MappedToIPv6) - { - address = address.MapToIPv4(); - } - - var (altAddress, altPrefix) = NetworkAddressOf(address, PrefixLength); - return NetworkAddress.Address.Equals(altAddress) && NetworkAddress.PrefixLength >= altPrefix; - } - - /// - 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).Address; - return NetworkAddress.Address.Equals(altAddress); - } - - return false; - } - - /// - 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; - } - - /// - public override bool Equals(IPAddress ip) - { - if (ip != null && !ip.Equals(IPAddress.None) && !Address.Equals(IPAddress.None)) - { - return ip.Equals(Address); - } - - return false; - } - - /// - public override string ToString() - { - return ToString(false); - } - - /// - /// Returns a textual representation of this object. - /// - /// Set to true, if the subnet is to be excluded as part of the address. - /// String representation of this object. - 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; - } - - /// - protected override IPObject CalculateNetworkAddress() - { - var (address, prefixLength) = NetworkAddressOf(_address, PrefixLength); - return new IPNetAddress(address, prefixLength); - } - } -} diff --git a/MediaBrowser.Common/Net/IPObject.cs b/MediaBrowser.Common/Net/IPObject.cs deleted file mode 100644 index 3a5187bc3d..0000000000 --- a/MediaBrowser.Common/Net/IPObject.cs +++ /dev/null @@ -1,370 +0,0 @@ -using System; -using System.Net; -using System.Net.Sockets; - -namespace MediaBrowser.Common.Net -{ - /// - /// Base network object class. - /// - public abstract class IPObject : IEquatable - { - /// - /// The network address of this object. - /// - private IPObject? _networkAddress; - - /// - /// Gets or sets a user defined value that is associated with this object. - /// - public int Tag { get; set; } - - /// - /// Gets or sets the object's IP address. - /// - public abstract IPAddress Address { get; set; } - - /// - /// Gets the object's network address. - /// - public IPObject NetworkAddress => _networkAddress ??= CalculateNetworkAddress(); - - /// - /// Gets or sets the object's IP address. - /// - public abstract byte PrefixLength { get; set; } - - /// - /// Gets the AddressFamily of this object. - /// - 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; - } - } - - /// - /// Returns the network address of an object. - /// - /// IP Address to convert. - /// Subnet prefix. - /// IPAddress. - 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 (IPAddress.IsLoopback(address)) - { - return (address, 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. - - // GetAddressBytes - Span addressBytes = stackalloc byte[address.AddressFamily == AddressFamily.InterNetwork ? 4 : 16]; - address.TryWriteBytes(addressBytes, out _); - - 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 (new IPAddress(addressBytes), prefixLength); - } - - /// - /// Tests to see if the ip address is an IP6 address. - /// - /// Value to test. - /// True if it is. - 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); - } - - /// - /// Tests to see if the address in the private address range. - /// - /// Object to test. - /// True if it contains a private address. - public static bool IsPrivateAddressRange(IPAddress address) - { - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } - - if (!address.Equals(IPAddress.None)) - { - if (address.IsIPv4MappedToIPv6) - { - address = address.MapToIPv4(); - } - - if (address.AddressFamily == AddressFamily.InterNetwork) - { - // GetAddressBytes - Span octet = stackalloc byte[4]; - address.TryWriteBytes(octet, out _); - - 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 - { - // GetAddressBytes - Span octet = stackalloc byte[16]; - address.TryWriteBytes(octet, out _); - - 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; - } - - /// - /// Returns true if the IPAddress contains an IP6 Local link address. - /// - /// IPAddress object to check. - /// True if it is a local link address. - /// - /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress - /// it appears that the IPAddress.IsIPv6LinkLocal is out of date. - /// - 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; - } - - // GetAddressBytes - Span octet = stackalloc byte[16]; - address.TryWriteBytes(octet, out _); - uint word = (uint)(octet[0] << 8) + octet[1]; - - return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link. - } - - /// - /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. - /// - /// Subnet mask in CIDR notation. - /// IPv4 or IPv6 family. - /// String value of the subnet mask in dotted decimal notation. - 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); - } - - /// - /// Convert a mask to a CIDR. IPv4 only. - /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask. - /// - /// Subnet mask. - /// Byte CIDR representing the mask. - public static byte MaskToCidr(IPAddress mask) - { - if (mask == null) - { - throw new ArgumentNullException(nameof(mask)); - } - - byte cidrnet = 0; - if (!mask.Equals(IPAddress.Any)) - { - // GetAddressBytes - Span bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16]; - mask.TryWriteBytes(bytes, out _); - - 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; - } - - /// - /// Tests to see if this object is a Loopback address. - /// - /// True if it is. - public virtual bool IsLoopback() - { - return IPAddress.IsLoopback(Address); - } - - /// - /// Removes all addresses of a specific type from this object. - /// - /// Type of address to remove. - public virtual void Remove(AddressFamily family) - { - // This method only performs a function in the IPHost implementation of IPObject. - } - - /// - /// Tests to see if this object is an IPv6 address. - /// - /// True if it is. - public virtual bool IsIP6() - { - return IsIP6(Address); - } - - /// - /// Returns true if this IP address is in the RFC private address range. - /// - /// True this object has a private address. - public virtual bool IsPrivateAddressRange() - { - return IsPrivateAddressRange(Address); - } - - /// - /// Compares this to the object passed as a parameter. - /// - /// Object to compare to. - /// Equality result. - 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; - } - - /// - /// Compares this to the object passed as a parameter. - /// - /// Object to compare to. - /// Equality result. - public virtual bool Equals(IPObject? other) - { - if (other != null) - { - return !Address.Equals(IPAddress.None) && Address.Equals(other.Address); - } - - return false; - } - - /// - /// Compares the address in this object and the address in the object passed as a parameter. - /// - /// Object's IP address to compare to. - /// Comparison result. - public abstract bool Contains(IPObject address); - - /// - /// Compares the address in this object and the address in the object passed as a parameter. - /// - /// Object's IP address to compare to. - /// Comparison result. - public abstract bool Contains(IPAddress address); - - /// - public override int GetHashCode() - { - return Address.GetHashCode(); - } - - /// - public override bool Equals(object? obj) - { - return Equals(obj as IPObject); - } - - /// - /// Calculates the network address of this object. - /// - /// Returns the network address of this object. - protected abstract IPObject CalculateNetworkAddress(); - } -} diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 264bfacb49..55ec322f43 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -1,6 +1,9 @@ using System; -using System.Collections.ObjectModel; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Net; +using System.Net.Sockets; +using System.Text.RegularExpressions; namespace MediaBrowser.Common.Net { @@ -10,251 +13,209 @@ namespace MediaBrowser.Common.Net public static class NetworkExtensions { /// - /// Add an address to the collection. + /// Returns true if the IPAddress contains an IP6 Local link address. /// - /// The . - /// Item to add. - public static void AddItem(this Collection source, IPAddress ip) + /// IPAddress object to check. + /// True if it is a local link address. + /// + /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress + /// it appears that the IPAddress.IsIPv6LinkLocal is out of date. + /// + public static bool IsIPv6LinkLocal(IPAddress address) { - if (!source.ContainsAddress(ip)) + if (address == null) { - source.Add(new IPNetAddress(ip, 32)); + throw new ArgumentNullException(nameof(address)); } - } - /// - /// Adds a network to the collection. - /// - /// The . - /// Item to add. - /// If true the values are treated as subnets. - /// If false items are addresses. - public static void AddItem(this Collection source, IPObject item, bool itemsAreNetworks = true) - { - if (!source.ContainsAddress(item) || !itemsAreNetworks) + if (address.IsIPv4MappedToIPv6) { - source.Add(item); + address = address.MapToIPv4(); } - } - /// - /// Converts this object to a string. - /// - /// The . - /// Returns a string representation of this object. - public static string AsString(this Collection source) - { - return $"[{string.Join(',', source)}]"; - } - - /// - /// 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. - /// - /// The . - /// The item to look for. - /// True if the collection contains the item. - public static bool ContainsAddress(this Collection source, IPAddress item) - { - if (source.Count == 0) + if (address.AddressFamily != AddressFamily.InterNetworkV6) { return false; } - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } - - if (item.IsIPv4MappedToIPv6) - { - item = item.MapToIPv4(); - } + // GetAddressBytes + Span octet = stackalloc byte[16]; + address.TryWriteBytes(octet, out _); + uint word = (uint)(octet[0] << 8) + octet[1]; - foreach (var i in source) - { - if (i.Contains(item)) - { - return true; - } - } + return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link. + } - return false; + /// + /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. + /// + /// Subnet mask in CIDR notation. + /// IPv4 or IPv6 family. + /// String value of the subnet mask in dotted decimal notation. + 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); } /// - /// 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. + /// Convert a subnet mask to a CIDR. IPv4 only. + /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask. /// - /// The . - /// The item to look for. - /// True if the collection contains the item. - public static bool ContainsAddress(this Collection source, IPObject item) + /// Subnet mask. + /// Byte CIDR representing the mask. + public static byte MaskToCidr(IPAddress mask) { - if (source.Count == 0) + if (mask == null) { - return false; + throw new ArgumentNullException(nameof(mask)); } - if (item == null) + byte cidrnet = 0; + if (!mask.Equals(IPAddress.Any)) { - throw new ArgumentNullException(nameof(item)); - } + // GetAddressBytes + Span bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16]; + mask.TryWriteBytes(bytes, out _); - foreach (var i in source) - { - if (i.Contains(item)) + var zeroed = false; + for (var i = 0; i < bytes.Length; i++) { - return true; + 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 false; + return cidrnet; } /// - /// Compares two Collection{IPObject} objects. The order is ignored. + /// Converts an IPAddress into a string. + /// Ipv6 addresses are returned in [ ], with their scope removed. /// - /// The . - /// Item to compare to. - /// True if both are equal. - public static bool Compare(this Collection source, Collection dest) + /// Address to convert. + /// URI safe conversion of the address. + public static string FormatIpString(IPAddress? address) { - if (dest == null || source.Count != dest.Count) + if (address == null) { - return false; + return string.Empty; } - foreach (var sourceItem in source) + var str = address.ToString(); + if (address.AddressFamily == AddressFamily.InterNetworkV6) { - bool found = false; - foreach (var destItem in dest) + int i = str.IndexOf('%', StringComparison.Ordinal); + if (i != -1) { - if (sourceItem.Equals(destItem)) - { - found = true; - break; - } + str = str.Substring(0, i); } - if (!found) - { - return false; - } + return $"[{str}]"; } - return true; + return str; } /// - /// Returns a collection containing the subnets of this collection given. + /// Attempts to parse a host string. /// - /// The . - /// Collection{IPObject} object containing the subnets. - public static Collection AsNetworks(this Collection source) + /// Host name to parse. + /// Object representing the string, if it has successfully been parsed. + /// true if IPv4 is enabled. + /// true if IPv6 is enabled. + /// true if the parsing is successful, false if not. + public static bool TryParseHost(string host, [NotNullWhen(true)] out IPAddress[] addresses, bool isIpv4Enabled = true, bool isIpv6Enabled = false) { - if (source == null) + if (string.IsNullOrWhiteSpace(host)) { - throw new ArgumentNullException(nameof(source)); + addresses = Array.Empty(); + return false; } - Collection res = new Collection(); + host = host.Trim(); - foreach (IPObject i in source) + // See if it's an IPv6 with port address e.g. [::1] or [::1]:120. + if (host[0] == '[') { - 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) + int i = host.IndexOf(']', StringComparison.Ordinal); + if (i != -1) { - // 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 TryParseHost(host.Remove(i)[1..], out addresses); } - } - - return res; - } - /// - /// Excludes all the items from this list that are found in excludeList. - /// - /// The . - /// Items to exclude. - /// Collection is a network collection. - /// A new collection, with the items excluded. - public static Collection Exclude(this Collection source, Collection excludeList, bool isNetwork) - { - if (source.Count == 0 || excludeList == null) - { - return new Collection(source); + addresses = Array.Empty(); + return false; } - Collection results = new Collection(); + var hosts = host.Split(':'); - bool found; - foreach (var outer in source) + if (hosts.Length <= 2) { - found = false; + // 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 + string pattern = @"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)(:(\d){1,5}){0,1}$"; - foreach (var inner in excludeList) + // Is hostname or hostname:port + if (Regex.IsMatch(hosts[0], pattern)) { - if (outer.Equals(inner)) + try + { + addresses = Dns.GetHostAddresses(hosts[0]); + return true; + } + catch (SocketException) { - found = true; - break; + // Log and then ignore socket errors, as the result value will just be an empty array. + Console.WriteLine("GetHostAddresses failed."); } } - if (!found) - { - results.AddItem(outer, isNetwork); - } - } + // Is an IP4 or IP4:port + host = hosts[0].Split('/')[0]; - return results; - } + if (IPAddress.TryParse(host, out var address)) + { + if (((address.AddressFamily == AddressFamily.InterNetwork) && (!isIpv4Enabled && isIpv6Enabled)) || + ((address.AddressFamily == AddressFamily.InterNetworkV6) && (isIpv4Enabled && !isIpv6Enabled))) + { + addresses = Array.Empty(); + return false; + } - /// - /// Returns all items that co-exist in this object and target. - /// - /// The . - /// Collection to compare with. - /// A collection containing all the matches. - public static Collection ThatAreContainedInNetworks(this Collection source, Collection target) - { - if (source.Count == 0) - { - return new Collection(); - } + addresses = new[] { address }; - if (target == null) - { - throw new ArgumentNullException(nameof(target)); + // Host name is an ip4 address, so fake resolve. + return true; + } } - - Collection nc = new Collection(); - - foreach (IPObject i in source) + else if (hosts.Length <= 9 && IPAddress.TryParse(host.Split('/')[0], out var address)) // 8 octets + port { - if (target.ContainsAddress(i)) - { - nc.AddItem(i); - } + addresses = new[] { address }; + return true; } - return nc; + addresses = Array.Empty(); + return false; } } } diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs index 11afdc4aed..45ac5c3a85 100644 --- a/MediaBrowser.Controller/IServerApplicationHost.cs +++ b/MediaBrowser.Controller/IServerApplicationHost.cs @@ -4,7 +4,6 @@ using System.Net; using MediaBrowser.Common; -using MediaBrowser.Common.Net; using MediaBrowser.Model.System; using Microsoft.AspNetCore.Http; @@ -75,10 +74,10 @@ namespace MediaBrowser.Controller /// /// Gets an URL that can be used to access the API over LAN. /// - /// An optional hostname to use. + /// An optional IP address to use. /// A value indicating whether to allow HTTPS. /// The API URL. - string GetApiUrlForLocalAccess(IPObject hostname = null, bool allowHttps = true); + string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true); /// /// Gets a local (LAN) URL that can be used to access the API. diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs index a7767b3c04..37c4128ba4 100644 --- a/RSSDP/SsdpDevicePublisher.cs +++ b/RSSDP/SsdpDevicePublisher.cs @@ -7,6 +7,7 @@ using System.Net; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Net; +using Microsoft.AspNetCore.HttpOverrides; namespace Rssdp.Infrastructure { @@ -297,9 +298,9 @@ namespace Rssdp.Infrastructure foreach (var device in deviceList) { 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)) + var source = new IPData(root.Address, new IPNetwork(root.Address, root.PrefixLength), root.FriendlyName); + var destination = new IPData(remoteEndPoint.Address, new IPNetwork(root.Address, root.PrefixLength)); + if (!_sendOnlyMatchedHost || source.Address.Equals(destination.Address)) { SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIpAddress, cancellationToken); } diff --git a/tests/Jellyfin.Networking.Tests/IPNetAddressTests.cs b/tests/Jellyfin.Networking.Tests/IPNetAddressTests.cs deleted file mode 100644 index aa2dbc57a2..0000000000 --- a/tests/Jellyfin.Networking.Tests/IPNetAddressTests.cs +++ /dev/null @@ -1,49 +0,0 @@ -using FsCheck; -using FsCheck.Xunit; -using MediaBrowser.Common.Net; -using Xunit; - -namespace Jellyfin.Networking.Tests -{ - public static class IPNetAddressTests - { - /// - /// Checks IP address formats. - /// - /// IP Address. - [Theory] - [InlineData("127.0.0.1")] - [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]")] - [InlineData("fe80::7add:12ff:febb:c67b%16")] - [InlineData("[fe80::7add:12ff:febb:c67b%16]:123")] - [InlineData("fe80::7add:12ff:febb:c67b%16:123")] - [InlineData("[fe80::7add:12ff:febb:c67b%16]")] - [InlineData("192.168.1.2/255.255.255.0")] - [InlineData("192.168.1.2/24")] - public static void TryParse_ValidIPStrings_True(string address) - => Assert.True(IPNetAddress.TryParse(address, out _)); - - [Property] - public static Property TryParse_IPv4Address_True(IPv4Address address) - => IPNetAddress.TryParse(address.Item.ToString(), out _).ToProperty(); - - [Property] - public static Property TryParse_IPv6Address_True(IPv6Address address) - => IPNetAddress.TryParse(address.Item.ToString(), out _).ToProperty(); - - /// - /// All should be invalid address strings. - /// - /// Invalid address strings. - [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")] - [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517:1231]")] - public static void TryParse_InvalidAddressString_False(string address) - => Assert.False(IPNetAddress.TryParse(address, out _)); - } -} diff --git a/tests/Jellyfin.Networking.Tests/IPHostTests.cs b/tests/Jellyfin.Networking.Tests/NetworkExtensionsTests.cs similarity index 80% rename from tests/Jellyfin.Networking.Tests/IPHostTests.cs rename to tests/Jellyfin.Networking.Tests/NetworkExtensionsTests.cs index ec3a1300c8..c81fdefe95 100644 --- a/tests/Jellyfin.Networking.Tests/IPHostTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkExtensionsTests.cs @@ -5,7 +5,7 @@ using Xunit; namespace Jellyfin.Networking.Tests { - public static class IPHostTests + public static class NetworkExtensionsTests { /// /// Checks IP address formats. @@ -27,15 +27,15 @@ namespace Jellyfin.Networking.Tests [InlineData("192.168.1.2/255.255.255.0")] [InlineData("192.168.1.2/24")] public static void TryParse_ValidHostStrings_True(string address) - => Assert.True(IPHost.TryParse(address, out _)); + => Assert.True(NetworkExtensions.TryParseHost(address, out _, true, true)); [Property] public static Property TryParse_IPv4Address_True(IPv4Address address) - => IPHost.TryParse(address.Item.ToString(), out _).ToProperty(); + => NetworkExtensions.TryParseHost(address.Item.ToString(), out _, true, true).ToProperty(); [Property] public static Property TryParse_IPv6Address_True(IPv6Address address) - => IPHost.TryParse(address.Item.ToString(), out _).ToProperty(); + => NetworkExtensions.TryParseHost(address.Item.ToString(), out _, true, true).ToProperty(); /// /// All should be invalid address strings. @@ -48,6 +48,6 @@ namespace Jellyfin.Networking.Tests [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517:1231")] [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517:1231]")] public static void TryParse_InvalidAddressString_False(string address) - => Assert.False(IPHost.TryParse(address, out _)); + => Assert.False(NetworkExtensions.TryParseHost(address, out _, true, true)); } } diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index 6b93974373..ce638c9136 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -1,10 +1,13 @@ using System; using System.Collections.ObjectModel; +using System.Globalization; +using System.Linq; using System.Net; using Jellyfin.Networking.Configuration; using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; +using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Logging.Abstractions; using Moq; using Xunit; @@ -46,6 +49,8 @@ namespace Jellyfin.Networking.Tests { EnableIPV6 = true, EnableIPV4 = true, + IgnoreVirtualInterfaces = true, + VirtualInterfaceNames = "veth", LocalNetworkSubnets = lan?.Split(';') ?? throw new ArgumentNullException(nameof(lan)) }; @@ -53,135 +58,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - Assert.Equal(nm.GetInternalBindAddresses().AsString(), value); - } - - /// - /// Test collection parsing. - /// - /// Collection to parse. - /// Included addresses from the collection. - /// Included IP4 addresses from the collection. - /// Excluded addresses from the collection. - /// Excluded IP4 addresses from the collection. - /// Network addresses of the collection. - [Theory] - [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/16, localhost, fd23:184f:2029:0:3139:7386:67d7:d517, !10.10.10.10", - "[192.158.1.2/16,[127.0.0.1/32,::1/128],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,::1/128,fd23:184f:2029:0:3139:7386:67d7:d517/128]")] - [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]")] - 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()); - - // Test included. - Collection nc = nm.CreateIPCollection(settings.Split(','), false); - Assert.Equal(nc.AsString(), result1); - - // Test excluded. - nc = nm.CreateIPCollection(settings.Split(','), true); - Assert.Equal(nc.AsString(), result3); - - conf.EnableIPV6 = false; - nm.UpdateSettings(conf); - - // Test IP4 included. - nc = nm.CreateIPCollection(settings.Split(','), false); - Assert.Equal(nc.AsString(), result2); - - // Test IP4 excluded. - nc = nm.CreateIPCollection(settings.Split(','), true); - Assert.Equal(nc.AsString(), result4); - - conf.EnableIPV6 = true; - nm.UpdateSettings(conf); - - // Test network addresses of collection. - nc = nm.CreateIPCollection(settings.Split(','), false); - nc = nc.AsNetworks(); - Assert.Equal(nc.AsString(), result5); - } - - /// - /// Union two collections. - /// - /// Source. - /// Destination. - /// Result. - [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()); - - Collection nc1 = nm.CreateIPCollection(settings.Split(','), false); - Collection nc2 = nm.CreateIPCollection(compare.Split(','), false); - - Assert.Equal(nc1.ThatAreContainedInNetworks(nc2).AsString(), result); + Assert.Equal(value, "[" + String.Join(",", nm.GetInternalBindAddresses().Select(x => x.Address + "/" + x.Subnet.PrefixLength)) + "]"); } [Theory] @@ -194,8 +71,11 @@ namespace Jellyfin.Networking.Tests [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))); + var split = netMask.Split("/"); + var mask = int.Parse(split[1], CultureInfo.InvariantCulture); + var ipa = IPAddress.Parse(split[0]); + var ipn = new IPNetwork(ipa, mask); + Assert.True(ipn.Contains(IPAddress.Parse(ipAddress))); } [Theory] @@ -207,8 +87,11 @@ namespace Jellyfin.Networking.Tests [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))); + var split = netMask.Split("/"); + var mask = int.Parse(split[1], CultureInfo.InvariantCulture); + var ipa = IPAddress.Parse(split[0]); + var ipn = new IPNetwork(ipa, mask); + Assert.False(ipn.Contains(IPAddress.Parse(ipAddress))); } [Theory] @@ -219,8 +102,11 @@ namespace Jellyfin.Networking.Tests [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))); + var split = netMask.Split("/"); + var mask = int.Parse(split[1], CultureInfo.InvariantCulture); + var ipa = IPAddress.Parse(split[0]); + var ipn = new IPNetwork(ipa, mask); + Assert.True(ipn.Contains(IPAddress.Parse(ipAddress))); } [Theory] @@ -231,86 +117,18 @@ namespace Jellyfin.Networking.Tests [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 TestSubnetContains(string network, string ip) - { - Assert.True(IPNetAddress.TryParse(network, out var networkObj)); - Assert.True(IPNetAddress.TryParse(ip, out var 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 TestCollectionEquality(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()); - - // Test included, IP6. - Collection ncSource = nm.CreateIPCollection(source.Split(',')); - Collection ncDest = nm.CreateIPCollection(dest.Split(',')); - Collection ncResult = ncSource.ThatAreContainedInNetworks(ncDest); - Collection 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))); + var split = netMask.Split("/"); + var mask = int.Parse(split[1], CultureInfo.InvariantCulture); + var ipa = IPAddress.Parse(split[0]); + var ipn = new IPNetwork(ipa, mask); + Assert.False(ipn.Contains(IPAddress.Parse(ipAddress))); } [Theory] - // Testing bind interfaces. // On my system eth16 is internal, eth11 external (Windows defines the indexes). // - // This test is to replicate how DNLA requests work throughout the system. + // This test is to replicate how DLNA 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")] @@ -357,14 +175,14 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - _ = nm.TryParseInterface(result, out Collection? resultObj); + _ = nm.TryParseInterface(result, out Collection? resultObj); // Check to see if dns resolution is working. If not, skip test. - _ = IPHost.TryParse(source, out var host); + _ = NetworkExtensions.TryParseHost(source, out var host); - if (resultObj != null && host?.HasAddress == true) + if (resultObj != null && host.Length > 0) { - result = ((IPNetAddress)resultObj[0]).ToString(true); + result = resultObj.First().Address.ToString(); var intf = nm.GetBindInterface(source, out _); Assert.Equal(intf, result); @@ -394,7 +212,7 @@ namespace Jellyfin.Networking.Tests [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")] + [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")] @@ -426,15 +244,15 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - if (nm.TryParseInterface(result, out Collection? resultObj) && resultObj != null) + if (nm.TryParseInterface(result, out Collection? resultObj) && resultObj != null) { // Parse out IPAddresses so we can do a string comparison. (Ignore subnet masks). - result = ((IPNetAddress)resultObj[0]).ToString(true); + result = resultObj.First().Address.ToString(); } var intf = nm.GetBindInterface(source, out int? _); - Assert.Equal(intf, result); + Assert.Equal(result, intf); } [Theory] @@ -461,6 +279,7 @@ namespace Jellyfin.Networking.Tests [InlineData("185.10.10.10", "79.2.3.4", false)] [InlineData("185.10.10.10", "185.10.10.10", true)] [InlineData("", "100.100.100.100", false)] + public void HasRemoteAccess_GivenBlacklist_BlacklistTheIps(string addresses, string remoteIp, bool denied) { // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely. From 997aa3f1e74d6bbe4f9f928e1162638d75feb12e Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Tue, 19 Jul 2022 21:53:10 +0200 Subject: [PATCH 005/358] Fix build --- Jellyfin.Networking/Manager/NetworkManager.cs | 14 +++++++------- MediaBrowser.Common/Net/INetworkManager.cs | 4 ++-- .../Jellyfin.Networking.Tests/NetworkParseTests.cs | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index f51fd85dd5..d9ef2c6a4c 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -241,7 +241,7 @@ namespace Jellyfin.Networking.Manager { var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength), adapter.Name); interfaceObject.Index = ipProperties.GetIPv4Properties().Index; - interfaceObject.Name = adapter.Name.ToLower(CultureInfo.InvariantCulture); + interfaceObject.Name = adapter.Name.ToLowerInvariant(); _interfaces.Add(interfaceObject); } @@ -249,7 +249,7 @@ namespace Jellyfin.Networking.Manager { var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength), adapter.Name); interfaceObject.Index = ipProperties.GetIPv6Properties().Index; - interfaceObject.Name = adapter.Name.ToLower(CultureInfo.InvariantCulture); + interfaceObject.Name = adapter.Name.ToLowerInvariant(); _interfaces.Add(interfaceObject); } @@ -381,7 +381,7 @@ namespace Jellyfin.Networking.Manager if (config.IgnoreVirtualInterfaces) { // Remove potentially exisiting * and split config string into prefixes - var virtualInterfacePrefixes = config.VirtualInterfaceNames.Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase).ToLower().Split(','); + var virtualInterfacePrefixes = config.VirtualInterfaceNames.Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase).ToLowerInvariant().Split(','); // Check all interfaces for matches against the prefixes and add the interface IPs to _bindExclusions if (_bindAddresses.Count > 0 && virtualInterfacePrefixes.Length > 0) @@ -419,10 +419,10 @@ namespace Jellyfin.Networking.Manager if (remoteIPFilter.Any() && !string.IsNullOrWhiteSpace(remoteIPFilter.First())) { // Parse all IPs with netmask to a subnet - _ = TryParseSubnets(remoteIPFilter.Where(x => x.Contains("/", StringComparison.OrdinalIgnoreCase)).ToArray(), out _remoteAddressFilter, false); + _ = TryParseSubnets(remoteIPFilter.Where(x => x.Contains('/', StringComparison.OrdinalIgnoreCase)).ToArray(), out _remoteAddressFilter, false); // Parse everything else as an IP and construct subnet with a single IP - var ips = remoteIPFilter.Where(x => !x.Contains("/", StringComparison.OrdinalIgnoreCase)); + var ips = remoteIPFilter.Where(x => !x.Contains('/', StringComparison.OrdinalIgnoreCase)); foreach (var ip in ips) { if (IPAddress.TryParse(ip, out var ipp)) @@ -573,7 +573,7 @@ namespace Jellyfin.Networking.Manager if (_interfaces != null) { // Match all interfaces starting with names starting with token - var matchedInterfaces = _interfaces.Where(s => s.Name.Equals(intf.ToLower(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase)); + var matchedInterfaces = _interfaces.Where(s => s.Name.Equals(intf.ToLowerInvariant(), StringComparison.OrdinalIgnoreCase)); if (matchedInterfaces.Any()) { _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", intf); @@ -998,7 +998,7 @@ namespace Jellyfin.Networking.Manager var validPublishedServerUrls = _publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.Any)).ToList(); validPublishedServerUrls.AddRange(_publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.IPv6Any))); validPublishedServerUrls.AddRange(_publishedServerUrls.Where(x => x.Key.Subnet.Contains(source))); - validPublishedServerUrls.Distinct(); + validPublishedServerUrls = validPublishedServerUrls.GroupBy(x => x.Key).Select(y => y.First()).ToList(); // Check for user override. foreach (var data in validPublishedServerUrls) diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index fdf42bdbce..9f48535576 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -18,12 +18,12 @@ namespace MediaBrowser.Common.Net event EventHandler NetworkChanged; /// - /// Gets a value indicating whether iP6 is enabled. + /// Gets a value indicating whether IPv6 is enabled. /// bool IsIpv6Enabled { get; } /// - /// Gets a value indicating whether iP4 is enabled. + /// Gets a value indicating whether IPv4 is enabled. /// bool IsIpv4Enabled { get; } diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index ce638c9136..d451fbaef1 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -58,7 +58,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - Assert.Equal(value, "[" + String.Join(",", nm.GetInternalBindAddresses().Select(x => x.Address + "/" + x.Subnet.PrefixLength)) + "]"); + Assert.Equal(value, "[" + string.Join(",", nm.GetInternalBindAddresses().Select(x => x.Address + "/" + x.Subnet.PrefixLength)) + "]"); } [Theory] From bdb148316719c32e2aa3a3eba94e161c7824dbac Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Tue, 19 Jul 2022 23:42:32 +0200 Subject: [PATCH 006/358] Add generic IPAddress.Parse tests --- .../NetworkParseTests.cs | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index d451fbaef1..5b9739dd3d 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -61,6 +61,39 @@ namespace Jellyfin.Networking.Tests Assert.Equal(value, "[" + string.Join(",", nm.GetInternalBindAddresses().Select(x => x.Address + "/" + x.Subnet.PrefixLength)) + "]"); } + /// + /// Checks valid IP address formats. + /// + /// IP Address. + [Theory] + [InlineData("127.0.0.1")] + [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517")] + [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517]")] + [InlineData("fe80::7add:12ff:febb:c67b%16")] + [InlineData("[fe80::7add:12ff:febb:c67b%16]:123")] + [InlineData("fe80::7add:12ff:febb:c67b%16:123")] + [InlineData("[fe80::7add:12ff:febb:c67b%16]")] + [InlineData("192.168.1.2")] + public static void TryParseValidIPStringsTrue(string address) + => Assert.True(IPAddress.TryParse(address, out _)); + + /// + /// Checks invalid IP address formats. + /// + /// IP Address. + [Theory] + [InlineData("192.168.1.2/255.255.255.0")] + [InlineData("192.168.1.2/24")] + [InlineData("127.0.0.1/8")] + [InlineData("127.0.0.1#")] + [InlineData("localhost!")] + [InlineData("256.128.0.0.0.1")] + [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517/56")] + [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517:1231")] + [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517:1231]")] + public static void TryParseInvalidIPStringsFalse(string address) + => Assert.False(IPAddress.TryParse(address, out _)); + [Theory] [InlineData("192.168.5.85/24", "192.168.5.1")] [InlineData("192.168.5.85/24", "192.168.5.254")] From 1c6b6f5d36cb09c0352bebc1ab26b88e4f511921 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 20 Jul 2022 07:42:52 +0200 Subject: [PATCH 007/358] Remove socket wrkaround --- Jellyfin.Server/Program.cs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 63055a61d4..2bbc2546ed 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -335,13 +335,6 @@ namespace Jellyfin.Server if (startupConfig.UseUnixSocket() && Environment.OSVersion.Platform == PlatformID.Unix) { var socketPath = GetUnixSocketPath(startupConfig, appPaths); - - // Workaround for https://github.com/aspnet/AspNetCore/issues/14134 - if (File.Exists(socketPath)) - { - File.Delete(socketPath); - } - options.ListenUnixSocket(socketPath); _logger.LogInformation("Kestrel listening to unix socket {SocketPath}", socketPath); } From daf33143f6ad30e0d76e038840a1583e4302cd7b Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 20 Jul 2022 09:44:15 +0200 Subject: [PATCH 008/358] Handle forwarded requests not having port set in GetSmartApiUrl --- Emby.Server.Implementations/ApplicationHost.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index a0ad4a9ab5..56f997b3b5 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1080,7 +1080,8 @@ namespace Emby.Server.Implementations if (ConfigurationManager.GetNetworkConfiguration().EnablePublishedServerUriByRequest) { int? requestPort = request.Host.Port; - if ((requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase)) || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase))) + if (((requestPort == 80 || requestPort == null) && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase)) + || ((requestPort == 443 || requestPort == null) && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase))) { requestPort = -1; } From 64ffd5fd9526762e27d97e13c59cc6552c97e7bc Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 20 Jul 2022 09:45:57 +0200 Subject: [PATCH 009/358] Move subnet parser to NetworkExtensions --- Jellyfin.Networking/Manager/NetworkManager.cs | 72 ++----------------- MediaBrowser.Common/Net/NetworkExtensions.cs | 58 ++++++++++++++- 2 files changed, 62 insertions(+), 68 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index d9ef2c6a4c..e9e3e18022 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -326,8 +326,8 @@ namespace Jellyfin.Networking.Manager // Get configuration options string[] subnets = config.LocalNetworkSubnets; - _ = TryParseSubnets(subnets, out _lanSubnets, false); - _ = TryParseSubnets(subnets, out _excludedSubnets, true); + _ = NetworkExtensions.TryParseSubnets(subnets, out _lanSubnets, false); + _ = NetworkExtensions.TryParseSubnets(subnets, out _excludedSubnets, true); if (_lanSubnets.Count == 0) { @@ -419,7 +419,7 @@ namespace Jellyfin.Networking.Manager if (remoteIPFilter.Any() && !string.IsNullOrWhiteSpace(remoteIPFilter.First())) { // Parse all IPs with netmask to a subnet - _ = TryParseSubnets(remoteIPFilter.Where(x => x.Contains('/', StringComparison.OrdinalIgnoreCase)).ToArray(), out _remoteAddressFilter, false); + _ = NetworkExtensions.TryParseSubnets(remoteIPFilter.Where(x => x.Contains('/', StringComparison.OrdinalIgnoreCase)).ToArray(), out _remoteAddressFilter, false); // Parse everything else as an IP and construct subnet with a single IP var ips = remoteIPFilter.Where(x => !x.Contains('/', StringComparison.OrdinalIgnoreCase)); @@ -595,68 +595,6 @@ namespace Jellyfin.Networking.Manager return false; } - /// - /// Try parsing an array of strings into subnets, respecting exclusions. - /// - /// Input string to be parsed. - /// Collection of . - /// Boolean signaling if negated or not negated values should be parsed. - /// True if parsing was successful. - public bool TryParseSubnets(string[] values, out Collection result, bool negated = false) - { - result = new Collection(); - - if (values == null || values.Length == 0) - { - return false; - } - - for (int a = 0; a < values.Length; a++) - { - string[] v = values[a].Trim().Split("/"); - - try - { - var address = IPAddress.None; - if (negated && v[0].StartsWith('!')) - { - _ = IPAddress.TryParse(v[0][1..], out address); - } - else if (!negated) - { - _ = IPAddress.TryParse(v[0][0..], out address); - } - - if (address != IPAddress.None && address != null) - { - if (int.TryParse(v[1], out var netmask)) - { - result.Add(new IPNetwork(address, netmask)); - } - else if (address.AddressFamily == AddressFamily.InterNetwork) - { - result.Add(new IPNetwork(address, 32)); - } - else if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - result.Add(new IPNetwork(address, 128)); - } - } - } - catch (ArgumentException e) - { - _logger.LogWarning(e, "Ignoring LAN value {Value}.", v); - } - } - - if (result.Count > 0) - { - return true; - } - - return false; - } - /// public bool HasRemoteAccess(IPAddress remoteIp) { @@ -802,12 +740,12 @@ namespace Jellyfin.Networking.Manager if (source != null) { - if (IsIpv4Enabled && source.AddressFamily == AddressFamily.InterNetworkV6) + if (IsIpv4Enabled && !IsIpv6Enabled && 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 (IsIpv6Enabled && source.AddressFamily == AddressFamily.InterNetwork) + if (!IsIpv4Enabled && IsIpv6Enabled && source.AddressFamily == AddressFamily.InterNetwork) { _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); } diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 55ec322f43..4cba1c99f2 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -1,5 +1,6 @@ +using Microsoft.AspNetCore.HttpOverrides; using System; -using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Sockets; @@ -136,6 +137,61 @@ namespace MediaBrowser.Common.Net return str; } + /// + /// Try parsing an array of strings into subnets, respecting exclusions. + /// + /// Input string to be parsed. + /// Collection of . + /// Boolean signaling if negated or not negated values should be parsed. + /// True if parsing was successful. + public static bool TryParseSubnets(string[] values, out Collection result, bool negated = false) + { + result = new Collection(); + + if (values == null || values.Length == 0) + { + return false; + } + + for (int a = 0; a < values.Length; a++) + { + string[] v = values[a].Trim().Split("/"); + + var address = IPAddress.None; + if (negated && v[0].StartsWith('!')) + { + _ = IPAddress.TryParse(v[0][1..], out address); + } + else if (!negated) + { + _ = IPAddress.TryParse(v[0][0..], out address); + } + + if (address != IPAddress.None && address != null) + { + if (int.TryParse(v[1], out var netmask)) + { + result.Add(new IPNetwork(address, netmask)); + } + else if (address.AddressFamily == AddressFamily.InterNetwork) + { + result.Add(new IPNetwork(address, 32)); + } + else if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + result.Add(new IPNetwork(address, 128)); + } + } + } + + if (result.Count > 0) + { + return true; + } + + return false; + } + /// /// Attempts to parse a host string. /// From 34d8e531e02c995836546e702e8dc4b02f2206e7 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 20 Jul 2022 09:48:20 +0200 Subject: [PATCH 010/358] Properly handle subnets in KnownProxies --- .../Extensions/ApiServiceCollectionExtensions.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 7030b726cd..5f9f50e315 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -182,7 +182,7 @@ namespace Jellyfin.Server.Extensions } /// - /// Extension method for adding the jellyfin API to the service collection. + /// Extension method for adding the Jellyfin API to the service collection. /// /// The service collection. /// An IEnumerable containing all plugin assemblies with API controllers. @@ -335,7 +335,7 @@ namespace Jellyfin.Server.Extensions } /// - /// Sets up the proxy configuration based on the addresses in . + /// Sets up the proxy configuration based on the addresses/subnets in . /// /// The containing the config settings. /// The string array to parse. @@ -348,6 +348,13 @@ namespace Jellyfin.Server.Extensions { AddIpAddress(config, options, addr, addr.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); } + else if (NetworkExtensions.TryParseSubnets(new[] { allowedProxies[i] }, out var subnets)) + { + for (var j = 0; j < subnets.Count; j++) + { + AddIpAddress(config, options, subnets[j].Prefix, subnets[j].PrefixLength); + } + } else if (NetworkExtensions.TryParseHost(allowedProxies[i], out var host)) { foreach (var address in host) From 748907b9208aa91adc2dcf08672ea8eda7ed7c9c Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 20 Jul 2022 09:50:16 +0200 Subject: [PATCH 011/358] Remove workaround, this only applies to the IPs set by the middleware --- .../Extensions/ApiServiceCollectionExtensions.cs | 8 -------- 1 file changed, 8 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 5f9f50e315..5073951067 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -372,14 +372,6 @@ namespace Jellyfin.Server.Extensions return; } - // In order for dual-mode sockets to be used, IP6 has to be enabled in JF and an interface has to have an IP6 address. - if (addr.AddressFamily == AddressFamily.InterNetwork && config.EnableIPV6) - { - // If the server is using dual-mode sockets, IPv4 addresses are supplied in an IPv6 format. - // https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-5.0 . - addr = addr.MapToIPv6(); - } - if (prefixLength == 32) { options.KnownProxies.Add(addr); From 2043a33f815d9a16aa819095e6310620ca4e72a2 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 20 Jul 2022 09:50:41 +0200 Subject: [PATCH 012/358] Small cleanup and logging fix --- Emby.Dlna/Main/DlnaEntryPoint.cs | 2 -- Jellyfin.Server/Program.cs | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 01a9def0bf..7bc761b71c 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -3,10 +3,8 @@ #pragma warning disable CS1591 using System; -using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Net; using System.Net.Http; using System.Net.Sockets; using System.Threading.Tasks; diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 2bbc2546ed..438994851d 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -302,7 +302,7 @@ namespace Jellyfin.Server bool flagged = false; foreach (IPData netAdd in addresses) { - _logger.LogInformation("Kestrel listening on {Address}", netAdd.Address == IPAddress.IPv6Any ? "All Addresses" : netAdd); + _logger.LogInformation("Kestrel listening on {Address}", netAdd.Address == IPAddress.IPv6Any ? "All Addresses" : netAdd.Address); options.Listen(netAdd.Address, appHost.HttpPort); if (appHost.ListenWithHttps) { From a492082f4e015d6d38368c4ac05d39d236387214 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 20 Jul 2022 11:47:48 +0200 Subject: [PATCH 013/358] Apply review suggestions and fix build --- .../ApiServiceCollectionExtensions.cs | 5 +++++ MediaBrowser.Common/Net/IPData.cs | 17 +++++------------ MediaBrowser.Common/Net/NetworkExtensions.cs | 10 +++++----- .../Jellyfin.Server.Tests/ParseNetworkTests.cs | 8 ++++---- 4 files changed, 19 insertions(+), 21 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 5073951067..a393b80db5 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -372,6 +372,11 @@ namespace Jellyfin.Server.Extensions return; } + if (addr.IsIPv4MappedToIPv6) + { + addr = addr.MapToIPv4(); + } + if (prefixLength == 32) { options.KnownProxies.Add(addr); diff --git a/MediaBrowser.Common/Net/IPData.cs b/MediaBrowser.Common/Net/IPData.cs index 3c6adc7e86..6901d6ad8a 100644 --- a/MediaBrowser.Common/Net/IPData.cs +++ b/MediaBrowser.Common/Net/IPData.cs @@ -14,13 +14,12 @@ namespace MediaBrowser.Common.Net /// /// An . /// The . - public IPData( - IPAddress address, - IPNetwork? subnet) + /// The object's name. + public IPData(IPAddress address, IPNetwork? subnet, string name) { Address = address; Subnet = subnet ?? (address.AddressFamily == AddressFamily.InterNetwork ? new IPNetwork(address, 32) : new IPNetwork(address, 128)); - Name = string.Empty; + Name = name; } /// @@ -28,15 +27,9 @@ namespace MediaBrowser.Common.Net /// /// An . /// The . - /// The object's name. - public IPData( - IPAddress address, - IPNetwork? subnet, - string name) + public IPData(IPAddress address, IPNetwork? subnet) + : this(address, subnet, string.Empty) { - Address = address; - Subnet = subnet ?? (address.AddressFamily == AddressFamily.InterNetwork ? new IPNetwork(address, 32) : new IPNetwork(address, 128)); - Name = name; } /// diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 4cba1c99f2..ae1e47ccc2 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -13,6 +13,10 @@ namespace MediaBrowser.Common.Net /// public static class NetworkExtensions { + // 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 + private static readonly Regex _fqdnRegex = new Regex(@"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)(:(\d){1,5}){0,1}$"); + /// /// Returns true if the IPAddress contains an IP6 Local link address. /// @@ -227,12 +231,8 @@ namespace MediaBrowser.Common.Net if (hosts.Length <= 2) { - // 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 - string pattern = @"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)(:(\d){1,5}){0,1}$"; - // Is hostname or hostname:port - if (Regex.IsMatch(hosts[0], pattern)) + if (_fqdnRegex.IsMatch(hosts[0])) { try { diff --git a/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs index a1bdfa31b8..fc5f5f4c6c 100644 --- a/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs +++ b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs @@ -21,9 +21,9 @@ namespace Jellyfin.Server.Tests data.Add( true, true, - new string[] { "192.168.t", "127.0.0.1", "1234.1232.12.1234" }, - new IPAddress[] { IPAddress.Loopback.MapToIPv6() }, - Array.Empty()); + new string[] { "192.168.t", "127.0.0.1", "::1", "1234.1232.12.1234" }, + new IPAddress[] { IPAddress.Loopback, }, + new IPNetwork[] { new IPNetwork(IPAddress.IPv6Loopback, 128) }); data.Add( true, @@ -64,7 +64,7 @@ namespace Jellyfin.Server.Tests true, true, new string[] { "localhost" }, - new IPAddress[] { IPAddress.Loopback.MapToIPv6() }, + new IPAddress[] { IPAddress.Loopback }, new IPNetwork[] { new IPNetwork(IPAddress.IPv6Loopback, 128) }); return data; } From 2281b8c997dff0fa148bf0f193b37664420aca3e Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 20 Jul 2022 14:29:30 +0200 Subject: [PATCH 014/358] Move away from using Collection, simplify code, add proper ordering --- Emby.Dlna/Main/DlnaEntryPoint.cs | 2 +- .../Configuration/NetworkConfiguration.cs | 4 +- Jellyfin.Networking/Manager/NetworkManager.cs | 54 +++++++++---------- .../CreateNetworkConfiguration.cs | 2 +- MediaBrowser.Common/Net/INetworkManager.cs | 13 +++-- MediaBrowser.Common/Net/NetworkExtensions.cs | 6 +-- .../NetworkParseTests.cs | 8 ++- 7 files changed, 42 insertions(+), 47 deletions(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 7bc761b71c..90c985a816 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -293,7 +293,7 @@ namespace Emby.Dlna.Main if (bindAddresses.Count == 0) { // No interfaces returned, so use loopback. - bindAddresses = _networkManager.GetLoopbacks(); + bindAddresses = _networkManager.GetLoopbacks().ToList(); } foreach (var address in bindAddresses) diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index 0ac55c986e..be8dc738d9 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -151,9 +151,9 @@ namespace Jellyfin.Networking.Configuration public bool IgnoreVirtualInterfaces { get; set; } = true; /// - /// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. . + /// Gets or sets a value indicating the interface name prefixes that should be ignored. The list can be comma separated and values are case-insensitive. . /// - public string VirtualInterfaceNames { get; set; } = "vEthernet*"; + public string VirtualInterfaceNames { get; set; } = "veth"; /// /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor. diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index e9e3e18022..757b5994b9 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Net; @@ -47,7 +46,7 @@ namespace Jellyfin.Networking.Manager /// private readonly Dictionary _publishedServerUrls; - private Collection _remoteAddressFilter; + private List _remoteAddressFilter; /// /// Used to stop "event-racing conditions". @@ -58,12 +57,12 @@ namespace Jellyfin.Networking.Manager /// Unfiltered user defined LAN subnets () /// or internal interface network subnets if undefined by user. /// - private Collection _lanSubnets; + private List _lanSubnets; /// /// User defined list of subnets to excluded from the LAN. /// - private Collection _excludedSubnets; + private List _excludedSubnets; /// /// List of interfaces to bind to. @@ -95,7 +94,7 @@ namespace Jellyfin.Networking.Manager _macAddresses = new List(); _publishedServerUrls = new Dictionary(); _eventFireLock = new object(); - _remoteAddressFilter = new Collection(); + _remoteAddressFilter = new List(); UpdateSettings(_configurationManager.GetNetworkConfiguration()); @@ -225,8 +224,8 @@ namespace Jellyfin.Networking.Manager { try { - IPInterfaceProperties ipProperties = adapter.GetIPProperties(); - PhysicalAddress mac = adapter.GetPhysicalAddress(); + var ipProperties = adapter.GetIPProperties(); + var mac = adapter.GetPhysicalAddress(); // Populate MAC list if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && PhysicalAddress.None.Equals(mac)) @@ -235,7 +234,7 @@ namespace Jellyfin.Networking.Manager } // Populate interface list - foreach (UnicastIPAddressInformation info in ipProperties.UnicastAddresses) + foreach (var info in ipProperties.UnicastAddresses) { if (IsIpv4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork) { @@ -364,8 +363,8 @@ namespace Jellyfin.Networking.Manager // Use explicit bind addresses if (config.LocalNetworkAddresses.Length > 0) { - _bindAddresses = config.LocalNetworkAddresses.Select(p => IPAddress.TryParse(p, out var address) - ? address + _bindAddresses = config.LocalNetworkAddresses.Select(p => IPAddress.TryParse(p, out var addresses) + ? addresses : (_interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase)).Select(x => x.Address).FirstOrDefault() ?? IPAddress.None)).ToList(); _bindAddresses.RemoveAll(x => x == IPAddress.None); } @@ -525,13 +524,11 @@ namespace Jellyfin.Networking.Manager var address = IPAddress.Parse(split[0]); var network = new IPNetwork(address, int.Parse(split[1], CultureInfo.InvariantCulture)); var index = int.Parse(parts[1], CultureInfo.InvariantCulture); - if (address.AddressFamily == AddressFamily.InterNetwork) + if (address.AddressFamily == AddressFamily.InterNetwork || address.AddressFamily == AddressFamily.InterNetworkV6) { - _interfaces.Add(new IPData(address, network, parts[2])); - } - else if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - _interfaces.Add(new IPData(address, network, parts[2])); + var data = new IPData(address, network, parts[2]); + data.Index = index; + _interfaces.Add(data); } } } @@ -562,9 +559,9 @@ namespace Jellyfin.Networking.Manager } /// - public bool TryParseInterface(string intf, out Collection result) + public bool TryParseInterface(string intf, out List result) { - result = new Collection(); + result = new List(); if (string.IsNullOrEmpty(intf)) { return false; @@ -573,7 +570,7 @@ namespace Jellyfin.Networking.Manager if (_interfaces != null) { // Match all interfaces starting with names starting with token - var matchedInterfaces = _interfaces.Where(s => s.Name.Equals(intf.ToLowerInvariant(), StringComparison.OrdinalIgnoreCase)); + var matchedInterfaces = _interfaces.Where(s => s.Name.Equals(intf.ToLowerInvariant(), StringComparison.OrdinalIgnoreCase)).OrderBy(x => x.Index); if (matchedInterfaces.Any()) { _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", intf); @@ -626,14 +623,14 @@ namespace Jellyfin.Networking.Manager } /// - public IReadOnlyCollection GetMacAddresses() + public IReadOnlyList GetMacAddresses() { // Populated in construction - so always has values. return _macAddresses; } /// - public List GetLoopbacks() + public IReadOnlyList GetLoopbacks() { var loopbackNetworks = new List(); if (IsIpv4Enabled) @@ -650,7 +647,7 @@ namespace Jellyfin.Networking.Manager } /// - public List GetAllBindInterfaces(bool individualInterfaces = false) + public IReadOnlyList GetAllBindInterfaces(bool individualInterfaces = false) { if (_bindAddresses.Count == 0) { @@ -816,7 +813,7 @@ namespace Jellyfin.Networking.Manager } /// - public List GetInternalBindAddresses() + public IReadOnlyList GetInternalBindAddresses() { if (_bindAddresses.Count == 0) { @@ -833,7 +830,8 @@ namespace Jellyfin.Networking.Manager // Select all local bind addresses return _interfaces.Where(x => _bindAddresses.Contains(x.Address)) .Where(x => IsInLocalNetwork(x.Address)) - .OrderBy(x => x.Index).ToList(); + .OrderBy(x => x.Index) + .ToList(); } /// @@ -892,7 +890,7 @@ namespace Jellyfin.Networking.Manager interfaces = interfaces.Where(x => IsInLocalNetwork(x.Address)).ToList(); } - foreach (var intf in _interfaces) + foreach (var intf in interfaces) { if (intf.Subnet.Contains(address)) { @@ -942,7 +940,7 @@ namespace Jellyfin.Networking.Manager foreach (var data in validPublishedServerUrls) { // Get address interface - var intf = _interfaces.FirstOrDefault(s => s.Subnet.Contains(data.Key.Address)); + var intf = _interfaces.OrderBy(x => x.Index).FirstOrDefault(s => s.Subnet.Contains(data.Key.Address)); // Remaining. Match anything. if (data.Key.Address.Equals(IPAddress.Broadcast)) @@ -1017,7 +1015,7 @@ namespace Jellyfin.Networking.Manager defaultGateway = addr; } - var intf = _interfaces.Where(x => x.Subnet.Contains(addr)).FirstOrDefault(); + var intf = _interfaces.Where(x => x.Subnet.Contains(addr)).OrderBy(x => x.Index).FirstOrDefault(); if (bindAddress == null && intf != null && intf.Subnet.Contains(source)) { @@ -1082,7 +1080,7 @@ namespace Jellyfin.Networking.Manager { result = string.Empty; // Get the first WAN interface address that isn't a loopback. - var extResult = _interfaces.Where(p => !IsInLocalNetwork(p.Address)); + var extResult = _interfaces.Where(p => !IsInLocalNetwork(p.Address)).OrderBy(x => x.Index); IPAddress? hasResult = null; // Does the request originate in one of the interface subnets? diff --git a/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs b/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs index ceeaa26e62..b670172814 100644 --- a/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs +++ b/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs @@ -114,7 +114,7 @@ public class CreateNetworkConfiguration : IMigrationRoutine public bool IgnoreVirtualInterfaces { get; set; } = true; - public string VirtualInterfaceNames { get; set; } = "veth*"; + public string VirtualInterfaceNames { get; set; } = "veth"; public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty(); diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 9f48535576..bb0e2dcb36 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Net; using System.Net.NetworkInformation; using Microsoft.AspNetCore.Http; @@ -34,13 +33,13 @@ namespace MediaBrowser.Common.Net /// If all the interfaces are specified, and none are excluded, it returns zero items /// to represent any address. /// When false, return or for all interfaces. - List GetAllBindInterfaces(bool individualInterfaces = false); + IReadOnlyList GetAllBindInterfaces(bool individualInterfaces = false); /// - /// Returns a collection containing the loopback interfaces. + /// Returns a list containing the loopback interfaces. /// /// List{IPData}. - List GetLoopbacks(); + IReadOnlyList GetLoopbacks(); /// /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) @@ -97,7 +96,7 @@ namespace MediaBrowser.Common.Net /// Get a list of all the MAC addresses associated with active interfaces. /// /// List of MAC addresses. - IReadOnlyCollection GetMacAddresses(); + IReadOnlyList GetMacAddresses(); /// /// Returns true if the address is part of the user defined LAN. @@ -122,13 +121,13 @@ namespace MediaBrowser.Common.Net /// Interface name. /// Resultant object's ip addresses, if successful. /// Success of the operation. - bool TryParseInterface(string intf, out Collection? result); + bool TryParseInterface(string intf, out List? result); /// /// Returns all the internal Bind interface addresses. /// /// An internal list of interfaces addresses. - List GetInternalBindAddresses(); + IReadOnlyList GetInternalBindAddresses(); /// /// Checks to see if has access. diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index ae1e47ccc2..316c2ebcd1 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -1,6 +1,6 @@ using Microsoft.AspNetCore.HttpOverrides; using System; -using System.Collections.ObjectModel; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Sockets; @@ -148,9 +148,9 @@ namespace MediaBrowser.Common.Net /// Collection of . /// Boolean signaling if negated or not negated values should be parsed. /// True if parsing was successful. - public static bool TryParseSubnets(string[] values, out Collection result, bool negated = false) + public static bool TryParseSubnets(string[] values, out List result, bool negated = false) { - result = new Collection(); + result = new List(); if (values == null || values.Length == 0) { diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index 5b9739dd3d..c45a9c9f54 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -1,5 +1,5 @@ using System; -using System.Collections.ObjectModel; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; @@ -49,8 +49,6 @@ namespace Jellyfin.Networking.Tests { EnableIPV6 = true, EnableIPV4 = true, - IgnoreVirtualInterfaces = true, - VirtualInterfaceNames = "veth", LocalNetworkSubnets = lan?.Split(';') ?? throw new ArgumentNullException(nameof(lan)) }; @@ -208,7 +206,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - _ = nm.TryParseInterface(result, out Collection? resultObj); + _ = nm.TryParseInterface(result, out List? resultObj); // Check to see if dns resolution is working. If not, skip test. _ = NetworkExtensions.TryParseHost(source, out var host); @@ -277,7 +275,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - if (nm.TryParseInterface(result, out Collection? resultObj) && resultObj != null) + if (nm.TryParseInterface(result, out List? resultObj) && resultObj != null) { // Parse out IPAddresses so we can do a string comparison. (Ignore subnet masks). result = resultObj.First().Address.ToString(); From 8075cb4e99da4468d9474d1ad2e7668d96cd5224 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 20 Jul 2022 16:14:56 +0200 Subject: [PATCH 015/358] Cleanup and sort NetworkConfiguration --- .../Configuration/NetworkConfiguration.cs | 151 +++++++++--------- 1 file changed, 73 insertions(+), 78 deletions(-) diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index be8dc738d9..e9f6d597b4 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -21,21 +21,6 @@ namespace Jellyfin.Networking.Configuration private string _baseUrl = string.Empty; - /// - /// Gets or sets a value indicating whether the server should force connections over HTTPS. - /// - public bool RequireHttps { get; set; } - - /// - /// Gets or sets the filesystem path of an X.509 certificate to use for SSL. - /// - public string CertificatePath { get; set; } = string.Empty; - - /// - /// Gets or sets the password required to access the X.509 certificate data in the file specified by . - /// - public string CertificatePassword { get; set; } = string.Empty; - /// /// Gets or sets a value used to specify the URL prefix that your Jellyfin instance can be accessed at. /// @@ -70,16 +55,28 @@ namespace Jellyfin.Networking.Configuration } /// - /// Gets or sets the public HTTPS port. + /// Gets or sets a value indicating whether to use HTTPS. /// - /// The public HTTPS port. - public int PublicHttpsPort { get; set; } = DefaultHttpsPort; + /// + /// In order for HTTPS to be used, in addition to setting this to true, valid values must also be + /// provided for and . + /// + public bool EnableHttps { get; set; } /// - /// Gets or sets the HTTP server port number. + /// Gets or sets a value indicating whether the server should force connections over HTTPS. /// - /// The HTTP server port number. - public int HttpServerPortNumber { get; set; } = DefaultHttpPort; + public bool RequireHttps { get; set; } + + /// + /// Gets or sets the filesystem path of an X.509 certificate to use for SSL. + /// + public string CertificatePath { get; set; } = string.Empty; + + /// + /// Gets or sets the password required to access the X.509 certificate data in the file specified by . + /// + public string CertificatePassword { get; set; } = string.Empty; /// /// Gets or sets the HTTPS server port number. @@ -88,13 +85,16 @@ namespace Jellyfin.Networking.Configuration public int HttpsPortNumber { get; set; } = DefaultHttpsPort; /// - /// Gets or sets a value indicating whether to use HTTPS. + /// Gets or sets the public HTTPS port. /// - /// - /// In order for HTTPS to be used, in addition to setting this to true, valid values must also be - /// provided for and . - /// - public bool EnableHttps { get; set; } + /// The public HTTPS port. + public int PublicHttpsPort { get; set; } = DefaultHttpsPort; + + /// + /// Gets or sets the HTTP server port number. + /// + /// The HTTP server port number. + public int HttpServerPortNumber { get; set; } = DefaultHttpPort; /// /// Gets or sets the public mapped port. @@ -108,14 +108,19 @@ namespace Jellyfin.Networking.Configuration public bool UPnPCreateHttpPortMap { get; set; } /// - /// Gets or sets the UDPPortRange. + /// Gets or sets a value indicating whether Autodiscovery is enabled. /// - public string UDPPortRange { get; set; } = string.Empty; + public bool AutoDiscovery { get; set; } = true; /// - /// Gets or sets a value indicating whether IPv6 is enabled or not. + /// Gets or sets a value indicating whether Autodiscovery tracing is enabled. /// - public bool EnableIPV6 { get; set; } + public bool AutoDiscoveryTracing { get; set; } + + /// + /// Gets or sets a value indicating whether to enable automatic port forwarding. + /// + public bool EnableUPnP { get; set; } /// /// Gets or sets a value indicating whether IPv6 is enabled or not. @@ -123,17 +128,34 @@ namespace Jellyfin.Networking.Configuration public bool EnableIPV4 { get; set; } = true; /// - /// 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 have any effect. + /// Gets or sets a value indicating whether IPv6 is enabled or not. /// - public bool EnableSSDPTracing { get; set; } + public bool EnableIPV6 { get; set; } /// - /// 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. + /// Gets or sets a value indicating whether access outside of the LAN is permitted. /// - public string SSDPTracingFilter { get; set; } = string.Empty; + public bool EnableRemoteAccess { get; set; } = true; + + /// + /// Gets or sets the subnets that are deemed to make up the LAN. + /// + public string[] LocalNetworkSubnets { get; set; } = Array.Empty(); + + /// + /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used. + /// + public string[] LocalNetworkAddresses { get; set; } = Array.Empty(); + + /// + /// Gets or sets the known proxies. If the proxy is a network, it's added to the KnownNetworks. + /// + public string[] KnownProxies { get; set; } = Array.Empty(); + + /// + /// Gets or sets the UDPPortRange. + /// + public string UDPPortRange { get; set; } = string.Empty; /// /// Gets or sets the number of times SSDP UDP messages are sent. @@ -156,19 +178,9 @@ namespace Jellyfin.Networking.Configuration public string VirtualInterfaceNames { get; set; } = "veth"; /// - /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor. - /// - public int GatewayMonitorPeriod { get; set; } = 60; - - /// - /// Gets a value indicating whether multi-socket binding is available. - /// - public bool EnableMultiSocketBinding { get; } = true; - - /// - /// Gets or sets the ports that HDHomerun uses. + /// Gets or sets a value indicating whether the published server uri is based on information in HTTP requests. /// - public string HDHomerunPortRange { get; set; } = string.Empty; + public bool EnablePublishedServerUriByRequest { get; set; } = false; /// /// Gets or sets the PublishedServerUriBySubnet @@ -177,14 +189,14 @@ namespace Jellyfin.Networking.Configuration public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty(); /// - /// Gets or sets a value indicating whether Autodiscovery tracing is enabled. + /// Gets a value indicating whether multi-socket binding is available. /// - public bool AutoDiscoveryTracing { get; set; } + public bool EnableMultiSocketBinding { get; } = true; /// - /// Gets or sets a value indicating whether Autodiscovery is enabled. + /// Gets or sets the ports that HDHomerun uses. /// - public bool AutoDiscovery { get; set; } = true; + public string HDHomerunPortRange { get; set; } = string.Empty; /// /// Gets or sets the filter for remote IP connectivity. Used in conjuntion with . @@ -197,33 +209,16 @@ namespace Jellyfin.Networking.Configuration public bool IsRemoteIPFilterBlacklist { get; set; } /// - /// Gets or sets a value indicating whether to enable automatic port forwarding. - /// - public bool EnableUPnP { get; set; } - - /// - /// Gets or sets a value indicating whether access outside of the LAN is permitted. - /// - public bool EnableRemoteAccess { get; set; } = true; - - /// - /// Gets or sets the subnets that are deemed to make up the LAN. - /// - public string[] LocalNetworkSubnets { get; set; } = Array.Empty(); - - /// - /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used. - /// - public string[] LocalNetworkAddresses { get; set; } = Array.Empty(); - - /// - /// Gets or sets the known proxies. If the proxy is a network, it's added to the KnownNetworks. + /// 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 have any effect. /// - public string[] KnownProxies { get; set; } = Array.Empty(); + public bool EnableSSDPTracing { get; set; } /// - /// Gets or sets a value indicating whether the published server uri is based on information in HTTP requests. + /// 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. /// - public bool EnablePublishedServerUriByRequest { get; set; } = false; + public string SSDPTracingFilter { get; set; } = string.Empty; } } From 2d3a16ad0f814c4e26a741744b8fc7f3c31890dc Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 20 Jul 2022 21:19:35 +0200 Subject: [PATCH 016/358] Simplify code --- Jellyfin.Networking/Manager/NetworkManager.cs | 267 +++++------------- MediaBrowser.Common/Net/INetworkManager.cs | 2 +- 2 files changed, 72 insertions(+), 197 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 757b5994b9..50fc974616 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -25,11 +25,6 @@ namespace Jellyfin.Networking.Manager /// private readonly object _initLock; - /// - /// Dictionary containing interface addresses and their subnets. - /// - private readonly List _interfaces; - /// /// List of all interface MAC addresses. /// @@ -53,6 +48,11 @@ namespace Jellyfin.Networking.Manager /// private bool _eventfire; + /// + /// Dictionary containing interface addresses and their subnets. + /// + private List _interfaces; + /// /// Unfiltered user defined LAN subnets () /// or internal interface network subnets if undefined by user. @@ -64,16 +64,6 @@ namespace Jellyfin.Networking.Manager /// private List _excludedSubnets; - /// - /// List of interfaces to bind to. - /// - private List _bindAddresses; - - /// - /// List of interface addresses to exclude from bind. - /// - private List _bindExclusions; - /// /// True if this object is disposed. /// @@ -190,9 +180,10 @@ namespace Jellyfin.Networking.Manager try { await Task.Delay(2000).ConfigureAwait(false); + var networkConfig = _configurationManager.GetNetworkConfiguration(); + InitialiseLan(networkConfig); InitialiseInterfaces(); - // Recalculate LAN caches. - InitialiseLan(_configurationManager.GetNetworkConfiguration()); + EnforceBindRestrictions(networkConfig); NetworkChanged?.Invoke(this, EventArgs.Empty); } @@ -217,7 +208,7 @@ namespace Jellyfin.Networking.Manager try { - IEnumerable nics = NetworkInterface.GetAllNetworkInterfaces() + var nics = NetworkInterface.GetAllNetworkInterfaces() .Where(i => i.SupportsMulticast && i.OperationalStatus == OperationalStatus.Up); foreach (NetworkInterface adapter in nics) @@ -270,33 +261,7 @@ namespace Jellyfin.Networking.Manager _logger.LogError(ex, "Error obtaining interfaces."); } - // If for some reason we don't have an interface info, resolve the DNS name. - if (_interfaces.Count == 0) - { - _logger.LogError("No interfaces information available. Resolving DNS name."); - var hostName = Dns.GetHostName(); - if (Uri.CheckHostName(hostName).Equals(UriHostNameType.Dns)) - { - try - { - IPHostEntry hip = Dns.GetHostEntry(hostName); - foreach (var address in hip.AddressList) - { - _interfaces.Add(new IPData(address, null)); - } - } - catch (SocketException ex) - { - // Log and then ignore socket errors, as the result value will just be an empty array. - _logger.LogWarning("GetHostEntryAsync failed with {Message}.", ex.Message); - } - } - - if (_interfaces.Count == 0) - { - _logger.LogWarning("No interfaces information available. Using loopback."); - } - } + _logger.LogWarning("No interfaces information available. Using loopback."); if (IsIpv4Enabled && !IsIpv6Enabled) { @@ -354,55 +319,46 @@ namespace Jellyfin.Networking.Manager } /// - /// Initialises the network bind addresses. + /// Enforce bind addresses and exclusions on available interfaces. /// - private void InitialiseBind(NetworkConfiguration config) + private void EnforceBindRestrictions(NetworkConfiguration config) { lock (_initLock) { - // Use explicit bind addresses - if (config.LocalNetworkAddresses.Length > 0) + // Respect explicit bind addresses + var localNetworkAddresses = config.LocalNetworkAddresses; + if (localNetworkAddresses.Length > 0 && !string.IsNullOrWhiteSpace(localNetworkAddresses.First())) { - _bindAddresses = config.LocalNetworkAddresses.Select(p => IPAddress.TryParse(p, out var addresses) + var bindAddresses = config.LocalNetworkAddresses.Select(p => IPAddress.TryParse(p, out var addresses) ? addresses - : (_interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase)).Select(x => x.Address).FirstOrDefault() ?? IPAddress.None)).ToList(); - _bindAddresses.RemoveAll(x => x == IPAddress.None); + : (_interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase)) + .Select(x => x.Address) + .FirstOrDefault() ?? IPAddress.None)) + .ToList(); + bindAddresses.RemoveAll(x => x == IPAddress.None); + _interfaces = _interfaces.Where(x => bindAddresses.Contains(x.Address)).ToList(); } - else - { - // Use all addresses from all interfaces - _bindAddresses = _interfaces.Select(x => x.Address).ToList(); - } - - _bindExclusions = new List(); - // Add all interfaces matching any virtual machine interface prefix to _bindExclusions + // Remove all interfaces matching any virtual machine interface prefix if (config.IgnoreVirtualInterfaces) { // Remove potentially exisiting * and split config string into prefixes - var virtualInterfacePrefixes = config.VirtualInterfaceNames.Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase).ToLowerInvariant().Split(','); + var virtualInterfacePrefixes = config.VirtualInterfaceNames + .Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase) + .ToLowerInvariant() + .Split(','); - // Check all interfaces for matches against the prefixes and add the interface IPs to _bindExclusions - if (_bindAddresses.Count > 0 && virtualInterfacePrefixes.Length > 0) + // Check all interfaces for matches against the prefixes and remove them + if (_interfaces.Count > 0 && virtualInterfacePrefixes.Length > 0) { - var localInterfaces = _interfaces.ToList(); foreach (var virtualInterfacePrefix in virtualInterfacePrefixes) { - var excludedInterfaceIps = localInterfaces.Where(intf => intf.Name.StartsWith(virtualInterfacePrefix, StringComparison.OrdinalIgnoreCase)) - .Select(intf => intf.Address); - foreach (var interfaceIp in excludedInterfaceIps) - { - _bindExclusions.Add(interfaceIp); - } + _interfaces.RemoveAll(x => x.Name.StartsWith(virtualInterfacePrefix, StringComparison.OrdinalIgnoreCase)); } } } - // Remove all excluded addresses from _bindAddresses - _bindAddresses.RemoveAll(x => _bindExclusions.Contains(x)); - - _logger.LogInformation("Using bind addresses: {0}", _bindAddresses); - _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions); + _logger.LogInformation("Using bind addresses: {0}", _interfaces.Select(x => x.Address)); } } @@ -477,7 +433,7 @@ namespace Jellyfin.Networking.Manager _publishedServerUrls[data] = replacement; } - else if (TryParseInterface(parts[0], out var ifaces)) + else if (TryParseInterface(ipParts[0], out var ifaces)) { foreach (var iface in ifaces) { @@ -509,6 +465,9 @@ namespace Jellyfin.Networking.Manager { NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration)); + InitialiseLan(config); + InitialiseRemote(config); + if (string.IsNullOrEmpty(MockNetworkSettings)) { InitialiseInterfaces(); @@ -533,9 +492,7 @@ namespace Jellyfin.Networking.Manager } } - InitialiseLan(config); - InitialiseBind(config); - InitialiseRemote(config); + EnforceBindRestrictions(config); InitialiseOverrides(config); } @@ -649,19 +606,8 @@ namespace Jellyfin.Networking.Manager /// public IReadOnlyList GetAllBindInterfaces(bool individualInterfaces = false) { - if (_bindAddresses.Count == 0) + if (_interfaces.Count == 0) { - if (_bindExclusions.Count > 0) - { - foreach (var exclusion in _bindExclusions) - { - // Return all the interfaces except the ones specifically excluded. - _interfaces.RemoveAll(intf => intf.Address == exclusion); - } - - return _interfaces; - } - // No bind address and no exclusions, so listen on all interfaces. var result = new List(); @@ -699,14 +645,7 @@ namespace Jellyfin.Networking.Manager return result; } - // Remove any excluded bind interfaces. - foreach (var exclusion in _bindExclusions) - { - // Return all the interfaces except the ones specifically excluded. - _bindAddresses.Remove(exclusion); - } - - return _bindAddresses.Select(s => new IPData(s, null)).ToList(); + return _interfaces; } /// @@ -770,8 +709,7 @@ namespace Jellyfin.Networking.Manager // Get the first LAN interface address that's not excluded and not a loopback address. var availableInterfaces = _interfaces.Where(x => !IPAddress.IsLoopback(x.Address)) - .OrderByDescending(x => _bindAddresses.Contains(x.Address)) - .ThenByDescending(x => IsInLocalNetwork(x.Address)) + .OrderByDescending(x => IsInLocalNetwork(x.Address)) .ThenBy(x => x.Index); if (availableInterfaces.Any()) @@ -815,21 +753,8 @@ namespace Jellyfin.Networking.Manager /// public IReadOnlyList GetInternalBindAddresses() { - if (_bindAddresses.Count == 0) - { - if (_bindExclusions.Count > 0) - { - // Return all the internal interfaces except the ones excluded. - return _interfaces.Where(p => !_bindExclusions.Contains(p.Address)).ToList(); - } - - // No bind address, so return all internal interfaces. - return _interfaces; - } - // Select all local bind addresses - return _interfaces.Where(x => _bindAddresses.Contains(x.Address)) - .Where(x => IsInLocalNetwork(x.Address)) + return _interfaces.Where(x => IsInLocalNetwork(x.Address)) .OrderBy(x => x.Index) .ToList(); } @@ -876,31 +801,6 @@ namespace Jellyfin.Networking.Manager return address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback) || match; } - private IPData? FindInterfaceForIp(IPAddress address, bool localNetwork = false) - { - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } - - var interfaces = _interfaces; - - if (localNetwork) - { - interfaces = interfaces.Where(x => IsInLocalNetwork(x.Address)).ToList(); - } - - foreach (var intf in interfaces) - { - if (intf.Subnet.Contains(address)) - { - return intf; - } - } - - return null; - } - private bool CheckIfLanAndNotExcluded(IPAddress address) { bool match = false; @@ -992,79 +892,54 @@ namespace Jellyfin.Networking.Manager { result = string.Empty; - int count = _bindAddresses.Count; - if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses[0].Equals(IPAddress.IPv6Any))) + int count = _interfaces.Count(); + if (count == 1 && (_interfaces[0].Equals(IPAddress.Any) || _interfaces[0].Equals(IPAddress.IPv6Any))) { // Ignore IPAny addresses. count = 0; } - if (count != 0) + if (count > 0) { - // Check to see if any of the bind interfaces are in the same subnet as the source. - IPAddress? defaultGateway = null; IPAddress? bindAddress = null; + var externalInterfaces = _interfaces.Where(x => !IsInLocalNetwork(x.Address)) + .OrderBy(x => x.Index) + .ToList(); - if (isInExternalSubnet) + if (isInExternalSubnet && externalInterfaces.Any()) { - // Find all external bind addresses. Store the default gateway, but check to see if there is a better match first. - foreach (var addr in _bindAddresses) - { - if (defaultGateway == null && !IsInLocalNetwork(addr)) - { - defaultGateway = addr; - } - - var intf = _interfaces.Where(x => x.Subnet.Contains(addr)).OrderBy(x => x.Index).FirstOrDefault(); + // Check to see if any of the external bind interfaces are in the same subnet as the source. + // If none exists, this will select the first external interface if there is one. + bindAddress = externalInterfaces + .OrderByDescending(x => x.Subnet.Contains(source)) + .ThenBy(x => x.Index) + .Select(x => x.Address) + .FirstOrDefault(); - if (bindAddress == null && intf != null && intf.Subnet.Contains(source)) - { - bindAddress = intf.Address; - } - - if (defaultGateway != null && bindAddress != null) - { - break; - } + if (bindAddress != null) + { + result = NetworkExtensions.FormatIpString(bindAddress); + _logger.LogDebug("{Source}: GetBindInterface: Has source, found a matching external bind interface. {Result}", source, result); + return true; } } else { - // Look for the best internal address. - foreach (var bA in _bindAddresses.Where(x => IsInLocalNetwork(x))) + // Check to see if any of the internal bind interfaces are in the same subnet as the source. + // If none exists, this will select the first internal interface if there is one. + bindAddress = _interfaces.Where(x => IsInLocalNetwork(x.Address)) + .OrderByDescending(x => x.Subnet.Contains(source)) + .ThenBy(x => x.Index) + .Select(x => x.Address) + .FirstOrDefault(); + + if (bindAddress != null) { - var intf = FindInterfaceForIp(source, true); - if (intf != null) - { - bindAddress = intf.Address; - break; - } + result = NetworkExtensions.FormatIpString(bindAddress); + _logger.LogWarning("{Source}: External request received, only an internal interface bind found. {Result}", source, result); + return true; } } - - if (bindAddress != null) - { - result = NetworkExtensions.FormatIpString(bindAddress); - _logger.LogDebug("{Source}: GetBindInterface: Has source, found a matching bind interface subnet. {Result}", source, result); - return true; - } - - if (isInExternalSubnet && defaultGateway != null) - { - result = NetworkExtensions.FormatIpString(defaultGateway); - _logger.LogDebug("{Source}: GetBindInterface: Using first user defined external interface. {Result}", source, result); - return true; - } - - result = NetworkExtensions.FormatIpString(_bindAddresses[0]); - _logger.LogDebug("{Source}: GetBindInterface: Selected first user defined interface. {Result}", source, result); - - if (isInExternalSubnet) - { - _logger.LogWarning("{Source}: External request received, only an internal interface bind found.", source); - } - - return true; } return false; diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index bb0e2dcb36..21ff982376 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -124,7 +124,7 @@ namespace MediaBrowser.Common.Net bool TryParseInterface(string intf, out List? result); /// - /// Returns all the internal Bind interface addresses. + /// Returns all the internal bind interface addresses. /// /// An internal list of interfaces addresses. IReadOnlyList GetInternalBindAddresses(); From 358642c2d9b0475cd7e4ed18e9507cc87c15935d Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 20 Jul 2022 21:51:12 +0200 Subject: [PATCH 017/358] Fix build, fix loopback binding, exclude unsupported IPs from bind --- Jellyfin.Networking/Manager/NetworkManager.cs | 49 ++++++++++++++----- 1 file changed, 36 insertions(+), 13 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 50fc974616..af2429cc28 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -183,7 +183,7 @@ namespace Jellyfin.Networking.Manager var networkConfig = _configurationManager.GetNetworkConfiguration(); InitialiseLan(networkConfig); InitialiseInterfaces(); - EnforceBindRestrictions(networkConfig); + EnforceBindSettings(networkConfig); NetworkChanged?.Invoke(this, EventArgs.Empty); } @@ -261,16 +261,19 @@ namespace Jellyfin.Networking.Manager _logger.LogError(ex, "Error obtaining interfaces."); } - _logger.LogWarning("No interfaces information available. Using loopback."); - - if (IsIpv4Enabled && !IsIpv6Enabled) + if (_interfaces.Count == 0) { - _interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); - } + _logger.LogWarning("No interfaces information available. Using loopback."); - if (!IsIpv4Enabled && IsIpv6Enabled) - { - _interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); + if (IsIpv4Enabled && !IsIpv6Enabled) + { + _interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); + } + + if (!IsIpv4Enabled && IsIpv6Enabled) + { + _interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); + } } _logger.LogDebug("Discovered {0} interfaces.", _interfaces.Count); @@ -321,7 +324,7 @@ namespace Jellyfin.Networking.Manager /// /// Enforce bind addresses and exclusions on available interfaces. /// - private void EnforceBindRestrictions(NetworkConfiguration config) + private void EnforceBindSettings(NetworkConfiguration config) { lock (_initLock) { @@ -329,7 +332,7 @@ namespace Jellyfin.Networking.Manager var localNetworkAddresses = config.LocalNetworkAddresses; if (localNetworkAddresses.Length > 0 && !string.IsNullOrWhiteSpace(localNetworkAddresses.First())) { - var bindAddresses = config.LocalNetworkAddresses.Select(p => IPAddress.TryParse(p, out var addresses) + var bindAddresses = localNetworkAddresses.Select(p => IPAddress.TryParse(p, out var addresses) ? addresses : (_interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase)) .Select(x => x.Address) @@ -337,6 +340,16 @@ namespace Jellyfin.Networking.Manager .ToList(); bindAddresses.RemoveAll(x => x == IPAddress.None); _interfaces = _interfaces.Where(x => bindAddresses.Contains(x.Address)).ToList(); + + if (bindAddresses.Contains(IPAddress.Loopback)) + { + _interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); + } + + if (bindAddresses.Contains(IPAddress.IPv6Loopback)) + { + _interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); + } } // Remove all interfaces matching any virtual machine interface prefix @@ -358,6 +371,16 @@ namespace Jellyfin.Networking.Manager } } + if (!IsIpv4Enabled) + { + _interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetwork); + } + + if (!IsIpv6Enabled) + { + _interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetworkV6); + } + _logger.LogInformation("Using bind addresses: {0}", _interfaces.Select(x => x.Address)); } } @@ -492,7 +515,7 @@ namespace Jellyfin.Networking.Manager } } - EnforceBindRestrictions(config); + EnforceBindSettings(config); InitialiseOverrides(config); } @@ -892,7 +915,7 @@ namespace Jellyfin.Networking.Manager { result = string.Empty; - int count = _interfaces.Count(); + int count = _interfaces.Count; if (count == 1 && (_interfaces[0].Equals(IPAddress.Any) || _interfaces[0].Equals(IPAddress.IPv6Any))) { // Ignore IPAny addresses. From 05458a4a4240d2b15db93de6c9ec25376677b5e1 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Thu, 21 Jul 2022 00:32:51 +0200 Subject: [PATCH 018/358] Fix some ssdp errors --- RSSDP/SsdpCommunicationsServer.cs | 6 ++++-- RSSDP/SsdpDevicePublisher.cs | 4 +--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index 6e4f5634da..53f872b600 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -348,8 +348,6 @@ namespace Rssdp.Infrastructure { var sockets = new List(); - sockets.Add(_SocketFactory.CreateSsdpUdpSocket(IPAddress.Any, _LocalPort)); - if (_enableMultiSocketBinding) { foreach (var address in _networkManager.GetInternalBindAddresses()) @@ -370,6 +368,10 @@ namespace Rssdp.Infrastructure } } } + else + { + sockets.Add(_SocketFactory.CreateSsdpUdpSocket(IPAddress.Any, _LocalPort)); + } foreach (var socket in sockets) { diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs index 37c4128ba4..adaac5fa38 100644 --- a/RSSDP/SsdpDevicePublisher.cs +++ b/RSSDP/SsdpDevicePublisher.cs @@ -298,9 +298,7 @@ namespace Rssdp.Infrastructure foreach (var device in deviceList) { var root = device.ToRootDevice(); - var source = new IPData(root.Address, new IPNetwork(root.Address, root.PrefixLength), root.FriendlyName); - var destination = new IPData(remoteEndPoint.Address, new IPNetwork(root.Address, root.PrefixLength)); - if (!_sendOnlyMatchedHost || source.Address.Equals(destination.Address)) + if (!_sendOnlyMatchedHost || root.Address.Equals(remoteEndPoint.Address)) { SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIpAddress, cancellationToken); } From f6e41269d94e4c3096b136a47d3616cb0c5fe316 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Thu, 21 Jul 2022 09:26:18 +0200 Subject: [PATCH 019/358] Enforce interface bindings on SSDP, add Loopback to LAN if no LAN defined --- Emby.Dlna/Main/DlnaEntryPoint.cs | 7 +- .../Net/SocketFactory.cs | 13 ++-- Jellyfin.Networking/Manager/NetworkManager.cs | 16 ++-- MediaBrowser.Model/Net/ISocketFactory.cs | 4 +- RSSDP/SsdpCommunicationsServer.cs | 75 +++++++++++++------ 5 files changed, 74 insertions(+), 41 deletions(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 90c985a816..89119d31dc 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -284,6 +284,7 @@ namespace Emby.Dlna.Main var udn = CreateUuid(_appHost.SystemId); var descriptorUri = "/dlna/" + udn + "/description.xml"; + // Only get bind addresses in LAN var bindAddresses = _networkManager .GetInternalBindAddresses() .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork @@ -304,12 +305,6 @@ namespace Emby.Dlna.Main continue; } - // Limit to LAN addresses only - if (!_networkManager.IsInLocalNetwork(address.Address)) - { - continue; - } - var fullService = "urn:schemas-upnp-org:device:MediaServer:1"; _logger.LogInformation("Registering publisher for {ResourceName} on {DeviceAddress}", fullService, address); diff --git a/Emby.Server.Implementations/Net/SocketFactory.cs b/Emby.Server.Implementations/Net/SocketFactory.cs index 21795c8f86..a1baf30064 100644 --- a/Emby.Server.Implementations/Net/SocketFactory.cs +++ b/Emby.Server.Implementations/Net/SocketFactory.cs @@ -61,13 +61,18 @@ namespace Emby.Server.Implementations.Net } /// - public ISocket CreateUdpMulticastSocket(IPAddress ipAddress, int multicastTimeToLive, int localPort) + public ISocket CreateUdpMulticastSocket(IPAddress ipAddress, IPAddress bindIpAddress, int multicastTimeToLive, int localPort) { if (ipAddress == null) { throw new ArgumentNullException(nameof(ipAddress)); } + if (bindIpAddress == null) + { + bindIpAddress = IPAddress.Any; + } + if (multicastTimeToLive <= 0) { throw new ArgumentException("multicastTimeToLive cannot be zero or less.", nameof(multicastTimeToLive)); @@ -98,12 +103,10 @@ namespace Emby.Server.Implementations.Net // retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true); retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive); - var localIp = IPAddress.Any; - - retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ipAddress, localIp)); + retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ipAddress, bindIpAddress)); retVal.MulticastLoopback = true; - return new UdpSocket(retVal, localPort, localIp); + return new UdpSocket(retVal, localPort, bindIpAddress); } catch { diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index af2429cc28..b1112626c4 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -298,20 +298,22 @@ namespace Jellyfin.Networking.Manager if (_lanSubnets.Count == 0) { - // If no LAN addresses are specified, all private subnets are deemed to be the LAN + // If no LAN addresses are specified, all private subnets and Loopback are deemed to be the LAN _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); if (IsIpv6Enabled) { - _lanSubnets.Add(new IPNetwork(IPAddress.Parse("fc00::"), 7)); // ULA - _lanSubnets.Add(new IPNetwork(IPAddress.Parse("fe80::"), 10)); // Site local + _lanSubnets.Add(new IPNetwork(IPAddress.IPv6Loopback, 128)); // RFC 4291 (Loopback) + _lanSubnets.Add(new IPNetwork(IPAddress.Parse("fe80::"), 10)); // RFC 4291 (Site local) + _lanSubnets.Add(new IPNetwork(IPAddress.Parse("fc00::"), 7)); // RFC 4193 (Unique local) } if (IsIpv4Enabled) { - _lanSubnets.Add(new IPNetwork(IPAddress.Parse("10.0.0.0"), 8)); - _lanSubnets.Add(new IPNetwork(IPAddress.Parse("172.16.0.0"), 12)); - _lanSubnets.Add(new IPNetwork(IPAddress.Parse("192.168.0.0"), 16)); + _lanSubnets.Add(new IPNetwork(IPAddress.Loopback, 8)); // RFC 5735 (Loopback) + _lanSubnets.Add(new IPNetwork(IPAddress.Parse("10.0.0.0"), 8)); // RFC 1918 (private) + _lanSubnets.Add(new IPNetwork(IPAddress.Parse("172.16.0.0"), 12)); // RFC 1918 (private) + _lanSubnets.Add(new IPNetwork(IPAddress.Parse("192.168.0.0"), 16)); // RFC 1918 (private) } } @@ -371,11 +373,13 @@ namespace Jellyfin.Networking.Manager } } + // Remove all IPv4 interfaces if IPv4 is disabled if (!IsIpv4Enabled) { _interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetwork); } + // Remove all IPv6 interfaces if IPv6 is disabled if (!IsIpv6Enabled) { _interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetworkV6); diff --git a/MediaBrowser.Model/Net/ISocketFactory.cs b/MediaBrowser.Model/Net/ISocketFactory.cs index a2835b711b..e5cf7adbc0 100644 --- a/MediaBrowser.Model/Net/ISocketFactory.cs +++ b/MediaBrowser.Model/Net/ISocketFactory.cs @@ -1,5 +1,6 @@ #pragma warning disable CS1591 +using System.Collections.Generic; using System.Net; namespace MediaBrowser.Model.Net @@ -23,9 +24,10 @@ namespace MediaBrowser.Model.Net /// Creates a new multicast socket using the specified multicast IP address, multicast time to live and local port. /// /// The multicast IP address to bind to. + /// The bind IP address. /// The multicast time to live value. Actually a maximum number of network hops for UDP packets. /// The local port to bind to. /// A implementation. - ISocket CreateUdpMulticastSocket(IPAddress ipAddress, int multicastTimeToLive, int localPort); + ISocket CreateUdpMulticastSocket(IPAddress ipAddress, IPAddress bindIpAddress, int multicastTimeToLive, int localPort); } } diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index 53f872b600..e6c0a44039 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -33,7 +33,7 @@ namespace Rssdp.Infrastructure */ private object _BroadcastListenSocketSynchroniser = new object(); - private ISocket _BroadcastListenSocket; + private List _BroadcastListenSockets; private object _SendSocketSynchroniser = new object(); private List _sendSockets; @@ -111,24 +111,21 @@ namespace Rssdp.Infrastructure { ThrowIfDisposed(); - if (_BroadcastListenSocket == null) + lock (_BroadcastListenSocketSynchroniser) { - lock (_BroadcastListenSocketSynchroniser) + if (_BroadcastListenSockets == null) { - if (_BroadcastListenSocket == null) + try + { + _BroadcastListenSockets = ListenForBroadcastsAsync(); + } + catch (SocketException ex) + { + _logger.LogError("Failed to bind to port 1900: {Message}. DLNA will be unavailable", ex.Message); + } + catch (Exception ex) { - try - { - _BroadcastListenSocket = ListenForBroadcastsAsync(); - } - catch (SocketException ex) - { - _logger.LogError("Failed to bind to port 1900: {Message}. DLNA will be unavailable", ex.Message); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error in BeginListeningForBroadcasts"); - } + _logger.LogError(ex, "Error in BeginListeningForBroadcasts"); } } } @@ -142,11 +139,15 @@ namespace Rssdp.Infrastructure { lock (_BroadcastListenSocketSynchroniser) { - if (_BroadcastListenSocket != null) + if (_BroadcastListenSockets != null) { _logger.LogInformation("{0} disposing _BroadcastListenSocket", GetType().Name); - _BroadcastListenSocket.Dispose(); - _BroadcastListenSocket = null; + foreach (var socket in _BroadcastListenSockets) + { + socket.Dispose(); + } + + _BroadcastListenSockets = null; } } } @@ -336,12 +337,40 @@ namespace Rssdp.Infrastructure return Task.CompletedTask; } - private ISocket ListenForBroadcastsAsync() + private List ListenForBroadcastsAsync() { - var socket = _SocketFactory.CreateUdpMulticastSocket(IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress), _MulticastTtl, SsdpConstants.MulticastPort); - _ = ListenToSocketInternal(socket); + var sockets = new List(); + if (_enableMultiSocketBinding) + { + foreach (var address in _networkManager.GetInternalBindAddresses()) + { + if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + // Not support IPv6 right now + continue; + } - return socket; + try + { + sockets.Add(_SocketFactory.CreateUdpMulticastSocket(IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress), address.Address, _MulticastTtl, SsdpConstants.MulticastPort)); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error in ListenForBroadcastsAsync. IPAddress: {0}", address); + } + } + } + else + { + sockets.Add(_SocketFactory.CreateUdpMulticastSocket(IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress), IPAddress.Any, _MulticastTtl, SsdpConstants.MulticastPort)); + } + + foreach (var socket in sockets) + { + _ = ListenToSocketInternal(socket); + } + + return sockets; } private List CreateSocketAndListenForResponsesAsync() From b01d169d28cb7cfffa33796dfe7bf8be5570593a Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Thu, 21 Jul 2022 09:42:45 +0200 Subject: [PATCH 020/358] Implement discovery respecting bind addresses --- .../EntryPoints/UdpServerEntryPoint.cs | 20 ++++++++++++++++--- Emby.Server.Implementations/Udp/UdpServer.cs | 4 +++- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index e45baedd7f..9ac2310b4f 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -5,6 +5,7 @@ using System.Threading.Tasks; using Emby.Server.Implementations.Udp; using Jellyfin.Networking.Configuration; using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.Plugins; using Microsoft.Extensions.Configuration; @@ -29,6 +30,7 @@ namespace Emby.Server.Implementations.EntryPoints private readonly IServerApplicationHost _appHost; private readonly IConfiguration _config; private readonly IConfigurationManager _configurationManager; + private readonly INetworkManager _networkManager; /// /// The UDP server. @@ -44,16 +46,19 @@ namespace Emby.Server.Implementations.EntryPoints /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// Instance of the interface. public UdpServerEntryPoint( ILogger logger, IServerApplicationHost appHost, IConfiguration configuration, - IConfigurationManager configurationManager) + IConfigurationManager configurationManager, + INetworkManager networkManager) { _logger = logger; _appHost = appHost; _config = configuration; _configurationManager = configurationManager; + _networkManager = networkManager; } /// @@ -68,8 +73,17 @@ namespace Emby.Server.Implementations.EntryPoints try { - _udpServer = new UdpServer(_logger, _appHost, _config, PortNumber); - _udpServer.Start(_cancellationTokenSource.Token); + foreach (var bindAddress in _networkManager.GetInternalBindAddresses()) + { + if (bindAddress.AddressFamily == AddressFamily.InterNetworkV6) + { + // Not supporting IPv6 right now + continue; + } + + _udpServer = new UdpServer(_logger, _appHost, _config, bindAddress.Address, PortNumber); + _udpServer.Start(_cancellationTokenSource.Token); + } } catch (SocketException ex) { diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs index 937e792f57..a3bbd6df0c 100644 --- a/Emby.Server.Implementations/Udp/UdpServer.cs +++ b/Emby.Server.Implementations/Udp/UdpServer.cs @@ -37,18 +37,20 @@ namespace Emby.Server.Implementations.Udp /// The logger. /// The application host. /// The configuration manager. + /// The bind address. /// The port. public UdpServer( ILogger logger, IServerApplicationHost appHost, IConfiguration configuration, + IPAddress bindAddress, int port) { _logger = logger; _appHost = appHost; _config = configuration; - _endpoint = new IPEndPoint(IPAddress.Any, port); + _endpoint = new IPEndPoint(bindAddress, port); _udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); _udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); From a2857c5a02746d1cfd36d484b61961293de2b889 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Thu, 21 Jul 2022 10:20:20 +0200 Subject: [PATCH 021/358] Check if OS is capable of binding multiple sockets before creating autodiscovery sockets --- .../EntryPoints/UdpServerEntryPoint.cs | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index 9ac2310b4f..46b66dab3e 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -31,6 +31,7 @@ namespace Emby.Server.Implementations.EntryPoints private readonly IConfiguration _config; private readonly IConfigurationManager _configurationManager; private readonly INetworkManager _networkManager; + private readonly bool _enableMultiSocketBinding; /// /// The UDP server. @@ -59,6 +60,7 @@ namespace Emby.Server.Implementations.EntryPoints _config = configuration; _configurationManager = configurationManager; _networkManager = networkManager; + _enableMultiSocketBinding = OperatingSystem.IsWindows() || OperatingSystem.IsLinux(); } /// @@ -73,15 +75,23 @@ namespace Emby.Server.Implementations.EntryPoints try { - foreach (var bindAddress in _networkManager.GetInternalBindAddresses()) + if (_enableMultiSocketBinding) { - if (bindAddress.AddressFamily == AddressFamily.InterNetworkV6) + foreach (var bindAddress in _networkManager.GetInternalBindAddresses()) { - // Not supporting IPv6 right now - continue; - } + if (bindAddress.AddressFamily == AddressFamily.InterNetworkV6) + { + // Not supporting IPv6 right now + continue; + } - _udpServer = new UdpServer(_logger, _appHost, _config, bindAddress.Address, PortNumber); + _udpServer = new UdpServer(_logger, _appHost, _config, bindAddress.Address, PortNumber); + _udpServer.Start(_cancellationTokenSource.Token); + } + } + else + { + _udpServer = new UdpServer(_logger, _appHost, _config, System.Net.IPAddress.Any, PortNumber); _udpServer.Start(_cancellationTokenSource.Token); } } From b5c1d6129e394e40cd8a6bf338184edfe58c0ef4 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Thu, 21 Jul 2022 11:43:45 +0200 Subject: [PATCH 022/358] Remove more unused network configuration parameters --- .../Configuration/NetworkConfiguration.cs | 48 ------------------- 1 file changed, 48 deletions(-) diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index e9f6d597b4..642af7dda0 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -102,21 +102,11 @@ namespace Jellyfin.Networking.Configuration /// The public mapped port. public int PublicPort { get; set; } = DefaultHttpPort; - /// - /// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding. - /// - public bool UPnPCreateHttpPortMap { get; set; } - /// /// Gets or sets a value indicating whether Autodiscovery is enabled. /// public bool AutoDiscovery { get; set; } = true; - /// - /// Gets or sets a value indicating whether Autodiscovery tracing is enabled. - /// - public bool AutoDiscoveryTracing { get; set; } - /// /// Gets or sets a value indicating whether to enable automatic port forwarding. /// @@ -152,21 +142,6 @@ namespace Jellyfin.Networking.Configuration /// public string[] KnownProxies { get; set; } = Array.Empty(); - /// - /// Gets or sets the UDPPortRange. - /// - public string UDPPortRange { get; set; } = string.Empty; - - /// - /// Gets or sets the number of times SSDP UDP messages are sent. - /// - public int UDPSendCount { get; set; } = 2; - - /// - /// Gets or sets the delay between each groups of SSDP messages (in ms). - /// - public int UDPSendDelay { get; set; } = 100; - /// /// Gets or sets a value indicating whether address names that match should be Ignore for the purposes of binding. /// @@ -188,16 +163,6 @@ namespace Jellyfin.Networking.Configuration /// public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty(); - /// - /// Gets a value indicating whether multi-socket binding is available. - /// - public bool EnableMultiSocketBinding { get; } = true; - - /// - /// Gets or sets the ports that HDHomerun uses. - /// - public string HDHomerunPortRange { get; set; } = string.Empty; - /// /// Gets or sets the filter for remote IP connectivity. Used in conjuntion with . /// @@ -207,18 +172,5 @@ namespace Jellyfin.Networking.Configuration /// Gets or sets a value indicating whether contains a blacklist or a whitelist. Default is a whitelist. /// public bool IsRemoteIPFilterBlacklist { get; set; } - - /// - /// 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 have any effect. - /// - public bool EnableSSDPTracing { get; set; } - - /// - /// 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. - /// - public string SSDPTracingFilter { get; set; } = string.Empty; } } From cea8e8bbf601b97119c8b0b0a2e666414b53050c Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Thu, 21 Jul 2022 19:17:44 +0200 Subject: [PATCH 023/358] Fix logging output --- Emby.Dlna/Main/DlnaEntryPoint.cs | 2 +- Jellyfin.Networking/Manager/NetworkManager.cs | 33 +++++++++++-------- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 89119d31dc..0aea7855a6 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -307,7 +307,7 @@ namespace Emby.Dlna.Main var fullService = "urn:schemas-upnp-org:device:MediaServer:1"; - _logger.LogInformation("Registering publisher for {ResourceName} on {DeviceAddress}", fullService, address); + _logger.LogInformation("Registering publisher for {ResourceName} on {DeviceAddress}", fullService, address.Address); var uri = new UriBuilder(_appHost.GetApiUrlForLocalAccess(address.Address, false) + descriptorUri); diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index b1112626c4..12edb0e55c 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -933,22 +933,27 @@ namespace Jellyfin.Networking.Manager .OrderBy(x => x.Index) .ToList(); - if (isInExternalSubnet && externalInterfaces.Any()) + if (isInExternalSubnet) { - // Check to see if any of the external bind interfaces are in the same subnet as the source. - // If none exists, this will select the first external interface if there is one. - bindAddress = externalInterfaces - .OrderByDescending(x => x.Subnet.Contains(source)) - .ThenBy(x => x.Index) - .Select(x => x.Address) - .FirstOrDefault(); - - if (bindAddress != null) + if (externalInterfaces.Any()) { - result = NetworkExtensions.FormatIpString(bindAddress); - _logger.LogDebug("{Source}: GetBindInterface: Has source, found a matching external bind interface. {Result}", source, result); - return true; + // Check to see if any of the external bind interfaces are in the same subnet as the source. + // If none exists, this will select the first external interface if there is one. + bindAddress = externalInterfaces + .OrderByDescending(x => x.Subnet.Contains(source)) + .ThenBy(x => x.Index) + .Select(x => x.Address) + .FirstOrDefault(); + + if (bindAddress != null) + { + result = NetworkExtensions.FormatIpString(bindAddress); + _logger.LogDebug("{Source}: GetBindInterface: Has source, found a matching external bind interface. {Result}", source, result); + return true; + } } + + _logger.LogWarning("{Source}: External request received, no external interface bind found, trying internal interfaces.", source); } else { @@ -963,7 +968,7 @@ namespace Jellyfin.Networking.Manager if (bindAddress != null) { result = NetworkExtensions.FormatIpString(bindAddress); - _logger.LogWarning("{Source}: External request received, only an internal interface bind found. {Result}", source, result); + _logger.LogWarning("{Source}: Request received, matching internal interface bind found. {Result}", source, result); return true; } } From ff22f597d219b74ce392e4bbbaf1123e5a269f99 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Thu, 21 Jul 2022 19:38:19 +0200 Subject: [PATCH 024/358] Fix multiple UDP servers for AutoDiscovery --- .../EntryPoints/UdpServerEntryPoint.cs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index 46b66dab3e..82c6abb8c8 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; @@ -36,7 +37,7 @@ namespace Emby.Server.Implementations.EntryPoints /// /// The UDP server. /// - private UdpServer? _udpServer; + private List _udpServers; private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private bool _disposed = false; @@ -60,6 +61,7 @@ namespace Emby.Server.Implementations.EntryPoints _config = configuration; _configurationManager = configurationManager; _networkManager = networkManager; + _udpServers = new List(); _enableMultiSocketBinding = OperatingSystem.IsWindows() || OperatingSystem.IsLinux(); } @@ -85,15 +87,15 @@ namespace Emby.Server.Implementations.EntryPoints continue; } - _udpServer = new UdpServer(_logger, _appHost, _config, bindAddress.Address, PortNumber); - _udpServer.Start(_cancellationTokenSource.Token); + _udpServers.Add(new UdpServer(_logger, _appHost, _config, bindAddress.Address, PortNumber)); } } else { - _udpServer = new UdpServer(_logger, _appHost, _config, System.Net.IPAddress.Any, PortNumber); - _udpServer.Start(_cancellationTokenSource.Token); + _udpServers.Add(new UdpServer(_logger, _appHost, _config, System.Net.IPAddress.Any, PortNumber)); } + + _udpServers.ForEach(u => u.Start(_cancellationTokenSource.Token)); } catch (SocketException ex) { @@ -121,8 +123,8 @@ namespace Emby.Server.Implementations.EntryPoints _cancellationTokenSource.Cancel(); _cancellationTokenSource.Dispose(); - _udpServer?.Dispose(); - _udpServer = null; + _udpServers.ForEach(s => s.Dispose()); + _udpServers.Clear(); _disposed = true; } From 59a86568d9539245dee30cf3a33ef6beb31f4bba Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Thu, 21 Jul 2022 22:09:54 +0200 Subject: [PATCH 025/358] Cleanup and fixes --- Jellyfin.Networking/Manager/NetworkManager.cs | 12 +++++- .../ApiServiceCollectionExtensions.cs | 8 ++-- MediaBrowser.Common/Net/INetworkManager.cs | 42 +++++++++---------- MediaBrowser.Common/Net/IPData.cs | 8 ++-- MediaBrowser.Model/Net/ISocketFactory.cs | 1 - RSSDP/SsdpCommunicationsServer.cs | 6 +-- 6 files changed, 39 insertions(+), 38 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 12edb0e55c..0f8f1a36a0 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -263,7 +263,7 @@ namespace Jellyfin.Networking.Manager if (_interfaces.Count == 0) { - _logger.LogWarning("No interfaces information available. Using loopback."); + _logger.LogWarning("No interface information available. Using loopback interface(s)."); if (IsIpv4Enabled && !IsIpv6Enabled) { @@ -450,6 +450,14 @@ namespace Jellyfin.Networking.Manager _publishedServerUrls[new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))] = replacement; _publishedServerUrls[new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))] = replacement; } + else if (string.Equals(parts[0], "internal", StringComparison.OrdinalIgnoreCase)) + { + foreach (var lan in _lanSubnets) + { + var lanPrefix = lan.Prefix; + _publishedServerUrls[new IPData(lanPrefix, new IPNetwork(lanPrefix, lan.PrefixLength))] = replacement; + } + } else if (IPAddress.TryParse(ipParts[0], out IPAddress? result)) { var data = new IPData(result, null); @@ -469,7 +477,7 @@ namespace Jellyfin.Networking.Manager } else { - _logger.LogError("Unable to parse bind ip address. {Parts}", parts[1]); + _logger.LogError("Unable to parse bind override: {Entry}", entry); } } } diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index a393b80db5..25516271c5 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -350,14 +350,14 @@ namespace Jellyfin.Server.Extensions } else if (NetworkExtensions.TryParseSubnets(new[] { allowedProxies[i] }, out var subnets)) { - for (var j = 0; j < subnets.Count; j++) + foreach (var subnet in subnets) { - AddIpAddress(config, options, subnets[j].Prefix, subnets[j].PrefixLength); + AddIpAddress(config, options, subnet.Prefix, subnet.PrefixLength); } } - else if (NetworkExtensions.TryParseHost(allowedProxies[i], out var host)) + else if (NetworkExtensions.TryParseHost(allowedProxies[i], out var addresses)) { - foreach (var address in host) + foreach (var address in addresses) { AddIpAddress(config, options, address, address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); } diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 21ff982376..d462e954a8 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -17,14 +17,14 @@ namespace MediaBrowser.Common.Net event EventHandler NetworkChanged; /// - /// Gets a value indicating whether IPv6 is enabled. + /// Gets a value indicating whether IPv4 is enabled. /// - bool IsIpv6Enabled { get; } + bool IsIpv4Enabled { get; } /// - /// Gets a value indicating whether IPv4 is enabled. + /// Gets a value indicating whether IPv6 is enabled. /// - bool IsIpv4Enabled { get; } + bool IsIpv6Enabled { get; } /// /// Calculates the list of interfaces to use for Kestrel. @@ -42,7 +42,7 @@ namespace MediaBrowser.Common.Net IReadOnlyList GetLoopbacks(); /// - /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) + /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. /// The priority of selection is as follows:- /// @@ -56,40 +56,40 @@ namespace MediaBrowser.Common.Net /// /// 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. + /// The first public interface that isn't a loopback. + /// The first internal interface that isn't a loopback. /// /// 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. + /// The first private interface that isn't a loopback. /// /// 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. + /// Interfaces that have been specifically excluded from binding are not used in any of the calculations. /// /// Source of the request. /// Optional port returned, if it's part of an override. - /// IP Address to use, or loopback address if all else fails. + /// IP address to use, or loopback address if all else fails. string GetBindInterface(HttpRequest source, out int? port); /// - /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) + /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. /// (See . /// /// IP address of the request. /// Optional port returned, if it's part of an override. - /// IP Address to use, or loopback address if all else fails. + /// IP address to use, or loopback address if all else fails. string GetBindInterface(IPAddress source, out int? port); /// - /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) + /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. /// (See . /// /// Source of the request. /// Optional port returned, if it's part of an override. - /// IP Address to use, or loopback address if all else fails. + /// IP address to use, or loopback address if all else fails. string GetBindInterface(string source, out int? port); /// @@ -100,7 +100,6 @@ namespace MediaBrowser.Common.Net /// /// Returns true if the address is part of the user defined LAN. - /// The configuration option TrustIP6Interfaces overrides this functions behaviour. /// /// IP to check. /// True if endpoint is within the LAN range. @@ -108,7 +107,6 @@ namespace MediaBrowser.Common.Net /// /// Returns true if the address is part of the user defined LAN. - /// The configuration option TrustIP6Interfaces overrides this functions behaviour. /// /// IP to check. /// True if endpoint is within the LAN range. @@ -119,21 +117,21 @@ namespace MediaBrowser.Common.Net /// eg. "eth1", or "enp3s5". /// /// Interface name. - /// Resultant object's ip addresses, if successful. + /// Resulting object's IP addresses, if successful. /// Success of the operation. bool TryParseInterface(string intf, out List? result); /// - /// Returns all the internal bind interface addresses. + /// Returns all internal (LAN) bind interface addresses. /// - /// An internal list of interfaces addresses. + /// An list of internal (LAN) interfaces addresses. IReadOnlyList GetInternalBindAddresses(); /// - /// Checks to see if has access. + /// Checks if has access to the server. /// - /// IP Address of client. - /// True if has access, otherwise false. + /// IP address of the client. + /// True if it has access, otherwise false. bool HasRemoteAccess(IPAddress remoteIp); } } diff --git a/MediaBrowser.Common/Net/IPData.cs b/MediaBrowser.Common/Net/IPData.cs index 6901d6ad8a..384efe8f68 100644 --- a/MediaBrowser.Common/Net/IPData.cs +++ b/MediaBrowser.Common/Net/IPData.cs @@ -12,9 +12,9 @@ namespace MediaBrowser.Common.Net /// /// Initializes a new instance of the class. /// - /// An . + /// The . /// The . - /// The object's name. + /// The interface name. public IPData(IPAddress address, IPNetwork? subnet, string name) { Address = address; @@ -25,7 +25,7 @@ namespace MediaBrowser.Common.Net /// /// Initializes a new instance of the class. /// - /// An . + /// The . /// The . public IPData(IPAddress address, IPNetwork? subnet) : this(address, subnet, string.Empty) @@ -53,7 +53,7 @@ namespace MediaBrowser.Common.Net public string Name { get; set; } /// - /// Gets the AddressFamily of this object. + /// Gets the AddressFamily of the object. /// public AddressFamily AddressFamily { diff --git a/MediaBrowser.Model/Net/ISocketFactory.cs b/MediaBrowser.Model/Net/ISocketFactory.cs index e5cf7adbc0..f3bc31796d 100644 --- a/MediaBrowser.Model/Net/ISocketFactory.cs +++ b/MediaBrowser.Model/Net/ISocketFactory.cs @@ -1,6 +1,5 @@ #pragma warning disable CS1591 -using System.Collections.Generic; using System.Net; namespace MediaBrowser.Model.Net diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index e6c0a44039..92c9c83c0f 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -142,11 +142,7 @@ namespace Rssdp.Infrastructure if (_BroadcastListenSockets != null) { _logger.LogInformation("{0} disposing _BroadcastListenSocket", GetType().Name); - foreach (var socket in _BroadcastListenSockets) - { - socket.Dispose(); - } - + _BroadcastListenSockets.ForEach(s => s.Dispose()); _BroadcastListenSockets = null; } } From bd9a940fed129d99fe9ffedafec324e795549c90 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Sat, 1 Oct 2022 20:00:35 +0200 Subject: [PATCH 026/358] Declare VirtualInterfaceNames as string array for consistency --- .../Configuration/NetworkConfiguration.cs | 2 +- Jellyfin.Networking/Manager/NetworkManager.cs | 31 ++++++++++++------- .../CreateNetworkConfiguration.cs | 2 +- 3 files changed, 21 insertions(+), 14 deletions(-) diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index 642af7dda0..f904198510 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -150,7 +150,7 @@ namespace Jellyfin.Networking.Configuration /// /// Gets or sets a value indicating the interface name prefixes that should be ignored. The list can be comma separated and values are case-insensitive. . /// - public string VirtualInterfaceNames { get; set; } = "veth"; + public string[] VirtualInterfaceNames { get; set; } = new string[] { "veth" }; /// /// Gets or sets a value indicating whether the published server uri is based on information in HTTP requests. diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 0f8f1a36a0..146340989b 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -359,12 +359,11 @@ namespace Jellyfin.Networking.Manager { // Remove potentially exisiting * and split config string into prefixes var virtualInterfacePrefixes = config.VirtualInterfaceNames - .Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase) - .ToLowerInvariant() - .Split(','); + .Select(i => i.ToLowerInvariant() + .Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase)); // Check all interfaces for matches against the prefixes and remove them - if (_interfaces.Count > 0 && virtualInterfacePrefixes.Length > 0) + if (_interfaces.Count > 0 && virtualInterfacePrefixes.Any()) { foreach (var virtualInterfacePrefix in virtualInterfacePrefixes) { @@ -726,7 +725,15 @@ namespace Jellyfin.Networking.Manager if (MatchesPublishedServerUrl(source, isExternal, out string res, out port)) { - _logger.LogInformation("{Source}: Using BindAddress {Address}:{Port}", source, res, port); + if (port != null) + { + _logger.LogInformation("{Source}: Using BindAddress {Address}:{Port}", source, res, port); + } + else + { + _logger.LogInformation("{Source}: Using BindAddress {Address}", source, res); + } + return res; } @@ -756,7 +763,7 @@ namespace Jellyfin.Networking.Manager if (intf.Address.Equals(source)) { result = NetworkExtensions.FormatIpString(intf.Address); - _logger.LogDebug("{Source}: GetBindInterface: Has found matching interface. {Result}", source, result); + _logger.LogDebug("{Source}: GetBindInterface: Has found matching interface: {Result}", source, result); return result; } } @@ -768,14 +775,14 @@ namespace Jellyfin.Networking.Manager if (intf.Subnet.Contains(source)) { result = NetworkExtensions.FormatIpString(intf.Address); - _logger.LogDebug("{Source}: GetBindInterface: Has source, matched best internal interface on range. {Result}", source, result); + _logger.LogDebug("{Source}: GetBindInterface: Has source, matched best internal interface on range: {Result}", source, result); return result; } } } result = NetworkExtensions.FormatIpString(availableInterfaces.First().Address); - _logger.LogDebug("{Source}: GetBindInterface: Matched first internal interface. {Result}", source, result); + _logger.LogDebug("{Source}: GetBindInterface: Matched first internal interface: {Result}", source, result); return result; } @@ -956,7 +963,7 @@ namespace Jellyfin.Networking.Manager if (bindAddress != null) { result = NetworkExtensions.FormatIpString(bindAddress); - _logger.LogDebug("{Source}: GetBindInterface: Has source, found a matching external bind interface. {Result}", source, result); + _logger.LogDebug("{Source}: GetBindInterface: Has source, found a matching external bind interface: {Result}", source, result); return true; } } @@ -976,7 +983,7 @@ namespace Jellyfin.Networking.Manager if (bindAddress != null) { result = NetworkExtensions.FormatIpString(bindAddress); - _logger.LogWarning("{Source}: Request received, matching internal interface bind found. {Result}", source, result); + _logger.LogWarning("{Source}: Request received, matching internal interface bind found: {Result}", source, result); return true; } } @@ -1006,7 +1013,7 @@ namespace Jellyfin.Networking.Manager if (!IsInLocalNetwork(intf.Address) && intf.Subnet.Contains(source)) { result = NetworkExtensions.FormatIpString(intf.Address); - _logger.LogDebug("{Source}: GetBindInterface: Selected best external on interface on range. {Result}", source, result); + _logger.LogDebug("{Source}: GetBindInterface: Selected best external on interface on range: {Result}", source, result); return true; } } @@ -1014,7 +1021,7 @@ namespace Jellyfin.Networking.Manager if (hasResult != null) { result = NetworkExtensions.FormatIpString(hasResult); - _logger.LogDebug("{Source}: GetBindInterface: Selected first external interface. {Result}", source, result); + _logger.LogDebug("{Source}: GetBindInterface: Selected first external interface: {Result}", source, result); return true; } diff --git a/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs b/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs index b670172814..2c2715526f 100644 --- a/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs +++ b/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs @@ -114,7 +114,7 @@ public class CreateNetworkConfiguration : IMigrationRoutine public bool IgnoreVirtualInterfaces { get; set; } = true; - public string VirtualInterfaceNames { get; set; } = "veth"; + public string[] VirtualInterfaceNames { get; set; } = new string[] { "veth" }; public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty(); From 4aec41752f63594e169511a314f8f86a0dde9c35 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Fri, 14 Oct 2022 10:25:57 +0200 Subject: [PATCH 027/358] Apply review suggestions --- Emby.Dlna/Main/DlnaEntryPoint.cs | 8 +-- Jellyfin.Networking/Manager/NetworkManager.cs | 58 ++++++++++--------- .../ApiServiceCollectionExtensions.cs | 4 +- MediaBrowser.Common/Net/NetworkExtensions.cs | 54 ++++++++++++++++- RSSDP/SsdpCommunicationsServer.cs | 6 +- 5 files changed, 92 insertions(+), 38 deletions(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 0aea7855a6..7c26262fe1 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -286,10 +286,10 @@ namespace Emby.Dlna.Main // Only get bind addresses in LAN var bindAddresses = _networkManager - .GetInternalBindAddresses() - .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork - || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0)) - .ToList(); + .GetInternalBindAddresses() + .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork + || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0)) + .ToList(); if (bindAddresses.Count == 0) { diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 333afd7484..42b66bbed3 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; +using System.Threading; using System.Threading.Tasks; using Jellyfin.Networking.Configuration; using MediaBrowser.Common.Configuration; @@ -34,7 +35,7 @@ namespace Jellyfin.Networking.Manager private readonly IConfigurationManager _configurationManager; - private readonly object _eventFireLock; + private readonly SemaphoreSlim _networkEvent; /// /// Holds the published server URLs and the IPs to use them on. @@ -86,7 +87,7 @@ namespace Jellyfin.Networking.Manager _interfaces = new List(); _macAddresses = new List(); _publishedServerUrls = new Dictionary(); - _eventFireLock = new object(); + _networkEvent = new SemaphoreSlim(1, 1); _remoteAddressFilter = new List(); UpdateSettings(_configurationManager.GetNetworkConfiguration()); @@ -143,7 +144,7 @@ namespace Jellyfin.Networking.Manager private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e) { _logger.LogDebug("Network availability changed."); - OnNetworkChanged(); + HandleNetworkChange(); } /// @@ -154,35 +155,34 @@ namespace Jellyfin.Networking.Manager private void OnNetworkAddressChanged(object? sender, EventArgs e) { _logger.LogDebug("Network address change detected."); - OnNetworkChanged(); + HandleNetworkChange(); } /// /// Triggers our event, and re-loads interface information. /// - private void OnNetworkChanged() + private void HandleNetworkChange() { - lock (_eventFireLock) + _networkEvent.Wait(); + if (!_eventfire) { - 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(); - } + _logger.LogDebug("Network Address Change Event."); + // As network events tend to fire one after the other only fire once every second. + _eventfire = true; + OnNetworkChange(); } + + _networkEvent.Release(); } /// - /// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession. + /// Waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession. /// - /// A representing the asynchronous operation. - private async Task OnNetworkChangeAsync() + private void OnNetworkChange() { try { - await Task.Delay(2000).ConfigureAwait(false); + Thread.Sleep(2000); var networkConfig = _configurationManager.GetNetworkConfiguration(); InitialiseLan(networkConfig); InitialiseInterfaces(); @@ -234,7 +234,7 @@ namespace Jellyfin.Networking.Manager { var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength), adapter.Name); interfaceObject.Index = ipProperties.GetIPv4Properties().Index; - interfaceObject.Name = adapter.Name.ToLowerInvariant(); + interfaceObject.Name = adapter.Name; _interfaces.Add(interfaceObject); } @@ -242,7 +242,7 @@ namespace Jellyfin.Networking.Manager { var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength), adapter.Name); interfaceObject.Index = ipProperties.GetIPv6Properties().Index; - interfaceObject.Name = adapter.Name.ToLowerInvariant(); + interfaceObject.Name = adapter.Name; _interfaces.Add(interfaceObject); } @@ -362,11 +362,10 @@ namespace Jellyfin.Networking.Manager { // Remove potentially exisiting * and split config string into prefixes var virtualInterfacePrefixes = config.VirtualInterfaceNames - .Select(i => i.ToLowerInvariant() - .Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase)); + .Select(i => i.Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase)); // Check all interfaces for matches against the prefixes and remove them - if (_interfaces.Count > 0 && virtualInterfacePrefixes.Any()) + if (_interfaces.Count > 0) { foreach (var virtualInterfacePrefix in virtualInterfacePrefixes) { @@ -548,6 +547,7 @@ namespace Jellyfin.Networking.Manager _configurationManager.NamedConfigurationUpdated -= ConfigurationUpdated; NetworkChange.NetworkAddressChanged -= OnNetworkAddressChanged; NetworkChange.NetworkAvailabilityChanged -= OnNetworkAvailabilityChanged; + _networkEvent.Dispose(); } _disposed = true; @@ -566,7 +566,7 @@ namespace Jellyfin.Networking.Manager if (_interfaces != null) { // Match all interfaces starting with names starting with token - var matchedInterfaces = _interfaces.Where(s => s.Name.Equals(intf.ToLowerInvariant(), StringComparison.OrdinalIgnoreCase)).OrderBy(x => x.Index); + var matchedInterfaces = _interfaces.Where(s => s.Name.Equals(intf, StringComparison.OrdinalIgnoreCase)).OrderBy(x => x.Index); if (matchedInterfaces.Any()) { _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", intf); @@ -609,7 +609,7 @@ namespace Jellyfin.Networking.Manager return false; } } - else if (!_lanSubnets.Where(x => x.Contains(remoteIp)).Any()) + else if (!_lanSubnets.Any(x => x.Contains(remoteIp))) { // Remote not enabled. So everyone should be LAN. return false; @@ -875,10 +875,12 @@ namespace Jellyfin.Networking.Manager bindPreference = string.Empty; port = null; - var validPublishedServerUrls = _publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.Any)).ToList(); - validPublishedServerUrls.AddRange(_publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.IPv6Any))); - validPublishedServerUrls.AddRange(_publishedServerUrls.Where(x => x.Key.Subnet.Contains(source))); - validPublishedServerUrls = validPublishedServerUrls.GroupBy(x => x.Key).Select(y => y.First()).ToList(); + var validPublishedServerUrls = _publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.Any) + || x.Key.Address.Equals(IPAddress.IPv6Any) + || x.Key.Subnet.Contains(source)) + .GroupBy(x => x.Key) + .Select(y => y.First()) + .ToList(); // Check for user override. foreach (var data in validPublishedServerUrls) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 25516271c5..a1adddcbb3 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -348,9 +348,9 @@ namespace Jellyfin.Server.Extensions { AddIpAddress(config, options, addr, addr.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); } - else if (NetworkExtensions.TryParseSubnets(new[] { allowedProxies[i] }, out var subnets)) + else if (NetworkExtensions.TryParseSubnet(allowedProxies[i], out var subnet)) { - foreach (var subnet in subnets) + if (subnet != null) { AddIpAddress(config, options, subnet.Prefix, subnet.PrefixLength); } diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 3d7d58b273..d7632c0deb 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -138,7 +138,7 @@ namespace MediaBrowser.Common.Net /// /// Try parsing an array of strings into subnets, respecting exclusions. /// - /// Input string to be parsed. + /// Input string array to be parsed. /// Collection of . /// Boolean signaling if negated or not negated values should be parsed. /// True if parsing was successful. @@ -190,6 +190,58 @@ namespace MediaBrowser.Common.Net return false; } + /// + /// Try parsing a string into a subnet, respecting exclusions. + /// + /// Input string to be parsed. + /// An . + /// Boolean signaling if negated or not negated values should be parsed. + /// True if parsing was successful. + public static bool TryParseSubnet(string value, out IPNetwork? result, bool negated = false) + { + result = null; + + if (string.IsNullOrEmpty(value)) + { + return false; + } + + string[] v = value.Trim().Split("/"); + + var address = IPAddress.None; + if (negated && v[0].StartsWith('!')) + { + _ = IPAddress.TryParse(v[0][1..], out address); + } + else if (!negated) + { + _ = IPAddress.TryParse(v[0][0..], out address); + } + + if (address != IPAddress.None && address != null) + { + if (int.TryParse(v[1], out var netmask)) + { + result = new IPNetwork(address, netmask); + } + else if (address.AddressFamily == AddressFamily.InterNetwork) + { + result = new IPNetwork(address, 32); + } + else if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + result = new IPNetwork(address, 128); + } + } + + if (result != null) + { + return true; + } + + return false; + } + /// /// Attempts to parse a host string. /// diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index 92c9c83c0f..da357546dd 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -117,7 +117,7 @@ namespace Rssdp.Infrastructure { try { - _BroadcastListenSockets = ListenForBroadcastsAsync(); + _BroadcastListenSockets = ListenForBroadcasts(); } catch (SocketException ex) { @@ -333,7 +333,7 @@ namespace Rssdp.Infrastructure return Task.CompletedTask; } - private List ListenForBroadcastsAsync() + private List ListenForBroadcasts() { var sockets = new List(); if (_enableMultiSocketBinding) @@ -352,7 +352,7 @@ namespace Rssdp.Infrastructure } catch (Exception ex) { - _logger.LogError(ex, "Error in ListenForBroadcastsAsync. IPAddress: {0}", address); + _logger.LogError(ex, "Error in ListenForBroadcasts. IPAddress: {0}", address); } } } From 87d0158a4af9d8c982736cbae77019fa6dd03126 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Sat, 15 Oct 2022 17:27:37 +0200 Subject: [PATCH 028/358] Fix autodiscovery --- .../EntryPoints/UdpServerEntryPoint.cs | 9 ++- Jellyfin.Networking/Manager/NetworkManager.cs | 59 +++++++++---------- MediaBrowser.Common/Net/NetworkExtensions.cs | 32 +++++++++- 3 files changed, 67 insertions(+), 33 deletions(-) diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index 82c6abb8c8..01a987b6ab 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -79,6 +79,10 @@ namespace Emby.Server.Implementations.EntryPoints { if (_enableMultiSocketBinding) { + // Add global broadcast socket + _udpServers.Add(new UdpServer(_logger, _appHost, _config, System.Net.IPAddress.Broadcast, PortNumber)); + + // Add bind address specific broadcast sockets foreach (var bindAddress in _networkManager.GetInternalBindAddresses()) { if (bindAddress.AddressFamily == AddressFamily.InterNetworkV6) @@ -87,7 +91,10 @@ namespace Emby.Server.Implementations.EntryPoints continue; } - _udpServers.Add(new UdpServer(_logger, _appHost, _config, bindAddress.Address, PortNumber)); + var broadcastAddress = NetworkExtensions.GetBroadcastAddress(bindAddress.Subnet); + _logger.LogDebug("Binding UDP server to {Address}", broadcastAddress.ToString()); + + _udpServers.Add(new UdpServer(_logger, _appHost, _config, broadcastAddress, PortNumber)); } } else diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 42b66bbed3..3c347461a7 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -280,7 +280,7 @@ namespace Jellyfin.Networking.Manager } _logger.LogDebug("Discovered {0} interfaces.", _interfaces.Count); - _logger.LogDebug("Interfaces addresses : {0}", _interfaces.Select(s => s.Address).ToString()); + _logger.LogDebug("Interfaces addresses : {0}", _interfaces.Select(s => s.Address.ToString())); } } @@ -726,20 +726,11 @@ namespace Jellyfin.Networking.Manager } bool isExternal = !_lanSubnets.Any(network => network.Contains(source)); - _logger.LogDebug("GetBindInterface with source. External: {IsExternal}:", isExternal); + _logger.LogDebug("GetBindInterface with source {Source}. External: {IsExternal}:", source, isExternal); - if (MatchesPublishedServerUrl(source, isExternal, out string res, out port)) + if (MatchesPublishedServerUrl(source, isExternal, out result)) { - if (port != null) - { - _logger.LogInformation("{Source}: Using BindAddress {Address}:{Port}", source, res, port); - } - else - { - _logger.LogInformation("{Source}: Using BindAddress {Address}", source, res); - } - - return res; + return result; } // No preference given, so move on to bind addresses. @@ -868,41 +859,37 @@ namespace Jellyfin.Networking.Manager /// IP source address to use. /// True if the source is in an external subnet. /// The published server URL that matches the source address. - /// The resultant port, if one exists. /// true if a match is found, false otherwise. - private bool MatchesPublishedServerUrl(IPAddress source, bool isInExternalSubnet, out string bindPreference, out int? port) + private bool MatchesPublishedServerUrl(IPAddress source, bool isInExternalSubnet, out string bindPreference) { bindPreference = string.Empty; - port = null; + int? port = null; var validPublishedServerUrls = _publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.Any) || x.Key.Address.Equals(IPAddress.IPv6Any) || x.Key.Subnet.Contains(source)) .GroupBy(x => x.Key) - .Select(y => y.First()) + .Select(x => x.First()) + .OrderBy(x => x.Key.Address.Equals(IPAddress.Any) + || x.Key.Address.Equals(IPAddress.IPv6Any)) .ToList(); // Check for user override. foreach (var data in validPublishedServerUrls) { - // Get address interface - var intf = _interfaces.OrderBy(x => x.Index).FirstOrDefault(s => s.Subnet.Contains(data.Key.Address)); + // Get address interface. + var intf = _interfaces.OrderBy(x => x.Index).FirstOrDefault(x => data.Key.Subnet.Contains(x.Address)); - // Remaining. Match anything. - if (data.Key.Address.Equals(IPAddress.Broadcast)) - { - bindPreference = data.Value; - break; - } - else if ((data.Key.Address.Equals(IPAddress.Any) || data.Key.Address.Equals(IPAddress.IPv6Any)) && isInExternalSubnet) + if (isInExternalSubnet && (data.Key.Address.Equals(IPAddress.Any) || data.Key.Address.Equals(IPAddress.IPv6Any))) { // External. bindPreference = data.Value; break; } - else if (intf?.Address != null) + + if (intf?.Address != null) { - // Match ip address. + // Match IP address. bindPreference = data.Value; break; } @@ -910,6 +897,7 @@ namespace Jellyfin.Networking.Manager if (string.IsNullOrEmpty(bindPreference)) { + _logger.LogInformation("{Source}: No matching bind address override found", source); return false; } @@ -924,6 +912,15 @@ namespace Jellyfin.Networking.Manager } } + if (port != null) + { + _logger.LogInformation("{Source}: Matching bind address override found {Address}:{Port}", source, bindPreference, port); + } + else + { + _logger.LogInformation("{Source}: Matching bind address override found {Address}", source, bindPreference); + } + return true; } @@ -967,12 +964,12 @@ namespace Jellyfin.Networking.Manager if (bindAddress != null) { result = NetworkExtensions.FormatIpString(bindAddress); - _logger.LogDebug("{Source}: GetBindInterface: Has source, found a matching external bind interface: {Result}", source, result); + _logger.LogDebug("{Source}: External request received, matching external bind interface found: {Result}", source, result); return true; } } - _logger.LogWarning("{Source}: External request received, no external interface bind found, trying internal interfaces.", source); + _logger.LogWarning("{Source}: External request received, no matching external bind interface found, trying internal interfaces.", source); } else { @@ -987,7 +984,7 @@ namespace Jellyfin.Networking.Manager if (bindAddress != null) { result = NetworkExtensions.FormatIpString(bindAddress); - _logger.LogWarning("{Source}: Request received, matching internal interface bind found: {Result}", source, result); + _logger.LogDebug("{Source}: Internal request received, matching internal bind interface found: {Result}", source, result); return true; } } diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index d7632c0deb..1c2b65346c 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -56,7 +56,23 @@ namespace MediaBrowser.Common.Net /// String value of the subnet mask in dotted decimal notation. public static IPAddress CidrToMask(byte cidr, AddressFamily family) { - uint addr = 0xFFFFFFFF << (family == AddressFamily.InterNetwork ? 32 : 128 - cidr); + 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); + } + + /// + /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. + /// + /// Subnet mask in CIDR notation. + /// IPv4 or IPv6 family. + /// String value of the subnet mask in dotted decimal notation. + public static IPAddress CidrToMask(int cidr, AddressFamily family) + { + uint addr = 0xFFFFFFFF << ((family == AddressFamily.InterNetwork ? 32 : 128) - cidr); addr = ((addr & 0xff000000) >> 24) | ((addr & 0x00ff0000) >> 8) | ((addr & 0x0000ff00) << 8) @@ -319,5 +335,19 @@ namespace MediaBrowser.Common.Net addresses = Array.Empty(); return false; } + + /// + /// Gets the broadcast address for a . + /// + /// The . + /// The broadcast address. + public static IPAddress GetBroadcastAddress(IPNetwork network) + { + uint ipAddress = BitConverter.ToUInt32(network.Prefix.GetAddressBytes(), 0); + uint ipMaskV4 = BitConverter.ToUInt32(CidrToMask(network.PrefixLength, AddressFamily.InterNetwork).GetAddressBytes(), 0); + uint broadCastIpAddress = ipAddress | ~ipMaskV4; + + return new IPAddress(BitConverter.GetBytes(broadCastIpAddress)); + } } } From 26d79a5ce3639700131d0359c60c096cd0fbb093 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Sat, 15 Oct 2022 20:57:02 +0200 Subject: [PATCH 029/358] Properly name some bind address functions, cleanup logging --- .../ApplicationHost.cs | 4 +- .../EntryPoints/UdpServerEntryPoint.cs | 2 +- Jellyfin.Networking/Manager/NetworkManager.cs | 47 +++++++++---------- MediaBrowser.Common/Net/INetworkManager.cs | 6 +-- 4 files changed, 29 insertions(+), 30 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 2ca5e6ded8..7004af3d43 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1069,7 +1069,7 @@ namespace Emby.Server.Implementations return PublishedServerUrl.Trim('/'); } - string smart = NetManager.GetBindInterface(remoteAddr, out var port); + string smart = NetManager.GetBindAddress(remoteAddr, out var port); return GetLocalApiUrl(smart.Trim('/'), null, port); } @@ -1118,7 +1118,7 @@ namespace Emby.Server.Implementations public string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true) { // With an empty source, the port will be null - var smart = NetManager.GetBindInterface(ipAddress, out _); + var smart = NetManager.GetBindAddress(ipAddress, out _); var scheme = !allowHttps ? Uri.UriSchemeHttp : null; int? port = !allowHttps ? HttpPort : null; return GetLocalApiUrl(smart, scheme, port); diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index 01a987b6ab..c2ffaf1bdd 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -92,7 +92,7 @@ namespace Emby.Server.Implementations.EntryPoints } var broadcastAddress = NetworkExtensions.GetBroadcastAddress(bindAddress.Subnet); - _logger.LogDebug("Binding UDP server to {Address}", broadcastAddress.ToString()); + _logger.LogDebug("Binding UDP server to {Address} on port {PortNumber}", broadcastAddress.ToString(), PortNumber); _udpServers.Add(new UdpServer(_logger, _appHost, _config, broadcastAddress, PortNumber)); } diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 3c347461a7..7e9fb4df71 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -6,7 +6,6 @@ using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading; -using System.Threading.Tasks; using Jellyfin.Networking.Configuration; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; @@ -280,7 +279,7 @@ namespace Jellyfin.Networking.Manager } _logger.LogDebug("Discovered {0} interfaces.", _interfaces.Count); - _logger.LogDebug("Interfaces addresses : {0}", _interfaces.Select(s => s.Address.ToString())); + _logger.LogDebug("Interfaces addresses: {0}", _interfaces.OrderByDescending(s => s.AddressFamily == AddressFamily.InterNetwork).Select(s => s.Address.ToString())); } } @@ -320,8 +319,8 @@ namespace Jellyfin.Networking.Manager } } - _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets.Select(s => s.Prefix + "/" + s.PrefixLength)); - _logger.LogInformation("Defined LAN exclusions : {0}", _excludedSubnets.Select(s => s.Prefix + "/" + s.PrefixLength)); + _logger.LogInformation("Defined LAN addresses: {0}", _lanSubnets.Select(s => s.Prefix + "/" + s.PrefixLength)); + _logger.LogInformation("Defined LAN exclusions: {0}", _excludedSubnets.Select(s => s.Prefix + "/" + s.PrefixLength)); _logger.LogInformation("Using LAN addresses: {0}", _lanSubnets.Where(s => !_excludedSubnets.Contains(s)).Select(s => s.Prefix + "/" + s.PrefixLength)); } } @@ -386,7 +385,7 @@ namespace Jellyfin.Networking.Manager _interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetworkV6); } - _logger.LogInformation("Using bind addresses: {0}", _interfaces.Select(x => x.Address)); + _logger.LogInformation("Using bind addresses: {0}", _interfaces.OrderByDescending(x => x.AddressFamily == AddressFamily.InterNetwork).Select(x => x.Address)); } } @@ -691,7 +690,7 @@ namespace Jellyfin.Networking.Manager public string GetBindInterface(string source, out int? port) { _ = NetworkExtensions.TryParseHost(source, out var address, IsIpv4Enabled, IsIpv6Enabled); - var result = GetBindInterface(address.FirstOrDefault(), out port); + var result = GetBindAddress(address.FirstOrDefault(), out port); return result; } @@ -700,14 +699,14 @@ namespace Jellyfin.Networking.Manager { string result; _ = NetworkExtensions.TryParseHost(source.Host.Host, out var addresses, IsIpv4Enabled, IsIpv6Enabled); - result = GetBindInterface(addresses.FirstOrDefault(), out port); + result = GetBindAddress(addresses.FirstOrDefault(), out port); port ??= source.Host.Port; return result; } /// - public string GetBindInterface(IPAddress? source, out int? port) + public string GetBindAddress(IPAddress? source, out int? port) { port = null; @@ -726,7 +725,7 @@ namespace Jellyfin.Networking.Manager } bool isExternal = !_lanSubnets.Any(network => network.Contains(source)); - _logger.LogDebug("GetBindInterface with source {Source}. External: {IsExternal}:", source, isExternal); + _logger.LogDebug("Trying to get bind address for source {Source} - External: {IsExternal}", source, isExternal); if (MatchesPublishedServerUrl(source, isExternal, out result)) { @@ -759,7 +758,7 @@ namespace Jellyfin.Networking.Manager if (intf.Address.Equals(source)) { result = NetworkExtensions.FormatIpString(intf.Address); - _logger.LogDebug("{Source}: GetBindInterface: Has found matching interface: {Result}", source, result); + _logger.LogDebug("{Source}: Found matching interface to use as bind address: {Result}", source, result); return result; } } @@ -771,20 +770,20 @@ namespace Jellyfin.Networking.Manager if (intf.Subnet.Contains(source)) { result = NetworkExtensions.FormatIpString(intf.Address); - _logger.LogDebug("{Source}: GetBindInterface: Has source, matched best internal interface on range: {Result}", source, result); + _logger.LogDebug("{Source}: Found internal interface with matching subnet, using it as bind address: {Result}", source, result); return result; } } } result = NetworkExtensions.FormatIpString(availableInterfaces.First().Address); - _logger.LogDebug("{Source}: GetBindInterface: Matched first internal interface: {Result}", source, result); + _logger.LogDebug("{Source}: Using first internal interface as bind address: {Result}", source, result); return result; } // There isn't any others, so we'll use the loopback. result = IsIpv4Enabled && !IsIpv6Enabled ? "127.0.0.1" : "::1"; - _logger.LogWarning("{Source}: GetBindInterface: Loopback {Result} returned.", source, result); + _logger.LogWarning("{Source}: Only loopback {Result} returned, using that as bind address.", source, result); return result; } @@ -897,7 +896,7 @@ namespace Jellyfin.Networking.Manager if (string.IsNullOrEmpty(bindPreference)) { - _logger.LogInformation("{Source}: No matching bind address override found", source); + _logger.LogDebug("{Source}: No matching bind address override found.", source); return false; } @@ -914,18 +913,18 @@ namespace Jellyfin.Networking.Manager if (port != null) { - _logger.LogInformation("{Source}: Matching bind address override found {Address}:{Port}", source, bindPreference, port); + _logger.LogDebug("{Source}: Matching bind address override found: {Address}:{Port}", source, bindPreference, port); } else { - _logger.LogInformation("{Source}: Matching bind address override found {Address}", source, bindPreference); + _logger.LogDebug("{Source}: Matching bind address override found: {Address}", source, bindPreference); } return true; } /// - /// Attempts to match the source against a user defined bind interface. + /// Attempts to match the source against the user defined bind interfaces. /// /// IP source address to use. /// True if the source is in the external subnet. @@ -964,12 +963,12 @@ namespace Jellyfin.Networking.Manager if (bindAddress != null) { result = NetworkExtensions.FormatIpString(bindAddress); - _logger.LogDebug("{Source}: External request received, matching external bind interface found: {Result}", source, result); + _logger.LogDebug("{Source}: External request received, matching external bind address found: {Result}", source, result); return true; } } - _logger.LogWarning("{Source}: External request received, no matching external bind interface found, trying internal interfaces.", source); + _logger.LogWarning("{Source}: External request received, no matching external bind address found, trying internal addresses.", source); } else { @@ -984,7 +983,7 @@ namespace Jellyfin.Networking.Manager if (bindAddress != null) { result = NetworkExtensions.FormatIpString(bindAddress); - _logger.LogDebug("{Source}: Internal request received, matching internal bind interface found: {Result}", source, result); + _logger.LogDebug("{Source}: Internal request received, matching internal bind address found: {Result}", source, result); return true; } } @@ -994,7 +993,7 @@ namespace Jellyfin.Networking.Manager } /// - /// Attempts to match the source against an external interface. + /// Attempts to match the source against external interfaces. /// /// IP source address to use. /// The result, if a match is found. @@ -1014,7 +1013,7 @@ namespace Jellyfin.Networking.Manager if (!IsInLocalNetwork(intf.Address) && intf.Subnet.Contains(source)) { result = NetworkExtensions.FormatIpString(intf.Address); - _logger.LogDebug("{Source}: GetBindInterface: Selected best external on interface on range: {Result}", source, result); + _logger.LogDebug("{Source}: Found external interface with matching subnet, using it as bind address: {Result}", source, result); return true; } } @@ -1022,11 +1021,11 @@ namespace Jellyfin.Networking.Manager if (hasResult != null) { result = NetworkExtensions.FormatIpString(hasResult); - _logger.LogDebug("{Source}: GetBindInterface: Selected first external interface: {Result}", source, result); + _logger.LogDebug("{Source}: Using first external interface as bind address: {Result}", source, result); return true; } - _logger.LogDebug("{Source}: External request received, but no WAN interface found. Need to route through internal network.", source); + _logger.LogWarning("{Source}: External request received, but no external interface found. Need to route through internal network.", source); return false; } } diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index d462e954a8..f0f16af78f 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -75,17 +75,17 @@ namespace MediaBrowser.Common.Net /// /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. - /// (See . + /// (See . /// /// IP address of the request. /// Optional port returned, if it's part of an override. /// IP address to use, or loopback address if all else fails. - string GetBindInterface(IPAddress source, out int? port); + string GetBindAddress(IPAddress source, out int? port); /// /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. - /// (See . + /// (See . /// /// Source of the request. /// Optional port returned, if it's part of an override. From f6d6f0367bf62435dfaf7d122415d31977f889aa Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Mon, 17 Oct 2022 15:38:42 +0200 Subject: [PATCH 030/358] Properly handle IPs with subnetmasks --- Jellyfin.Networking/Manager/NetworkManager.cs | 54 +++++++-------- .../ApiServiceCollectionExtensions.cs | 2 +- MediaBrowser.Common/Net/NetworkExtensions.cs | 26 +++++--- .../NetworkParseTests.cs | 65 ++++++++++--------- 4 files changed, 81 insertions(+), 66 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 7e9fb4df71..4a32423e5e 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -295,8 +295,8 @@ namespace Jellyfin.Networking.Manager // Get configuration options string[] subnets = config.LocalNetworkSubnets; - _ = NetworkExtensions.TryParseSubnets(subnets, out _lanSubnets, false); - _ = NetworkExtensions.TryParseSubnets(subnets, out _excludedSubnets, true); + _ = NetworkExtensions.TryParseToSubnets(subnets, out _lanSubnets, false); + _ = NetworkExtensions.TryParseToSubnets(subnets, out _excludedSubnets, true); if (_lanSubnets.Count == 0) { @@ -336,8 +336,8 @@ namespace Jellyfin.Networking.Manager var localNetworkAddresses = config.LocalNetworkAddresses; if (localNetworkAddresses.Length > 0 && !string.IsNullOrWhiteSpace(localNetworkAddresses.First())) { - var bindAddresses = localNetworkAddresses.Select(p => IPAddress.TryParse(p, out var addresses) - ? addresses + var bindAddresses = localNetworkAddresses.Select(p => NetworkExtensions.TryParseToSubnet(p, out var network) + ? network.Prefix : (_interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase)) .Select(x => x.Address) .FirstOrDefault() ?? IPAddress.None)) @@ -401,7 +401,7 @@ namespace Jellyfin.Networking.Manager if (remoteIPFilter.Any() && !string.IsNullOrWhiteSpace(remoteIPFilter.First())) { // Parse all IPs with netmask to a subnet - _ = NetworkExtensions.TryParseSubnets(remoteIPFilter.Where(x => x.Contains('/', StringComparison.OrdinalIgnoreCase)).ToArray(), out _remoteAddressFilter, false); + _ = NetworkExtensions.TryParseToSubnets(remoteIPFilter.Where(x => x.Contains('/', StringComparison.OrdinalIgnoreCase)).ToArray(), out _remoteAddressFilter, false); // Parse everything else as an IP and construct subnet with a single IP var ips = remoteIPFilter.Where(x => !x.Contains('/', StringComparison.OrdinalIgnoreCase)); @@ -440,17 +440,17 @@ namespace Jellyfin.Networking.Manager else { var replacement = parts[1].Trim(); - var ipParts = parts[0].Split("/"); - if (string.Equals(parts[0], "all", StringComparison.OrdinalIgnoreCase)) + var identifier = parts[0]; + if (string.Equals(identifier, "all", StringComparison.OrdinalIgnoreCase)) { _publishedServerUrls[new IPData(IPAddress.Broadcast, null)] = replacement; } - else if (string.Equals(parts[0], "external", StringComparison.OrdinalIgnoreCase)) + else if (string.Equals(identifier, "external", StringComparison.OrdinalIgnoreCase)) { _publishedServerUrls[new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))] = replacement; _publishedServerUrls[new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))] = replacement; } - else if (string.Equals(parts[0], "internal", StringComparison.OrdinalIgnoreCase)) + else if (string.Equals(identifier, "internal", StringComparison.OrdinalIgnoreCase)) { foreach (var lan in _lanSubnets) { @@ -458,17 +458,12 @@ namespace Jellyfin.Networking.Manager _publishedServerUrls[new IPData(lanPrefix, new IPNetwork(lanPrefix, lan.PrefixLength))] = replacement; } } - else if (IPAddress.TryParse(ipParts[0], out IPAddress? result)) + else if (NetworkExtensions.TryParseToSubnet(identifier, out var result) && result != null) { - var data = new IPData(result, null); - if (ipParts.Length > 1 && int.TryParse(ipParts[1], out var netmask)) - { - data.Subnet = new IPNetwork(result, netmask); - } - + var data = new IPData(result.Prefix, result); _publishedServerUrls[data] = replacement; } - else if (TryParseInterface(ipParts[0], out var ifaces)) + else if (TryParseInterface(identifier, out var ifaces)) { foreach (var iface in ifaces) { @@ -516,15 +511,20 @@ namespace Jellyfin.Networking.Manager foreach (var details in interfaceList) { var parts = details.Split(','); - var split = parts[0].Split("/"); - var address = IPAddress.Parse(split[0]); - var network = new IPNetwork(address, int.Parse(split[1], CultureInfo.InvariantCulture)); - var index = int.Parse(parts[1], CultureInfo.InvariantCulture); - if (address.AddressFamily == AddressFamily.InterNetwork || address.AddressFamily == AddressFamily.InterNetworkV6) + if (NetworkExtensions.TryParseToSubnet(parts[0], out var subnet)) + { + var address = subnet.Prefix; + var index = int.Parse(parts[1], CultureInfo.InvariantCulture); + if (address.AddressFamily == AddressFamily.InterNetwork || address.AddressFamily == AddressFamily.InterNetworkV6) + { + var data = new IPData(address, subnet, parts[2]); + data.Index = index; + _interfaces.Add(data); + } + } + else { - var data = new IPData(address, network, parts[2]); - data.Index = index; - _interfaces.Add(data); + _logger.LogWarning("Could not parse mock interface settings: {Part}", details); } } } @@ -799,9 +799,9 @@ namespace Jellyfin.Networking.Manager /// public bool IsInLocalNetwork(string address) { - if (IPAddress.TryParse(address, out var ep)) + if (NetworkExtensions.TryParseToSubnet(address, out var subnet)) { - return IPAddress.IsLoopback(ep) || (_lanSubnets.Any(x => x.Contains(ep)) && !_excludedSubnets.Any(x => x.Contains(ep))); + return IPAddress.IsLoopback(subnet.Prefix) || (_lanSubnets.Any(x => x.Contains(subnet.Prefix)) && !_excludedSubnets.Any(x => x.Contains(subnet.Prefix))); } if (NetworkExtensions.TryParseHost(address, out var addresses, IsIpv4Enabled, IsIpv6Enabled)) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index a1adddcbb3..439147bfd9 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -348,7 +348,7 @@ namespace Jellyfin.Server.Extensions { AddIpAddress(config, options, addr, addr.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); } - else if (NetworkExtensions.TryParseSubnet(allowedProxies[i], out var subnet)) + else if (NetworkExtensions.TryParseToSubnet(allowedProxies[i], out var subnet)) { if (subnet != null) { diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 1c2b65346c..e37a5dc6bc 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -152,13 +152,14 @@ namespace MediaBrowser.Common.Net } /// - /// Try parsing an array of strings into subnets, respecting exclusions. + /// Try parsing an array of strings into objects, respecting exclusions. + /// Elements without a subnet mask will be represented as with a single IP. /// /// Input string array to be parsed. /// Collection of . /// Boolean signaling if negated or not negated values should be parsed. /// True if parsing was successful. - public static bool TryParseSubnets(string[] values, out List result, bool negated = false) + public static bool TryParseToSubnets(string[] values, out List result, bool negated = false) { result = new List(); @@ -183,10 +184,14 @@ namespace MediaBrowser.Common.Net if (address != IPAddress.None && address != null) { - if (int.TryParse(v[1], out var netmask)) + if (v.Length > 1 && int.TryParse(v[1], out var netmask)) { result.Add(new IPNetwork(address, netmask)); } + else if (v.Length > 1 && IPAddress.TryParse(v[1], out var netmaskAddress)) + { + result.Add(new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress))); + } else if (address.AddressFamily == AddressFamily.InterNetwork) { result.Add(new IPNetwork(address, 32)); @@ -207,15 +212,16 @@ namespace MediaBrowser.Common.Net } /// - /// Try parsing a string into a subnet, respecting exclusions. + /// Try parsing a string into an , respecting exclusions. + /// Inputs without a subnet mask will be represented as with a single IP. /// /// Input string to be parsed. /// An . /// Boolean signaling if negated or not negated values should be parsed. /// True if parsing was successful. - public static bool TryParseSubnet(string value, out IPNetwork? result, bool negated = false) + public static bool TryParseToSubnet(string value, out IPNetwork result, bool negated = false) { - result = null; + result = new IPNetwork(IPAddress.None, 32); if (string.IsNullOrEmpty(value)) { @@ -236,10 +242,14 @@ namespace MediaBrowser.Common.Net if (address != IPAddress.None && address != null) { - if (int.TryParse(v[1], out var netmask)) + if (v.Length > 1 && int.TryParse(v[1], out var netmask)) { result = new IPNetwork(address, netmask); } + else if (v.Length > 1 && IPAddress.TryParse(v[1], out var netmaskAddress)) + { + result = new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress)); + } else if (address.AddressFamily == AddressFamily.InterNetwork) { result = new IPNetwork(address, 32); @@ -250,7 +260,7 @@ namespace MediaBrowser.Common.Net } } - if (result != null) + if (!result.Prefix.Equals(IPAddress.None)) { return true; } diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index d492b64393..86b2ab21a3 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -1,13 +1,11 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Linq; using System.Net; using Jellyfin.Networking.Configuration; using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; -using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Logging.Abstractions; using Moq; using Xunit; @@ -37,6 +35,8 @@ namespace Jellyfin.Networking.Tests [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]")] // eth16 only [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]")] + // eth16 only without mask + [InlineData("192.168.1.208,-16,eth16|200.200.200.200,11,eth11", "192.168.1.0/24", "[192.168.1.208/32]")] // All interfaces excluded. (including loopbacks) [InlineData("192.168.1.208/24,-16,vEthernet1|192.168.2.208/24,-16,vEthernet212|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[]")] // vEthernet1 and vEthernet212 should be excluded. @@ -65,66 +65,79 @@ namespace Jellyfin.Networking.Tests /// IP Address. [Theory] [InlineData("127.0.0.1")] + [InlineData("127.0.0.1/8")] + [InlineData("192.168.1.2")] + [InlineData("192.168.1.2/24")] + [InlineData("192.168.1.2/255.255.255.0")] [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517")] [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517]")] [InlineData("fe80::7add:12ff:febb:c67b%16")] [InlineData("[fe80::7add:12ff:febb:c67b%16]:123")] [InlineData("fe80::7add:12ff:febb:c67b%16:123")] [InlineData("[fe80::7add:12ff:febb:c67b%16]")] - [InlineData("192.168.1.2")] + [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517/56")] public static void TryParseValidIPStringsTrue(string address) - => Assert.True(IPAddress.TryParse(address, out _)); + => Assert.True(NetworkExtensions.TryParseToSubnet(address, out _)); /// /// Checks invalid IP address formats. /// /// IP Address. [Theory] - [InlineData("192.168.1.2/255.255.255.0")] - [InlineData("192.168.1.2/24")] - [InlineData("127.0.0.1/8")] [InlineData("127.0.0.1#")] [InlineData("localhost!")] [InlineData("256.128.0.0.0.1")] - [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517/56")] [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517:1231")] [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517:1231]")] public static void TryParseInvalidIPStringsFalse(string address) - => Assert.False(IPAddress.TryParse(address, out _)); + => Assert.False(NetworkExtensions.TryParseToSubnet(address, out _)); + /// + /// Checks if IPv4 address is within a defined subnet. + /// + /// Network mask. + /// IP Address. [Theory] [InlineData("192.168.5.85/24", "192.168.5.1")] [InlineData("192.168.5.85/24", "192.168.5.254")] + [InlineData("192.168.5.85/255.255.255.0", "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("10.128.240.50/255.255.255.252", "10.128.240.51")] [InlineData("127.0.0.1/8", "127.0.0.1")] public void IpV4SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress) { - var split = netMask.Split("/"); - var mask = int.Parse(split[1], CultureInfo.InvariantCulture); - var ipa = IPAddress.Parse(split[0]); - var ipn = new IPNetwork(ipa, mask); - Assert.True(ipn.Contains(IPAddress.Parse(ipAddress))); + var ipa = IPAddress.Parse(ipAddress); + Assert.True(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress))); } + /// + /// Checks if IPv4 address is not within a defined subnet. + /// + /// Network mask. + /// IP Address. [Theory] [InlineData("192.168.5.85/24", "192.168.4.254")] [InlineData("192.168.5.85/24", "191.168.5.254")] + [InlineData("192.168.5.85/255.255.255.252", "192.168.4.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")] + [InlineData("10.128.240.50/255.255.255.252", "10.127.240.51")] public void IpV4SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress) { - var split = netMask.Split("/"); - var mask = int.Parse(split[1], CultureInfo.InvariantCulture); - var ipa = IPAddress.Parse(split[0]); - var ipn = new IPNetwork(ipa, mask); - Assert.False(ipn.Contains(IPAddress.Parse(ipAddress))); + var ipa = IPAddress.Parse(ipAddress); + Assert.False(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress))); } + /// + /// Checks if IPv6 address is within a defined subnet. + /// + /// Network mask. + /// IP Address. [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")] @@ -133,11 +146,7 @@ namespace Jellyfin.Networking.Tests [InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")] public void IpV6SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress) { - var split = netMask.Split("/"); - var mask = int.Parse(split[1], CultureInfo.InvariantCulture); - var ipa = IPAddress.Parse(split[0]); - var ipn = new IPNetwork(ipa, mask); - Assert.True(ipn.Contains(IPAddress.Parse(ipAddress))); + Assert.True(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress))); } [Theory] @@ -148,11 +157,7 @@ namespace Jellyfin.Networking.Tests [InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0001")] public void IpV6SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress) { - var split = netMask.Split("/"); - var mask = int.Parse(split[1], CultureInfo.InvariantCulture); - var ipa = IPAddress.Parse(split[0]); - var ipn = new IPNetwork(ipa, mask); - Assert.False(ipn.Contains(IPAddress.Parse(ipAddress))); + Assert.False(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress))); } [Theory] @@ -262,7 +267,7 @@ namespace Jellyfin.Networking.Tests if (nm.TryParseInterface(result, out List? resultObj) && resultObj != null) { - // Parse out IPAddresses so we can do a string comparison. (Ignore subnet masks). + // Parse out IPAddresses so we can do a string comparison (ignore subnet masks). result = resultObj.First().Address.ToString(); } From 36994c17bf5f71f37a5002a51840306fa09fb0ef Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Thu, 17 Nov 2022 11:34:48 +0100 Subject: [PATCH 031/358] Apply review suggestions --- Jellyfin.Networking/Manager/NetworkManager.cs | 22 +++++++++---------- 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 4a32423e5e..4a6a4a5766 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -34,7 +34,7 @@ namespace Jellyfin.Networking.Manager private readonly IConfigurationManager _configurationManager; - private readonly SemaphoreSlim _networkEvent; + private readonly object _networkEventLock; /// /// Holds the published server URLs and the IPs to use them on. @@ -86,7 +86,7 @@ namespace Jellyfin.Networking.Manager _interfaces = new List(); _macAddresses = new List(); _publishedServerUrls = new Dictionary(); - _networkEvent = new SemaphoreSlim(1, 1); + _networkEventLock = new object(); _remoteAddressFilter = new List(); UpdateSettings(_configurationManager.GetNetworkConfiguration()); @@ -162,16 +162,15 @@ namespace Jellyfin.Networking.Manager /// private void HandleNetworkChange() { - _networkEvent.Wait(); - 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; - OnNetworkChange(); + lock(_networkEventLock){ + 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; + OnNetworkChange(); + } } - - _networkEvent.Release(); } /// @@ -546,7 +545,6 @@ namespace Jellyfin.Networking.Manager _configurationManager.NamedConfigurationUpdated -= ConfigurationUpdated; NetworkChange.NetworkAddressChanged -= OnNetworkAddressChanged; NetworkChange.NetworkAvailabilityChanged -= OnNetworkAvailabilityChanged; - _networkEvent.Dispose(); } _disposed = true; From 95740ef9a21f76b51ab777ef34162910b3da1b3c Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Sat, 3 Dec 2022 12:44:59 +0100 Subject: [PATCH 032/358] Fix build --- Jellyfin.Networking/Manager/NetworkManager.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 4a6a4a5766..0318582061 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -162,7 +162,8 @@ namespace Jellyfin.Networking.Manager /// private void HandleNetworkChange() { - lock(_networkEventLock){ + lock (_networkEventLock) + { if (!_eventfire) { _logger.LogDebug("Network Address Change Event."); From dd5f90802e71083347b6095eb79a9de0b9d34615 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Sat, 3 Dec 2022 14:32:20 +0100 Subject: [PATCH 033/358] Apply review suggestions --- Emby.Server.Implementations/ApplicationHost.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 1398bb373b..d4bf8a418b 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1093,8 +1093,9 @@ namespace Emby.Server.Implementations if (ConfigurationManager.GetNetworkConfiguration().EnablePublishedServerUriByRequest) { int? requestPort = request.Host.Port; - if (((requestPort == 80 || requestPort == null) && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase)) - || ((requestPort == 443 || requestPort == null) && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase))) + if (requestPort == null + || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase)) + || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase))) { requestPort = -1; } From 3f6354cdb832560ec811f1766666dd9ca1f2a208 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 7 Dec 2022 17:41:32 +0100 Subject: [PATCH 034/358] Fix .NET 7 compatibility --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- MediaBrowser.Common/Net/NetworkExtensions.cs | 10 +++++----- tests/Jellyfin.Networking.Tests/NetworkParseTests.cs | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 4733b39abe..df4f3e6762 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1094,7 +1094,7 @@ namespace Emby.Server.Implementations { int? requestPort = request.Host.Port; if (requestPort == null - || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase)) + || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase)) || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase))) { requestPort = -1; diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index e37a5dc6bc..97f0abbb52 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -1,10 +1,10 @@ -using Microsoft.AspNetCore.HttpOverrides; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; +using Microsoft.AspNetCore.HttpOverrides; namespace MediaBrowser.Common.Net { @@ -131,7 +131,7 @@ namespace MediaBrowser.Common.Net /// URI safe conversion of the address. public static string FormatIpString(IPAddress? address) { - if (address == null) + if (address is null) { return string.Empty; } @@ -163,7 +163,7 @@ namespace MediaBrowser.Common.Net { result = new List(); - if (values == null || values.Length == 0) + if (values is null || values.Length == 0) { return false; } @@ -182,7 +182,7 @@ namespace MediaBrowser.Common.Net _ = IPAddress.TryParse(v[0][0..], out address); } - if (address != IPAddress.None && address != null) + if (address != IPAddress.None && address is not null) { if (v.Length > 1 && int.TryParse(v[1], out var netmask)) { @@ -240,7 +240,7 @@ namespace MediaBrowser.Common.Net _ = IPAddress.TryParse(v[0][0..], out address); } - if (address != IPAddress.None && address != null) + if (address != IPAddress.None && address is not null) { if (v.Length > 1 && int.TryParse(v[1], out var netmask)) { diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index 86b2ab21a3..241d2314bf 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -207,7 +207,7 @@ namespace Jellyfin.Networking.Tests // Check to see if dns resolution is working. If not, skip test. _ = NetworkExtensions.TryParseHost(source, out var host); - if (resultObj != null && host.Length > 0) + if (resultObj is not null && host.Length > 0) { result = resultObj.First().Address.ToString(); var intf = nm.GetBindInterface(source, out _); @@ -265,7 +265,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - if (nm.TryParseInterface(result, out List? resultObj) && resultObj != null) + if (nm.TryParseInterface(result, out List? resultObj) && resultObj is not null) { // Parse out IPAddresses so we can do a string comparison (ignore subnet masks). result = resultObj.First().Address.ToString(); From b725fbe51af22ca270912eeb4929a8ee2a3b37a4 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Tue, 13 Dec 2022 10:39:37 +0100 Subject: [PATCH 035/358] Apply review suggestions --- Emby.Dlna/Main/DlnaEntryPoint.cs | 2 +- Emby.Server.Implementations/ApplicationHost.cs | 4 ++-- Emby.Server.Implementations/Net/SocketFactory.cs | 2 +- tests/Jellyfin.Server.Tests/ParseNetworkTests.cs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index ec483199d8..22903ec8f3 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -288,7 +288,7 @@ namespace Emby.Dlna.Main var bindAddresses = _networkManager .GetInternalBindAddresses() .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork - || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0)) + || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0)) .ToList(); if (bindAddresses.Count == 0) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index df4f3e6762..d0c744d2fb 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1094,8 +1094,8 @@ namespace Emby.Server.Implementations { int? requestPort = request.Host.Port; if (requestPort == null - || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase)) - || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase))) + || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase)) + || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase))) { requestPort = -1; } diff --git a/Emby.Server.Implementations/Net/SocketFactory.cs b/Emby.Server.Implementations/Net/SocketFactory.cs index 02e45e6899..e0c75698d2 100644 --- a/Emby.Server.Implementations/Net/SocketFactory.cs +++ b/Emby.Server.Implementations/Net/SocketFactory.cs @@ -61,7 +61,7 @@ namespace Emby.Server.Implementations.Net } /// - public ISocket CreateUdpMulticastSocket(IPAddress ipAddress, IPAddress bindIpAddress, int multicastTimeToLive, int localPort) + public ISocket CreateUdpMulticastSocket(IPAddress ipAddress, IPAddress? bindIpAddress, int multicastTimeToLive, int localPort) { ArgumentNullException.ThrowIfNull(ipAddress); diff --git a/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs index fc5f5f4c6c..12a9beb9e3 100644 --- a/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs +++ b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs @@ -22,7 +22,7 @@ namespace Jellyfin.Server.Tests true, true, new string[] { "192.168.t", "127.0.0.1", "::1", "1234.1232.12.1234" }, - new IPAddress[] { IPAddress.Loopback, }, + new IPAddress[] { IPAddress.Loopback }, new IPNetwork[] { new IPNetwork(IPAddress.IPv6Loopback, 128) }); data.Add( From f0376cdad9626f5ae0b41a5f54e765fc10dffa05 Mon Sep 17 00:00:00 2001 From: Brad Beattie Date: Wed, 14 Dec 2022 19:14:15 -0800 Subject: [PATCH 036/358] Augment tag searching to consider all ItemValues --- Emby.Server.Implementations/Data/SqliteItemRepository.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 1514762608..c189fc8780 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -2461,7 +2461,9 @@ namespace Emby.Server.Implementations.Data if (query.SearchTerm.Length > 1) { builder.Append("+ ((CleanName like @SearchTermContains or (OriginalTitle not null and OriginalTitle like @SearchTermContains)) * 10)"); - builder.Append("+ ((Tags not null and Tags like @SearchTermContains) * 5)"); + builder.Append("+ (SELECT COUNT(1) * 1 from ItemValues where ItemId=Guid and CleanValue like @SearchTermContains)"); + builder.Append("+ (SELECT COUNT(1) * 2 from ItemValues where ItemId=Guid and CleanValue like @SearchTermStartsWith)"); + builder.Append("+ (SELECT COUNT(1) * 10 from ItemValues where ItemId=Guid and CleanValue like @SearchTermEquals)"); } builder.Append(") as SearchScore"); @@ -2492,6 +2494,11 @@ namespace Emby.Server.Implementations.Data { statement.TryBind("@SearchTermContains", "%" + searchTerm + "%"); } + + if (commandText.Contains("@SearchTermEquals", StringComparison.OrdinalIgnoreCase)) + { + statement.TryBind("@SearchTermEquals", searchTerm); + } } private void BindSimilarParams(InternalItemsQuery query, IStatement statement) From 343a94f185213d238364896a27a2968cc32ea618 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Thu, 19 Jan 2023 10:19:53 +0100 Subject: [PATCH 037/358] Fix CA1851 --- Jellyfin.Networking/Manager/NetworkManager.cs | 7 ++++--- Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 0318582061..f4bd4e7662 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -564,13 +564,13 @@ namespace Jellyfin.Networking.Manager if (_interfaces != null) { // Match all interfaces starting with names starting with token - var matchedInterfaces = _interfaces.Where(s => s.Name.Equals(intf, StringComparison.OrdinalIgnoreCase)).OrderBy(x => x.Index); + var matchedInterfaces = _interfaces.Where(s => s.Name.Equals(intf, StringComparison.OrdinalIgnoreCase)).OrderBy(x => x.Index).ToList(); if (matchedInterfaces.Any()) { _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", intf); // Use interface IP instead of name - foreach (IPData iface in matchedInterfaces) + foreach (var iface in matchedInterfaces) { if ((IsIpv4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) || (IsIpv6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)) @@ -746,7 +746,8 @@ namespace Jellyfin.Networking.Manager // Get the first LAN interface address that's not excluded and not a loopback address. var availableInterfaces = _interfaces.Where(x => !IPAddress.IsLoopback(x.Address)) .OrderByDescending(x => IsInLocalNetwork(x.Address)) - .ThenBy(x => x.Index); + .ThenBy(x => x.Index) + .ToList(); if (availableInterfaces.Any()) { diff --git a/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs b/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs index 58d3e1b2d9..eac13f7610 100644 --- a/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs +++ b/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs @@ -39,7 +39,7 @@ public static class WebHostBuilderExtensions var addresses = appHost.NetManager.GetAllBindInterfaces(); bool flagged = false; - foreach (IPObject netAdd in addresses) + foreach (var netAdd in addresses) { logger.LogInformation("Kestrel listening on {Address}", IPAddress.IPv6Any.Equals(netAdd.Address) ? "All Addresses" : netAdd); options.Listen(netAdd.Address, appHost.HttpPort); From 6954283af3b5c75d38aa1bf2a399538fb19a8f0f Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Thu, 19 Jan 2023 18:48:22 +0100 Subject: [PATCH 038/358] Update Emby.Dlna/Main/DlnaEntryPoint.cs Co-authored-by: Patrick Barron --- Emby.Dlna/Main/DlnaEntryPoint.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 22903ec8f3..c9a091d8c2 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -286,10 +286,10 @@ namespace Emby.Dlna.Main // Only get bind addresses in LAN var bindAddresses = _networkManager - .GetInternalBindAddresses() - .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork - || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0)) - .ToList(); + .GetInternalBindAddresses() + .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork + || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0)) + .ToList(); if (bindAddresses.Count == 0) { From 6e460754142380eb7d2a509ee41b58e6a1c1665f Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Thu, 19 Jan 2023 19:03:43 +0100 Subject: [PATCH 039/358] Apply review suggestions --- Emby.Server.Implementations/Net/SocketFactory.cs | 8 ++------ RSSDP/SsdpCommunicationsServer.cs | 8 +++++--- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/Emby.Server.Implementations/Net/SocketFactory.cs b/Emby.Server.Implementations/Net/SocketFactory.cs index e0c75698d2..b6d87a7880 100644 --- a/Emby.Server.Implementations/Net/SocketFactory.cs +++ b/Emby.Server.Implementations/Net/SocketFactory.cs @@ -61,14 +61,10 @@ namespace Emby.Server.Implementations.Net } /// - public ISocket CreateUdpMulticastSocket(IPAddress ipAddress, IPAddress? bindIpAddress, int multicastTimeToLive, int localPort) + public ISocket CreateUdpMulticastSocket(IPAddress ipAddress, IPAddress bindIpAddress, int multicastTimeToLive, int localPort) { ArgumentNullException.ThrowIfNull(ipAddress); - - if (bindIpAddress == null) - { - bindIpAddress = IPAddress.Any; - } + ArgumentNullException.ThrowIfNull(bindIpAddress); if (multicastTimeToLive <= 0) { diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index da357546dd..fb5a66aa10 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -336,13 +336,15 @@ namespace Rssdp.Infrastructure private List ListenForBroadcasts() { var sockets = new List(); + var nonNullBindAddresses = _networkManager.GetInternalBindAddresses().Where(x => x.Address != null); + if (_enableMultiSocketBinding) { - foreach (var address in _networkManager.GetInternalBindAddresses()) + foreach (var address in nonNullBindAddresses) { if (address.AddressFamily == AddressFamily.InterNetworkV6) { - // Not support IPv6 right now + // Not supporting IPv6 right now continue; } @@ -379,7 +381,7 @@ namespace Rssdp.Infrastructure { if (address.AddressFamily == AddressFamily.InterNetworkV6) { - // Not support IPv6 right now + // Not supporting IPv6 right now continue; } From a2ac791bb779297bedb608825602912228d415c1 Mon Sep 17 00:00:00 2001 From: Ronan Charles-Lorel Date: Tue, 31 Jan 2023 15:20:57 +0100 Subject: [PATCH 040/358] Add a way to add more invalid characters when sanitizing a filename --- Emby.Server.Implementations/IO/ManagedFileSystem.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 55f384ae8f..9b8831a1fe 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -294,7 +294,9 @@ namespace Emby.Server.Implementations.IO /// The filename is null. public string GetValidFilename(string filename) { - var invalid = Path.GetInvalidFileNameChars(); + //necessary because (as per the doc) GetInvalidFileNameChars is not exhaustive and may not return all invalid chars, which creates issues + char[] genericInvalidChars = {':'}; + var invalid = Path.GetInvalidFileNameChars().Concat(genericInvalidChars).ToArray(); var first = filename.IndexOfAny(invalid); if (first == -1) { From 31ac861b8560547c7e0c46513077abf76e6bc618 Mon Sep 17 00:00:00 2001 From: Ronan Charles-Lorel Date: Tue, 31 Jan 2023 15:47:47 +0100 Subject: [PATCH 041/358] Formatting --- Emby.Server.Implementations/IO/ManagedFileSystem.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 9b8831a1fe..7b8c79e8a9 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -294,8 +294,8 @@ namespace Emby.Server.Implementations.IO /// The filename is null. public string GetValidFilename(string filename) { - //necessary because (as per the doc) GetInvalidFileNameChars is not exhaustive and may not return all invalid chars, which creates issues - char[] genericInvalidChars = {':'}; + // necessary because (as per the doc) GetInvalidFileNameChars is not exhaustive and may not return all invalid chars, which creates issues + char[] genericInvalidChars = { ':' }; var invalid = Path.GetInvalidFileNameChars().Concat(genericInvalidChars).ToArray(); var first = filename.IndexOfAny(invalid); if (first == -1) From 1cc7572445789c703bb9456224e3f768083c4f65 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 15 Feb 2023 11:31:47 +0100 Subject: [PATCH 042/358] Apply review suggestions --- Jellyfin.Networking/Manager/NetworkManager.cs | 372 +++++++++--------- MediaBrowser.Common/Net/IPData.cs | 14 +- 2 files changed, 206 insertions(+), 180 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index f4bd4e7662..ca9e9274f3 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -263,6 +263,7 @@ namespace Jellyfin.Networking.Manager _logger.LogError(ex, "Error obtaining interfaces."); } + // If no interfaces are found, fallback to loopback interfaces. if (_interfaces.Count == 0) { _logger.LogWarning("No interface information available. Using loopback interface(s)."); @@ -278,8 +279,8 @@ namespace Jellyfin.Networking.Manager } } - _logger.LogDebug("Discovered {0} interfaces.", _interfaces.Count); - _logger.LogDebug("Interfaces addresses: {0}", _interfaces.OrderByDescending(s => s.AddressFamily == AddressFamily.InterNetwork).Select(s => s.Address.ToString())); + _logger.LogDebug("Discovered {NumberOfInterfaces} interfaces.", _interfaces.Count); + _logger.LogDebug("Interfaces addresses: {Addresses}", _interfaces.OrderByDescending(s => s.AddressFamily == AddressFamily.InterNetwork).Select(s => s.Address.ToString())); } } @@ -293,14 +294,21 @@ namespace Jellyfin.Networking.Manager _logger.LogDebug("Refreshing LAN information."); // Get configuration options - string[] subnets = config.LocalNetworkSubnets; + var subnets = config.LocalNetworkSubnets; - _ = NetworkExtensions.TryParseToSubnets(subnets, out _lanSubnets, false); - _ = NetworkExtensions.TryParseToSubnets(subnets, out _excludedSubnets, true); + if (!NetworkExtensions.TryParseToSubnets(subnets, out _lanSubnets, false)) + { + _lanSubnets.Clear(); + } + + if (!NetworkExtensions.TryParseToSubnets(subnets, out _excludedSubnets, true)) + { + _excludedSubnets.Clear(); + } + // If no LAN addresses are specified, all private subnets and Loopback are deemed to be the LAN if (_lanSubnets.Count == 0) { - // If no LAN addresses are specified, all private subnets and Loopback are deemed to be the LAN _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); if (IsIpv6Enabled) @@ -334,15 +342,15 @@ namespace Jellyfin.Networking.Manager { // Respect explicit bind addresses var localNetworkAddresses = config.LocalNetworkAddresses; - if (localNetworkAddresses.Length > 0 && !string.IsNullOrWhiteSpace(localNetworkAddresses.First())) + if (localNetworkAddresses.Length > 0 && !string.IsNullOrWhiteSpace(localNetworkAddresses[0])) { var bindAddresses = localNetworkAddresses.Select(p => NetworkExtensions.TryParseToSubnet(p, out var network) ? network.Prefix : (_interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase)) .Select(x => x.Address) .FirstOrDefault() ?? IPAddress.None)) - .ToList(); - bindAddresses.RemoveAll(x => x == IPAddress.None); + .Where(x => x != IPAddress.None) + .ToHashSet(); _interfaces = _interfaces.Where(x => bindAddresses.Contains(x.Address)).ToList(); if (bindAddresses.Contains(IPAddress.Loopback)) @@ -401,11 +409,15 @@ namespace Jellyfin.Networking.Manager if (remoteIPFilter.Any() && !string.IsNullOrWhiteSpace(remoteIPFilter.First())) { // Parse all IPs with netmask to a subnet - _ = NetworkExtensions.TryParseToSubnets(remoteIPFilter.Where(x => x.Contains('/', StringComparison.OrdinalIgnoreCase)).ToArray(), out _remoteAddressFilter, false); + var remoteFilteredSubnets = remoteIPFilter.Where(x => x.Contains('/', StringComparison.OrdinalIgnoreCase)).ToArray(); + if (!NetworkExtensions.TryParseToSubnets(remoteFilteredSubnets, out _remoteAddressFilter, false)) + { + _remoteAddressFilter.Clear(); + } // Parse everything else as an IP and construct subnet with a single IP - var ips = remoteIPFilter.Where(x => !x.Contains('/', StringComparison.OrdinalIgnoreCase)); - foreach (var ip in ips) + var remoteFilteredIPs = remoteIPFilter.Where(x => !x.Contains('/', StringComparison.OrdinalIgnoreCase)); + foreach (var ip in remoteFilteredIPs) { if (IPAddress.TryParse(ip, out var ipp)) { @@ -436,45 +448,44 @@ namespace Jellyfin.Networking.Manager if (parts.Length != 2) { _logger.LogError("Unable to parse bind override: {Entry}", entry); + return; } - else + + var replacement = parts[1].Trim(); + var identifier = parts[0]; + if (string.Equals(identifier, "all", StringComparison.OrdinalIgnoreCase)) { - var replacement = parts[1].Trim(); - var identifier = parts[0]; - if (string.Equals(identifier, "all", StringComparison.OrdinalIgnoreCase)) - { - _publishedServerUrls[new IPData(IPAddress.Broadcast, null)] = replacement; - } - else if (string.Equals(identifier, "external", StringComparison.OrdinalIgnoreCase)) - { - _publishedServerUrls[new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))] = replacement; - _publishedServerUrls[new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))] = replacement; - } - else if (string.Equals(identifier, "internal", StringComparison.OrdinalIgnoreCase)) - { - foreach (var lan in _lanSubnets) - { - var lanPrefix = lan.Prefix; - _publishedServerUrls[new IPData(lanPrefix, new IPNetwork(lanPrefix, lan.PrefixLength))] = replacement; - } - } - else if (NetworkExtensions.TryParseToSubnet(identifier, out var result) && result != null) - { - var data = new IPData(result.Prefix, result); - _publishedServerUrls[data] = replacement; - } - else if (TryParseInterface(identifier, out var ifaces)) + _publishedServerUrls[new IPData(IPAddress.Broadcast, null)] = replacement; + } + else if (string.Equals(identifier, "external", StringComparison.OrdinalIgnoreCase)) + { + _publishedServerUrls[new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))] = replacement; + _publishedServerUrls[new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))] = replacement; + } + else if (string.Equals(identifier, "internal", StringComparison.OrdinalIgnoreCase)) + { + foreach (var lan in _lanSubnets) { - foreach (var iface in ifaces) - { - _publishedServerUrls[iface] = replacement; - } + var lanPrefix = lan.Prefix; + _publishedServerUrls[new IPData(lanPrefix, new IPNetwork(lanPrefix, lan.PrefixLength))] = replacement; } - else + } + else if (NetworkExtensions.TryParseToSubnet(identifier, out var result) && result != null) + { + var data = new IPData(result.Prefix, result); + _publishedServerUrls[data] = replacement; + } + else if (TryParseInterface(identifier, out var ifaces)) + { + foreach (var iface in ifaces) { - _logger.LogError("Unable to parse bind override: {Entry}", entry); + _publishedServerUrls[iface] = replacement; } } + else + { + _logger.LogError("Unable to parse bind override: {Entry}", entry); + } } } } @@ -556,31 +567,28 @@ namespace Jellyfin.Networking.Manager public bool TryParseInterface(string intf, out List result) { result = new List(); - if (string.IsNullOrEmpty(intf)) + if (string.IsNullOrEmpty(intf) || _interfaces is null) { return false; } - if (_interfaces != null) + // Match all interfaces starting with names starting with token + var matchedInterfaces = _interfaces.Where(s => s.Name.Equals(intf, StringComparison.OrdinalIgnoreCase)).OrderBy(x => x.Index).ToList(); + if (matchedInterfaces.Count > 0) { - // Match all interfaces starting with names starting with token - var matchedInterfaces = _interfaces.Where(s => s.Name.Equals(intf, StringComparison.OrdinalIgnoreCase)).OrderBy(x => x.Index).ToList(); - if (matchedInterfaces.Any()) - { - _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", intf); + _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", intf); - // Use interface IP instead of name - foreach (var iface in matchedInterfaces) + // Use interface IP instead of name + foreach (var iface in matchedInterfaces) + { + if ((IsIpv4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) + || (IsIpv6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)) { - if ((IsIpv4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) - || (IsIpv6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)) - { - result.Add(iface); - } + result.Add(iface); } - - return true; } + + return true; } return false; @@ -626,6 +634,11 @@ namespace Jellyfin.Networking.Manager /// public IReadOnlyList GetLoopbacks() { + if (!(IsIpv4Enabled && IsIpv4Enabled)) + { + return Array.Empty(); + } + var loopbackNetworks = new List(); if (IsIpv4Enabled) { @@ -643,62 +656,64 @@ namespace Jellyfin.Networking.Manager /// public IReadOnlyList GetAllBindInterfaces(bool individualInterfaces = false) { - if (_interfaces.Count == 0) + if (_interfaces.Count != 0) { - // No bind address and no exclusions, so listen on all interfaces. - var result = new List(); - - if (individualInterfaces) - { - foreach (var iface in _interfaces) - { - result.Add(iface); - } + return _interfaces; + } - return result; - } + // No bind address and no exclusions, so listen on all interfaces. + var result = new List(); - if (IsIpv4Enabled && IsIpv6Enabled) - { - // Kestrel source code shows it uses Sockets.DualMode - so this also covers IPAddress.Any by default - result.Add(new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))); - } - else if (IsIpv4Enabled) + if (individualInterfaces) + { + foreach (var iface in _interfaces) { - result.Add(new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))); + result.Add(iface); } - else if (IsIpv6Enabled) + + return result; + } + + if (IsIpv4Enabled && IsIpv6Enabled) + { + // Kestrel source code shows it uses Sockets.DualMode - so this also covers IPAddress.Any by default + result.Add(new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))); + } + else if (IsIpv4Enabled) + { + result.Add(new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))); + } + else if (IsIpv6Enabled) + { + // Cannot use IPv6Any as Kestrel will bind to IPv4 addresses too. + foreach (var iface in _interfaces) { - // Cannot use IPv6Any as Kestrel will bind to IPv4 addresses too. - foreach (var iface in _interfaces) + if (iface.AddressFamily == AddressFamily.InterNetworkV6) { - if (iface.AddressFamily == AddressFamily.InterNetworkV6) - { - result.Add(iface); - } + result.Add(iface); } } - - return result; } - return _interfaces; + return result; } /// public string GetBindInterface(string source, out int? port) { - _ = NetworkExtensions.TryParseHost(source, out var address, IsIpv4Enabled, IsIpv6Enabled); - var result = GetBindAddress(address.FirstOrDefault(), out port); + if (!NetworkExtensions.TryParseHost(source, out var addresses, IsIpv4Enabled, IsIpv6Enabled)) + { + addresses = Array.Empty(); + } + + var result = GetBindAddress(addresses.FirstOrDefault(), out port); return result; } /// public string GetBindInterface(HttpRequest source, out int? port) { - string result; - _ = NetworkExtensions.TryParseHost(source.Host.Host, out var addresses, IsIpv4Enabled, IsIpv6Enabled); - result = GetBindAddress(addresses.FirstOrDefault(), out port); + var result = GetBindInterface(source.Host.Host, out port); port ??= source.Host.Port; return result; @@ -749,36 +764,36 @@ namespace Jellyfin.Networking.Manager .ThenBy(x => x.Index) .ToList(); - if (availableInterfaces.Any()) + if (availableInterfaces.Count > 0) { - if (source != null) + if (source is null) + { + result = NetworkExtensions.FormatIpString(availableInterfaces.First().Address); + _logger.LogDebug("{Source}: Using first internal interface as bind address: {Result}", source, result); + return result; + } + + foreach (var intf in availableInterfaces) { - foreach (var intf in availableInterfaces) + if (intf.Address.Equals(source)) { - if (intf.Address.Equals(source)) - { - result = NetworkExtensions.FormatIpString(intf.Address); - _logger.LogDebug("{Source}: Found matching interface to use as bind address: {Result}", source, result); - return result; - } + result = NetworkExtensions.FormatIpString(intf.Address); + _logger.LogDebug("{Source}: Found matching interface to use as bind address: {Result}", source, result); + return result; } + } - // Does the request originate in one of the interface subnets? - // (For systems with multiple internal network cards, and multiple subnets) - foreach (var intf in availableInterfaces) + // Does the request originate in one of the interface subnets? + // (For systems with multiple internal network cards, and multiple subnets) + foreach (var intf in availableInterfaces) + { + if (intf.Subnet.Contains(source)) { - if (intf.Subnet.Contains(source)) - { - result = NetworkExtensions.FormatIpString(intf.Address); - _logger.LogDebug("{Source}: Found internal interface with matching subnet, using it as bind address: {Result}", source, result); - return result; - } + result = NetworkExtensions.FormatIpString(intf.Address); + _logger.LogDebug("{Source}: Found internal interface with matching subnet, using it as bind address: {Result}", source, result); + return result; } } - - result = NetworkExtensions.FormatIpString(availableInterfaces.First().Address); - _logger.LogDebug("{Source}: Using first internal interface as bind address: {Result}", source, result); - return result; } // There isn't any others, so we'll use the loopback. @@ -810,6 +825,11 @@ namespace Jellyfin.Networking.Manager foreach (var ept in addresses) { match |= IPAddress.IsLoopback(ept) || (_lanSubnets.Any(x => x.Contains(ept)) && !_excludedSubnets.Any(x => x.Contains(ept))); + + if (match) + { + break; + } } return match; @@ -824,15 +844,15 @@ namespace Jellyfin.Networking.Manager ArgumentNullException.ThrowIfNull(address); // See conversation at https://github.com/jellyfin/jellyfin/pull/3515. - if (TrustAllIpv6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) + if ((TrustAllIpv6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) + || address.Equals(IPAddress.Loopback) + || address.Equals(IPAddress.IPv6Loopback)) { return true; } // As private addresses can be redefined by Configuration.LocalNetworkAddresses - var match = CheckIfLanAndNotExcluded(address); - - return address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback) || match; + return CheckIfLanAndNotExcluded(address); } private bool CheckIfLanAndNotExcluded(IPAddress address) @@ -865,20 +885,16 @@ namespace Jellyfin.Networking.Manager int? port = null; var validPublishedServerUrls = _publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.Any) - || x.Key.Address.Equals(IPAddress.IPv6Any) - || x.Key.Subnet.Contains(source)) - .GroupBy(x => x.Key) - .Select(x => x.First()) - .OrderBy(x => x.Key.Address.Equals(IPAddress.Any) - || x.Key.Address.Equals(IPAddress.IPv6Any)) - .ToList(); + || x.Key.Address.Equals(IPAddress.IPv6Any) + || x.Key.Subnet.Contains(source)) + .DistinctBy(x => x.Key) + .OrderBy(x => x.Key.Address.Equals(IPAddress.Any) + || x.Key.Address.Equals(IPAddress.IPv6Any)) + .ToList(); // Check for user override. foreach (var data in validPublishedServerUrls) { - // Get address interface. - var intf = _interfaces.OrderBy(x => x.Index).FirstOrDefault(x => data.Key.Subnet.Contains(x.Address)); - if (isInExternalSubnet && (data.Key.Address.Equals(IPAddress.Any) || data.Key.Address.Equals(IPAddress.IPv6Any))) { // External. @@ -886,6 +902,9 @@ namespace Jellyfin.Networking.Manager break; } + // Get address interface. + var intf = _interfaces.OrderBy(x => x.Index).FirstOrDefault(x => data.Key.Subnet.Contains(x.Address)); + if (intf?.Address != null) { // Match IP address. @@ -896,7 +915,7 @@ namespace Jellyfin.Networking.Manager if (string.IsNullOrEmpty(bindPreference)) { - _logger.LogDebug("{Source}: No matching bind address override found.", source); + _logger.LogDebug("{Source}: No matching bind address override found", source); return false; } @@ -941,40 +960,22 @@ namespace Jellyfin.Networking.Manager count = 0; } - if (count > 0) + if (count == 0) + { + return false; + } + + IPAddress? bindAddress = null; + if (isInExternalSubnet) { - IPAddress? bindAddress = null; var externalInterfaces = _interfaces.Where(x => !IsInLocalNetwork(x.Address)) .OrderBy(x => x.Index) .ToList(); - - if (isInExternalSubnet) - { - if (externalInterfaces.Any()) - { - // Check to see if any of the external bind interfaces are in the same subnet as the source. - // If none exists, this will select the first external interface if there is one. - bindAddress = externalInterfaces - .OrderByDescending(x => x.Subnet.Contains(source)) - .ThenBy(x => x.Index) - .Select(x => x.Address) - .FirstOrDefault(); - - if (bindAddress != null) - { - result = NetworkExtensions.FormatIpString(bindAddress); - _logger.LogDebug("{Source}: External request received, matching external bind address found: {Result}", source, result); - return true; - } - } - - _logger.LogWarning("{Source}: External request received, no matching external bind address found, trying internal addresses.", source); - } - else + if (externalInterfaces.Count > 0) { - // Check to see if any of the internal bind interfaces are in the same subnet as the source. - // If none exists, this will select the first internal interface if there is one. - bindAddress = _interfaces.Where(x => IsInLocalNetwork(x.Address)) + // Check to see if any of the external bind interfaces are in the same subnet as the source. + // If none exists, this will select the first external interface if there is one. + bindAddress = externalInterfaces .OrderByDescending(x => x.Subnet.Contains(source)) .ThenBy(x => x.Index) .Select(x => x.Address) @@ -983,10 +984,29 @@ namespace Jellyfin.Networking.Manager if (bindAddress != null) { result = NetworkExtensions.FormatIpString(bindAddress); - _logger.LogDebug("{Source}: Internal request received, matching internal bind address found: {Result}", source, result); + _logger.LogDebug("{Source}: External request received, matching external bind address found: {Result}", source, result); return true; } } + + _logger.LogWarning("{Source}: External request received, no matching external bind address found, trying internal addresses.", source); + } + else + { + // Check to see if any of the internal bind interfaces are in the same subnet as the source. + // If none exists, this will select the first internal interface if there is one. + bindAddress = _interfaces.Where(x => IsInLocalNetwork(x.Address)) + .OrderByDescending(x => x.Subnet.Contains(source)) + .ThenBy(x => x.Index) + .Select(x => x.Address) + .FirstOrDefault(); + + if (bindAddress != null) + { + result = NetworkExtensions.FormatIpString(bindAddress); + _logger.LogDebug("{Source}: Internal request received, matching internal bind address found: {Result}", source, result); + return true; + } } return false; @@ -1000,16 +1020,21 @@ namespace Jellyfin.Networking.Manager /// true if a match is found, false otherwise. private bool MatchesExternalInterface(IPAddress source, out string result) { - result = string.Empty; - // Get the first WAN interface address that isn't a loopback. - var extResult = _interfaces.Where(p => !IsInLocalNetwork(p.Address)).OrderBy(x => x.Index); + // Get the first external interface address that isn't a loopback. + var extResult = _interfaces.Where(p => !IsInLocalNetwork(p.Address)).OrderBy(x => x.Index).ToArray(); + + // No external interface found + if (extResult.Length == 0) + { + result = string.Empty; + _logger.LogWarning("{Source}: External request received, but no external interface found. Need to route through internal network.", source); + return false; + } - IPAddress? hasResult = null; // Does the request originate in one of the interface subnets? - // (For systems with multiple internal network cards, and multiple subnets) + // (For systems with multiple network cards and/or multiple subnets) foreach (var intf in extResult) { - hasResult ??= intf.Address; if (!IsInLocalNetwork(intf.Address) && intf.Subnet.Contains(source)) { result = NetworkExtensions.FormatIpString(intf.Address); @@ -1018,15 +1043,10 @@ namespace Jellyfin.Networking.Manager } } - if (hasResult != null) - { - result = NetworkExtensions.FormatIpString(hasResult); - _logger.LogDebug("{Source}: Using first external interface as bind address: {Result}", source, result); - return true; - } - - _logger.LogWarning("{Source}: External request received, but no external interface found. Need to route through internal network.", source); - return false; + // Fallback to first external interface. + result = NetworkExtensions.FormatIpString(extResult.First().Address); + _logger.LogDebug("{Source}: Using first external interface as bind address: {Result}", source, result); + return true; } } } diff --git a/MediaBrowser.Common/Net/IPData.cs b/MediaBrowser.Common/Net/IPData.cs index 384efe8f68..05842632c8 100644 --- a/MediaBrowser.Common/Net/IPData.cs +++ b/MediaBrowser.Common/Net/IPData.cs @@ -59,10 +59,16 @@ namespace MediaBrowser.Common.Net { get { - return Address.Equals(IPAddress.None) - ? (Subnet.Prefix.AddressFamily.Equals(IPAddress.None) - ? AddressFamily.Unspecified : Subnet.Prefix.AddressFamily) - : Address.AddressFamily; + if (Address.Equals(IPAddress.None)) + { + return Subnet.Prefix.AddressFamily.Equals(IPAddress.None) + ? AddressFamily.Unspecified + : Subnet.Prefix.AddressFamily; + } + else + { + return Address.AddressFamily; + } } } } From 4eba16c6726564b159e395e188ec89f69d990e52 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 15 Feb 2023 22:34:44 +0100 Subject: [PATCH 043/358] Apply review suggestions --- .../EntryPoints/UdpServerEntryPoint.cs | 5 +- .../Configuration/NetworkConfiguration.cs | 4 +- .../NetworkConfigurationExtensions.cs | 2 +- Jellyfin.Networking/Manager/NetworkManager.cs | 101 ++++++++++-------- .../ApiServiceCollectionExtensions.cs | 2 +- MediaBrowser.Common/Net/INetworkManager.cs | 6 +- MediaBrowser.Common/Net/NetworkExtensions.cs | 67 +++++------- .../NetworkManagerTests.cs | 8 +- .../NetworkParseTests.cs | 32 +++--- .../ParseNetworkTests.cs | 8 +- 10 files changed, 117 insertions(+), 118 deletions(-) diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index c2ffaf1bdd..b5a33a735d 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -102,7 +102,10 @@ namespace Emby.Server.Implementations.EntryPoints _udpServers.Add(new UdpServer(_logger, _appHost, _config, System.Net.IPAddress.Any, PortNumber)); } - _udpServers.ForEach(u => u.Start(_cancellationTokenSource.Token)); + foreach (var server in _udpServers) + { + server.Start(_cancellationTokenSource.Token); + } } catch (SocketException ex) { diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index f904198510..f31d2bce2d 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -115,12 +115,12 @@ namespace Jellyfin.Networking.Configuration /// /// Gets or sets a value indicating whether IPv6 is enabled or not. /// - public bool EnableIPV4 { get; set; } = true; + public bool EnableIPv4 { get; set; } = true; /// /// Gets or sets a value indicating whether IPv6 is enabled or not. /// - public bool EnableIPV6 { get; set; } + public bool EnableIPv6 { get; set; } /// /// Gets or sets a value indicating whether access outside of the LAN is permitted. diff --git a/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs b/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs index 8cbe398b07..3ba6bb8fcb 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs @@ -14,7 +14,7 @@ namespace Jellyfin.Networking.Configuration /// The . public static NetworkConfiguration GetNetworkConfiguration(this IConfigurationManager config) { - return config.GetConfiguration("network"); + return config.GetConfiguration(NetworkConfigurationStore.StoreKey); } } } diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index ca9e9274f3..5f82950fce 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -111,12 +111,12 @@ namespace Jellyfin.Networking.Manager /// /// Gets a value indicating whether IP4 is enabled. /// - public bool IsIpv4Enabled => _configurationManager.GetNetworkConfiguration().EnableIPV4; + public bool IsIPv4Enabled => _configurationManager.GetNetworkConfiguration().EnableIPv4; /// /// Gets a value indicating whether IP6 is enabled. /// - public bool IsIpv6Enabled => _configurationManager.GetNetworkConfiguration().EnableIPV6; + public bool IsIPv6Enabled => _configurationManager.GetNetworkConfiguration().EnableIPv6; /// /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. @@ -229,7 +229,7 @@ namespace Jellyfin.Networking.Manager // Populate interface list foreach (var info in ipProperties.UnicastAddresses) { - if (IsIpv4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork) + if (IsIPv4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork) { var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength), adapter.Name); interfaceObject.Index = ipProperties.GetIPv4Properties().Index; @@ -237,7 +237,7 @@ namespace Jellyfin.Networking.Manager _interfaces.Add(interfaceObject); } - else if (IsIpv6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6) + else if (IsIPv6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6) { var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength), adapter.Name); interfaceObject.Index = ipProperties.GetIPv6Properties().Index; @@ -268,12 +268,12 @@ namespace Jellyfin.Networking.Manager { _logger.LogWarning("No interface information available. Using loopback interface(s)."); - if (IsIpv4Enabled && !IsIpv6Enabled) + if (IsIPv4Enabled && !IsIPv6Enabled) { _interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); } - if (!IsIpv4Enabled && IsIpv6Enabled) + if (!IsIPv4Enabled && IsIPv6Enabled) { _interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); } @@ -311,14 +311,14 @@ namespace Jellyfin.Networking.Manager { _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); - if (IsIpv6Enabled) + if (IsIPv6Enabled) { _lanSubnets.Add(new IPNetwork(IPAddress.IPv6Loopback, 128)); // RFC 4291 (Loopback) _lanSubnets.Add(new IPNetwork(IPAddress.Parse("fe80::"), 10)); // RFC 4291 (Site local) _lanSubnets.Add(new IPNetwork(IPAddress.Parse("fc00::"), 7)); // RFC 4193 (Unique local) } - if (IsIpv4Enabled) + if (IsIPv4Enabled) { _lanSubnets.Add(new IPNetwork(IPAddress.Loopback, 8)); // RFC 5735 (Loopback) _lanSubnets.Add(new IPNetwork(IPAddress.Parse("10.0.0.0"), 8)); // RFC 1918 (private) @@ -382,13 +382,13 @@ namespace Jellyfin.Networking.Manager } // Remove all IPv4 interfaces if IPv4 is disabled - if (!IsIpv4Enabled) + if (!IsIPv4Enabled) { _interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetwork); } // Remove all IPv6 interfaces if IPv6 is disabled - if (!IsIpv6Enabled) + if (!IsIPv6Enabled) { _interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetworkV6); } @@ -470,7 +470,7 @@ namespace Jellyfin.Networking.Manager _publishedServerUrls[new IPData(lanPrefix, new IPNetwork(lanPrefix, lan.PrefixLength))] = replacement; } } - else if (NetworkExtensions.TryParseToSubnet(identifier, out var result) && result != null) + else if (NetworkExtensions.TryParseToSubnet(identifier, out var result) && result is not null) { var data = new IPData(result.Prefix, result); _publishedServerUrls[data] = replacement; @@ -492,7 +492,7 @@ namespace Jellyfin.Networking.Manager private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt) { - if (evt.Key.Equals("network", StringComparison.Ordinal)) + if (evt.Key.Equals(NetworkConfigurationStore.StoreKey, StringComparison.Ordinal)) { UpdateSettings((NetworkConfiguration)evt.NewConfiguration); } @@ -581,8 +581,8 @@ namespace Jellyfin.Networking.Manager // Use interface IP instead of name foreach (var iface in matchedInterfaces) { - if ((IsIpv4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) - || (IsIpv6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)) + if ((IsIPv4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) + || (IsIPv6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)) { result.Add(iface); } @@ -634,18 +634,18 @@ namespace Jellyfin.Networking.Manager /// public IReadOnlyList GetLoopbacks() { - if (!(IsIpv4Enabled && IsIpv4Enabled)) + if (!(IsIPv4Enabled && IsIPv4Enabled)) { return Array.Empty(); } var loopbackNetworks = new List(); - if (IsIpv4Enabled) + if (IsIPv4Enabled) { loopbackNetworks.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); } - if (IsIpv6Enabled) + if (IsIPv6Enabled) { loopbackNetworks.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); } @@ -674,16 +674,16 @@ namespace Jellyfin.Networking.Manager return result; } - if (IsIpv4Enabled && IsIpv6Enabled) + if (IsIPv4Enabled && IsIPv6Enabled) { // Kestrel source code shows it uses Sockets.DualMode - so this also covers IPAddress.Any by default result.Add(new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))); } - else if (IsIpv4Enabled) + else if (IsIPv4Enabled) { result.Add(new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))); } - else if (IsIpv6Enabled) + else if (IsIPv6Enabled) { // Cannot use IPv6Any as Kestrel will bind to IPv4 addresses too. foreach (var iface in _interfaces) @@ -701,7 +701,7 @@ namespace Jellyfin.Networking.Manager /// public string GetBindInterface(string source, out int? port) { - if (!NetworkExtensions.TryParseHost(source, out var addresses, IsIpv4Enabled, IsIpv6Enabled)) + if (!NetworkExtensions.TryParseHost(source, out var addresses, IsIPv4Enabled, IsIPv6Enabled)) { addresses = Array.Empty(); } @@ -726,14 +726,14 @@ namespace Jellyfin.Networking.Manager string result; - if (source != null) + if (source is not null) { - if (IsIpv4Enabled && !IsIpv6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6) + if (IsIPv4Enabled && !IsIPv6Enabled && 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 (!IsIpv4Enabled && IsIpv6Enabled && source.AddressFamily == AddressFamily.InterNetwork) + if (!IsIPv4Enabled && IsIPv6Enabled && source.AddressFamily == AddressFamily.InterNetwork) { _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); } @@ -759,6 +759,7 @@ namespace Jellyfin.Networking.Manager } // Get the first LAN interface address that's not excluded and not a loopback address. + // Get all available interfaces, prefer local interfaces var availableInterfaces = _interfaces.Where(x => !IPAddress.IsLoopback(x.Address)) .OrderByDescending(x => IsInLocalNetwork(x.Address)) .ThenBy(x => x.Index) @@ -766,6 +767,7 @@ namespace Jellyfin.Networking.Manager if (availableInterfaces.Count > 0) { + // If no source address is given, use the preferred (first) interface if (source is null) { result = NetworkExtensions.FormatIpString(availableInterfaces.First().Address); @@ -773,16 +775,6 @@ namespace Jellyfin.Networking.Manager return result; } - foreach (var intf in availableInterfaces) - { - if (intf.Address.Equals(source)) - { - result = NetworkExtensions.FormatIpString(intf.Address); - _logger.LogDebug("{Source}: Found matching interface to use as bind address: {Result}", source, result); - return result; - } - } - // Does the request originate in one of the interface subnets? // (For systems with multiple internal network cards, and multiple subnets) foreach (var intf in availableInterfaces) @@ -790,14 +782,19 @@ namespace Jellyfin.Networking.Manager if (intf.Subnet.Contains(source)) { result = NetworkExtensions.FormatIpString(intf.Address); - _logger.LogDebug("{Source}: Found internal interface with matching subnet, using it as bind address: {Result}", source, result); + _logger.LogDebug("{Source}: Found interface with matching subnet, using it as bind address: {Result}", source, result); return result; } } + + // Fallback to first available interface + result = NetworkExtensions.FormatIpString(availableInterfaces[0].Address); + _logger.LogDebug("{Source}: No matching interfaces found, using preferred interface as bind address: {Result}", source, result); + return result; } // There isn't any others, so we'll use the loopback. - result = IsIpv4Enabled && !IsIpv6Enabled ? "127.0.0.1" : "::1"; + result = IsIPv4Enabled && !IsIPv6Enabled ? "127.0.0.1" : "::1"; _logger.LogWarning("{Source}: Only loopback {Result} returned, using that as bind address.", source, result); return result; } @@ -819,12 +816,12 @@ namespace Jellyfin.Networking.Manager return IPAddress.IsLoopback(subnet.Prefix) || (_lanSubnets.Any(x => x.Contains(subnet.Prefix)) && !_excludedSubnets.Any(x => x.Contains(subnet.Prefix))); } - if (NetworkExtensions.TryParseHost(address, out var addresses, IsIpv4Enabled, IsIpv6Enabled)) + if (NetworkExtensions.TryParseHost(address, out var addresses, IsIPv4Enabled, IsIPv6Enabled)) { bool match = false; foreach (var ept in addresses) { - match |= IPAddress.IsLoopback(ept) || (_lanSubnets.Any(x => x.Contains(ept)) && !_excludedSubnets.Any(x => x.Contains(ept))); + match = match || IPAddress.IsLoopback(ept) || (_lanSubnets.Any(x => x.Contains(ept)) && !_excludedSubnets.Any(x => x.Contains(ept))); if (match) { @@ -860,15 +857,29 @@ namespace Jellyfin.Networking.Manager bool match = false; foreach (var lanSubnet in _lanSubnets) { - match |= lanSubnet.Contains(address); + match = lanSubnet.Contains(address); + + if (match) + { + break; + } + } + + if (!match) + { + return match; } foreach (var excludedSubnet in _excludedSubnets) { - match &= !excludedSubnet.Contains(address); + match = match && !excludedSubnet.Contains(address); + + if (!match) + { + break; + } } - NetworkExtensions.IsIPv6LinkLocal(address); return match; } @@ -905,7 +916,7 @@ namespace Jellyfin.Networking.Manager // Get address interface. var intf = _interfaces.OrderBy(x => x.Index).FirstOrDefault(x => data.Key.Subnet.Contains(x.Address)); - if (intf?.Address != null) + if (intf?.Address is not null) { // Match IP address. bindPreference = data.Value; @@ -930,7 +941,7 @@ namespace Jellyfin.Networking.Manager } } - if (port != null) + if (port is not null) { _logger.LogDebug("{Source}: Matching bind address override found: {Address}:{Port}", source, bindPreference, port); } @@ -981,7 +992,7 @@ namespace Jellyfin.Networking.Manager .Select(x => x.Address) .FirstOrDefault(); - if (bindAddress != null) + if (bindAddress is not null) { result = NetworkExtensions.FormatIpString(bindAddress); _logger.LogDebug("{Source}: External request received, matching external bind address found: {Result}", source, result); @@ -1001,7 +1012,7 @@ namespace Jellyfin.Networking.Manager .Select(x => x.Address) .FirstOrDefault(); - if (bindAddress != null) + if (bindAddress is not null) { result = NetworkExtensions.FormatIpString(bindAddress); _logger.LogDebug("{Source}: Internal request received, matching internal bind address found: {Result}", source, result); diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 5065fbdbb9..71f23b7889 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -367,7 +367,7 @@ namespace Jellyfin.Server.Extensions private static void AddIpAddress(NetworkConfiguration config, ForwardedHeadersOptions options, IPAddress addr, int prefixLength) { - if ((!config.EnableIPV4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPV6 && addr.AddressFamily == AddressFamily.InterNetworkV6)) + if ((!config.EnableIPv4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPv6 && addr.AddressFamily == AddressFamily.InterNetworkV6)) { return; } diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index f0f16af78f..5721b19ca2 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -19,12 +19,12 @@ namespace MediaBrowser.Common.Net /// /// Gets a value indicating whether IPv4 is enabled. /// - bool IsIpv4Enabled { get; } + bool IsIPv4Enabled { get; } /// /// Gets a value indicating whether IPv6 is enabled. /// - bool IsIpv6Enabled { get; } + bool IsIPv6Enabled { get; } /// /// Calculates the list of interfaces to use for Kestrel. @@ -119,7 +119,7 @@ namespace MediaBrowser.Common.Net /// Interface name. /// Resulting object's IP addresses, if successful. /// Success of the operation. - bool TryParseInterface(string intf, out List? result); + bool TryParseInterface(string intf, out List result); /// /// Returns all internal (LAN) bind interface addresses. diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 97f0abbb52..7c36081e60 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; @@ -170,36 +171,9 @@ namespace MediaBrowser.Common.Net for (int a = 0; a < values.Length; a++) { - string[] v = values[a].Trim().Split("/"); - - var address = IPAddress.None; - if (negated && v[0].StartsWith('!')) - { - _ = IPAddress.TryParse(v[0][1..], out address); - } - else if (!negated) + if (TryParseToSubnet(values[a], out var innerResult, negated)) { - _ = IPAddress.TryParse(v[0][0..], out address); - } - - if (address != IPAddress.None && address is not null) - { - if (v.Length > 1 && int.TryParse(v[1], out var netmask)) - { - result.Add(new IPNetwork(address, netmask)); - } - else if (v.Length > 1 && IPAddress.TryParse(v[1], out var netmaskAddress)) - { - result.Add(new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress))); - } - else if (address.AddressFamily == AddressFamily.InterNetwork) - { - result.Add(new IPNetwork(address, 32)); - } - else if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - result.Add(new IPNetwork(address, 128)); - } + result.Add(innerResult); } } @@ -228,27 +202,32 @@ namespace MediaBrowser.Common.Net return false; } - string[] v = value.Trim().Split("/"); + var splitString = value.Trim().Split("/"); + var ipBlock = splitString[0]; var address = IPAddress.None; - if (negated && v[0].StartsWith('!')) + if (negated && ipBlock.StartsWith('!') && IPAddress.TryParse(ipBlock[1..], out var tmpAddress)) { - _ = IPAddress.TryParse(v[0][1..], out address); + address = tmpAddress; } - else if (!negated) + else if (!negated && IPAddress.TryParse(ipBlock, out tmpAddress)) { - _ = IPAddress.TryParse(v[0][0..], out address); + address = tmpAddress; } if (address != IPAddress.None && address is not null) { - if (v.Length > 1 && int.TryParse(v[1], out var netmask)) - { - result = new IPNetwork(address, netmask); - } - else if (v.Length > 1 && IPAddress.TryParse(v[1], out var netmaskAddress)) + if (splitString.Length > 1) { - result = new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress)); + var subnetBlock = splitString[1]; + if (int.TryParse(subnetBlock, out var netmask)) + { + result = new IPNetwork(address, netmask); + } + else if (IPAddress.TryParse(subnetBlock, out var netmaskAddress)) + { + result = new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress)); + } } else if (address.AddressFamily == AddressFamily.InterNetwork) { @@ -353,7 +332,13 @@ namespace MediaBrowser.Common.Net /// The broadcast address. public static IPAddress GetBroadcastAddress(IPNetwork network) { - uint ipAddress = BitConverter.ToUInt32(network.Prefix.GetAddressBytes(), 0); + var addressBytes = network.Prefix.GetAddressBytes(); + if (BitConverter.IsLittleEndian) + { + addressBytes.Reverse(); + } + + uint ipAddress = BitConverter.ToUInt32(addressBytes, 0); uint ipMaskV4 = BitConverter.ToUInt32(CidrToMask(network.PrefixLength, AddressFamily.InterNetwork).GetAddressBytes(), 0); uint broadCastIpAddress = ipAddress | ~ipMaskV4; diff --git a/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs b/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs index 61f9132528..85226d4305 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs @@ -23,8 +23,8 @@ namespace Jellyfin.Networking.Tests var ip = IPAddress.Parse(value); var conf = new NetworkConfiguration() { - EnableIPV6 = true, - EnableIPV4 = true, + EnableIPv6 = true, + EnableIPv4 = true, LocalNetworkSubnets = network.Split(',') }; @@ -50,8 +50,8 @@ namespace Jellyfin.Networking.Tests var ip = IPAddress.Parse(value); var conf = new NetworkConfiguration() { - EnableIPV6 = true, - EnableIPV4 = true, + EnableIPv6 = true, + EnableIPv4 = true, LocalNetworkSubnets = network.Split(',') }; diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index 241d2314bf..c493ce5ea8 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -47,8 +47,8 @@ namespace Jellyfin.Networking.Tests { var conf = new NetworkConfiguration() { - EnableIPV6 = true, - EnableIPV4 = true, + EnableIPv6 = true, + EnableIPv4 = true, LocalNetworkSubnets = lan?.Split(';') ?? throw new ArgumentNullException(nameof(lan)) }; @@ -107,7 +107,7 @@ namespace Jellyfin.Networking.Tests [InlineData("10.128.240.50/30", "10.128.240.51")] [InlineData("10.128.240.50/255.255.255.252", "10.128.240.51")] [InlineData("127.0.0.1/8", "127.0.0.1")] - public void IpV4SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress) + public void IPv4SubnetMaskMatchesValidIPAddress(string netMask, string ipAddress) { var ipa = IPAddress.Parse(ipAddress); Assert.True(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress))); @@ -127,7 +127,7 @@ namespace Jellyfin.Networking.Tests [InlineData("10.128.240.50/30", "10.128.239.50")] [InlineData("10.128.240.50/30", "10.127.240.51")] [InlineData("10.128.240.50/255.255.255.252", "10.127.240.51")] - public void IpV4SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress) + public void IPv4SubnetMaskDoesNotMatchInvalidIPAddress(string netMask, string ipAddress) { var ipa = IPAddress.Parse(ipAddress); Assert.False(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress))); @@ -144,7 +144,7 @@ namespace Jellyfin.Networking.Tests [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) + public void IPv6SubnetMaskMatchesValidIPAddress(string netMask, string ipAddress) { Assert.True(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress))); } @@ -155,7 +155,7 @@ namespace Jellyfin.Networking.Tests [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) + public void IPv6SubnetMaskDoesNotMatchInvalidIPAddress(string netMask, string ipAddress) { Assert.False(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress))); } @@ -194,8 +194,8 @@ namespace Jellyfin.Networking.Tests var conf = new NetworkConfiguration() { LocalNetworkAddresses = bindAddresses.Split(','), - EnableIPV6 = ipv6enabled, - EnableIPV4 = true + EnableIPv6 = ipv6enabled, + EnableIPv4 = true }; NetworkManager.MockNetworkSettings = "192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11"; @@ -256,8 +256,8 @@ namespace Jellyfin.Networking.Tests { LocalNetworkSubnets = lan.Split(','), LocalNetworkAddresses = bindAddresses.Split(','), - EnableIPV6 = ipv6enabled, - EnableIPV4 = true, + EnableIPv6 = ipv6enabled, + EnableIPv4 = true, PublishedServerUriBySubnet = new string[] { publishedServers } }; @@ -281,13 +281,13 @@ namespace Jellyfin.Networking.Tests [InlineData("185.10.10.10", "185.10.10.10", false)] [InlineData("", "100.100.100.100", false)] - public void HasRemoteAccess_GivenWhitelist_AllowsOnlyIpsInWhitelist(string addresses, string remoteIp, bool denied) + public void HasRemoteAccess_GivenWhitelist_AllowsOnlyIPsInWhitelist(string addresses, string remoteIp, bool denied) { // 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 conf = new NetworkConfiguration() { - EnableIPV4 = true, + EnableIPv4 = true, RemoteIPFilter = addresses.Split(','), IsRemoteIPFilterBlacklist = false }; @@ -301,13 +301,13 @@ namespace Jellyfin.Networking.Tests [InlineData("185.10.10.10", "185.10.10.10", true)] [InlineData("", "100.100.100.100", false)] - public void HasRemoteAccess_GivenBlacklist_BlacklistTheIps(string addresses, string remoteIp, bool denied) + public void HasRemoteAccess_GivenBlacklist_BlacklistTheIPs(string addresses, string remoteIp, bool denied) { // 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 conf = new NetworkConfiguration() { - EnableIPV4 = true, + EnableIPv4 = true, RemoteIPFilter = addresses.Split(','), IsRemoteIPFilterBlacklist = true }; @@ -326,7 +326,7 @@ namespace Jellyfin.Networking.Tests { var conf = new NetworkConfiguration { - EnableIPV4 = true, + EnableIPv4 = true, LocalNetworkSubnets = lan.Split(','), LocalNetworkAddresses = bind.Split(',') }; @@ -350,7 +350,7 @@ namespace Jellyfin.Networking.Tests { var conf = new NetworkConfiguration { - EnableIPV4 = true, + EnableIPv4 = true, LocalNetworkSubnets = lan.Split(','), LocalNetworkAddresses = bind.Split(',') }; diff --git a/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs index 12a9beb9e3..49516ccccd 100644 --- a/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs +++ b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs @@ -77,8 +77,8 @@ namespace Jellyfin.Server.Tests var settings = new NetworkConfiguration { - EnableIPV4 = ip4, - EnableIPV6 = ip6 + EnableIPv4 = ip4, + EnableIPv6 = ip6 }; ForwardedHeadersOptions options = new ForwardedHeadersOptions(); @@ -116,8 +116,8 @@ namespace Jellyfin.Server.Tests { var conf = new NetworkConfiguration() { - EnableIPV6 = true, - EnableIPV4 = true, + EnableIPv6 = true, + EnableIPv4 = true, }; return new NetworkManager(GetMockConfig(conf), new NullLogger()); From 42498194d9a4069b8cdeb9446f2714f74e3169de Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Thu, 16 Feb 2023 18:15:12 +0100 Subject: [PATCH 044/358] Replace ISocket and UdpSocket, fix DLNA and SSDP binding and discovery --- Emby.Dlna/Configuration/DlnaOptions.cs | 2 +- Emby.Dlna/Main/DlnaEntryPoint.cs | 47 ++- Emby.Dlna/Ssdp/DeviceDiscovery.cs | 6 +- .../ApplicationHost.cs | 4 +- .../EntryPoints/UdpServerEntryPoint.cs | 34 +-- .../TunerHosts/HdHomerun/HdHomerunHost.cs | 10 +- .../Net/SocketFactory.cs | 69 ++--- Emby.Server.Implementations/Net/UdpSocket.cs | 267 ------------------ Jellyfin.Networking/Manager/NetworkManager.cs | 11 +- .../Extensions/WebHostBuilderExtensions.cs | 2 +- MediaBrowser.Common/Net/INetworkManager.cs | 12 +- MediaBrowser.Model/MediaBrowser.Model.csproj | 1 + .../Net/IPData.cs | 2 +- MediaBrowser.Model/Net/ISocket.cs | 34 --- MediaBrowser.Model/Net/ISocketFactory.cs | 24 +- RSSDP/ISsdpCommunicationsServer.cs | 4 +- RSSDP/SsdpCommunicationsServer.cs | 168 +++++------ RSSDP/SsdpConstants.cs | 2 + RSSDP/SsdpDeviceLocator.cs | 74 +++-- RSSDP/SsdpDevicePublisher.cs | 64 ++--- .../NetworkParseTests.cs | 9 +- 21 files changed, 289 insertions(+), 557 deletions(-) delete mode 100644 Emby.Server.Implementations/Net/UdpSocket.cs rename {MediaBrowser.Common => MediaBrowser.Model}/Net/IPData.cs (98%) delete mode 100644 MediaBrowser.Model/Net/ISocket.cs diff --git a/Emby.Dlna/Configuration/DlnaOptions.cs b/Emby.Dlna/Configuration/DlnaOptions.cs index e95a878c67..f233468de3 100644 --- a/Emby.Dlna/Configuration/DlnaOptions.cs +++ b/Emby.Dlna/Configuration/DlnaOptions.cs @@ -17,7 +17,7 @@ namespace Emby.Dlna.Configuration BlastAliveMessages = true; SendOnlyMatchedHost = true; ClientDiscoveryIntervalSeconds = 60; - AliveMessageIntervalSeconds = 1800; + AliveMessageIntervalSeconds = 180; } /// diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 87c52163d9..f6ec9574b6 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -7,7 +7,6 @@ using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Sockets; -using System.Runtime.InteropServices; using System.Threading.Tasks; using Emby.Dlna.PlayTo; using Emby.Dlna.Ssdp; @@ -201,8 +200,7 @@ namespace Emby.Dlna.Main { if (_communicationsServer is null) { - var enableMultiSocketBinding = OperatingSystem.IsWindows() || - OperatingSystem.IsLinux(); + var enableMultiSocketBinding = OperatingSystem.IsWindows() || OperatingSystem.IsLinux(); _communicationsServer = new SsdpCommunicationsServer(_socketFactory, _networkManager, _logger, enableMultiSocketBinding) { @@ -248,11 +246,6 @@ namespace Emby.Dlna.Main public void StartDevicePublisher(Configuration.DlnaOptions options) { - if (!options.BlastAliveMessages) - { - return; - } - if (_publisher is not null) { return; @@ -263,7 +256,8 @@ namespace Emby.Dlna.Main _publisher = new SsdpDevicePublisher( _communicationsServer, Environment.OSVersion.Platform.ToString(), - Environment.OSVersion.VersionString, + // Can not use VersionString here since that includes OS and version + Environment.OSVersion.Version.ToString(), _config.GetDlnaConfiguration().SendOnlyMatchedHost) { LogFunction = (msg) => _logger.LogDebug("{Msg}", msg), @@ -272,7 +266,10 @@ namespace Emby.Dlna.Main RegisterServerEndpoints(); - _publisher.StartBroadcastingAliveMessages(TimeSpan.FromSeconds(options.BlastAliveMessageIntervalSeconds)); + if (options.BlastAliveMessages) + { + _publisher.StartSendingAliveNotifications(TimeSpan.FromSeconds(options.BlastAliveMessageIntervalSeconds)); + } } catch (Exception ex) { @@ -286,38 +283,32 @@ namespace Emby.Dlna.Main var descriptorUri = "/dlna/" + udn + "/description.xml"; // Only get bind addresses in LAN - var bindAddresses = _networkManager - .GetInternalBindAddresses() - .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork - || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0)) + // IPv6 is currently unsupported + var validInterfaces = _networkManager.GetInternalBindAddresses() + .Where(x => x.Address is not null) + .Where(x => x.AddressFamily != AddressFamily.InterNetworkV6) .ToList(); - if (bindAddresses.Count == 0) + if (validInterfaces.Count == 0) { - // No interfaces returned, so use loopback. - bindAddresses = _networkManager.GetLoopbacks().ToList(); + // No interfaces returned, fall back to loopback + validInterfaces = _networkManager.GetLoopbacks().ToList(); } - foreach (var address in bindAddresses) + foreach (var intf in validInterfaces) { - if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - // Not supporting IPv6 right now - continue; - } - var fullService = "urn:schemas-upnp-org:device:MediaServer:1"; - _logger.LogInformation("Registering publisher for {ResourceName} on {DeviceAddress}", fullService, address.Address); + _logger.LogInformation("Registering publisher for {ResourceName} on {DeviceAddress}", fullService, intf.Address); - var uri = new UriBuilder(_appHost.GetApiUrlForLocalAccess(address.Address, false) + descriptorUri); + var uri = new UriBuilder(_appHost.GetApiUrlForLocalAccess(intf.Address, false) + descriptorUri); var device = new SsdpRootDevice { CacheLifetime = TimeSpan.FromSeconds(1800), // How long SSDP clients can cache this info. Location = uri.Uri, // Must point to the URL that serves your devices UPnP description document. - Address = address.Address, - PrefixLength = NetworkExtensions.MaskToCidr(address.Subnet.Prefix), + Address = intf.Address, + PrefixLength = NetworkExtensions.MaskToCidr(intf.Subnet.Prefix), FriendlyName = "Jellyfin", Manufacturer = "Jellyfin", ModelName = "Jellyfin Server", diff --git a/Emby.Dlna/Ssdp/DeviceDiscovery.cs b/Emby.Dlna/Ssdp/DeviceDiscovery.cs index 8a4e5ff455..43d673c772 100644 --- a/Emby.Dlna/Ssdp/DeviceDiscovery.cs +++ b/Emby.Dlna/Ssdp/DeviceDiscovery.cs @@ -73,7 +73,11 @@ namespace Emby.Dlna.Ssdp { if (_listenerCount > 0 && _deviceLocator is null && _commsServer is not null) { - _deviceLocator = new SsdpDeviceLocator(_commsServer); + _deviceLocator = new SsdpDeviceLocator( + _commsServer, + Environment.OSVersion.Platform.ToString(), + // Can not use VersionString here since that includes OS and version + Environment.OSVersion.Version.ToString()); // (Optional) Set the filter so we only see notifications for devices we care about // (can be any search target value i.e device type, uuid value etc - any value that appears in the diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 50befaa537..485253bf74 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1025,7 +1025,7 @@ namespace Emby.Server.Implementations return PublishedServerUrl.Trim('/'); } - string smart = NetManager.GetBindInterface(hostname, out var port); + string smart = NetManager.GetBindAddress(hostname, out var port); return GetLocalApiUrl(smart.Trim('/'), null, port); } @@ -1033,7 +1033,7 @@ namespace Emby.Server.Implementations public string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true) { // With an empty source, the port will be null - var smart = NetManager.GetBindAddress(ipAddress, out _); + var smart = NetManager.GetBindAddress(ipAddress, out _, true); var scheme = !allowHttps ? Uri.UriSchemeHttp : null; int? port = !allowHttps ? HttpPort : null; return GetLocalApiUrl(smart, scheme, port); diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index b5a33a735d..8fb1f93228 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using System.Linq; +using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; @@ -80,31 +82,26 @@ namespace Emby.Server.Implementations.EntryPoints if (_enableMultiSocketBinding) { // Add global broadcast socket - _udpServers.Add(new UdpServer(_logger, _appHost, _config, System.Net.IPAddress.Broadcast, PortNumber)); + _udpServers.Add(new UdpServer(_logger, _appHost, _config, IPAddress.Broadcast, PortNumber)); // Add bind address specific broadcast sockets - foreach (var bindAddress in _networkManager.GetInternalBindAddresses()) + // IPv6 is currently unsupported + var validInterfaces = _networkManager.GetInternalBindAddresses().Where(i => i.AddressFamily == AddressFamily.InterNetwork); + foreach (var intf in validInterfaces) { - if (bindAddress.AddressFamily == AddressFamily.InterNetworkV6) - { - // Not supporting IPv6 right now - continue; - } - - var broadcastAddress = NetworkExtensions.GetBroadcastAddress(bindAddress.Subnet); + var broadcastAddress = NetworkExtensions.GetBroadcastAddress(intf.Subnet); _logger.LogDebug("Binding UDP server to {Address} on port {PortNumber}", broadcastAddress.ToString(), PortNumber); - _udpServers.Add(new UdpServer(_logger, _appHost, _config, broadcastAddress, PortNumber)); + var server = new UdpServer(_logger, _appHost, _config, broadcastAddress, PortNumber); + server.Start(_cancellationTokenSource.Token); + _udpServers.Add(server); } } else { - _udpServers.Add(new UdpServer(_logger, _appHost, _config, System.Net.IPAddress.Any, PortNumber)); - } - - foreach (var server in _udpServers) - { + var server = new UdpServer(_logger, _appHost, _config, IPAddress.Any, PortNumber); server.Start(_cancellationTokenSource.Token); + _udpServers.Add(server); } } catch (SocketException ex) @@ -133,9 +130,12 @@ namespace Emby.Server.Implementations.EntryPoints _cancellationTokenSource.Cancel(); _cancellationTokenSource.Dispose(); - _udpServers.ForEach(s => s.Dispose()); - _udpServers.Clear(); + foreach (var server in _udpServers) + { + server.Dispose(); + } + _udpServers.Clear(); _disposed = true; } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 98bbc15406..e76961ce9e 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -661,16 +661,16 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun // Need a way to set the Receive timeout on the socket otherwise this might never timeout? try { - await udpClient.SendToAsync(discBytes, 0, discBytes.Length, new IPEndPoint(IPAddress.Parse("255.255.255.255"), 65001), cancellationToken).ConfigureAwait(false); + await udpClient.SendToAsync(discBytes, new IPEndPoint(IPAddress.Parse("255.255.255.255"), 65001), cancellationToken).ConfigureAwait(false); var receiveBuffer = new byte[8192]; while (!cancellationToken.IsCancellationRequested) { - var response = await udpClient.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, cancellationToken).ConfigureAwait(false); - var deviceIp = response.RemoteEndPoint.Address.ToString(); + var response = await udpClient.ReceiveMessageFromAsync(receiveBuffer, new IPEndPoint(IPAddress.Any, 0), cancellationToken).ConfigureAwait(false); + var deviceIp = ((IPEndPoint)response.RemoteEndPoint).Address.ToString(); - // check to make sure we have enough bytes received to be a valid message and make sure the 2nd byte is the discover reply byte - if (response.ReceivedBytes > 13 && response.Buffer[1] == 3) + // Check to make sure we have enough bytes received to be a valid message and make sure the 2nd byte is the discover reply byte + if (response.ReceivedBytes > 13 && receiveBuffer[1] == 3) { var deviceAddress = "http://" + deviceIp; diff --git a/Emby.Server.Implementations/Net/SocketFactory.cs b/Emby.Server.Implementations/Net/SocketFactory.cs index b6d87a7880..d134d948ab 100644 --- a/Emby.Server.Implementations/Net/SocketFactory.cs +++ b/Emby.Server.Implementations/Net/SocketFactory.cs @@ -10,61 +10,63 @@ namespace Emby.Server.Implementations.Net public class SocketFactory : ISocketFactory { /// - public ISocket CreateUdpBroadcastSocket(int localPort) + public Socket CreateUdpBroadcastSocket(int localPort) { if (localPort < 0) { throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort)); } - var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { - retVal.EnableBroadcast = true; - retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); - retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); + socket.EnableBroadcast = true; + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); + socket.Bind(new IPEndPoint(IPAddress.Any, localPort)); - return new UdpSocket(retVal, localPort, IPAddress.Any); + return socket; } catch { - retVal?.Dispose(); + socket?.Dispose(); throw; } } /// - public ISocket CreateSsdpUdpSocket(IPAddress localIp, int localPort) + public Socket CreateSsdpUdpSocket(IPData bindInterface, int localPort) { + ArgumentNullException.ThrowIfNull(bindInterface.Address); + if (localPort < 0) { throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort)); } - var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { - retVal.EnableBroadcast = true; - retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); - retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4); + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + socket.Bind(new IPEndPoint(bindInterface.Address, localPort)); - retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.255.255.250"), localIp)); - return new UdpSocket(retVal, localPort, localIp); + return socket; } catch { - retVal?.Dispose(); + socket?.Dispose(); throw; } } /// - public ISocket CreateUdpMulticastSocket(IPAddress ipAddress, IPAddress bindIpAddress, int multicastTimeToLive, int localPort) + public Socket CreateUdpMulticastSocket(IPAddress multicastAddress, IPData bindInterface, int multicastTimeToLive, int localPort) { - ArgumentNullException.ThrowIfNull(ipAddress); - ArgumentNullException.ThrowIfNull(bindIpAddress); + var bindIPAddress = bindInterface.Address; + ArgumentNullException.ThrowIfNull(multicastAddress); + ArgumentNullException.ThrowIfNull(bindIPAddress); if (multicastTimeToLive <= 0) { @@ -76,34 +78,25 @@ namespace Emby.Server.Implementations.Net throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort)); } - var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); - - retVal.ExclusiveAddressUse = false; - - try - { - // seeing occasional exceptions thrown on qnap - // System.Net.Sockets.SocketException (0x80004005): Protocol not available - retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); - } - catch (SocketException) - { - } + var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { - retVal.EnableBroadcast = true; - // retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true); - retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive); + var interfaceIndex = (int)IPAddress.HostToNetworkOrder(bindInterface.Index); - retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ipAddress, bindIpAddress)); - retVal.MulticastLoopback = true; + socket.MulticastLoopback = false; + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true); + socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive); + socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, interfaceIndex); + socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastAddress, interfaceIndex)); + socket.Bind(new IPEndPoint(multicastAddress, localPort)); - return new UdpSocket(retVal, localPort, bindIpAddress); + return socket; } catch { - retVal?.Dispose(); + socket?.Dispose(); throw; } diff --git a/Emby.Server.Implementations/Net/UdpSocket.cs b/Emby.Server.Implementations/Net/UdpSocket.cs deleted file mode 100644 index 577b79283a..0000000000 --- a/Emby.Server.Implementations/Net/UdpSocket.cs +++ /dev/null @@ -1,267 +0,0 @@ -#nullable disable - -#pragma warning disable CS1591 - -using System; -using System.Net; -using System.Net.Sockets; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Model.Net; - -namespace Emby.Server.Implementations.Net -{ - // THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS - // Be careful to check any changes compile and work for all platform projects it is shared in. - - public sealed class UdpSocket : ISocket, IDisposable - { - private readonly int _localPort; - - private readonly SocketAsyncEventArgs _receiveSocketAsyncEventArgs = new SocketAsyncEventArgs() - { - SocketFlags = SocketFlags.None - }; - - private readonly SocketAsyncEventArgs _sendSocketAsyncEventArgs = new SocketAsyncEventArgs() - { - SocketFlags = SocketFlags.None - }; - - private Socket _socket; - private bool _disposed = false; - private TaskCompletionSource _currentReceiveTaskCompletionSource; - private TaskCompletionSource _currentSendTaskCompletionSource; - - public UdpSocket(Socket socket, int localPort, IPAddress ip) - { - ArgumentNullException.ThrowIfNull(socket); - - _socket = socket; - _localPort = localPort; - LocalIPAddress = ip; - - _socket.Bind(new IPEndPoint(ip, _localPort)); - - InitReceiveSocketAsyncEventArgs(); - } - - public UdpSocket(Socket socket, IPEndPoint endPoint) - { - ArgumentNullException.ThrowIfNull(socket); - - _socket = socket; - _socket.Connect(endPoint); - - InitReceiveSocketAsyncEventArgs(); - } - - public Socket Socket => _socket; - - public IPAddress LocalIPAddress { get; } - - private void InitReceiveSocketAsyncEventArgs() - { - var receiveBuffer = new byte[8192]; - _receiveSocketAsyncEventArgs.SetBuffer(receiveBuffer, 0, receiveBuffer.Length); - _receiveSocketAsyncEventArgs.Completed += OnReceiveSocketAsyncEventArgsCompleted; - - var sendBuffer = new byte[8192]; - _sendSocketAsyncEventArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length); - _sendSocketAsyncEventArgs.Completed += OnSendSocketAsyncEventArgsCompleted; - } - - private void OnReceiveSocketAsyncEventArgsCompleted(object sender, SocketAsyncEventArgs e) - { - var tcs = _currentReceiveTaskCompletionSource; - if (tcs is not null) - { - _currentReceiveTaskCompletionSource = null; - - if (e.SocketError == SocketError.Success) - { - tcs.TrySetResult(new SocketReceiveResult - { - Buffer = e.Buffer, - ReceivedBytes = e.BytesTransferred, - RemoteEndPoint = e.RemoteEndPoint as IPEndPoint, - LocalIPAddress = LocalIPAddress - }); - } - else - { - tcs.TrySetException(new SocketException((int)e.SocketError)); - } - } - } - - private void OnSendSocketAsyncEventArgsCompleted(object sender, SocketAsyncEventArgs e) - { - var tcs = _currentSendTaskCompletionSource; - if (tcs is not null) - { - _currentSendTaskCompletionSource = null; - - if (e.SocketError == SocketError.Success) - { - tcs.TrySetResult(e.BytesTransferred); - } - else - { - tcs.TrySetException(new SocketException((int)e.SocketError)); - } - } - } - - public IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback) - { - ThrowIfDisposed(); - - EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0); - - return _socket.BeginReceiveFrom(buffer, offset, count, SocketFlags.None, ref receivedFromEndPoint, callback, buffer); - } - - public int Receive(byte[] buffer, int offset, int count) - { - ThrowIfDisposed(); - - return _socket.Receive(buffer, 0, buffer.Length, SocketFlags.None); - } - - public SocketReceiveResult EndReceive(IAsyncResult result) - { - ThrowIfDisposed(); - - var sender = new IPEndPoint(IPAddress.Any, 0); - var remoteEndPoint = (EndPoint)sender; - - var receivedBytes = _socket.EndReceiveFrom(result, ref remoteEndPoint); - - var buffer = (byte[])result.AsyncState; - - return new SocketReceiveResult - { - ReceivedBytes = receivedBytes, - RemoteEndPoint = (IPEndPoint)remoteEndPoint, - Buffer = buffer, - LocalIPAddress = LocalIPAddress - }; - } - - public Task ReceiveAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - ThrowIfDisposed(); - - var taskCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - bool isResultSet = false; - - Action callback = callbackResult => - { - try - { - if (!isResultSet) - { - isResultSet = true; - taskCompletion.TrySetResult(EndReceive(callbackResult)); - } - } - catch (Exception ex) - { - taskCompletion.TrySetException(ex); - } - }; - - var result = BeginReceive(buffer, offset, count, new AsyncCallback(callback)); - - if (result.CompletedSynchronously) - { - callback(result); - return taskCompletion.Task; - } - - cancellationToken.Register(() => taskCompletion.TrySetCanceled()); - - return taskCompletion.Task; - } - - public Task SendToAsync(byte[] buffer, int offset, int bytes, IPEndPoint endPoint, CancellationToken cancellationToken) - { - ThrowIfDisposed(); - - var taskCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - bool isResultSet = false; - - Action callback = callbackResult => - { - try - { - if (!isResultSet) - { - isResultSet = true; - taskCompletion.TrySetResult(EndSendTo(callbackResult)); - } - } - catch (Exception ex) - { - taskCompletion.TrySetException(ex); - } - }; - - var result = BeginSendTo(buffer, offset, bytes, endPoint, new AsyncCallback(callback), null); - - if (result.CompletedSynchronously) - { - callback(result); - return taskCompletion.Task; - } - - cancellationToken.Register(() => taskCompletion.TrySetCanceled()); - - return taskCompletion.Task; - } - - public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, IPEndPoint endPoint, AsyncCallback callback, object state) - { - ThrowIfDisposed(); - - return _socket.BeginSendTo(buffer, offset, size, SocketFlags.None, endPoint, callback, state); - } - - public int EndSendTo(IAsyncResult result) - { - ThrowIfDisposed(); - - return _socket.EndSendTo(result); - } - - private void ThrowIfDisposed() - { - if (_disposed) - { - throw new ObjectDisposedException(nameof(UdpSocket)); - } - } - - /// - public void Dispose() - { - if (_disposed) - { - return; - } - - _socket?.Dispose(); - _receiveSocketAsyncEventArgs.Dispose(); - _sendSocketAsyncEventArgs.Dispose(); - _currentReceiveTaskCompletionSource?.TrySetCanceled(); - _currentSendTaskCompletionSource?.TrySetCanceled(); - - _socket = null; - _currentReceiveTaskCompletionSource = null; - _currentSendTaskCompletionSource = null; - - _disposed = true; - } - } -} diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 5f82950fce..cdd34bc896 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -9,6 +9,7 @@ using System.Threading; using Jellyfin.Networking.Configuration; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; +using MediaBrowser.Model.Net; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Logging; @@ -699,7 +700,7 @@ namespace Jellyfin.Networking.Manager } /// - public string GetBindInterface(string source, out int? port) + public string GetBindAddress(string source, out int? port) { if (!NetworkExtensions.TryParseHost(source, out var addresses, IsIPv4Enabled, IsIPv6Enabled)) { @@ -711,16 +712,16 @@ namespace Jellyfin.Networking.Manager } /// - public string GetBindInterface(HttpRequest source, out int? port) + public string GetBindAddress(HttpRequest source, out int? port) { - var result = GetBindInterface(source.Host.Host, out port); + var result = GetBindAddress(source.Host.Host, out port); port ??= source.Host.Port; return result; } /// - public string GetBindAddress(IPAddress? source, out int? port) + public string GetBindAddress(IPAddress? source, out int? port, bool skipOverrides = false) { port = null; @@ -741,7 +742,7 @@ namespace Jellyfin.Networking.Manager bool isExternal = !_lanSubnets.Any(network => network.Contains(source)); _logger.LogDebug("Trying to get bind address for source {Source} - External: {IsExternal}", source, isExternal); - if (MatchesPublishedServerUrl(source, isExternal, out result)) + if (!skipOverrides && MatchesPublishedServerUrl(source, isExternal, out result)) { return result; } diff --git a/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs b/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs index eac13f7610..3cb791b571 100644 --- a/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs +++ b/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs @@ -41,7 +41,7 @@ public static class WebHostBuilderExtensions bool flagged = false; foreach (var netAdd in addresses) { - logger.LogInformation("Kestrel listening on {Address}", IPAddress.IPv6Any.Equals(netAdd.Address) ? "All Addresses" : netAdd); + logger.LogInformation("Kestrel is listening on {Address}", IPAddress.IPv6Any.Equals(netAdd.Address) ? "All IPv6 addresses" : netAdd.Address); options.Listen(netAdd.Address, appHost.HttpPort); if (appHost.ListenWithHttps) { diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 5721b19ca2..68974f738d 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Net; using System.Net.NetworkInformation; +using MediaBrowser.Model.Net; using Microsoft.AspNetCore.Http; namespace MediaBrowser.Common.Net @@ -70,27 +71,28 @@ namespace MediaBrowser.Common.Net /// Source of the request. /// Optional port returned, if it's part of an override. /// IP address to use, or loopback address if all else fails. - string GetBindInterface(HttpRequest source, out int? port); + string GetBindAddress(HttpRequest source, out int? port); /// /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. - /// (See . + /// (See . /// /// IP address of the request. /// Optional port returned, if it's part of an override. + /// Optional boolean denoting if published server overrides should be ignored. Defaults to false. /// IP address to use, or loopback address if all else fails. - string GetBindAddress(IPAddress source, out int? port); + string GetBindAddress(IPAddress source, out int? port, bool skipOverrides = false); /// /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. - /// (See . + /// (See . /// /// Source of the request. /// Optional port returned, if it's part of an override. /// IP address to use, or loopback address if all else fails. - string GetBindInterface(string source, out int? port); + string GetBindAddress(string source, out int? port); /// /// Get a list of all the MAC addresses associated with active interfaces. diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index 9a58044853..087e6369e6 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -58,6 +58,7 @@ + diff --git a/MediaBrowser.Common/Net/IPData.cs b/MediaBrowser.Model/Net/IPData.cs similarity index 98% rename from MediaBrowser.Common/Net/IPData.cs rename to MediaBrowser.Model/Net/IPData.cs index 05842632c8..16d74dcddd 100644 --- a/MediaBrowser.Common/Net/IPData.cs +++ b/MediaBrowser.Model/Net/IPData.cs @@ -2,7 +2,7 @@ using System.Net; using System.Net.Sockets; using Microsoft.AspNetCore.HttpOverrides; -namespace MediaBrowser.Common.Net +namespace MediaBrowser.Model.Net { /// /// Base network object class. diff --git a/MediaBrowser.Model/Net/ISocket.cs b/MediaBrowser.Model/Net/ISocket.cs deleted file mode 100644 index 3de41d565a..0000000000 --- a/MediaBrowser.Model/Net/ISocket.cs +++ /dev/null @@ -1,34 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using System.Net; -using System.Threading; -using System.Threading.Tasks; - -namespace MediaBrowser.Model.Net -{ - /// - /// Provides a common interface across platforms for UDP sockets used by this SSDP implementation. - /// - public interface ISocket : IDisposable - { - IPAddress LocalIPAddress { get; } - - Task ReceiveAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken); - - IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback); - - SocketReceiveResult EndReceive(IAsyncResult result); - - /// - /// Sends a UDP message to a particular end point (uni or multicast). - /// - /// An array of type that contains the data to send. - /// The zero-based position in buffer at which to begin sending data. - /// The number of bytes to send. - /// An that represents the remote device. - /// The cancellation token to cancel operation. - /// The task object representing the asynchronous operation. - Task SendToAsync(byte[] buffer, int offset, int bytes, IPEndPoint endPoint, CancellationToken cancellationToken); - } -} diff --git a/MediaBrowser.Model/Net/ISocketFactory.cs b/MediaBrowser.Model/Net/ISocketFactory.cs index f3bc31796d..49a88c2277 100644 --- a/MediaBrowser.Model/Net/ISocketFactory.cs +++ b/MediaBrowser.Model/Net/ISocketFactory.cs @@ -1,32 +1,36 @@ -#pragma warning disable CS1591 - using System.Net; +using System.Net.Sockets; namespace MediaBrowser.Model.Net { /// - /// Implemented by components that can create a platform specific UDP socket implementation, and wrap it in the cross platform interface. + /// Implemented by components that can create specific socket configurations. /// public interface ISocketFactory { - ISocket CreateUdpBroadcastSocket(int localPort); + /// + /// Creates a new unicast socket using the specified local port number. + /// + /// The local port to bind to. + /// A new unicast socket using the specified local port number. + Socket CreateUdpBroadcastSocket(int localPort); /// /// Creates a new unicast socket using the specified local port number. /// - /// The local IP address to bind to. + /// The bind interface. /// The local port to bind to. /// A new unicast socket using the specified local port number. - ISocket CreateSsdpUdpSocket(IPAddress localIp, int localPort); + Socket CreateSsdpUdpSocket(IPData bindInterface, int localPort); /// /// Creates a new multicast socket using the specified multicast IP address, multicast time to live and local port. /// - /// The multicast IP address to bind to. - /// The bind IP address. + /// The multicast IP address to bind to. + /// The bind interface. /// The multicast time to live value. Actually a maximum number of network hops for UDP packets. /// The local port to bind to. - /// A implementation. - ISocket CreateUdpMulticastSocket(IPAddress ipAddress, IPAddress bindIpAddress, int multicastTimeToLive, int localPort); + /// A new multicast socket using the specfied bind interface, multicast address, multicast time to live and port. + Socket CreateUdpMulticastSocket(IPAddress multicastAddress, IPData bindInterface, int multicastTimeToLive, int localPort); } } diff --git a/RSSDP/ISsdpCommunicationsServer.cs b/RSSDP/ISsdpCommunicationsServer.cs index 3cbc991d60..571c66c107 100644 --- a/RSSDP/ISsdpCommunicationsServer.cs +++ b/RSSDP/ISsdpCommunicationsServer.cs @@ -23,12 +23,12 @@ namespace Rssdp.Infrastructure /// /// Causes the server to begin listening for multicast messages, being SSDP search requests and notifications. /// - void BeginListeningForBroadcasts(); + void BeginListeningForMulticast(); /// /// Causes the server to stop listening for multicast messages, being SSDP search requests and notifications. /// - void StopListeningForBroadcasts(); + void StopListeningForMulticast(); /// /// Sends a message to a particular address (uni or multicast) and port. diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index fb5a66aa10..6ae260d557 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -25,18 +25,18 @@ namespace Rssdp.Infrastructure * Since stopping the service would be a bad idea (might not be allowed security wise and might * break other apps running on the system) the only other work around is to use two sockets. * - * We use one socket to listen for/receive notifications and search requests (_BroadcastListenSocket). - * We use a second socket, bound to a different local port, to send search requests and listen for - * responses (_SendSocket). The responses are sent to the local port this socket is bound to, - * which isn't port 1900 so the MS service doesn't steal them. While the caller can specify a local + * We use one group of sockets to listen for/receive notifications and search requests (_MulticastListenSockets). + * We use a second group, bound to a different local port, to send search requests and listen for + * responses (_SendSockets). The responses are sent to the local ports these sockets are bound to, + * which aren't port 1900 so the MS service doesn't steal them. While the caller can specify a local * port to use, we will default to 0 which allows the underlying system to auto-assign a free port. */ private object _BroadcastListenSocketSynchroniser = new object(); - private List _BroadcastListenSockets; + private List _MulticastListenSockets; private object _SendSocketSynchroniser = new object(); - private List _sendSockets; + private List _sendSockets; private HttpRequestParser _RequestParser; private HttpResponseParser _ResponseParser; @@ -78,7 +78,7 @@ namespace Rssdp.Infrastructure /// The argument is less than or equal to zero. public SsdpCommunicationsServer(ISocketFactory socketFactory, int localPort, int multicastTimeToLive, INetworkManager networkManager, ILogger logger, bool enableMultiSocketBinding) { - if (socketFactory == null) + if (socketFactory is null) { throw new ArgumentNullException(nameof(socketFactory)); } @@ -107,25 +107,25 @@ namespace Rssdp.Infrastructure /// Causes the server to begin listening for multicast messages, being SSDP search requests and notifications. /// /// Thrown if the property is true (because has been called previously). - public void BeginListeningForBroadcasts() + public void BeginListeningForMulticast() { ThrowIfDisposed(); lock (_BroadcastListenSocketSynchroniser) { - if (_BroadcastListenSockets == null) + if (_MulticastListenSockets is null) { try { - _BroadcastListenSockets = ListenForBroadcasts(); + _MulticastListenSockets = CreateMulticastSocketsAndListen(); } catch (SocketException ex) { - _logger.LogError("Failed to bind to port 1900: {Message}. DLNA will be unavailable", ex.Message); + _logger.LogError("Failed to bind to multicast address: {Message}. DLNA will be unavailable", ex.Message); } catch (Exception ex) { - _logger.LogError(ex, "Error in BeginListeningForBroadcasts"); + _logger.LogError(ex, "Error in BeginListeningForMulticast"); } } } @@ -135,15 +135,19 @@ namespace Rssdp.Infrastructure /// Causes the server to stop listening for multicast messages, being SSDP search requests and notifications. /// /// Thrown if the property is true (because has been called previously). - public void StopListeningForBroadcasts() + public void StopListeningForMulticast() { lock (_BroadcastListenSocketSynchroniser) { - if (_BroadcastListenSockets != null) + if (_MulticastListenSockets is not null) { _logger.LogInformation("{0} disposing _BroadcastListenSocket", GetType().Name); - _BroadcastListenSockets.ForEach(s => s.Dispose()); - _BroadcastListenSockets = null; + foreach (var socket in _MulticastListenSockets) + { + socket.Dispose(); + } + + _MulticastListenSockets = null; } } } @@ -153,7 +157,7 @@ namespace Rssdp.Infrastructure /// public async Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) { - if (messageData == null) + if (messageData is null) { throw new ArgumentNullException(nameof(messageData)); } @@ -177,11 +181,11 @@ namespace Rssdp.Infrastructure } } - private async Task SendFromSocket(ISocket socket, byte[] messageData, IPEndPoint destination, CancellationToken cancellationToken) + private async Task SendFromSocket(Socket socket, byte[] messageData, IPEndPoint destination, CancellationToken cancellationToken) { try { - await socket.SendToAsync(messageData, 0, messageData.Length, destination, cancellationToken).ConfigureAwait(false); + await socket.SendToAsync(messageData, destination, cancellationToken).ConfigureAwait(false); } catch (ObjectDisposedException) { @@ -191,37 +195,42 @@ namespace Rssdp.Infrastructure } catch (Exception ex) { - _logger.LogError(ex, "Error sending socket message from {0} to {1}", socket.LocalIPAddress.ToString(), destination.ToString()); + var localIP = ((IPEndPoint)socket.LocalEndPoint).Address; + _logger.LogError(ex, "Error sending socket message from {0} to {1}", localIP.ToString(), destination.ToString()); } } - private List GetSendSockets(IPAddress fromLocalIpAddress, IPEndPoint destination) + private List GetSendSockets(IPAddress fromLocalIpAddress, IPEndPoint destination) { EnsureSendSocketCreated(); lock (_SendSocketSynchroniser) { - var sockets = _sendSockets.Where(i => i.LocalIPAddress.AddressFamily == fromLocalIpAddress.AddressFamily); + var sockets = _sendSockets.Where(s => s.AddressFamily == fromLocalIpAddress.AddressFamily); // Send from the Any socket and the socket with the matching address if (fromLocalIpAddress.AddressFamily == AddressFamily.InterNetwork) { - sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.Any) || fromLocalIpAddress.Equals(i.LocalIPAddress)); + sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Any) + || ((IPEndPoint)s.LocalEndPoint).Address.Equals(fromLocalIpAddress)); // If sending to the loopback address, filter the socket list as well if (destination.Address.Equals(IPAddress.Loopback)) { - sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.Any) || i.LocalIPAddress.Equals(IPAddress.Loopback)); + sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Any) + || ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Loopback)); } } else if (fromLocalIpAddress.AddressFamily == AddressFamily.InterNetworkV6) { - sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.IPv6Any) || fromLocalIpAddress.Equals(i.LocalIPAddress)); + sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.IPv6Any) + || ((IPEndPoint)s.LocalEndPoint).Address.Equals(fromLocalIpAddress)); // If sending to the loopback address, filter the socket list as well if (destination.Address.Equals(IPAddress.IPv6Loopback)) { - sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.IPv6Any) || i.LocalIPAddress.Equals(IPAddress.IPv6Loopback)); + sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.IPv6Any) + || ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.IPv6Loopback)); } } @@ -239,7 +248,7 @@ namespace Rssdp.Infrastructure /// public async Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) { - if (message == null) + if (message is null) { throw new ArgumentNullException(nameof(message)); } @@ -275,7 +284,7 @@ namespace Rssdp.Infrastructure { lock (_SendSocketSynchroniser) { - if (_sendSockets != null) + if (_sendSockets is not null) { var sockets = _sendSockets.ToList(); _sendSockets = null; @@ -284,7 +293,8 @@ namespace Rssdp.Infrastructure foreach (var socket in sockets) { - _logger.LogInformation("{0} disposing sendSocket from {1}", GetType().Name, socket.LocalIPAddress); + var socketAddress = ((IPEndPoint)socket.LocalEndPoint).Address; + _logger.LogInformation("{0} disposing sendSocket from {1}", GetType().Name, socketAddress); socket.Dispose(); } } @@ -312,7 +322,7 @@ namespace Rssdp.Infrastructure { if (disposing) { - StopListeningForBroadcasts(); + StopListeningForMulticast(); StopListeningForResponses(); } @@ -321,11 +331,11 @@ namespace Rssdp.Infrastructure private Task SendMessageIfSocketNotDisposed(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) { var sockets = _sendSockets; - if (sockets != null) + if (sockets is not null) { sockets = sockets.ToList(); - var tasks = sockets.Where(s => (fromLocalIpAddress == null || fromLocalIpAddress.Equals(s.LocalIPAddress))) + var tasks = sockets.Where(s => (fromLocalIpAddress is null || fromLocalIpAddress.Equals(((IPEndPoint)s.LocalEndPoint).Address))) .Select(s => SendFromSocket(s, messageData, destination, cancellationToken)); return Task.WhenAll(tasks); } @@ -333,82 +343,78 @@ namespace Rssdp.Infrastructure return Task.CompletedTask; } - private List ListenForBroadcasts() + private List CreateMulticastSocketsAndListen() { - var sockets = new List(); - var nonNullBindAddresses = _networkManager.GetInternalBindAddresses().Where(x => x.Address != null); - + var sockets = new List(); + var multicastGroupAddress = IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress); if (_enableMultiSocketBinding) { - foreach (var address in nonNullBindAddresses) - { - if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - // Not supporting IPv6 right now - continue; - } + // IPv6 is currently unsupported + var validInterfaces = _networkManager.GetInternalBindAddresses() + .Where(x => x.Address is not null) + .Where(x => x.AddressFamily == AddressFamily.InterNetwork) + .DistinctBy(x => x.Index); + foreach (var intf in validInterfaces) + { try { - sockets.Add(_SocketFactory.CreateUdpMulticastSocket(IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress), address.Address, _MulticastTtl, SsdpConstants.MulticastPort)); + var socket = _SocketFactory.CreateUdpMulticastSocket(multicastGroupAddress, intf, _MulticastTtl, SsdpConstants.MulticastPort); + _ = ListenToSocketInternal(socket); + sockets.Add(socket); } catch (Exception ex) { - _logger.LogError(ex, "Error in ListenForBroadcasts. IPAddress: {0}", address); + _logger.LogError(ex, "Error in CreateMulticastSocketsAndListen. IP address: {0}", intf.Address); } } } else { - sockets.Add(_SocketFactory.CreateUdpMulticastSocket(IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress), IPAddress.Any, _MulticastTtl, SsdpConstants.MulticastPort)); - } - - foreach (var socket in sockets) - { + var socket = _SocketFactory.CreateUdpMulticastSocket(multicastGroupAddress, new IPData(IPAddress.Any, null), _MulticastTtl, SsdpConstants.MulticastPort); _ = ListenToSocketInternal(socket); + sockets.Add(socket); } return sockets; } - private List CreateSocketAndListenForResponsesAsync() + private List CreateSendSockets() { - var sockets = new List(); - + var sockets = new List(); if (_enableMultiSocketBinding) { - foreach (var address in _networkManager.GetInternalBindAddresses()) - { - if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - // Not supporting IPv6 right now - continue; - } + // IPv6 is currently unsupported + var validInterfaces = _networkManager.GetInternalBindAddresses() + .Where(x => x.Address is not null) + .Where(x => x.AddressFamily == AddressFamily.InterNetwork); + foreach (var intf in validInterfaces) + { try { - sockets.Add(_SocketFactory.CreateSsdpUdpSocket(address.Address, _LocalPort)); + var socket = _SocketFactory.CreateSsdpUdpSocket(intf, _LocalPort); + _ = ListenToSocketInternal(socket); + sockets.Add(socket); } catch (Exception ex) { - _logger.LogError(ex, "Error in CreateSsdpUdpSocket. IPAddress: {0}", address); + _logger.LogError(ex, "Error in CreateSsdpUdpSocket. IPAddress: {0}", intf.Address); } } } else { - sockets.Add(_SocketFactory.CreateSsdpUdpSocket(IPAddress.Any, _LocalPort)); - } - - foreach (var socket in sockets) - { + var socket = _SocketFactory.CreateSsdpUdpSocket(new IPData(IPAddress.Any, null), _LocalPort); _ = ListenToSocketInternal(socket); + sockets.Add(socket); } + return sockets; } - private async Task ListenToSocketInternal(ISocket socket) + private async Task ListenToSocketInternal(Socket socket) { var cancelled = false; var receiveBuffer = new byte[8192]; @@ -417,14 +423,17 @@ namespace Rssdp.Infrastructure { try { - var result = await socket.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, CancellationToken.None).ConfigureAwait(false); + var result = await socket.ReceiveMessageFromAsync(receiveBuffer, SocketFlags.None, new IPEndPoint(IPAddress.Any, 0), CancellationToken.None).ConfigureAwait(false);; if (result.ReceivedBytes > 0) { - // Strange cannot convert compiler error here if I don't explicitly - // assign or cast to Action first. Assignment is easier to read, - // so went with that. - ProcessMessage(UTF8Encoding.UTF8.GetString(result.Buffer, 0, result.ReceivedBytes), result.RemoteEndPoint, result.LocalIPAddress); + var remoteEndpoint = (IPEndPoint)result.RemoteEndPoint; + var localEndpointAddress = result.PacketInformation.Address; + + ProcessMessage( + UTF8Encoding.UTF8.GetString(receiveBuffer, 0, result.ReceivedBytes), + remoteEndpoint, + localEndpointAddress); } } catch (ObjectDisposedException) @@ -440,11 +449,11 @@ namespace Rssdp.Infrastructure private void EnsureSendSocketCreated() { - if (_sendSockets == null) + if (_sendSockets is null) { lock (_SendSocketSynchroniser) { - _sendSockets ??= CreateSocketAndListenForResponsesAsync(); + _sendSockets ??= CreateSendSockets(); } } } @@ -455,6 +464,7 @@ namespace Rssdp.Infrastructure // requests start with a method which can vary and might be one we haven't // seen/don't know. We'll check if this message is a request or a response // by checking for the HTTP/ prefix on the start of the message. + _logger.LogDebug("Received data from {From} on {Port} at {Address}:\n{Data}", endPoint.Address, endPoint.Port, receivedOnLocalIpAddress, data); if (data.StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase)) { HttpResponseMessage responseMessage = null; @@ -467,7 +477,7 @@ namespace Rssdp.Infrastructure // Ignore invalid packets. } - if (responseMessage != null) + if (responseMessage is not null) { OnResponseReceived(responseMessage, endPoint, receivedOnLocalIpAddress); } @@ -484,7 +494,7 @@ namespace Rssdp.Infrastructure // Ignore invalid packets. } - if (requestMessage != null) + if (requestMessage is not null) { OnRequestReceived(requestMessage, endPoint, receivedOnLocalIpAddress); } @@ -502,7 +512,7 @@ namespace Rssdp.Infrastructure } var handlers = this.RequestReceived; - if (handlers != null) + if (handlers is not null) { handlers(this, new RequestReceivedEventArgs(data, remoteEndPoint, receivedOnLocalIpAddress)); } @@ -511,7 +521,7 @@ namespace Rssdp.Infrastructure private void OnResponseReceived(HttpResponseMessage data, IPEndPoint endPoint, IPAddress localIpAddress) { var handlers = this.ResponseReceived; - if (handlers != null) + if (handlers is not null) { handlers(this, new ResponseReceivedEventArgs(data, endPoint) { diff --git a/RSSDP/SsdpConstants.cs b/RSSDP/SsdpConstants.cs index 798f050e1c..442f2b8f84 100644 --- a/RSSDP/SsdpConstants.cs +++ b/RSSDP/SsdpConstants.cs @@ -26,6 +26,8 @@ namespace Rssdp.Infrastructure internal const string SsdpDeviceDescriptionXmlNamespace = "urn:schemas-upnp-org:device-1-0"; + internal const string ServerVersion = "1.0"; + /// /// Default buffer size for receiving SSDP broadcasts. Value is 8192 (bytes). /// diff --git a/RSSDP/SsdpDeviceLocator.cs b/RSSDP/SsdpDeviceLocator.cs index 681ef0a5c1..25c3b4c4e8 100644 --- a/RSSDP/SsdpDeviceLocator.cs +++ b/RSSDP/SsdpDeviceLocator.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; - namespace Rssdp.Infrastructure { /// @@ -19,19 +19,48 @@ namespace Rssdp.Infrastructure private Timer _BroadcastTimer; private object _timerLock = new object(); + private string _OSName; + + private string _OSVersion; + private readonly TimeSpan DefaultSearchWaitTime = TimeSpan.FromSeconds(4); private readonly TimeSpan OneSecond = TimeSpan.FromSeconds(1); /// /// Default constructor. /// - public SsdpDeviceLocator(ISsdpCommunicationsServer communicationsServer) + public SsdpDeviceLocator( + ISsdpCommunicationsServer communicationsServer, + string osName, + string osVersion) { - if (communicationsServer == null) + if (communicationsServer is null) { throw new ArgumentNullException(nameof(communicationsServer)); } + if (osName is null) + { + throw new ArgumentNullException(nameof(osName)); + } + + if (osName.Length == 0) + { + throw new ArgumentException("osName cannot be an empty string.", nameof(osName)); + } + + if (osVersion is null) + { + throw new ArgumentNullException(nameof(osVersion)); + } + + if (osVersion.Length == 0) + { + throw new ArgumentException("osVersion cannot be an empty string.", nameof(osName)); + } + + _OSName = osName; + _OSVersion = osVersion; _CommunicationsServer = communicationsServer; _CommunicationsServer.ResponseReceived += CommsServer_ResponseReceived; @@ -72,7 +101,7 @@ namespace Rssdp.Infrastructure { lock (_timerLock) { - if (_BroadcastTimer == null) + if (_BroadcastTimer is null) { _BroadcastTimer = new Timer(OnBroadcastTimerCallback, null, dueTime, period); } @@ -87,7 +116,7 @@ namespace Rssdp.Infrastructure { lock (_timerLock) { - if (_BroadcastTimer != null) + if (_BroadcastTimer is not null) { _BroadcastTimer.Dispose(); _BroadcastTimer = null; @@ -148,7 +177,7 @@ namespace Rssdp.Infrastructure private Task SearchAsync(string searchTarget, TimeSpan searchWaitTime, CancellationToken cancellationToken) { - if (searchTarget == null) + if (searchTarget is null) { throw new ArgumentNullException(nameof(searchTarget)); } @@ -187,7 +216,7 @@ namespace Rssdp.Infrastructure { _CommunicationsServer.RequestReceived -= CommsServer_RequestReceived; _CommunicationsServer.RequestReceived += CommsServer_RequestReceived; - _CommunicationsServer.BeginListeningForBroadcasts(); + _CommunicationsServer.BeginListeningForMulticast(); } /// @@ -219,7 +248,7 @@ namespace Rssdp.Infrastructure } var handlers = this.DeviceAvailable; - if (handlers != null) + if (handlers is not null) { handlers(this, new DeviceAvailableEventArgs(device, isNewDevice) { @@ -242,7 +271,7 @@ namespace Rssdp.Infrastructure } var handlers = this.DeviceUnavailable; - if (handlers != null) + if (handlers is not null) { handlers(this, new DeviceUnavailableEventArgs(device, expired)); } @@ -281,7 +310,7 @@ namespace Rssdp.Infrastructure var commsServer = _CommunicationsServer; _CommunicationsServer = null; - if (commsServer != null) + if (commsServer is not null) { commsServer.ResponseReceived -= this.CommsServer_ResponseReceived; commsServer.RequestReceived -= this.CommsServer_RequestReceived; @@ -295,7 +324,7 @@ namespace Rssdp.Infrastructure lock (_Devices) { var existingDevice = FindExistingDeviceNotification(_Devices, device.NotificationType, device.Usn); - if (existingDevice == null) + if (existingDevice is null) { _Devices.Add(device); isNewDevice = true; @@ -329,12 +358,13 @@ namespace Rssdp.Infrastructure private Task BroadcastDiscoverMessage(string serviceType, TimeSpan mxValue, CancellationToken cancellationToken) { + const string header = "M-SEARCH * HTTP/1.1"; + var values = new Dictionary(StringComparer.OrdinalIgnoreCase); values["HOST"] = "239.255.255.250:1900"; values["USER-AGENT"] = "UPnP/1.0 DLNADOC/1.50 Platinum/1.0.4.2"; - // values["X-EMBY-SERVERID"] = _appHost.SystemId; - + values["USER-AGENT"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, SsdpConstants.ServerVersion); values["MAN"] = "\"ssdp:discover\""; // Search target @@ -343,8 +373,6 @@ namespace Rssdp.Infrastructure // Seconds to delay response values["MX"] = "3"; - var header = "M-SEARCH * HTTP/1.1"; - var message = BuildMessage(header, values); return _CommunicationsServer.SendMulticastMessage(message, null, cancellationToken); @@ -358,7 +386,7 @@ namespace Rssdp.Infrastructure } var location = GetFirstHeaderUriValue("Location", message); - if (location != null) + if (location is not null) { var device = new DiscoveredSsdpDevice() { @@ -395,7 +423,7 @@ namespace Rssdp.Infrastructure private void ProcessAliveNotification(HttpRequestMessage message, IPAddress IpAddress) { var location = GetFirstHeaderUriValue("Location", message); - if (location != null) + if (location is not null) { var device = new DiscoveredSsdpDevice() { @@ -445,7 +473,7 @@ namespace Rssdp.Infrastructure if (message.Headers.Contains(headerName)) { message.Headers.TryGetValues(headerName, out values); - if (values != null) + if (values is not null) { retVal = values.FirstOrDefault(); } @@ -461,7 +489,7 @@ namespace Rssdp.Infrastructure if (message.Headers.Contains(headerName)) { message.Headers.TryGetValues(headerName, out values); - if (values != null) + if (values is not null) { retVal = values.FirstOrDefault(); } @@ -477,7 +505,7 @@ namespace Rssdp.Infrastructure if (request.Headers.Contains(headerName)) { request.Headers.TryGetValues(headerName, out values); - if (values != null) + if (values is not null) { value = values.FirstOrDefault(); } @@ -495,7 +523,7 @@ namespace Rssdp.Infrastructure if (response.Headers.Contains(headerName)) { response.Headers.TryGetValues(headerName, out values); - if (values != null) + if (values is not null) { value = values.FirstOrDefault(); } @@ -508,7 +536,7 @@ namespace Rssdp.Infrastructure private TimeSpan CacheAgeFromHeader(System.Net.Http.Headers.CacheControlHeaderValue headerValue) { - if (headerValue == null) + if (headerValue is null) { return TimeSpan.Zero; } @@ -565,7 +593,7 @@ namespace Rssdp.Infrastructure } } - if (existingDevices != null && existingDevices.Count > 0) + if (existingDevices is not null && existingDevices.Count > 0) { foreach (var removedDevice in existingDevices) { diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs index adaac5fa38..40d93b6c0c 100644 --- a/RSSDP/SsdpDevicePublisher.cs +++ b/RSSDP/SsdpDevicePublisher.cs @@ -4,10 +4,9 @@ using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Net; +using System.Text; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Common.Net; -using Microsoft.AspNetCore.HttpOverrides; namespace Rssdp.Infrastructure { @@ -32,8 +31,6 @@ namespace Rssdp.Infrastructure private Random _Random; - private const string ServerVersion = "1.0"; - /// /// Default constructor. /// @@ -43,12 +40,12 @@ namespace Rssdp.Infrastructure string osVersion, bool sendOnlyMatchedHost) { - if (communicationsServer == null) + if (communicationsServer is null) { throw new ArgumentNullException(nameof(communicationsServer)); } - if (osName == null) + if (osName is null) { throw new ArgumentNullException(nameof(osName)); } @@ -58,7 +55,7 @@ namespace Rssdp.Infrastructure throw new ArgumentException("osName cannot be an empty string.", nameof(osName)); } - if (osVersion == null) + if (osVersion is null) { throw new ArgumentNullException(nameof(osVersion)); } @@ -80,10 +77,13 @@ namespace Rssdp.Infrastructure _OSVersion = osVersion; _sendOnlyMatchedHost = sendOnlyMatchedHost; - _CommsServer.BeginListeningForBroadcasts(); + _CommsServer.BeginListeningForMulticast(); + + // Send alive notification once on creation + SendAllAliveNotifications(null); } - public void StartBroadcastingAliveMessages(TimeSpan interval) + public void StartSendingAliveNotifications(TimeSpan interval) { _RebroadcastAliveNotificationsTimer = new Timer(SendAllAliveNotifications, null, TimeSpan.FromSeconds(5), interval); } @@ -99,10 +99,9 @@ namespace Rssdp.Infrastructure /// The instance to add. /// Thrown if the argument is null. /// Thrown if the contains property values that are not acceptable to the UPnP 1.0 specification. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capture task to local variable suppresses compiler warning, but task is not really needed.")] public void AddDevice(SsdpRootDevice device) { - if (device == null) + if (device is null) { throw new ArgumentNullException(nameof(device)); } @@ -138,7 +137,7 @@ namespace Rssdp.Infrastructure /// Thrown if the argument is null. public async Task RemoveDevice(SsdpRootDevice device) { - if (device == null) + if (device is null) { throw new ArgumentNullException(nameof(device)); } @@ -200,7 +199,7 @@ namespace Rssdp.Infrastructure DisposeRebroadcastTimer(); var commsServer = _CommsServer; - if (commsServer != null) + if (commsServer is not null) { commsServer.RequestReceived -= this.CommsServer_RequestReceived; } @@ -209,7 +208,7 @@ namespace Rssdp.Infrastructure Task.WaitAll(tasks); _CommsServer = null; - if (commsServer != null) + if (commsServer is not null) { if (!commsServer.IsShared) { @@ -282,23 +281,23 @@ namespace Rssdp.Infrastructure } else if (searchTarget.Trim().StartsWith("uuid:", StringComparison.OrdinalIgnoreCase)) { - devices = (from device in GetAllDevicesAsFlatEnumerable() where String.Compare(device.Uuid, searchTarget.Substring(5), StringComparison.OrdinalIgnoreCase) == 0 select device).ToArray(); + devices = GetAllDevicesAsFlatEnumerable().Where(d => String.Compare(d.Uuid, searchTarget.Substring(5), StringComparison.OrdinalIgnoreCase) == 0).ToArray(); } else if (searchTarget.StartsWith("urn:", StringComparison.OrdinalIgnoreCase)) { - devices = (from device in GetAllDevicesAsFlatEnumerable() where String.Compare(device.FullDeviceType, searchTarget, StringComparison.OrdinalIgnoreCase) == 0 select device).ToArray(); + devices = GetAllDevicesAsFlatEnumerable().Where(d => String.Compare(d.FullDeviceType, searchTarget, StringComparison.OrdinalIgnoreCase) == 0).ToArray(); } } - if (devices != null) + if (devices is not null) { - var deviceList = devices.ToList(); // WriteTrace(String.Format("Sending {0} search responses", deviceList.Count)); - foreach (var device in deviceList) + foreach (var device in devices) { var root = device.ToRootDevice(); - if (!_sendOnlyMatchedHost || root.Address.Equals(remoteEndPoint.Address)) + + if (!_sendOnlyMatchedHost || root.Address.Equals(receivedOnlocalIpAddress)) { SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIpAddress, cancellationToken); } @@ -318,7 +317,7 @@ namespace Rssdp.Infrastructure IPAddress receivedOnlocalIpAddress, CancellationToken cancellationToken) { - bool isRootDevice = (device as SsdpRootDevice) != null; + bool isRootDevice = (device as SsdpRootDevice) is not null; if (isRootDevice) { SendSearchResponse(SsdpConstants.UpnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), endPoint, receivedOnlocalIpAddress, cancellationToken); @@ -346,19 +345,17 @@ namespace Rssdp.Infrastructure IPAddress receivedOnlocalIpAddress, CancellationToken cancellationToken) { - var rootDevice = device.ToRootDevice(); - - // var additionalheaders = FormatCustomHeadersForResponse(device); - const string header = "HTTP/1.1 200 OK"; + var rootDevice = device.ToRootDevice(); var values = new Dictionary(StringComparer.OrdinalIgnoreCase); values["EXT"] = ""; values["DATE"] = DateTime.UtcNow.ToString("r"); + values["HOST"] = "239.255.255.250:1900"; values["CACHE-CONTROL"] = "max-age = " + rootDevice.CacheLifetime.TotalSeconds; values["ST"] = searchTarget; - values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion); + values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, SsdpConstants.ServerVersion); values["USN"] = uniqueServiceName; values["LOCATION"] = rootDevice.Location.ToString(); @@ -367,7 +364,7 @@ namespace Rssdp.Infrastructure try { await _CommsServer.SendMessage( - System.Text.Encoding.UTF8.GetBytes(message), + Encoding.UTF8.GetBytes(message), endPoint, receivedOnlocalIpAddress, cancellationToken) @@ -492,7 +489,7 @@ namespace Rssdp.Infrastructure values["DATE"] = DateTime.UtcNow.ToString("r"); values["CACHE-CONTROL"] = "max-age = " + rootDevice.CacheLifetime.TotalSeconds; values["LOCATION"] = rootDevice.Location.ToString(); - values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion); + values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, SsdpConstants.ServerVersion); values["NTS"] = "ssdp:alive"; values["NT"] = notificationType; values["USN"] = uniqueServiceName; @@ -527,7 +524,6 @@ namespace Rssdp.Infrastructure return Task.WhenAll(tasks); } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "byebye", Justification = "Correct value for this type of notification in SSDP.")] private Task SendByeByeNotification(SsdpDevice device, string notificationType, string uniqueServiceName, CancellationToken cancellationToken) { const string header = "NOTIFY * HTTP/1.1"; @@ -537,7 +533,7 @@ namespace Rssdp.Infrastructure // If needed later for non-server devices, these headers will need to be dynamic values["HOST"] = "239.255.255.250:1900"; values["DATE"] = DateTime.UtcNow.ToString("r"); - values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion); + values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, SsdpConstants.ServerVersion); values["NTS"] = "ssdp:byebye"; values["NT"] = notificationType; values["USN"] = uniqueServiceName; @@ -553,7 +549,7 @@ namespace Rssdp.Infrastructure { var timer = _RebroadcastAliveNotificationsTimer; _RebroadcastAliveNotificationsTimer = null; - if (timer != null) + if (timer is not null) { timer.Dispose(); } @@ -581,7 +577,7 @@ namespace Rssdp.Infrastructure { string retVal = null; IEnumerable values = null; - if (httpRequestHeaders.TryGetValues(headerName, out values) && values != null) + if (httpRequestHeaders.TryGetValues(headerName, out values) && values is not null) { retVal = values.FirstOrDefault(); } @@ -593,7 +589,7 @@ namespace Rssdp.Infrastructure private void WriteTrace(string text) { - if (LogFunction != null) + if (LogFunction is not null) { LogFunction(text); } @@ -603,7 +599,7 @@ namespace Rssdp.Infrastructure private void WriteTrace(string text, SsdpDevice device) { var rootDevice = device as SsdpRootDevice; - if (rootDevice != null) + if (rootDevice is not null) { WriteTrace(text + " " + device.DeviceType + " - " + device.Uuid + " - " + rootDevice.Location); } diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index c493ce5ea8..10706e9c21 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -6,6 +6,7 @@ using Jellyfin.Networking.Configuration; using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; +using MediaBrowser.Model.Net; using Microsoft.Extensions.Logging.Abstractions; using Moq; using Xunit; @@ -210,7 +211,7 @@ namespace Jellyfin.Networking.Tests if (resultObj is not null && host.Length > 0) { result = resultObj.First().Address.ToString(); - var intf = nm.GetBindInterface(source, out _); + var intf = nm.GetBindAddress(source, out _); Assert.Equal(intf, result); } @@ -271,7 +272,7 @@ namespace Jellyfin.Networking.Tests result = resultObj.First().Address.ToString(); } - var intf = nm.GetBindInterface(source, out int? _); + var intf = nm.GetBindAddress(source, out int? _); Assert.Equal(result, intf); } @@ -334,7 +335,7 @@ namespace Jellyfin.Networking.Tests NetworkManager.MockNetworkSettings = interfaces; using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); - var interfaceToUse = nm.GetBindInterface(string.Empty, out _); + var interfaceToUse = nm.GetBindAddress(string.Empty, out _); Assert.Equal(result, interfaceToUse); } @@ -358,7 +359,7 @@ namespace Jellyfin.Networking.Tests NetworkManager.MockNetworkSettings = interfaces; using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); - var interfaceToUse = nm.GetBindInterface(source, out _); + var interfaceToUse = nm.GetBindAddress(source, out _); Assert.Equal(result, interfaceToUse); } From bedee7922f3be0cd5d1f4f687e9766c1217e39e7 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Fri, 17 Feb 2023 18:24:13 +0100 Subject: [PATCH 045/358] Fix interface address assignment and resolution in SSDP --- Emby.Server.Implementations/Net/SocketFactory.cs | 5 +++-- RSSDP/SsdpCommunicationsServer.cs | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/Net/SocketFactory.cs b/Emby.Server.Implementations/Net/SocketFactory.cs index d134d948ab..51e92953df 100644 --- a/Emby.Server.Implementations/Net/SocketFactory.cs +++ b/Emby.Server.Implementations/Net/SocketFactory.cs @@ -82,13 +82,14 @@ namespace Emby.Server.Implementations.Net try { - var interfaceIndex = (int)IPAddress.HostToNetworkOrder(bindInterface.Index); + var interfaceIndex = bindInterface.Index; + var interfaceIndexSwapped = (int)IPAddress.HostToNetworkOrder(interfaceIndex); socket.MulticastLoopback = false; socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true); socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive); - socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, interfaceIndex); + socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, interfaceIndexSwapped); socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastAddress, interfaceIndex)); socket.Bind(new IPEndPoint(multicastAddress, localPort)); diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index 6ae260d557..f70a598fbe 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -428,12 +428,12 @@ namespace Rssdp.Infrastructure if (result.ReceivedBytes > 0) { var remoteEndpoint = (IPEndPoint)result.RemoteEndPoint; - var localEndpointAddress = result.PacketInformation.Address; + var localEndpointAdapter = _networkManager.GetAllBindInterfaces().Where(a => a.Index == result.PacketInformation.Interface).First(); ProcessMessage( UTF8Encoding.UTF8.GetString(receiveBuffer, 0, result.ReceivedBytes), remoteEndpoint, - localEndpointAddress); + localEndpointAdapter.Address); } } catch (ObjectDisposedException) From 20fd05b05081ad387e94128b4f26d907808c8f0c Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Fri, 17 Feb 2023 19:27:36 +0100 Subject: [PATCH 046/358] Consistently write IP in upercase --- Emby.Dlna/PlayTo/PlayToManager.cs | 2 +- Emby.Dlna/Ssdp/DeviceDiscovery.cs | 2 +- .../HttpServer/WebSocketManager.cs | 2 +- .../TunerHosts/HdHomerun/HdHomerunHost.cs | 4 +- .../TunerHosts/HdHomerun/HdHomerunManager.cs | 10 ++--- .../AnonymousLanAccessHandler.cs | 2 +- .../DefaultAuthorizationHandler.cs | 2 +- .../LocalAccessOrRequiresElevationHandler.cs | 2 +- .../Controllers/MediaInfoController.cs | 2 +- Jellyfin.Api/Controllers/SystemController.cs | 2 +- .../Controllers/UniversalAudioController.cs | 2 +- Jellyfin.Api/Controllers/UserController.cs | 18 ++++---- Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 2 +- Jellyfin.Api/Helpers/MediaInfoHelper.cs | 4 +- Jellyfin.Api/Helpers/RequestHelpers.cs | 2 +- .../IpBasedAccessValidationMiddleware.cs | 10 ++--- .../Middleware/LanFilteringMiddleware.cs | 2 +- .../Middleware/ResponseTimeMiddleware.cs | 4 +- Jellyfin.Networking/Manager/NetworkManager.cs | 26 +++++------ .../ApiApplicationBuilderExtensions.cs | 4 +- .../ApiServiceCollectionExtensions.cs | 8 ++-- Jellyfin.Server/Startup.cs | 2 +- .../Extensions/HttpContextExtensions.cs | 2 +- MediaBrowser.Common/Net/INetworkManager.cs | 6 +-- MediaBrowser.Common/Net/NetworkExtensions.cs | 20 ++++----- MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs | 4 +- RSSDP/DeviceAvailableEventArgs.cs | 2 +- RSSDP/ISsdpCommunicationsServer.cs | 6 +-- RSSDP/RequestReceivedEventArgs.cs | 6 +-- RSSDP/ResponseReceivedEventArgs.cs | 2 +- RSSDP/SsdpCommunicationsServer.cs | 44 +++++++++---------- RSSDP/SsdpDeviceLocator.cs | 26 +++++------ RSSDP/SsdpDevicePublisher.cs | 22 +++++----- .../NetworkParseTests.cs | 10 ++--- 34 files changed, 132 insertions(+), 132 deletions(-) diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs index f4a9a90af4..b9bfad9d9f 100644 --- a/Emby.Dlna/PlayTo/PlayToManager.cs +++ b/Emby.Dlna/PlayTo/PlayToManager.cs @@ -189,7 +189,7 @@ namespace Emby.Dlna.PlayTo _sessionManager.UpdateDeviceName(sessionInfo.Id, deviceName); - string serverAddress = _appHost.GetSmartApiUrl(info.RemoteIpAddress); + string serverAddress = _appHost.GetSmartApiUrl(info.RemoteIPAddress); controller = new PlayToController( sessionInfo, diff --git a/Emby.Dlna/Ssdp/DeviceDiscovery.cs b/Emby.Dlna/Ssdp/DeviceDiscovery.cs index 43d673c772..4fbbc38859 100644 --- a/Emby.Dlna/Ssdp/DeviceDiscovery.cs +++ b/Emby.Dlna/Ssdp/DeviceDiscovery.cs @@ -110,7 +110,7 @@ namespace Emby.Dlna.Ssdp { Location = e.DiscoveredDevice.DescriptionLocation, Headers = headers, - RemoteIpAddress = e.RemoteIpAddress + RemoteIPAddress = e.RemoteIPAddress }); DeviceDiscoveredInternal?.Invoke(this, args); diff --git a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs index 4f7d1c40a6..ecfb242f6f 100644 --- a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs +++ b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs @@ -51,7 +51,7 @@ namespace Emby.Server.Implementations.HttpServer using var connection = new WebSocketConnection( _loggerFactory.CreateLogger(), webSocket, - context.GetNormalizedRemoteIp()) + context.GetNormalizedRemoteIP()) { OnReceive = ProcessWebSocketMessageReceived }; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index e76961ce9e..a86c329d62 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -667,12 +667,12 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun while (!cancellationToken.IsCancellationRequested) { var response = await udpClient.ReceiveMessageFromAsync(receiveBuffer, new IPEndPoint(IPAddress.Any, 0), cancellationToken).ConfigureAwait(false); - var deviceIp = ((IPEndPoint)response.RemoteEndPoint).Address.ToString(); + var deviceIP = ((IPEndPoint)response.RemoteEndPoint).Address.ToString(); // Check to make sure we have enough bytes received to be a valid message and make sure the 2nd byte is the discover reply byte if (response.ReceivedBytes > 13 && receiveBuffer[1] == 3) { - var deviceAddress = "http://" + deviceIp; + var deviceAddress = "http://" + deviceIP; var info = await TryGetTunerHostInfo(deviceAddress, cancellationToken).ConfigureAwait(false); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs index 81eb083f6f..ae7df22f8e 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs @@ -48,10 +48,10 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun GC.SuppressFinalize(this); } - public async Task CheckTunerAvailability(IPAddress remoteIp, int tuner, CancellationToken cancellationToken) + public async Task CheckTunerAvailability(IPAddress remoteIP, int tuner, CancellationToken cancellationToken) { using var client = new TcpClient(); - await client.ConnectAsync(remoteIp, HdHomeRunPort).ConfigureAwait(false); + await client.ConnectAsync(remoteIP, HdHomeRunPort).ConfigureAwait(false); using var stream = client.GetStream(); return await CheckTunerAvailability(stream, tuner, cancellationToken).ConfigureAwait(false); @@ -75,9 +75,9 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun } } - public async Task StartStreaming(IPAddress remoteIp, IPAddress localIp, int localPort, IHdHomerunChannelCommands commands, int numTuners, CancellationToken cancellationToken) + public async Task StartStreaming(IPAddress remoteIP, IPAddress localIP, int localPort, IHdHomerunChannelCommands commands, int numTuners, CancellationToken cancellationToken) { - _remoteEndPoint = new IPEndPoint(remoteIp, HdHomeRunPort); + _remoteEndPoint = new IPEndPoint(remoteIP, HdHomeRunPort); _tcpClient = new TcpClient(); await _tcpClient.ConnectAsync(_remoteEndPoint, cancellationToken).ConfigureAwait(false); @@ -125,7 +125,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun } } - var targetValue = string.Format(CultureInfo.InvariantCulture, "rtp://{0}:{1}", localIp, localPort); + var targetValue = string.Format(CultureInfo.InvariantCulture, "rtp://{0}:{1}", localIP, localPort); var targetMsgLen = WriteSetMessage(buffer, i, "target", targetValue, lockKeyValue); await stream.WriteAsync(buffer.AsMemory(0, targetMsgLen), cancellationToken).ConfigureAwait(false); diff --git a/Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessHandler.cs b/Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessHandler.cs index 741b88ea95..3c1401dedc 100644 --- a/Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessHandler.cs +++ b/Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessHandler.cs @@ -30,7 +30,7 @@ namespace Jellyfin.Api.Auth.AnonymousLanAccessPolicy /// protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AnonymousLanAccessRequirement requirement) { - var ip = _httpContextAccessor.HttpContext?.GetNormalizedRemoteIp(); + var ip = _httpContextAccessor.HttpContext?.GetNormalizedRemoteIP(); // Loopback will be on LAN, so we can accept null. if (ip is null || _networkManager.IsInLocalNetwork(ip)) diff --git a/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs index b1d97e4a1d..c0db4d1fc2 100644 --- a/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs +++ b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs @@ -47,7 +47,7 @@ namespace Jellyfin.Api.Auth.DefaultAuthorizationPolicy } var isInLocalNetwork = _httpContextAccessor.HttpContext is not null - && _networkManager.IsInLocalNetwork(_httpContextAccessor.HttpContext.GetNormalizedRemoteIp()); + && _networkManager.IsInLocalNetwork(_httpContextAccessor.HttpContext.GetNormalizedRemoteIP()); var user = _userManager.GetUserById(userId); if (user is null) { diff --git a/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs b/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs index 6ed6fc90be..557b7d3aa4 100644 --- a/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs +++ b/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs @@ -31,7 +31,7 @@ namespace Jellyfin.Api.Auth.LocalAccessOrRequiresElevationPolicy /// protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, LocalAccessOrRequiresElevationRequirement requirement) { - var ip = _httpContextAccessor.HttpContext?.GetNormalizedRemoteIp(); + var ip = _httpContextAccessor.HttpContext?.GetNormalizedRemoteIP(); // Loopback will be on LAN, so we can accept null. if (ip is null || _networkManager.IsInLocalNetwork(ip)) diff --git a/Jellyfin.Api/Controllers/MediaInfoController.cs b/Jellyfin.Api/Controllers/MediaInfoController.cs index ea10dd771f..1bef35c274 100644 --- a/Jellyfin.Api/Controllers/MediaInfoController.cs +++ b/Jellyfin.Api/Controllers/MediaInfoController.cs @@ -183,7 +183,7 @@ public class MediaInfoController : BaseJellyfinApiController enableTranscoding.Value, allowVideoStreamCopy.Value, allowAudioStreamCopy.Value, - Request.HttpContext.GetNormalizedRemoteIp()); + Request.HttpContext.GetNormalizedRemoteIP()); } _mediaInfoHelper.SortMediaSources(info, maxStreamingBitrate); diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs index 4ab705f40a..91901518fa 100644 --- a/Jellyfin.Api/Controllers/SystemController.cs +++ b/Jellyfin.Api/Controllers/SystemController.cs @@ -179,7 +179,7 @@ public class SystemController : BaseJellyfinApiController return new EndPointInfo { IsLocal = HttpContext.IsLocal(), - IsInNetwork = _network.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp()) + IsInNetwork = _network.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIP()) }; } diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs index 3455215979..04f2109eaa 100644 --- a/Jellyfin.Api/Controllers/UniversalAudioController.cs +++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs @@ -143,7 +143,7 @@ public class UniversalAudioController : BaseJellyfinApiController true, true, true, - Request.HttpContext.GetNormalizedRemoteIp()); + Request.HttpContext.GetNormalizedRemoteIP()); } _mediaInfoHelper.SortMediaSources(info, maxStreamingBitrate); diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs index b0973b8a14..ec54255780 100644 --- a/Jellyfin.Api/Controllers/UserController.cs +++ b/Jellyfin.Api/Controllers/UserController.cs @@ -129,7 +129,7 @@ public class UserController : BaseJellyfinApiController return NotFound("User not found"); } - var result = _userManager.GetUserDto(user, HttpContext.GetNormalizedRemoteIp().ToString()); + var result = _userManager.GetUserDto(user, HttpContext.GetNormalizedRemoteIP().ToString()); return result; } @@ -211,7 +211,7 @@ public class UserController : BaseJellyfinApiController DeviceId = auth.DeviceId, DeviceName = auth.Device, Password = request.Pw, - RemoteEndPoint = HttpContext.GetNormalizedRemoteIp().ToString(), + RemoteEndPoint = HttpContext.GetNormalizedRemoteIP().ToString(), Username = request.Username }).ConfigureAwait(false); @@ -220,7 +220,7 @@ public class UserController : BaseJellyfinApiController catch (SecurityException e) { // rethrow adding IP address to message - throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIp()}] {e.Message}", e); + throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIP()}] {e.Message}", e); } } @@ -242,7 +242,7 @@ public class UserController : BaseJellyfinApiController catch (SecurityException e) { // rethrow adding IP address to message - throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIp()}] {e.Message}", e); + throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIP()}] {e.Message}", e); } } @@ -288,7 +288,7 @@ public class UserController : BaseJellyfinApiController user.Username, request.CurrentPw ?? string.Empty, request.CurrentPw ?? string.Empty, - HttpContext.GetNormalizedRemoteIp().ToString(), + HttpContext.GetNormalizedRemoteIP().ToString(), false).ConfigureAwait(false); if (success is null) @@ -489,7 +489,7 @@ public class UserController : BaseJellyfinApiController await _userManager.ChangePassword(newUser, request.Password).ConfigureAwait(false); } - var result = _userManager.GetUserDto(newUser, HttpContext.GetNormalizedRemoteIp().ToString()); + var result = _userManager.GetUserDto(newUser, HttpContext.GetNormalizedRemoteIP().ToString()); return result; } @@ -504,7 +504,7 @@ public class UserController : BaseJellyfinApiController [ProducesResponseType(StatusCodes.Status200OK)] public async Task> ForgotPassword([FromBody, Required] ForgotPasswordDto forgotPasswordRequest) { - var ip = HttpContext.GetNormalizedRemoteIp(); + var ip = HttpContext.GetNormalizedRemoteIP(); var isLocal = HttpContext.IsLocal() || _networkManager.IsInLocalNetwork(ip); @@ -585,7 +585,7 @@ public class UserController : BaseJellyfinApiController if (filterByNetwork) { - if (!_networkManager.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp())) + if (!_networkManager.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIP())) { users = users.Where(i => i.HasPermission(PermissionKind.EnableRemoteAccess)); } @@ -593,7 +593,7 @@ public class UserController : BaseJellyfinApiController var result = users .OrderBy(u => u.Username) - .Select(i => _userManager.GetUserDto(i, HttpContext.GetNormalizedRemoteIp().ToString())); + .Select(i => _userManager.GetUserDto(i, HttpContext.GetNormalizedRemoteIP().ToString())); return result; } diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index 245239233c..f9ca392099 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -273,7 +273,7 @@ public class DynamicHlsHelper } } - if (EnableAdaptiveBitrateStreaming(state, isLiveStream, enableAdaptiveBitrateStreaming, _httpContextAccessor.HttpContext.GetNormalizedRemoteIp())) + if (EnableAdaptiveBitrateStreaming(state, isLiveStream, enableAdaptiveBitrateStreaming, _httpContextAccessor.HttpContext.GetNormalizedRemoteIP())) { var requestedVideoBitrate = state.VideoRequest is null ? 0 : state.VideoRequest.VideoBitRate ?? 0; diff --git a/Jellyfin.Api/Helpers/MediaInfoHelper.cs b/Jellyfin.Api/Helpers/MediaInfoHelper.cs index 5910d80737..a36028cfeb 100644 --- a/Jellyfin.Api/Helpers/MediaInfoHelper.cs +++ b/Jellyfin.Api/Helpers/MediaInfoHelper.cs @@ -421,7 +421,7 @@ public class MediaInfoHelper true, true, true, - httpContext.GetNormalizedRemoteIp()); + httpContext.GetNormalizedRemoteIP()); } else { @@ -487,7 +487,7 @@ public class MediaInfoHelper { var isInLocalNetwork = _networkManager.IsInLocalNetwork(ipAddress); - _logger.LogInformation("RemoteClientBitrateLimit: {0}, RemoteIp: {1}, IsInLocalNetwork: {2}", remoteClientMaxBitrate, ipAddress, isInLocalNetwork); + _logger.LogInformation("RemoteClientBitrateLimit: {0}, RemoteIP: {1}, IsInLocalNetwork: {2}", remoteClientMaxBitrate, ipAddress, isInLocalNetwork); if (!isInLocalNetwork) { maxBitrate = Math.Min(maxBitrate ?? remoteClientMaxBitrate, remoteClientMaxBitrate); diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs index 0b7a4fa1ac..1ab55bc312 100644 --- a/Jellyfin.Api/Helpers/RequestHelpers.cs +++ b/Jellyfin.Api/Helpers/RequestHelpers.cs @@ -98,7 +98,7 @@ public static class RequestHelpers httpContext.User.GetVersion(), httpContext.User.GetDeviceId(), httpContext.User.GetDevice(), - httpContext.GetNormalizedRemoteIp().ToString(), + httpContext.GetNormalizedRemoteIP().ToString(), user).ConfigureAwait(false); if (session is null) diff --git a/Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs b/Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs index f45b6b5c0a..27bcd5570c 100644 --- a/Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs +++ b/Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs @@ -9,15 +9,15 @@ namespace Jellyfin.Api.Middleware; /// /// Validates the IP of requests coming from local networks wrt. remote access. /// -public class IpBasedAccessValidationMiddleware +public class IPBasedAccessValidationMiddleware { private readonly RequestDelegate _next; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The next delegate in the pipeline. - public IpBasedAccessValidationMiddleware(RequestDelegate next) + public IPBasedAccessValidationMiddleware(RequestDelegate next) { _next = next; } @@ -37,9 +37,9 @@ public class IpBasedAccessValidationMiddleware return; } - var remoteIp = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback; + var remoteIP = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback; - if (!networkManager.HasRemoteAccess(remoteIp)) + if (!networkManager.HasRemoteAccess(remoteIP)) { return; } diff --git a/Jellyfin.Api/Middleware/LanFilteringMiddleware.cs b/Jellyfin.Api/Middleware/LanFilteringMiddleware.cs index 9c2194fafd..94de30d1b1 100644 --- a/Jellyfin.Api/Middleware/LanFilteringMiddleware.cs +++ b/Jellyfin.Api/Middleware/LanFilteringMiddleware.cs @@ -38,7 +38,7 @@ public class LanFilteringMiddleware return; } - var host = httpContext.GetNormalizedRemoteIp(); + var host = httpContext.GetNormalizedRemoteIP(); if (!networkManager.IsInLocalNetwork(host)) { return; diff --git a/Jellyfin.Api/Middleware/ResponseTimeMiddleware.cs b/Jellyfin.Api/Middleware/ResponseTimeMiddleware.cs index db39177436..279ea70d80 100644 --- a/Jellyfin.Api/Middleware/ResponseTimeMiddleware.cs +++ b/Jellyfin.Api/Middleware/ResponseTimeMiddleware.cs @@ -51,9 +51,9 @@ public class ResponseTimeMiddleware if (enableWarning && responseTimeMs > warningThreshold && _logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug( - "Slow HTTP Response from {Url} to {RemoteIp} in {Elapsed:g} with Status Code {StatusCode}", + "Slow HTTP Response from {Url} to {RemoteIP} in {Elapsed:g} with Status Code {StatusCode}", context.Request.GetDisplayUrl(), - context.GetNormalizedRemoteIp(), + context.GetNormalizedRemoteIP(), responseTime, context.Response.StatusCode); } diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index cdd34bc896..dd90a5b516 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -122,7 +122,7 @@ namespace Jellyfin.Networking.Manager /// /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. /// - public bool TrustAllIpv6Interfaces { get; private set; } + public bool TrustAllIPv6Interfaces { get; private set; } /// /// Gets the Published server override list. @@ -596,17 +596,17 @@ namespace Jellyfin.Networking.Manager } /// - public bool HasRemoteAccess(IPAddress remoteIp) + public bool HasRemoteAccess(IPAddress remoteIP) { var config = _configurationManager.GetNetworkConfiguration(); if (config.EnableRemoteAccess) { // 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. - if (_remoteAddressFilter.Any() && !_lanSubnets.Any(x => x.Contains(remoteIp))) + if (_remoteAddressFilter.Any() && !_lanSubnets.Any(x => x.Contains(remoteIP))) { // remoteAddressFilter is a whitelist or blacklist. - var matches = _remoteAddressFilter.Count(remoteNetwork => remoteNetwork.Contains(remoteIp)); + var matches = _remoteAddressFilter.Count(remoteNetwork => remoteNetwork.Contains(remoteIP)); if ((!config.IsRemoteIPFilterBlacklist && matches > 0) || (config.IsRemoteIPFilterBlacklist && matches == 0)) { @@ -616,7 +616,7 @@ namespace Jellyfin.Networking.Manager return false; } } - else if (!_lanSubnets.Any(x => x.Contains(remoteIp))) + else if (!_lanSubnets.Any(x => x.Contains(remoteIP))) { // Remote not enabled. So everyone should be LAN. return false; @@ -771,7 +771,7 @@ namespace Jellyfin.Networking.Manager // If no source address is given, use the preferred (first) interface if (source is null) { - result = NetworkExtensions.FormatIpString(availableInterfaces.First().Address); + result = NetworkExtensions.FormatIPString(availableInterfaces.First().Address); _logger.LogDebug("{Source}: Using first internal interface as bind address: {Result}", source, result); return result; } @@ -782,14 +782,14 @@ namespace Jellyfin.Networking.Manager { if (intf.Subnet.Contains(source)) { - result = NetworkExtensions.FormatIpString(intf.Address); + result = NetworkExtensions.FormatIPString(intf.Address); _logger.LogDebug("{Source}: Found interface with matching subnet, using it as bind address: {Result}", source, result); return result; } } // Fallback to first available interface - result = NetworkExtensions.FormatIpString(availableInterfaces[0].Address); + result = NetworkExtensions.FormatIPString(availableInterfaces[0].Address); _logger.LogDebug("{Source}: No matching interfaces found, using preferred interface as bind address: {Result}", source, result); return result; } @@ -842,7 +842,7 @@ namespace Jellyfin.Networking.Manager ArgumentNullException.ThrowIfNull(address); // See conversation at https://github.com/jellyfin/jellyfin/pull/3515. - if ((TrustAllIpv6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) + if ((TrustAllIPv6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) || address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback)) { @@ -995,7 +995,7 @@ namespace Jellyfin.Networking.Manager if (bindAddress is not null) { - result = NetworkExtensions.FormatIpString(bindAddress); + result = NetworkExtensions.FormatIPString(bindAddress); _logger.LogDebug("{Source}: External request received, matching external bind address found: {Result}", source, result); return true; } @@ -1015,7 +1015,7 @@ namespace Jellyfin.Networking.Manager if (bindAddress is not null) { - result = NetworkExtensions.FormatIpString(bindAddress); + result = NetworkExtensions.FormatIPString(bindAddress); _logger.LogDebug("{Source}: Internal request received, matching internal bind address found: {Result}", source, result); return true; } @@ -1049,14 +1049,14 @@ namespace Jellyfin.Networking.Manager { if (!IsInLocalNetwork(intf.Address) && intf.Subnet.Contains(source)) { - result = NetworkExtensions.FormatIpString(intf.Address); + result = NetworkExtensions.FormatIPString(intf.Address); _logger.LogDebug("{Source}: Found external interface with matching subnet, using it as bind address: {Result}", source, result); return true; } } // Fallback to first external interface. - result = NetworkExtensions.FormatIpString(extResult.First().Address); + result = NetworkExtensions.FormatIPString(extResult.First().Address); _logger.LogDebug("{Source}: Using first external interface as bind address: {Result}", source, result); return true; } diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs index 463ca7321d..b6af9baec3 100644 --- a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs @@ -63,9 +63,9 @@ namespace Jellyfin.Server.Extensions /// /// The application builder. /// The updated application builder. - public static IApplicationBuilder UseIpBasedAccessValidation(this IApplicationBuilder appBuilder) + public static IApplicationBuilder UseIPBasedAccessValidation(this IApplicationBuilder appBuilder) { - return appBuilder.UseMiddleware(); + return appBuilder.UseMiddleware(); } /// diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 1dfbb89fa0..ea3c92011f 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -271,26 +271,26 @@ namespace Jellyfin.Server.Extensions { if (IPAddress.TryParse(allowedProxies[i], out var addr)) { - AddIpAddress(config, options, addr, addr.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); + AddIPAddress(config, options, addr, addr.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); } else if (NetworkExtensions.TryParseToSubnet(allowedProxies[i], out var subnet)) { if (subnet != null) { - AddIpAddress(config, options, subnet.Prefix, subnet.PrefixLength); + AddIPAddress(config, options, subnet.Prefix, subnet.PrefixLength); } } else if (NetworkExtensions.TryParseHost(allowedProxies[i], out var addresses)) { foreach (var address in addresses) { - AddIpAddress(config, options, address, address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); + AddIPAddress(config, options, address, address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); } } } } - private static void AddIpAddress(NetworkConfiguration config, ForwardedHeadersOptions options, IPAddress addr, int prefixLength) + private static void AddIPAddress(NetworkConfiguration config, ForwardedHeadersOptions options, IPAddress addr, int prefixLength) { if ((!config.EnableIPv4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPv6 && addr.AddressFamily == AddressFamily.InterNetworkV6)) { diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index 155f9fc8c1..4afaf12179 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -190,7 +190,7 @@ namespace Jellyfin.Server mainApp.UseAuthorization(); mainApp.UseLanFiltering(); - mainApp.UseIpBasedAccessValidation(); + mainApp.UseIPBasedAccessValidation(); mainApp.UseWebSocketHandler(); mainApp.UseServerStartupMessage(); diff --git a/MediaBrowser.Common/Extensions/HttpContextExtensions.cs b/MediaBrowser.Common/Extensions/HttpContextExtensions.cs index 6608704c0a..a1056b7c84 100644 --- a/MediaBrowser.Common/Extensions/HttpContextExtensions.cs +++ b/MediaBrowser.Common/Extensions/HttpContextExtensions.cs @@ -25,7 +25,7 @@ namespace MediaBrowser.Common.Extensions /// /// The HTTP context. /// The remote caller IP address. - public static IPAddress GetNormalizedRemoteIp(this HttpContext context) + public static IPAddress GetNormalizedRemoteIP(this HttpContext context) { // Default to the loopback address if no RemoteIpAddress is specified (i.e. during integration tests) var ip = context.Connection.RemoteIpAddress ?? IPAddress.Loopback; diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 68974f738d..efd87a8107 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -130,10 +130,10 @@ namespace MediaBrowser.Common.Net IReadOnlyList GetInternalBindAddresses(); /// - /// Checks if has access to the server. + /// Checks if has access to the server. /// - /// IP address of the client. + /// IP address of the client. /// True if it has access, otherwise false. - bool HasRemoteAccess(IPAddress remoteIp); + bool HasRemoteAccess(IPAddress remoteIP); } } diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 7c36081e60..cef4a5d965 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -126,11 +126,11 @@ namespace MediaBrowser.Common.Net /// /// Converts an IPAddress into a string. - /// Ipv6 addresses are returned in [ ], with their scope removed. + /// IPv6 addresses are returned in [ ], with their scope removed. /// /// Address to convert. /// URI safe conversion of the address. - public static string FormatIpString(IPAddress? address) + public static string FormatIPString(IPAddress? address) { if (address is null) { @@ -252,10 +252,10 @@ namespace MediaBrowser.Common.Net /// /// Host name to parse. /// Object representing the string, if it has successfully been parsed. - /// true if IPv4 is enabled. - /// true if IPv6 is enabled. + /// true if IPv4 is enabled. + /// true if IPv6 is enabled. /// true if the parsing is successful, false if not. - public static bool TryParseHost(string host, [NotNullWhen(true)] out IPAddress[] addresses, bool isIpv4Enabled = true, bool isIpv6Enabled = false) + public static bool TryParseHost(string host, [NotNullWhen(true)] out IPAddress[] addresses, bool isIPv4Enabled = true, bool isIPv6Enabled = false) { if (string.IsNullOrWhiteSpace(host)) { @@ -302,8 +302,8 @@ namespace MediaBrowser.Common.Net if (IPAddress.TryParse(host, out var address)) { - if (((address.AddressFamily == AddressFamily.InterNetwork) && (!isIpv4Enabled && isIpv6Enabled)) || - ((address.AddressFamily == AddressFamily.InterNetworkV6) && (isIpv4Enabled && !isIpv6Enabled))) + if (((address.AddressFamily == AddressFamily.InterNetwork) && (!isIPv4Enabled && isIPv6Enabled)) || + ((address.AddressFamily == AddressFamily.InterNetworkV6) && (isIPv4Enabled && !isIPv6Enabled))) { addresses = Array.Empty(); return false; @@ -338,11 +338,11 @@ namespace MediaBrowser.Common.Net addressBytes.Reverse(); } - uint ipAddress = BitConverter.ToUInt32(addressBytes, 0); + uint iPAddress = BitConverter.ToUInt32(addressBytes, 0); uint ipMaskV4 = BitConverter.ToUInt32(CidrToMask(network.PrefixLength, AddressFamily.InterNetwork).GetAddressBytes(), 0); - uint broadCastIpAddress = ipAddress | ~ipMaskV4; + uint broadCastIPAddress = iPAddress | ~ipMaskV4; - return new IPAddress(BitConverter.GetBytes(broadCastIpAddress)); + return new IPAddress(BitConverter.GetBytes(broadCastIPAddress)); } } } diff --git a/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs b/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs index 987a3a908f..c7489d57ae 100644 --- a/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs +++ b/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs @@ -13,10 +13,10 @@ namespace MediaBrowser.Model.Dlna public Dictionary Headers { get; set; } - public IPAddress LocalIpAddress { get; set; } + public IPAddress LocalIPAddress { get; set; } public int LocalPort { get; set; } - public IPAddress RemoteIpAddress { get; set; } + public IPAddress RemoteIPAddress { get; set; } } } diff --git a/RSSDP/DeviceAvailableEventArgs.cs b/RSSDP/DeviceAvailableEventArgs.cs index 9d477ea9f4..f933f258be 100644 --- a/RSSDP/DeviceAvailableEventArgs.cs +++ b/RSSDP/DeviceAvailableEventArgs.cs @@ -8,7 +8,7 @@ namespace Rssdp /// public sealed class DeviceAvailableEventArgs : EventArgs { - public IPAddress RemoteIpAddress { get; set; } + public IPAddress RemoteIPAddress { get; set; } private readonly DiscoveredSsdpDevice _DiscoveredDevice; diff --git a/RSSDP/ISsdpCommunicationsServer.cs b/RSSDP/ISsdpCommunicationsServer.cs index 571c66c107..95b0a1c704 100644 --- a/RSSDP/ISsdpCommunicationsServer.cs +++ b/RSSDP/ISsdpCommunicationsServer.cs @@ -33,13 +33,13 @@ namespace Rssdp.Infrastructure /// /// Sends a message to a particular address (uni or multicast) and port. /// - Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken); + Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIPAddress, CancellationToken cancellationToken); /// /// Sends a message to the SSDP multicast address and port. /// - Task SendMulticastMessage(string message, IPAddress fromLocalIpAddress, CancellationToken cancellationToken); - Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIpAddress, CancellationToken cancellationToken); + Task SendMulticastMessage(string message, IPAddress fromLocalIPAddress, CancellationToken cancellationToken); + Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIPAddress, CancellationToken cancellationToken); /// /// Gets or sets a boolean value indicating whether or not this instance is shared amongst multiple and/or instances. diff --git a/RSSDP/RequestReceivedEventArgs.cs b/RSSDP/RequestReceivedEventArgs.cs index 5cf74bd757..b8b2249e42 100644 --- a/RSSDP/RequestReceivedEventArgs.cs +++ b/RSSDP/RequestReceivedEventArgs.cs @@ -13,16 +13,16 @@ namespace Rssdp.Infrastructure private readonly IPEndPoint _ReceivedFrom; - public IPAddress LocalIpAddress { get; private set; } + public IPAddress LocalIPAddress { get; private set; } /// /// Full constructor. /// - public RequestReceivedEventArgs(HttpRequestMessage message, IPEndPoint receivedFrom, IPAddress localIpAddress) + public RequestReceivedEventArgs(HttpRequestMessage message, IPEndPoint receivedFrom, IPAddress localIPAddress) { _Message = message; _ReceivedFrom = receivedFrom; - LocalIpAddress = localIpAddress; + LocalIPAddress = localIPAddress; } /// diff --git a/RSSDP/ResponseReceivedEventArgs.cs b/RSSDP/ResponseReceivedEventArgs.cs index 93262a4608..e87ba14524 100644 --- a/RSSDP/ResponseReceivedEventArgs.cs +++ b/RSSDP/ResponseReceivedEventArgs.cs @@ -9,7 +9,7 @@ namespace Rssdp.Infrastructure /// public sealed class ResponseReceivedEventArgs : EventArgs { - public IPAddress LocalIpAddress { get; set; } + public IPAddress LocalIPAddress { get; set; } private readonly HttpResponseMessage _Message; diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index f70a598fbe..5b8916d021 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -155,7 +155,7 @@ namespace Rssdp.Infrastructure /// /// Sends a message to a particular address (uni or multicast) and port. /// - public async Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) + public async Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromlocalIPAddress, CancellationToken cancellationToken) { if (messageData is null) { @@ -164,7 +164,7 @@ namespace Rssdp.Infrastructure ThrowIfDisposed(); - var sockets = GetSendSockets(fromLocalIpAddress, destination); + var sockets = GetSendSockets(fromlocalIPAddress, destination); if (sockets.Count == 0) { @@ -200,19 +200,19 @@ namespace Rssdp.Infrastructure } } - private List GetSendSockets(IPAddress fromLocalIpAddress, IPEndPoint destination) + private List GetSendSockets(IPAddress fromlocalIPAddress, IPEndPoint destination) { EnsureSendSocketCreated(); lock (_SendSocketSynchroniser) { - var sockets = _sendSockets.Where(s => s.AddressFamily == fromLocalIpAddress.AddressFamily); + var sockets = _sendSockets.Where(s => s.AddressFamily == fromlocalIPAddress.AddressFamily); // Send from the Any socket and the socket with the matching address - if (fromLocalIpAddress.AddressFamily == AddressFamily.InterNetwork) + if (fromlocalIPAddress.AddressFamily == AddressFamily.InterNetwork) { sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Any) - || ((IPEndPoint)s.LocalEndPoint).Address.Equals(fromLocalIpAddress)); + || ((IPEndPoint)s.LocalEndPoint).Address.Equals(fromlocalIPAddress)); // If sending to the loopback address, filter the socket list as well if (destination.Address.Equals(IPAddress.Loopback)) @@ -221,10 +221,10 @@ namespace Rssdp.Infrastructure || ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Loopback)); } } - else if (fromLocalIpAddress.AddressFamily == AddressFamily.InterNetworkV6) + else if (fromlocalIPAddress.AddressFamily == AddressFamily.InterNetworkV6) { sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.IPv6Any) - || ((IPEndPoint)s.LocalEndPoint).Address.Equals(fromLocalIpAddress)); + || ((IPEndPoint)s.LocalEndPoint).Address.Equals(fromlocalIPAddress)); // If sending to the loopback address, filter the socket list as well if (destination.Address.Equals(IPAddress.IPv6Loopback)) @@ -238,15 +238,15 @@ namespace Rssdp.Infrastructure } } - public Task SendMulticastMessage(string message, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) + public Task SendMulticastMessage(string message, IPAddress fromlocalIPAddress, CancellationToken cancellationToken) { - return SendMulticastMessage(message, SsdpConstants.UdpResendCount, fromLocalIpAddress, cancellationToken); + return SendMulticastMessage(message, SsdpConstants.UdpResendCount, fromlocalIPAddress, cancellationToken); } /// /// Sends a message to the SSDP multicast address and port. /// - public async Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) + public async Task SendMulticastMessage(string message, int sendCount, IPAddress fromlocalIPAddress, CancellationToken cancellationToken) { if (message is null) { @@ -269,7 +269,7 @@ namespace Rssdp.Infrastructure new IPEndPoint( IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress), SsdpConstants.MulticastPort), - fromLocalIpAddress, + fromlocalIPAddress, cancellationToken).ConfigureAwait(false); await Task.Delay(100, cancellationToken).ConfigureAwait(false); @@ -328,14 +328,14 @@ namespace Rssdp.Infrastructure } } - private Task SendMessageIfSocketNotDisposed(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) + private Task SendMessageIfSocketNotDisposed(byte[] messageData, IPEndPoint destination, IPAddress fromlocalIPAddress, CancellationToken cancellationToken) { var sockets = _sendSockets; if (sockets is not null) { sockets = sockets.ToList(); - var tasks = sockets.Where(s => (fromLocalIpAddress is null || fromLocalIpAddress.Equals(((IPEndPoint)s.LocalEndPoint).Address))) + var tasks = sockets.Where(s => (fromlocalIPAddress is null || fromlocalIPAddress.Equals(((IPEndPoint)s.LocalEndPoint).Address))) .Select(s => SendFromSocket(s, messageData, destination, cancellationToken)); return Task.WhenAll(tasks); } @@ -458,13 +458,13 @@ namespace Rssdp.Infrastructure } } - private void ProcessMessage(string data, IPEndPoint endPoint, IPAddress receivedOnLocalIpAddress) + private void ProcessMessage(string data, IPEndPoint endPoint, IPAddress receivedOnlocalIPAddress) { // Responses start with the HTTP version, prefixed with HTTP/ while // requests start with a method which can vary and might be one we haven't // seen/don't know. We'll check if this message is a request or a response // by checking for the HTTP/ prefix on the start of the message. - _logger.LogDebug("Received data from {From} on {Port} at {Address}:\n{Data}", endPoint.Address, endPoint.Port, receivedOnLocalIpAddress, data); + _logger.LogDebug("Received data from {From} on {Port} at {Address}:\n{Data}", endPoint.Address, endPoint.Port, receivedOnlocalIPAddress, data); if (data.StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase)) { HttpResponseMessage responseMessage = null; @@ -479,7 +479,7 @@ namespace Rssdp.Infrastructure if (responseMessage is not null) { - OnResponseReceived(responseMessage, endPoint, receivedOnLocalIpAddress); + OnResponseReceived(responseMessage, endPoint, receivedOnlocalIPAddress); } } else @@ -496,12 +496,12 @@ namespace Rssdp.Infrastructure if (requestMessage is not null) { - OnRequestReceived(requestMessage, endPoint, receivedOnLocalIpAddress); + OnRequestReceived(requestMessage, endPoint, receivedOnlocalIPAddress); } } } - private void OnRequestReceived(HttpRequestMessage data, IPEndPoint remoteEndPoint, IPAddress receivedOnLocalIpAddress) + private void OnRequestReceived(HttpRequestMessage data, IPEndPoint remoteEndPoint, IPAddress receivedOnlocalIPAddress) { // SSDP specification says only * is currently used but other uri's might // be implemented in the future and should be ignored unless understood. @@ -514,18 +514,18 @@ namespace Rssdp.Infrastructure var handlers = this.RequestReceived; if (handlers is not null) { - handlers(this, new RequestReceivedEventArgs(data, remoteEndPoint, receivedOnLocalIpAddress)); + handlers(this, new RequestReceivedEventArgs(data, remoteEndPoint, receivedOnlocalIPAddress)); } } - private void OnResponseReceived(HttpResponseMessage data, IPEndPoint endPoint, IPAddress localIpAddress) + private void OnResponseReceived(HttpResponseMessage data, IPEndPoint endPoint, IPAddress localIPAddress) { var handlers = this.ResponseReceived; if (handlers is not null) { handlers(this, new ResponseReceivedEventArgs(data, endPoint) { - LocalIpAddress = localIpAddress + LocalIPAddress = localIPAddress }); } } diff --git a/RSSDP/SsdpDeviceLocator.cs b/RSSDP/SsdpDeviceLocator.cs index 25c3b4c4e8..9d756d0d4c 100644 --- a/RSSDP/SsdpDeviceLocator.cs +++ b/RSSDP/SsdpDeviceLocator.cs @@ -240,7 +240,7 @@ namespace Rssdp.Infrastructure /// Raises the event. /// /// - protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress IpAddress) + protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress IPAddress) { if (this.IsDisposed) { @@ -252,7 +252,7 @@ namespace Rssdp.Infrastructure { handlers(this, new DeviceAvailableEventArgs(device, isNewDevice) { - RemoteIpAddress = IpAddress + RemoteIPAddress = IPAddress }); } } @@ -318,7 +318,7 @@ namespace Rssdp.Infrastructure } } - private void AddOrUpdateDiscoveredDevice(DiscoveredSsdpDevice device, IPAddress IpAddress) + private void AddOrUpdateDiscoveredDevice(DiscoveredSsdpDevice device, IPAddress IPAddress) { bool isNewDevice = false; lock (_Devices) @@ -336,17 +336,17 @@ namespace Rssdp.Infrastructure } } - DeviceFound(device, isNewDevice, IpAddress); + DeviceFound(device, isNewDevice, IPAddress); } - private void DeviceFound(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress IpAddress) + private void DeviceFound(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress IPAddress) { if (!NotificationTypeMatchesFilter(device)) { return; } - OnDeviceAvailable(device, isNewDevice, IpAddress); + OnDeviceAvailable(device, isNewDevice, IPAddress); } private bool NotificationTypeMatchesFilter(DiscoveredSsdpDevice device) @@ -378,7 +378,7 @@ namespace Rssdp.Infrastructure return _CommunicationsServer.SendMulticastMessage(message, null, cancellationToken); } - private void ProcessSearchResponseMessage(HttpResponseMessage message, IPAddress IpAddress) + private void ProcessSearchResponseMessage(HttpResponseMessage message, IPAddress IPAddress) { if (!message.IsSuccessStatusCode) { @@ -398,11 +398,11 @@ namespace Rssdp.Infrastructure ResponseHeaders = message.Headers }; - AddOrUpdateDiscoveredDevice(device, IpAddress); + AddOrUpdateDiscoveredDevice(device, IPAddress); } } - private void ProcessNotificationMessage(HttpRequestMessage message, IPAddress IpAddress) + private void ProcessNotificationMessage(HttpRequestMessage message, IPAddress IPAddress) { if (String.Compare(message.Method.Method, "Notify", StringComparison.OrdinalIgnoreCase) != 0) { @@ -412,7 +412,7 @@ namespace Rssdp.Infrastructure var notificationType = GetFirstHeaderStringValue("NTS", message); if (String.Compare(notificationType, SsdpConstants.SsdpKeepAliveNotification, StringComparison.OrdinalIgnoreCase) == 0) { - ProcessAliveNotification(message, IpAddress); + ProcessAliveNotification(message, IPAddress); } else if (String.Compare(notificationType, SsdpConstants.SsdpByeByeNotification, StringComparison.OrdinalIgnoreCase) == 0) { @@ -420,7 +420,7 @@ namespace Rssdp.Infrastructure } } - private void ProcessAliveNotification(HttpRequestMessage message, IPAddress IpAddress) + private void ProcessAliveNotification(HttpRequestMessage message, IPAddress IPAddress) { var location = GetFirstHeaderUriValue("Location", message); if (location is not null) @@ -435,7 +435,7 @@ namespace Rssdp.Infrastructure ResponseHeaders = message.Headers }; - AddOrUpdateDiscoveredDevice(device, IpAddress); + AddOrUpdateDiscoveredDevice(device, IPAddress); } } @@ -651,7 +651,7 @@ namespace Rssdp.Infrastructure private void CommsServer_ResponseReceived(object sender, ResponseReceivedEventArgs e) { - ProcessSearchResponseMessage(e.Message, e.LocalIpAddress); + ProcessSearchResponseMessage(e.Message, e.LocalIPAddress); } private void CommsServer_RequestReceived(object sender, RequestReceivedEventArgs e) diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs index 40d93b6c0c..8b55518999 100644 --- a/RSSDP/SsdpDevicePublisher.cs +++ b/RSSDP/SsdpDevicePublisher.cs @@ -224,7 +224,7 @@ namespace Rssdp.Infrastructure string mx, string searchTarget, IPEndPoint remoteEndPoint, - IPAddress receivedOnlocalIpAddress, + IPAddress receivedOnlocalIPAddress, CancellationToken cancellationToken) { if (String.IsNullOrEmpty(searchTarget)) @@ -297,9 +297,9 @@ namespace Rssdp.Infrastructure { var root = device.ToRootDevice(); - if (!_sendOnlyMatchedHost || root.Address.Equals(receivedOnlocalIpAddress)) + if (!_sendOnlyMatchedHost || root.Address.Equals(receivedOnlocalIPAddress)) { - SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIpAddress, cancellationToken); + SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIPAddress, cancellationToken); } } } @@ -314,22 +314,22 @@ namespace Rssdp.Infrastructure private void SendDeviceSearchResponses( SsdpDevice device, IPEndPoint endPoint, - IPAddress receivedOnlocalIpAddress, + IPAddress receivedOnlocalIPAddress, CancellationToken cancellationToken) { bool isRootDevice = (device as SsdpRootDevice) is not null; if (isRootDevice) { - SendSearchResponse(SsdpConstants.UpnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), endPoint, receivedOnlocalIpAddress, cancellationToken); + SendSearchResponse(SsdpConstants.UpnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), endPoint, receivedOnlocalIPAddress, cancellationToken); if (this.SupportPnpRootDevice) { - SendSearchResponse(SsdpConstants.PnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), endPoint, receivedOnlocalIpAddress, cancellationToken); + SendSearchResponse(SsdpConstants.PnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), endPoint, receivedOnlocalIPAddress, cancellationToken); } } - SendSearchResponse(device.Udn, device, device.Udn, endPoint, receivedOnlocalIpAddress, cancellationToken); + SendSearchResponse(device.Udn, device, device.Udn, endPoint, receivedOnlocalIPAddress, cancellationToken); - SendSearchResponse(device.FullDeviceType, device, GetUsn(device.Udn, device.FullDeviceType), endPoint, receivedOnlocalIpAddress, cancellationToken); + SendSearchResponse(device.FullDeviceType, device, GetUsn(device.Udn, device.FullDeviceType), endPoint, receivedOnlocalIPAddress, cancellationToken); } private string GetUsn(string udn, string fullDeviceType) @@ -342,7 +342,7 @@ namespace Rssdp.Infrastructure SsdpDevice device, string uniqueServiceName, IPEndPoint endPoint, - IPAddress receivedOnlocalIpAddress, + IPAddress receivedOnlocalIPAddress, CancellationToken cancellationToken) { const string header = "HTTP/1.1 200 OK"; @@ -366,7 +366,7 @@ namespace Rssdp.Infrastructure await _CommsServer.SendMessage( Encoding.UTF8.GetBytes(message), endPoint, - receivedOnlocalIpAddress, + receivedOnlocalIPAddress, cancellationToken) .ConfigureAwait(false); } @@ -625,7 +625,7 @@ namespace Rssdp.Infrastructure // else if (!e.Message.Headers.Contains("MAN")) // WriteTrace("Ignoring search request - missing MAN header."); // else - ProcessSearchRequest(GetFirstHeaderValue(e.Message.Headers, "MX"), GetFirstHeaderValue(e.Message.Headers, "ST"), e.ReceivedFrom, e.LocalIpAddress, CancellationToken.None); + ProcessSearchRequest(GetFirstHeaderValue(e.Message.Headers, "MX"), GetFirstHeaderValue(e.Message.Headers, "ST"), e.ReceivedFrom, e.LocalIPAddress, CancellationToken.None); } } diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index 10706e9c21..d51ce19d75 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -97,7 +97,7 @@ namespace Jellyfin.Networking.Tests /// Checks if IPv4 address is within a defined subnet. /// /// Network mask. - /// IP Address. + /// IP Address. [Theory] [InlineData("192.168.5.85/24", "192.168.5.1")] [InlineData("192.168.5.85/24", "192.168.5.254")] @@ -282,7 +282,7 @@ namespace Jellyfin.Networking.Tests [InlineData("185.10.10.10", "185.10.10.10", false)] [InlineData("", "100.100.100.100", false)] - public void HasRemoteAccess_GivenWhitelist_AllowsOnlyIPsInWhitelist(string addresses, string remoteIp, bool denied) + public void HasRemoteAccess_GivenWhitelist_AllowsOnlyIPsInWhitelist(string addresses, string remoteIP, bool denied) { // 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. @@ -294,7 +294,7 @@ namespace Jellyfin.Networking.Tests }; using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); - Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIp)), denied); + Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIP)), denied); } [Theory] @@ -302,7 +302,7 @@ namespace Jellyfin.Networking.Tests [InlineData("185.10.10.10", "185.10.10.10", true)] [InlineData("", "100.100.100.100", false)] - public void HasRemoteAccess_GivenBlacklist_BlacklistTheIPs(string addresses, string remoteIp, bool denied) + public void HasRemoteAccess_GivenBlacklist_BlacklistTheIPs(string addresses, string remoteIP, bool denied) { // 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. @@ -315,7 +315,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); - Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIp)), denied); + Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIP)), denied); } [Theory] From af7acc000c961312bd4a2d061dc74c64c0e3647a Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Sat, 18 Feb 2023 21:10:09 +0100 Subject: [PATCH 047/358] Fix dependency on Microsoft.AspNetCore.HttpOverrides --- Directory.Packages.props | 1 + MediaBrowser.Model/MediaBrowser.Model.csproj | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index b72bb90709..86ad36941d 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -24,6 +24,7 @@ + diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index 087e6369e6..58ba83a35f 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -33,6 +33,7 @@ + @@ -58,7 +59,6 @@ - From a5f16136eb171b17b1e1ed661e9aeb017522ce89 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Mon, 20 Feb 2023 16:58:22 +0100 Subject: [PATCH 048/358] Apply review suggestions --- MediaBrowser.Common/Net/INetworkManager.cs | 1 - MediaBrowser.Model/Net/IPData.cs | 109 ++++++++++----------- MediaBrowser.Model/Net/ISocketFactory.cs | 53 +++++----- RSSDP/SsdpDeviceLocator.cs | 28 +----- RSSDP/SsdpDevicePublisher.cs | 27 +---- 5 files changed, 86 insertions(+), 132 deletions(-) diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index efd87a8107..1a3176b581 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -76,7 +76,6 @@ namespace MediaBrowser.Common.Net /// /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. - /// (See . /// /// IP address of the request. /// Optional port returned, if it's part of an override. diff --git a/MediaBrowser.Model/Net/IPData.cs b/MediaBrowser.Model/Net/IPData.cs index 16d74dcddd..985b16c6e4 100644 --- a/MediaBrowser.Model/Net/IPData.cs +++ b/MediaBrowser.Model/Net/IPData.cs @@ -2,73 +2,72 @@ using System.Net; using System.Net.Sockets; using Microsoft.AspNetCore.HttpOverrides; -namespace MediaBrowser.Model.Net +namespace MediaBrowser.Model.Net; + +/// +/// Base network object class. +/// +public class IPData { /// - /// Base network object class. + /// Initializes a new instance of the class. /// - public class IPData + /// The . + /// The . + /// The interface name. + public IPData(IPAddress address, IPNetwork? subnet, string name) { - /// - /// Initializes a new instance of the class. - /// - /// The . - /// The . - /// The interface name. - public IPData(IPAddress address, IPNetwork? subnet, string name) - { - Address = address; - Subnet = subnet ?? (address.AddressFamily == AddressFamily.InterNetwork ? new IPNetwork(address, 32) : new IPNetwork(address, 128)); - Name = name; - } + Address = address; + Subnet = subnet ?? (address.AddressFamily == AddressFamily.InterNetwork ? new IPNetwork(address, 32) : new IPNetwork(address, 128)); + Name = name; + } - /// - /// Initializes a new instance of the class. - /// - /// The . - /// The . - public IPData(IPAddress address, IPNetwork? subnet) - : this(address, subnet, string.Empty) - { - } + /// + /// Initializes a new instance of the class. + /// + /// The . + /// The . + public IPData(IPAddress address, IPNetwork? subnet) + : this(address, subnet, string.Empty) + { + } - /// - /// Gets or sets the object's IP address. - /// - public IPAddress Address { get; set; } + /// + /// Gets or sets the object's IP address. + /// + public IPAddress Address { get; set; } - /// - /// Gets or sets the object's IP address. - /// - public IPNetwork Subnet { get; set; } + /// + /// Gets or sets the object's IP address. + /// + public IPNetwork Subnet { get; set; } - /// - /// Gets or sets the interface index. - /// - public int Index { get; set; } + /// + /// Gets or sets the interface index. + /// + public int Index { get; set; } - /// - /// Gets or sets the interface name. - /// - public string Name { get; set; } + /// + /// Gets or sets the interface name. + /// + public string Name { get; set; } - /// - /// Gets the AddressFamily of the object. - /// - public AddressFamily AddressFamily + /// + /// Gets the AddressFamily of the object. + /// + public AddressFamily AddressFamily + { + get { - get + if (Address.Equals(IPAddress.None)) + { + return Subnet.Prefix.AddressFamily.Equals(IPAddress.None) + ? AddressFamily.Unspecified + : Subnet.Prefix.AddressFamily; + } + else { - if (Address.Equals(IPAddress.None)) - { - return Subnet.Prefix.AddressFamily.Equals(IPAddress.None) - ? AddressFamily.Unspecified - : Subnet.Prefix.AddressFamily; - } - else - { - return Address.AddressFamily; - } + return Address.AddressFamily; } } } diff --git a/MediaBrowser.Model/Net/ISocketFactory.cs b/MediaBrowser.Model/Net/ISocketFactory.cs index 49a88c2277..128034eb8f 100644 --- a/MediaBrowser.Model/Net/ISocketFactory.cs +++ b/MediaBrowser.Model/Net/ISocketFactory.cs @@ -1,36 +1,35 @@ using System.Net; using System.Net.Sockets; -namespace MediaBrowser.Model.Net +namespace MediaBrowser.Model.Net; + +/// +/// Implemented by components that can create specific socket configurations. +/// +public interface ISocketFactory { /// - /// Implemented by components that can create specific socket configurations. + /// Creates a new unicast socket using the specified local port number. /// - public interface ISocketFactory - { - /// - /// Creates a new unicast socket using the specified local port number. - /// - /// The local port to bind to. - /// A new unicast socket using the specified local port number. - Socket CreateUdpBroadcastSocket(int localPort); + /// The local port to bind to. + /// A new unicast socket using the specified local port number. + Socket CreateUdpBroadcastSocket(int localPort); - /// - /// Creates a new unicast socket using the specified local port number. - /// - /// The bind interface. - /// The local port to bind to. - /// A new unicast socket using the specified local port number. - Socket CreateSsdpUdpSocket(IPData bindInterface, int localPort); + /// + /// Creates a new unicast socket using the specified local port number. + /// + /// The bind interface. + /// The local port to bind to. + /// A new unicast socket using the specified local port number. + Socket CreateSsdpUdpSocket(IPData bindInterface, int localPort); - /// - /// Creates a new multicast socket using the specified multicast IP address, multicast time to live and local port. - /// - /// The multicast IP address to bind to. - /// The bind interface. - /// The multicast time to live value. Actually a maximum number of network hops for UDP packets. - /// The local port to bind to. - /// A new multicast socket using the specfied bind interface, multicast address, multicast time to live and port. - Socket CreateUdpMulticastSocket(IPAddress multicastAddress, IPData bindInterface, int multicastTimeToLive, int localPort); - } + /// + /// Creates a new multicast socket using the specified multicast IP address, multicast time to live and local port. + /// + /// The multicast IP address to bind to. + /// The bind interface. + /// The multicast time to live value. Actually a maximum number of network hops for UDP packets. + /// The local port to bind to. + /// A new multicast socket using the specfied bind interface, multicast address, multicast time to live and port. + Socket CreateUdpMulticastSocket(IPAddress multicastAddress, IPData bindInterface, int multicastTimeToLive, int localPort); } diff --git a/RSSDP/SsdpDeviceLocator.cs b/RSSDP/SsdpDeviceLocator.cs index 9d756d0d4c..ffe97754c7 100644 --- a/RSSDP/SsdpDeviceLocator.cs +++ b/RSSDP/SsdpDeviceLocator.cs @@ -34,30 +34,9 @@ namespace Rssdp.Infrastructure string osName, string osVersion) { - if (communicationsServer is null) - { - throw new ArgumentNullException(nameof(communicationsServer)); - } - - if (osName is null) - { - throw new ArgumentNullException(nameof(osName)); - } - - if (osName.Length == 0) - { - throw new ArgumentException("osName cannot be an empty string.", nameof(osName)); - } - - if (osVersion is null) - { - throw new ArgumentNullException(nameof(osVersion)); - } - - if (osVersion.Length == 0) - { - throw new ArgumentException("osVersion cannot be an empty string.", nameof(osName)); - } + ArgumentNullException.ThrowIfNull(communicationsServer); + ArgumentNullException.ThrowIfNullOrEmpty(osName); + ArgumentNullException.ThrowIfNullOrEmpty(osVersion); _OSName = osName; _OSVersion = osVersion; @@ -363,7 +342,6 @@ namespace Rssdp.Infrastructure var values = new Dictionary(StringComparer.OrdinalIgnoreCase); values["HOST"] = "239.255.255.250:1900"; - values["USER-AGENT"] = "UPnP/1.0 DLNADOC/1.50 Platinum/1.0.4.2"; values["USER-AGENT"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, SsdpConstants.ServerVersion); values["MAN"] = "\"ssdp:discover\""; diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs index 8b55518999..e443c62855 100644 --- a/RSSDP/SsdpDevicePublisher.cs +++ b/RSSDP/SsdpDevicePublisher.cs @@ -40,30 +40,9 @@ namespace Rssdp.Infrastructure string osVersion, bool sendOnlyMatchedHost) { - if (communicationsServer is null) - { - throw new ArgumentNullException(nameof(communicationsServer)); - } - - if (osName is null) - { - throw new ArgumentNullException(nameof(osName)); - } - - if (osName.Length == 0) - { - throw new ArgumentException("osName cannot be an empty string.", nameof(osName)); - } - - if (osVersion is null) - { - throw new ArgumentNullException(nameof(osVersion)); - } - - if (osVersion.Length == 0) - { - throw new ArgumentException("osVersion cannot be an empty string.", nameof(osName)); - } + ArgumentNullException.ThrowIfNull(communicationsServer); + ArgumentNullException.ThrowIfNullOrEmpty(osName); + ArgumentNullException.ThrowIfNullOrEmpty(osVersion); _SupportPnpRootDevice = true; _Devices = new List(); From a5bfeb28aa2c92e6e58f5f00e5651807794ac8ef Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Mon, 20 Feb 2023 21:51:15 +0100 Subject: [PATCH 049/358] Apply review suggestions --- Jellyfin.Networking/Manager/NetworkManager.cs | 141 ++++++++++-------- MediaBrowser.Common/Net/INetworkManager.cs | 6 +- MediaBrowser.Common/Net/NetworkExtensions.cs | 103 ++++++------- RSSDP/SsdpCommunicationsServer.cs | 2 +- .../NetworkParseTests.cs | 4 +- 5 files changed, 138 insertions(+), 118 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index dd90a5b516..f0f95f5fc8 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -26,11 +26,6 @@ namespace Jellyfin.Networking.Manager /// private readonly object _initLock; - /// - /// List of all interface MAC addresses. - /// - private readonly List _macAddresses; - private readonly ILogger _logger; private readonly IConfigurationManager _configurationManager; @@ -40,30 +35,35 @@ namespace Jellyfin.Networking.Manager /// /// Holds the published server URLs and the IPs to use them on. /// - private readonly Dictionary _publishedServerUrls; + private IReadOnlyDictionary _publishedServerUrls; - private List _remoteAddressFilter; + private IReadOnlyList _remoteAddressFilter; /// /// Used to stop "event-racing conditions". /// private bool _eventfire; + /// + /// List of all interface MAC addresses. + /// + private IReadOnlyList _macAddresses; + /// /// Dictionary containing interface addresses and their subnets. /// - private List _interfaces; + private IReadOnlyList _interfaces; /// /// Unfiltered user defined LAN subnets () /// or internal interface network subnets if undefined by user. /// - private List _lanSubnets; + private IReadOnlyList _lanSubnets; /// /// User defined list of subnets to excluded from the LAN. /// - private List _excludedSubnets; + private IReadOnlyList _excludedSubnets; /// /// True if this object is disposed. @@ -127,7 +127,7 @@ namespace Jellyfin.Networking.Manager /// /// Gets the Published server override list. /// - public Dictionary PublishedServerUrls => _publishedServerUrls; + public IReadOnlyDictionary PublishedServerUrls => _publishedServerUrls; /// public void Dispose() @@ -206,8 +206,8 @@ namespace Jellyfin.Networking.Manager { _logger.LogDebug("Refreshing interfaces."); - _interfaces.Clear(); - _macAddresses.Clear(); + var interfaces = new List(); + var macAddresses = new List(); try { @@ -224,7 +224,7 @@ namespace Jellyfin.Networking.Manager // Populate MAC list if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && PhysicalAddress.None.Equals(mac)) { - _macAddresses.Add(mac); + macAddresses.Add(mac); } // Populate interface list @@ -236,7 +236,7 @@ namespace Jellyfin.Networking.Manager interfaceObject.Index = ipProperties.GetIPv4Properties().Index; interfaceObject.Name = adapter.Name; - _interfaces.Add(interfaceObject); + interfaces.Add(interfaceObject); } else if (IsIPv6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6) { @@ -244,7 +244,7 @@ namespace Jellyfin.Networking.Manager interfaceObject.Index = ipProperties.GetIPv6Properties().Index; interfaceObject.Name = adapter.Name; - _interfaces.Add(interfaceObject); + interfaces.Add(interfaceObject); } } } @@ -265,23 +265,26 @@ namespace Jellyfin.Networking.Manager } // If no interfaces are found, fallback to loopback interfaces. - if (_interfaces.Count == 0) + if (interfaces.Count == 0) { _logger.LogWarning("No interface information available. Using loopback interface(s)."); if (IsIPv4Enabled && !IsIPv6Enabled) { - _interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); + interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); } if (!IsIPv4Enabled && IsIPv6Enabled) { - _interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); + interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); } } - _logger.LogDebug("Discovered {NumberOfInterfaces} interfaces.", _interfaces.Count); - _logger.LogDebug("Interfaces addresses: {Addresses}", _interfaces.OrderByDescending(s => s.AddressFamily == AddressFamily.InterNetwork).Select(s => s.Address.ToString())); + _logger.LogDebug("Discovered {NumberOfInterfaces} interfaces.", interfaces.Count); + _logger.LogDebug("Interfaces addresses: {Addresses}", interfaces.OrderByDescending(s => s.AddressFamily == AddressFamily.InterNetwork).Select(s => s.Address.ToString())); + + _macAddresses = macAddresses; + _interfaces = interfaces; } } @@ -297,37 +300,38 @@ namespace Jellyfin.Networking.Manager // Get configuration options var subnets = config.LocalNetworkSubnets; - if (!NetworkExtensions.TryParseToSubnets(subnets, out _lanSubnets, false)) - { - _lanSubnets.Clear(); - } - - if (!NetworkExtensions.TryParseToSubnets(subnets, out _excludedSubnets, true)) - { - _excludedSubnets.Clear(); - } - // If no LAN addresses are specified, all private subnets and Loopback are deemed to be the LAN - if (_lanSubnets.Count == 0) + if (!NetworkExtensions.TryParseToSubnets(subnets, out var lanSubnets, false) || lanSubnets.Count == 0) { _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); + var fallbackLanSubnets = new List(); if (IsIPv6Enabled) { - _lanSubnets.Add(new IPNetwork(IPAddress.IPv6Loopback, 128)); // RFC 4291 (Loopback) - _lanSubnets.Add(new IPNetwork(IPAddress.Parse("fe80::"), 10)); // RFC 4291 (Site local) - _lanSubnets.Add(new IPNetwork(IPAddress.Parse("fc00::"), 7)); // RFC 4193 (Unique local) + fallbackLanSubnets.Add(new IPNetwork(IPAddress.IPv6Loopback, 128)); // RFC 4291 (Loopback) + fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("fe80::"), 10)); // RFC 4291 (Site local) + fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("fc00::"), 7)); // RFC 4193 (Unique local) } if (IsIPv4Enabled) { - _lanSubnets.Add(new IPNetwork(IPAddress.Loopback, 8)); // RFC 5735 (Loopback) - _lanSubnets.Add(new IPNetwork(IPAddress.Parse("10.0.0.0"), 8)); // RFC 1918 (private) - _lanSubnets.Add(new IPNetwork(IPAddress.Parse("172.16.0.0"), 12)); // RFC 1918 (private) - _lanSubnets.Add(new IPNetwork(IPAddress.Parse("192.168.0.0"), 16)); // RFC 1918 (private) + fallbackLanSubnets.Add(new IPNetwork(IPAddress.Loopback, 8)); // RFC 5735 (Loopback) + fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("10.0.0.0"), 8)); // RFC 1918 (private) + fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("172.16.0.0"), 12)); // RFC 1918 (private) + fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("192.168.0.0"), 16)); // RFC 1918 (private) } + + _lanSubnets = fallbackLanSubnets; + } + else + { + _lanSubnets = lanSubnets; } + _excludedSubnets = NetworkExtensions.TryParseToSubnets(subnets, out var excludedSubnets, true) + ? excludedSubnets + : new List(); + _logger.LogInformation("Defined LAN addresses: {0}", _lanSubnets.Select(s => s.Prefix + "/" + s.PrefixLength)); _logger.LogInformation("Defined LAN exclusions: {0}", _excludedSubnets.Select(s => s.Prefix + "/" + s.PrefixLength)); _logger.LogInformation("Using LAN addresses: {0}", _lanSubnets.Where(s => !_excludedSubnets.Contains(s)).Select(s => s.Prefix + "/" + s.PrefixLength)); @@ -342,26 +346,27 @@ namespace Jellyfin.Networking.Manager lock (_initLock) { // Respect explicit bind addresses + var interfaces = _interfaces.ToList(); var localNetworkAddresses = config.LocalNetworkAddresses; if (localNetworkAddresses.Length > 0 && !string.IsNullOrWhiteSpace(localNetworkAddresses[0])) { var bindAddresses = localNetworkAddresses.Select(p => NetworkExtensions.TryParseToSubnet(p, out var network) ? network.Prefix - : (_interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase)) + : (interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase)) .Select(x => x.Address) .FirstOrDefault() ?? IPAddress.None)) .Where(x => x != IPAddress.None) .ToHashSet(); - _interfaces = _interfaces.Where(x => bindAddresses.Contains(x.Address)).ToList(); + interfaces = interfaces.Where(x => bindAddresses.Contains(x.Address)).ToList(); if (bindAddresses.Contains(IPAddress.Loopback)) { - _interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); + interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); } if (bindAddresses.Contains(IPAddress.IPv6Loopback)) { - _interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); + interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); } } @@ -377,7 +382,7 @@ namespace Jellyfin.Networking.Manager { foreach (var virtualInterfacePrefix in virtualInterfacePrefixes) { - _interfaces.RemoveAll(x => x.Name.StartsWith(virtualInterfacePrefix, StringComparison.OrdinalIgnoreCase)); + interfaces.RemoveAll(x => x.Name.StartsWith(virtualInterfacePrefix, StringComparison.OrdinalIgnoreCase)); } } } @@ -385,16 +390,17 @@ namespace Jellyfin.Networking.Manager // Remove all IPv4 interfaces if IPv4 is disabled if (!IsIPv4Enabled) { - _interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetwork); + interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetwork); } // Remove all IPv6 interfaces if IPv6 is disabled if (!IsIPv6Enabled) { - _interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetworkV6); + interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetworkV6); } - _logger.LogInformation("Using bind addresses: {0}", _interfaces.OrderByDescending(x => x.AddressFamily == AddressFamily.InterNetwork).Select(x => x.Address)); + _logger.LogInformation("Using bind addresses: {0}", interfaces.OrderByDescending(x => x.AddressFamily == AddressFamily.InterNetwork).Select(x => x.Address)); + _interfaces = interfaces; } } @@ -410,10 +416,11 @@ namespace Jellyfin.Networking.Manager if (remoteIPFilter.Any() && !string.IsNullOrWhiteSpace(remoteIPFilter.First())) { // Parse all IPs with netmask to a subnet + var remoteAddressFilter = new List(); var remoteFilteredSubnets = remoteIPFilter.Where(x => x.Contains('/', StringComparison.OrdinalIgnoreCase)).ToArray(); - if (!NetworkExtensions.TryParseToSubnets(remoteFilteredSubnets, out _remoteAddressFilter, false)) + if (NetworkExtensions.TryParseToSubnets(remoteFilteredSubnets, out var remoteAddressFilterResult, false)) { - _remoteAddressFilter.Clear(); + remoteAddressFilter = remoteAddressFilterResult.ToList(); } // Parse everything else as an IP and construct subnet with a single IP @@ -422,9 +429,11 @@ namespace Jellyfin.Networking.Manager { if (IPAddress.TryParse(ip, out var ipp)) { - _remoteAddressFilter.Add(new IPNetwork(ipp, ipp.AddressFamily == AddressFamily.InterNetwork ? 32 : 128)); + remoteAddressFilter.Add(new IPNetwork(ipp, ipp.AddressFamily == AddressFamily.InterNetwork ? 32 : 128)); } } + + _remoteAddressFilter = remoteAddressFilter; } } } @@ -440,8 +449,8 @@ namespace Jellyfin.Networking.Manager { lock (_initLock) { - _publishedServerUrls.Clear(); - string[] overrides = config.PublishedServerUriBySubnet; + var publishedServerUrls = new Dictionary(); + var overrides = config.PublishedServerUriBySubnet; foreach (var entry in overrides) { @@ -456,31 +465,31 @@ namespace Jellyfin.Networking.Manager var identifier = parts[0]; if (string.Equals(identifier, "all", StringComparison.OrdinalIgnoreCase)) { - _publishedServerUrls[new IPData(IPAddress.Broadcast, null)] = replacement; + publishedServerUrls[new IPData(IPAddress.Broadcast, null)] = replacement; } else if (string.Equals(identifier, "external", StringComparison.OrdinalIgnoreCase)) { - _publishedServerUrls[new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))] = replacement; - _publishedServerUrls[new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))] = replacement; + publishedServerUrls[new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))] = replacement; + publishedServerUrls[new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))] = replacement; } else if (string.Equals(identifier, "internal", StringComparison.OrdinalIgnoreCase)) { foreach (var lan in _lanSubnets) { var lanPrefix = lan.Prefix; - _publishedServerUrls[new IPData(lanPrefix, new IPNetwork(lanPrefix, lan.PrefixLength))] = replacement; + publishedServerUrls[new IPData(lanPrefix, new IPNetwork(lanPrefix, lan.PrefixLength))] = replacement; } } else if (NetworkExtensions.TryParseToSubnet(identifier, out var result) && result is not null) { var data = new IPData(result.Prefix, result); - _publishedServerUrls[data] = replacement; + publishedServerUrls[data] = replacement; } else if (TryParseInterface(identifier, out var ifaces)) { foreach (var iface in ifaces) { - _publishedServerUrls[iface] = replacement; + publishedServerUrls[iface] = replacement; } } else @@ -488,6 +497,8 @@ namespace Jellyfin.Networking.Manager _logger.LogError("Unable to parse bind override: {Entry}", entry); } } + + _publishedServerUrls = publishedServerUrls; } } @@ -520,6 +531,7 @@ namespace Jellyfin.Networking.Manager { // Format is ,,: . Set index to -ve to simulate a gateway. var interfaceList = MockNetworkSettings.Split('|'); + var interfaces = new List(); foreach (var details in interfaceList) { var parts = details.Split(','); @@ -531,7 +543,7 @@ namespace Jellyfin.Networking.Manager { var data = new IPData(address, subnet, parts[2]); data.Index = index; - _interfaces.Add(data); + interfaces.Add(data); } } else @@ -539,6 +551,8 @@ namespace Jellyfin.Networking.Manager _logger.LogWarning("Could not parse mock interface settings: {Part}", details); } } + + _interfaces = interfaces; } EnforceBindSettings(config); @@ -565,11 +579,12 @@ namespace Jellyfin.Networking.Manager } /// - public bool TryParseInterface(string intf, out List result) + public bool TryParseInterface(string intf, out IReadOnlyList result) { - result = new List(); + var resultList = new List(); if (string.IsNullOrEmpty(intf) || _interfaces is null) { + result = resultList.AsReadOnly(); return false; } @@ -585,13 +600,15 @@ namespace Jellyfin.Networking.Manager if ((IsIPv4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) || (IsIPv6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)) { - result.Add(iface); + resultList.Add(iface); } } + result = resultList.AsReadOnly(); return true; } + result = resultList.AsReadOnly(); return false; } diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 1a3176b581..a92b751f2a 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -30,7 +30,7 @@ namespace MediaBrowser.Common.Net /// /// Calculates the list of interfaces to use for Kestrel. /// - /// A List{IPData} object containing all the interfaces to bind. + /// A IReadOnlyList{IPData} 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. /// When false, return or for all interfaces. @@ -39,7 +39,7 @@ namespace MediaBrowser.Common.Net /// /// Returns a list containing the loopback interfaces. /// - /// List{IPData}. + /// IReadOnlyList{IPData}. IReadOnlyList GetLoopbacks(); /// @@ -120,7 +120,7 @@ namespace MediaBrowser.Common.Net /// Interface name. /// Resulting object's IP addresses, if successful. /// Success of the operation. - bool TryParseInterface(string intf, out List result); + bool TryParseInterface(string intf, out IReadOnlyList result); /// /// Returns all internal (LAN) bind interface addresses. diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index cef4a5d965..227f0483f4 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; +using Jellyfin.Extensions; using Microsoft.AspNetCore.HttpOverrides; namespace MediaBrowser.Common.Net @@ -193,71 +194,64 @@ namespace MediaBrowser.Common.Net /// An . /// Boolean signaling if negated or not negated values should be parsed. /// True if parsing was successful. - public static bool TryParseToSubnet(string value, out IPNetwork result, bool negated = false) + public static bool TryParseToSubnet(ReadOnlySpan value, out IPNetwork result, bool negated = false) { result = new IPNetwork(IPAddress.None, 32); - - if (string.IsNullOrEmpty(value)) - { - return false; - } - - var splitString = value.Trim().Split("/"); - var ipBlock = splitString[0]; - - var address = IPAddress.None; - if (negated && ipBlock.StartsWith('!') && IPAddress.TryParse(ipBlock[1..], out var tmpAddress)) - { - address = tmpAddress; - } - else if (!negated && IPAddress.TryParse(ipBlock, out tmpAddress)) + var splitString = value.Trim().Split('/'); + if (splitString.MoveNext()) { - address = tmpAddress; - } + var ipBlock = splitString.Current; + var address = IPAddress.None; + if (negated && ipBlock.StartsWith("!") && IPAddress.TryParse(ipBlock[1..], out var tmpAddress)) + { + address = tmpAddress; + } + else if (!negated && IPAddress.TryParse(ipBlock, out tmpAddress)) + { + address = tmpAddress; + } - if (address != IPAddress.None && address is not null) - { - if (splitString.Length > 1) + if (address != IPAddress.None) { - var subnetBlock = splitString[1]; - if (int.TryParse(subnetBlock, out var netmask)) + if (splitString.MoveNext()) { - result = new IPNetwork(address, netmask); + var subnetBlock = splitString.Current; + if (int.TryParse(subnetBlock, out var netmask)) + { + result = new IPNetwork(address, netmask); + } + else if (IPAddress.TryParse(subnetBlock, out var netmaskAddress)) + { + result = new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress)); + } } - else if (IPAddress.TryParse(subnetBlock, out var netmaskAddress)) + else if (address.AddressFamily == AddressFamily.InterNetwork) { - result = new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress)); + result = new IPNetwork(address, 32); + } + else if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + result = new IPNetwork(address, 128); } - } - else if (address.AddressFamily == AddressFamily.InterNetwork) - { - result = new IPNetwork(address, 32); - } - else if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - result = new IPNetwork(address, 128); - } - } - if (!result.Prefix.Equals(IPAddress.None)) - { - return true; + return true; + } } return false; } /// - /// Attempts to parse a host string. + /// Attempts to parse a host span. /// /// Host name to parse. - /// Object representing the string, if it has successfully been parsed. + /// Object representing the span, if it has successfully been parsed. /// true if IPv4 is enabled. /// true if IPv6 is enabled. /// true if the parsing is successful, false if not. - public static bool TryParseHost(string host, [NotNullWhen(true)] out IPAddress[] addresses, bool isIPv4Enabled = true, bool isIPv6Enabled = false) + public static bool TryParseHost(ReadOnlySpan host, [NotNullWhen(true)] out IPAddress[] addresses, bool isIPv4Enabled = true, bool isIPv6Enabled = false) { - if (string.IsNullOrWhiteSpace(host)) + if (host.IsEmpty) { addresses = Array.Empty(); return false; @@ -268,19 +262,24 @@ namespace MediaBrowser.Common.Net // See if it's an IPv6 with port address e.g. [::1] or [::1]:120. if (host[0] == '[') { - int i = host.IndexOf(']', StringComparison.Ordinal); + int i = host.IndexOf("]", StringComparison.Ordinal); if (i != -1) { - return TryParseHost(host.Remove(i)[1..], out addresses); + return TryParseHost(host[1..(i - 1)], out addresses); } addresses = Array.Empty(); return false; } - var hosts = host.Split(':'); + var hosts = new List(); + var splitSpan = host.Split(':'); + while (splitSpan.MoveNext()) + { + hosts.Add(splitSpan.Current.ToString()); + } - if (hosts.Length <= 2) + if (hosts.Count <= 2) { // Is hostname or hostname:port if (_fqdnRegex.IsMatch(hosts[0])) @@ -315,10 +314,14 @@ namespace MediaBrowser.Common.Net return true; } } - else if (hosts.Length <= 9 && IPAddress.TryParse(host.Split('/')[0], out var address)) // 8 octets + port + else if (hosts.Count <= 9) // 8 octets + port { - addresses = new[] { address }; - return true; + splitSpan = host.Split('/'); + if (splitSpan.MoveNext() && IPAddress.TryParse(splitSpan.Current, out var address)) + { + addresses = new[] { address }; + return true; + } } addresses = Array.Empty(); diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index 5b8916d021..0dce6c3bfa 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -428,7 +428,7 @@ namespace Rssdp.Infrastructure if (result.ReceivedBytes > 0) { var remoteEndpoint = (IPEndPoint)result.RemoteEndPoint; - var localEndpointAdapter = _networkManager.GetAllBindInterfaces().Where(a => a.Index == result.PacketInformation.Interface).First(); + var localEndpointAdapter = _networkManager.GetAllBindInterfaces().First(a => a.Index == result.PacketInformation.Interface); ProcessMessage( UTF8Encoding.UTF8.GetString(receiveBuffer, 0, result.ReceivedBytes), diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index d51ce19d75..8b7df0470d 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -203,7 +203,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - _ = nm.TryParseInterface(result, out List? resultObj); + _ = nm.TryParseInterface(result, out IReadOnlyList? resultObj); // Check to see if dns resolution is working. If not, skip test. _ = NetworkExtensions.TryParseHost(source, out var host); @@ -266,7 +266,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - if (nm.TryParseInterface(result, out List? resultObj) && resultObj is not null) + if (nm.TryParseInterface(result, out IReadOnlyList? resultObj) && resultObj is not null) { // Parse out IPAddresses so we can do a string comparison (ignore subnet masks). result = resultObj.First().Address.ToString(); From 7af6694594cfc71644b336a2bba459c2f439369b Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Thu, 23 Feb 2023 13:55:27 +0100 Subject: [PATCH 050/358] Fix AutoDiscovery socket creation --- .../EntryPoints/UdpServerEntryPoint.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index 8fb1f93228..2839e163e3 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -82,7 +82,9 @@ namespace Emby.Server.Implementations.EntryPoints if (_enableMultiSocketBinding) { // Add global broadcast socket - _udpServers.Add(new UdpServer(_logger, _appHost, _config, IPAddress.Broadcast, PortNumber)); + var server = new UdpServer(_logger, _appHost, _config, IPAddress.Broadcast, PortNumber); + server.Start(_cancellationTokenSource.Token); + _udpServers.Add(server); // Add bind address specific broadcast sockets // IPv6 is currently unsupported @@ -90,9 +92,9 @@ namespace Emby.Server.Implementations.EntryPoints foreach (var intf in validInterfaces) { var broadcastAddress = NetworkExtensions.GetBroadcastAddress(intf.Subnet); - _logger.LogDebug("Binding UDP server to {Address} on port {PortNumber}", broadcastAddress.ToString(), PortNumber); + _logger.LogDebug("Binding UDP server to {Address} on port {PortNumber}", broadcastAddress, PortNumber); - var server = new UdpServer(_logger, _appHost, _config, broadcastAddress, PortNumber); + server = new UdpServer(_logger, _appHost, _config, broadcastAddress, PortNumber); server.Start(_cancellationTokenSource.Token); _udpServers.Add(server); } From 891e2495c94fdfb3464cd0bb42c9950d27e28e38 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 7 Mar 2023 17:58:04 +0100 Subject: [PATCH 051/358] Disable real time monitoring by default --- Emby.Server.Implementations/Library/LibraryManager.cs | 4 +++- MediaBrowser.Model/Configuration/LibraryOptions.cs | 1 - 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 66bd68ddd0..c089bdce1e 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -2054,7 +2054,9 @@ namespace Emby.Server.Implementations.Library .Find(folder => folder is CollectionFolder) as CollectionFolder; } - return collectionFolder is null ? new LibraryOptions() : collectionFolder.GetLibraryOptions(); + return collectionFolder is null + ? new LibraryOptions() + : collectionFolder.GetLibraryOptions(); } public string GetContentType(BaseItem item) diff --git a/MediaBrowser.Model/Configuration/LibraryOptions.cs b/MediaBrowser.Model/Configuration/LibraryOptions.cs index 81f2f02bc5..885e86d4bf 100644 --- a/MediaBrowser.Model/Configuration/LibraryOptions.cs +++ b/MediaBrowser.Model/Configuration/LibraryOptions.cs @@ -20,7 +20,6 @@ namespace MediaBrowser.Model.Configuration AutomaticallyAddToCollection = false; EnablePhotos = true; SaveSubtitlesWithMedia = true; - EnableRealtimeMonitor = true; PathInfos = Array.Empty(); EnableAutomaticSeriesGrouping = true; SeasonZeroDisplayName = "Specials"; From b37e9209df94dcad757d0b9ad0a7a7076c3cf743 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Mon, 22 May 2023 10:39:48 +0200 Subject: [PATCH 052/358] Apply review suggestion --- .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index a86c329d62..1795e85a3c 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -661,7 +661,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun // Need a way to set the Receive timeout on the socket otherwise this might never timeout? try { - await udpClient.SendToAsync(discBytes, new IPEndPoint(IPAddress.Parse("255.255.255.255"), 65001), cancellationToken).ConfigureAwait(false); + await udpClient.SendToAsync(discBytes, new IPEndPoint(IPAddress.Broadcast, 65001), cancellationToken).ConfigureAwait(false); var receiveBuffer = new byte[8192]; while (!cancellationToken.IsCancellationRequested) From a381cd3c7652e4c802e697e367370f4dba3987f6 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Thu, 25 May 2023 17:10:53 +0200 Subject: [PATCH 053/358] Apply review suggestions --- MediaBrowser.Common/Net/NetworkExtensions.cs | 52 +++++++++++--------- 1 file changed, 28 insertions(+), 24 deletions(-) diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 227f0483f4..8a14bf48db 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -93,31 +93,36 @@ namespace MediaBrowser.Common.Net ArgumentNullException.ThrowIfNull(mask); byte cidrnet = 0; - if (!mask.Equals(IPAddress.Any)) + if (mask.Equals(IPAddress.Any)) { - // GetAddressBytes - Span bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16]; - mask.TryWriteBytes(bytes, out _); + return cidrnet; + } + + // GetAddressBytes + Span bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16]; + if (!mask.TryWriteBytes(bytes, out var bytesWritten)) + { + Console.WriteLine("Unable to write address bytes, only {Bytes} bytes written.", bytesWritten); + } - var zeroed = false; - for (var i = 0; i < bytes.Length; i++) + var zeroed = false; + for (var i = 0; i < bytes.Length; i++) + { + for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1) { - for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1) + if (zeroed) { - if (zeroed) - { - // Invalid netmask. - return (byte)~cidrnet; - } + // Invalid netmask. + return (byte)~cidrnet; + } - if ((v & 0x80) == 0) - { - zeroed = true; - } - else - { - cidrnet++; - } + if ((v & 0x80) == 0) + { + zeroed = true; + } + else + { + cidrnet++; } } } @@ -273,10 +278,9 @@ namespace MediaBrowser.Common.Net } var hosts = new List(); - var splitSpan = host.Split(':'); - while (splitSpan.MoveNext()) + foreach (var splitSpan in host.Split(':')) { - hosts.Add(splitSpan.Current.ToString()); + hosts.Add(splitSpan.ToString()); } if (hosts.Count <= 2) @@ -316,7 +320,7 @@ namespace MediaBrowser.Common.Net } else if (hosts.Count <= 9) // 8 octets + port { - splitSpan = host.Split('/'); + var splitSpan = host.Split('/'); if (splitSpan.MoveNext() && IPAddress.TryParse(splitSpan.Current, out var address)) { addresses = new[] { address }; From 6de56f05186b77042a611112d82208b8fa8675fb Mon Sep 17 00:00:00 2001 From: Niels van Velzen Date: Tue, 20 Jun 2023 16:51:07 +0200 Subject: [PATCH 054/358] Add support for lyric provider plugins --- Jellyfin.Server/CoreAppHost.cs | 6 ++ .../Lyrics/ILyricParser.cs | 28 ++++++++ MediaBrowser.Controller/Lyrics/LyricFile.cs | 28 ++++++++ MediaBrowser.Controller/Lyrics/LyricInfo.cs | 49 -------------- .../Lyric/DefaultLyricProvider.cs | 66 +++++++++++++++++++ .../Lyric}/ILyricProvider.cs | 12 ++-- ...{LrcLyricProvider.cs => LrcLyricParser.cs} | 53 +++++---------- MediaBrowser.Providers/Lyric/LyricManager.cs | 22 +++++-- .../Lyric/TxtLyricParser.cs | 49 ++++++++++++++ .../Lyric/TxtLyricProvider.cs | 60 ----------------- 10 files changed, 215 insertions(+), 158 deletions(-) create mode 100644 MediaBrowser.Controller/Lyrics/ILyricParser.cs create mode 100644 MediaBrowser.Controller/Lyrics/LyricFile.cs delete mode 100644 MediaBrowser.Controller/Lyrics/LyricInfo.cs create mode 100644 MediaBrowser.Providers/Lyric/DefaultLyricProvider.cs rename {MediaBrowser.Controller/Lyrics => MediaBrowser.Providers/Lyric}/ILyricProvider.cs (69%) rename MediaBrowser.Providers/Lyric/{LrcLyricProvider.cs => LrcLyricParser.cs} (76%) create mode 100644 MediaBrowser.Providers/Lyric/TxtLyricParser.cs delete mode 100644 MediaBrowser.Providers/Lyric/TxtLyricProvider.cs diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs index 939376dd8d..0c6315c667 100644 --- a/Jellyfin.Server/CoreAppHost.cs +++ b/Jellyfin.Server/CoreAppHost.cs @@ -22,6 +22,7 @@ using MediaBrowser.Controller.Lyrics; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Security; using MediaBrowser.Model.Activity; +using MediaBrowser.Providers.Lyric; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -93,6 +94,11 @@ namespace Jellyfin.Server serviceCollection.AddSingleton(typeof(ILyricProvider), type); } + foreach (var type in GetExportTypes()) + { + serviceCollection.AddSingleton(typeof(ILyricParser), type); + } + base.RegisterServices(serviceCollection); } diff --git a/MediaBrowser.Controller/Lyrics/ILyricParser.cs b/MediaBrowser.Controller/Lyrics/ILyricParser.cs new file mode 100644 index 0000000000..65a9471a3b --- /dev/null +++ b/MediaBrowser.Controller/Lyrics/ILyricParser.cs @@ -0,0 +1,28 @@ +using MediaBrowser.Controller.Resolvers; +using MediaBrowser.Providers.Lyric; + +namespace MediaBrowser.Controller.Lyrics; + +/// +/// Interface ILyricParser. +/// +public interface ILyricParser +{ + /// + /// Gets a value indicating the provider name. + /// + string Name { get; } + + /// + /// Gets the priority. + /// + /// The priority. + ResolverPriority Priority { get; } + + /// + /// Parses the raw lyrics into a response. + /// + /// The raw lyrics content. + /// The parsed lyrics or null if invalid. + LyricResponse? ParseLyrics(LyricFile lyrics); +} diff --git a/MediaBrowser.Controller/Lyrics/LyricFile.cs b/MediaBrowser.Controller/Lyrics/LyricFile.cs new file mode 100644 index 0000000000..21096797ac --- /dev/null +++ b/MediaBrowser.Controller/Lyrics/LyricFile.cs @@ -0,0 +1,28 @@ +namespace MediaBrowser.Providers.Lyric; + +/// +/// The information for a raw lyrics file before parsing. +/// +public class LyricFile +{ + /// + /// Initializes a new instance of the class. + /// + /// The name. + /// The content. + public LyricFile(string name, string content) + { + Name = name; + Content = content; + } + + /// + /// Gets or sets the name of the lyrics file. This must include the file extension. + /// + public string Name { get; set; } + + /// + /// Gets or sets the contents of the file. + /// + public string Content { get; set; } +} diff --git a/MediaBrowser.Controller/Lyrics/LyricInfo.cs b/MediaBrowser.Controller/Lyrics/LyricInfo.cs deleted file mode 100644 index 6ec6df5825..0000000000 --- a/MediaBrowser.Controller/Lyrics/LyricInfo.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.IO; -using Jellyfin.Extensions; - -namespace MediaBrowser.Controller.Lyrics; - -/// -/// Lyric helper methods. -/// -public static class LyricInfo -{ - /// - /// Gets matching lyric file for a requested item. - /// - /// The lyricProvider interface to use. - /// Path of requested item. - /// Lyric file path if passed lyric provider's supported media type is found; otherwise, null. - public static string? GetLyricFilePath(this ILyricProvider lyricProvider, string itemPath) - { - // Ensure we have a provider - if (lyricProvider is null) - { - return null; - } - - // Ensure the path to the item is not null - string? itemDirectoryPath = Path.GetDirectoryName(itemPath); - if (itemDirectoryPath is null) - { - return null; - } - - // Ensure the directory path exists - if (!Directory.Exists(itemDirectoryPath)) - { - return null; - } - - foreach (var lyricFilePath in Directory.GetFiles(itemDirectoryPath, $"{Path.GetFileNameWithoutExtension(itemPath)}.*")) - { - if (lyricProvider.SupportedMediaTypes.Contains(Path.GetExtension(lyricFilePath.AsSpan())[1..], StringComparison.OrdinalIgnoreCase)) - { - return lyricFilePath; - } - } - - return null; - } -} diff --git a/MediaBrowser.Providers/Lyric/DefaultLyricProvider.cs b/MediaBrowser.Providers/Lyric/DefaultLyricProvider.cs new file mode 100644 index 0000000000..f828ec26b9 --- /dev/null +++ b/MediaBrowser.Providers/Lyric/DefaultLyricProvider.cs @@ -0,0 +1,66 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using Jellyfin.Extensions; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Resolvers; + +namespace MediaBrowser.Providers.Lyric; + +/// +public class DefaultLyricProvider : ILyricProvider +{ + private static readonly string[] _lyricExtensions = { "lrc", "elrc", "txt", "elrc" }; + + /// + public string Name => "DefaultLyricProvider"; + + /// + public ResolverPriority Priority => ResolverPriority.First; + + /// + public bool HasLyrics(BaseItem item) + { + var path = GetLyricsPath(item); + return path is not null; + } + + /// + public async Task GetLyrics(BaseItem item) + { + var path = GetLyricsPath(item); + if (path is not null) + { + var content = await File.ReadAllTextAsync(path).ConfigureAwait(false); + return new LyricFile(path, content); + } + + return null; + } + + private string? GetLyricsPath(BaseItem item) + { + // Ensure the path to the item is not null + string? itemDirectoryPath = Path.GetDirectoryName(item.Path); + if (itemDirectoryPath is null) + { + return null; + } + + // Ensure the directory path exists + if (!Directory.Exists(itemDirectoryPath)) + { + return null; + } + + foreach (var lyricFilePath in Directory.GetFiles(itemDirectoryPath, $"{Path.GetFileNameWithoutExtension(item.Path)}.*")) + { + if (_lyricExtensions.Contains(Path.GetExtension(lyricFilePath.AsSpan())[1..], StringComparison.OrdinalIgnoreCase)) + { + return lyricFilePath; + } + } + + return null; + } +} diff --git a/MediaBrowser.Controller/Lyrics/ILyricProvider.cs b/MediaBrowser.Providers/Lyric/ILyricProvider.cs similarity index 69% rename from MediaBrowser.Controller/Lyrics/ILyricProvider.cs rename to MediaBrowser.Providers/Lyric/ILyricProvider.cs index 2a04c61520..27ceba72bf 100644 --- a/MediaBrowser.Controller/Lyrics/ILyricProvider.cs +++ b/MediaBrowser.Providers/Lyric/ILyricProvider.cs @@ -1,9 +1,8 @@ -using System.Collections.Generic; using System.Threading.Tasks; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Resolvers; -namespace MediaBrowser.Controller.Lyrics; +namespace MediaBrowser.Providers.Lyric; /// /// Interface ILyricsProvider. @@ -22,15 +21,16 @@ public interface ILyricProvider ResolverPriority Priority { get; } /// - /// Gets the supported media types for this provider. + /// Checks if an item has lyrics available. /// - /// The supported media types. - IReadOnlyCollection SupportedMediaTypes { get; } + /// The media item. + /// Whether lyrics where found or not. + bool HasLyrics(BaseItem item); /// /// Gets the lyrics. /// /// The media item. /// A task representing found lyrics. - Task GetLyrics(BaseItem item); + Task GetLyrics(BaseItem item); } diff --git a/MediaBrowser.Providers/Lyric/LrcLyricProvider.cs b/MediaBrowser.Providers/Lyric/LrcLyricParser.cs similarity index 76% rename from MediaBrowser.Providers/Lyric/LrcLyricProvider.cs rename to MediaBrowser.Providers/Lyric/LrcLyricParser.cs index 7b108921b3..01a0dddf1f 100644 --- a/MediaBrowser.Providers/Lyric/LrcLyricProvider.cs +++ b/MediaBrowser.Providers/Lyric/LrcLyricParser.cs @@ -3,34 +3,29 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; -using System.Threading.Tasks; +using Jellyfin.Extensions; using LrcParser.Model; using LrcParser.Parser; -using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Lyrics; using MediaBrowser.Controller.Resolvers; -using Microsoft.Extensions.Logging; namespace MediaBrowser.Providers.Lyric; /// -/// LRC Lyric Provider. +/// LRC Lyric Parser. /// -public class LrcLyricProvider : ILyricProvider +public class LrcLyricParser : ILyricParser { - private readonly ILogger _logger; - private readonly LyricParser _lrcLyricParser; + private static readonly string[] _supportedMediaTypes = { "lrc", "elrc" }; private static readonly string[] _acceptedTimeFormats = { "HH:mm:ss", "H:mm:ss", "mm:ss", "m:ss" }; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - /// Instance of the interface. - public LrcLyricProvider(ILogger logger) + public LrcLyricParser() { - _logger = logger; _lrcLyricParser = new LrcParser.Parser.Lrc.LrcParser(); } @@ -41,37 +36,25 @@ public class LrcLyricProvider : ILyricProvider /// Gets the priority. /// /// The priority. - public ResolverPriority Priority => ResolverPriority.First; + public ResolverPriority Priority => ResolverPriority.Fourth; /// - public IReadOnlyCollection SupportedMediaTypes { get; } = new[] { "lrc", "elrc" }; - - /// - /// Opens lyric file for the requested item, and processes it for API return. - /// - /// The item to to process. - /// If provider can determine lyrics, returns a with or without metadata; otherwise, null. - public async Task GetLyrics(BaseItem item) + public LyricResponse? ParseLyrics(LyricFile lyrics) { - string? lyricFilePath = this.GetLyricFilePath(item.Path); - - if (string.IsNullOrEmpty(lyricFilePath)) + if (!_supportedMediaTypes.Contains(Path.GetExtension(lyrics.Name.AsSpan())[1..], StringComparison.OrdinalIgnoreCase)) { return null; } - var fileMetaData = new Dictionary(StringComparer.OrdinalIgnoreCase); - string lrcFileContent = await File.ReadAllTextAsync(lyricFilePath).ConfigureAwait(false); - Song lyricData; try { - lyricData = _lrcLyricParser.Decode(lrcFileContent); + lyricData = _lrcLyricParser.Decode(lyrics.Content); } - catch (Exception ex) + catch (Exception) { - _logger.LogError(ex, "Error parsing lyric file {LyricFilePath} from {Provider}", lyricFilePath, Name); + // Failed to parse, return null so the next parser will be tried return null; } @@ -84,6 +67,7 @@ public class LrcLyricProvider : ILyricProvider .Select(x => x.Text) .ToList(); + var fileMetaData = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (string metaDataRow in metaDataRows) { var index = metaDataRow.IndexOf(':', StringComparison.OrdinalIgnoreCase); @@ -130,17 +114,10 @@ public class LrcLyricProvider : ILyricProvider // Map metaData values from LRC file to LyricMetadata properties LyricMetadata lyricMetadata = MapMetadataValues(fileMetaData); - return new LyricResponse - { - Metadata = lyricMetadata, - Lyrics = lyricList - }; + return new LyricResponse { Metadata = lyricMetadata, Lyrics = lyricList }; } - return new LyricResponse - { - Lyrics = lyricList - }; + return new LyricResponse { Lyrics = lyricList }; } /// diff --git a/MediaBrowser.Providers/Lyric/LyricManager.cs b/MediaBrowser.Providers/Lyric/LyricManager.cs index f9547e0f05..6da8119275 100644 --- a/MediaBrowser.Providers/Lyric/LyricManager.cs +++ b/MediaBrowser.Providers/Lyric/LyricManager.cs @@ -12,14 +12,17 @@ namespace MediaBrowser.Providers.Lyric; public class LyricManager : ILyricManager { private readonly ILyricProvider[] _lyricProviders; + private readonly ILyricParser[] _lyricParsers; /// /// Initializes a new instance of the class. /// /// All found lyricProviders. - public LyricManager(IEnumerable lyricProviders) + /// All found lyricParsers. + public LyricManager(IEnumerable lyricProviders, IEnumerable lyricParsers) { _lyricProviders = lyricProviders.OrderBy(i => i.Priority).ToArray(); + _lyricParsers = lyricParsers.OrderBy(i => i.Priority).ToArray(); } /// @@ -27,10 +30,19 @@ public class LyricManager : ILyricManager { foreach (ILyricProvider provider in _lyricProviders) { - var results = await provider.GetLyrics(item).ConfigureAwait(false); - if (results is not null) + var lyrics = await provider.GetLyrics(item).ConfigureAwait(false); + if (lyrics is null) { - return results; + continue; + } + + foreach (ILyricParser parser in _lyricParsers) + { + var result = parser.ParseLyrics(lyrics); + if (result is not null) + { + return result; + } } } @@ -47,7 +59,7 @@ public class LyricManager : ILyricManager continue; } - if (provider.GetLyricFilePath(item.Path) is not null) + if (provider.HasLyrics(item)) { return true; } diff --git a/MediaBrowser.Providers/Lyric/TxtLyricParser.cs b/MediaBrowser.Providers/Lyric/TxtLyricParser.cs new file mode 100644 index 0000000000..2ed0a6d8a6 --- /dev/null +++ b/MediaBrowser.Providers/Lyric/TxtLyricParser.cs @@ -0,0 +1,49 @@ +using System; +using System.IO; +using Jellyfin.Extensions; +using MediaBrowser.Controller.Lyrics; +using MediaBrowser.Controller.Resolvers; + +namespace MediaBrowser.Providers.Lyric; + +/// +/// TXT Lyric Parser. +/// +public class TxtLyricParser : ILyricParser +{ + private static readonly string[] _supportedMediaTypes = { "lrc", "elrc", "txt" }; + + /// + public string Name => "TxtLyricProvider"; + + /// + /// Gets the priority. + /// + /// The priority. + public ResolverPriority Priority => ResolverPriority.Fifth; + + /// + public LyricResponse? ParseLyrics(LyricFile lyrics) + { + if (!_supportedMediaTypes.Contains(Path.GetExtension(lyrics.Name.AsSpan())[1..], StringComparison.OrdinalIgnoreCase)) + { + return null; + } + + string[] lyricTextLines = lyrics.Content.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); + + if (lyricTextLines.Length == 0) + { + return null; + } + + LyricLine[] lyricList = new LyricLine[lyricTextLines.Length]; + + for (int lyricLineIndex = 0; lyricLineIndex < lyricTextLines.Length; lyricLineIndex++) + { + lyricList[lyricLineIndex] = new LyricLine(lyricTextLines[lyricLineIndex]); + } + + return new LyricResponse { Lyrics = lyricList }; + } +} diff --git a/MediaBrowser.Providers/Lyric/TxtLyricProvider.cs b/MediaBrowser.Providers/Lyric/TxtLyricProvider.cs deleted file mode 100644 index a9099d1927..0000000000 --- a/MediaBrowser.Providers/Lyric/TxtLyricProvider.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Lyrics; -using MediaBrowser.Controller.Resolvers; - -namespace MediaBrowser.Providers.Lyric; - -/// -/// TXT Lyric Provider. -/// -public class TxtLyricProvider : ILyricProvider -{ - /// - public string Name => "TxtLyricProvider"; - - /// - /// Gets the priority. - /// - /// The priority. - public ResolverPriority Priority => ResolverPriority.Second; - - /// - public IReadOnlyCollection SupportedMediaTypes { get; } = new[] { "lrc", "elrc", "txt" }; - - /// - /// Opens lyric file for the requested item, and processes it for API return. - /// - /// The item to to process. - /// If provider can determine lyrics, returns a ; otherwise, null. - public async Task GetLyrics(BaseItem item) - { - string? lyricFilePath = this.GetLyricFilePath(item.Path); - - if (string.IsNullOrEmpty(lyricFilePath)) - { - return null; - } - - string[] lyricTextLines = await File.ReadAllLinesAsync(lyricFilePath).ConfigureAwait(false); - - if (lyricTextLines.Length == 0) - { - return null; - } - - LyricLine[] lyricList = new LyricLine[lyricTextLines.Length]; - - for (int lyricLineIndex = 0; lyricLineIndex < lyricTextLines.Length; lyricLineIndex++) - { - lyricList[lyricLineIndex] = new LyricLine(lyricTextLines[lyricLineIndex]); - } - - return new LyricResponse - { - Lyrics = lyricList - }; - } -} From 1ed5f0a624abeebef16a960ed7a52942bce47502 Mon Sep 17 00:00:00 2001 From: Niels van Velzen Date: Sat, 24 Jun 2023 09:25:25 +0200 Subject: [PATCH 055/358] Move line break characters to static readonly string array in TxtLyricParser --- MediaBrowser.Providers/Lyric/TxtLyricParser.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Providers/Lyric/TxtLyricParser.cs b/MediaBrowser.Providers/Lyric/TxtLyricParser.cs index 2ed0a6d8a6..7e029ee42a 100644 --- a/MediaBrowser.Providers/Lyric/TxtLyricParser.cs +++ b/MediaBrowser.Providers/Lyric/TxtLyricParser.cs @@ -12,6 +12,7 @@ namespace MediaBrowser.Providers.Lyric; public class TxtLyricParser : ILyricParser { private static readonly string[] _supportedMediaTypes = { "lrc", "elrc", "txt" }; + private static readonly string[] _lineBreakCharacters = { "\r\n", "\r", "\n" }; /// public string Name => "TxtLyricProvider"; @@ -30,7 +31,7 @@ public class TxtLyricParser : ILyricParser return null; } - string[] lyricTextLines = lyrics.Content.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); + string[] lyricTextLines = lyrics.Content.Split(_lineBreakCharacters, StringSplitOptions.None); if (lyricTextLines.Length == 0) { From b5f0760db8dba96e9edd67d4b9c914cf25c3d26a Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 22 May 2023 22:48:09 +0200 Subject: [PATCH 056/358] Use RegexGenerator where possible --- Emby.Dlna/PlayTo/DlnaHttpClient.cs | 10 ++---- Emby.Naming/Audio/AlbumParser.cs | 13 ++++---- Emby.Naming/TV/SeriesResolver.cs | 7 +++-- Emby.Naming/Video/VideoListResolver.cs | 12 ++++--- .../Library/Resolvers/Movies/MovieResolver.cs | 10 +++--- .../LegacyHdHomerunChannelCommands.cs | 7 +++-- .../LiveTv/TunerHosts/M3uParser.cs | 9 ++++-- .../Users/UserManager.cs | 20 ++++++------ .../Extensions/BaseExtensions.cs | 13 ++++---- .../MediaEncoding/EncodingHelper.cs | 7 +++-- .../Encoder/EncoderValidator.cs | 15 +++++---- .../Encoder/MediaEncoder.cs | 11 ++++--- .../Subtitles/AssWriter.cs | 7 +++-- .../Subtitles/SrtWriter.cs | 7 +++-- .../Subtitles/SsaWriter.cs | 7 +++-- .../Subtitles/TtmlWriter.cs | 7 +++-- .../Subtitles/VttWriter.cs | 7 +++-- MediaBrowser.Model/Dlna/SearchCriteria.cs | 31 +++++-------------- .../MediaInfo/AudioFileProber.cs | 7 +++-- .../Plugins/Tmdb/TmdbUtils.cs | 9 +++--- .../Savers/BaseNfoSaver.cs | 15 ++++----- jellyfin.ruleset | 2 ++ .../StripCollageBuilder.cs | 3 +- src/Jellyfin.Extensions/StringExtensions.cs | 10 +++--- .../Manager/ItemImageProviderTests.cs | 7 +++-- 25 files changed, 137 insertions(+), 116 deletions(-) diff --git a/Emby.Dlna/PlayTo/DlnaHttpClient.cs b/Emby.Dlna/PlayTo/DlnaHttpClient.cs index 8b983e9e3d..8454c1afd3 100644 --- a/Emby.Dlna/PlayTo/DlnaHttpClient.cs +++ b/Emby.Dlna/PlayTo/DlnaHttpClient.cs @@ -31,6 +31,9 @@ namespace Emby.Dlna.PlayTo _httpClientFactory = httpClientFactory; } + [GeneratedRegex("(&(?![a-z]*;))")] + private static partial Regex EscapeAmpersandRegex(); + private static string NormalizeServiceUrl(string baseUrl, string serviceUrl) { // If it's already a complete url, don't stick anything onto the front of it @@ -128,12 +131,5 @@ namespace Emby.Dlna.PlayTo // Have to await here instead of returning the Task directly, otherwise request would be disposed too soon return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); } - - /// - /// Compile-time generated regular expression for escaping ampersands. - /// - /// Compiled regular expression. - [GeneratedRegex("(&(?![a-z]*;))")] - private static partial Regex EscapeAmpersandRegex(); } } diff --git a/Emby.Naming/Audio/AlbumParser.cs b/Emby.Naming/Audio/AlbumParser.cs index 86a5641531..73424a1345 100644 --- a/Emby.Naming/Audio/AlbumParser.cs +++ b/Emby.Naming/Audio/AlbumParser.cs @@ -10,7 +10,7 @@ namespace Emby.Naming.Audio /// /// Helper class to determine if Album is multipart. /// - public class AlbumParser + public partial class AlbumParser { private readonly NamingOptions _options; @@ -23,6 +23,9 @@ namespace Emby.Naming.Audio _options = options; } + [GeneratedRegex(@"([-\.\(\)]|\s+)")] + private static partial Regex CleanRegex(); + /// /// Function that determines if album is multipart. /// @@ -42,13 +45,9 @@ namespace Emby.Naming.Audio // Normalize // Remove whitespace - filename = filename.Replace('-', ' '); - filename = filename.Replace('.', ' '); - filename = filename.Replace('(', ' '); - filename = filename.Replace(')', ' '); - filename = Regex.Replace(filename, @"\s+", " "); + filename = CleanRegex().Replace(filename, " "); - ReadOnlySpan trimmedFilename = filename.TrimStart(); + ReadOnlySpan trimmedFilename = filename.AsSpan().TrimStart(); foreach (var prefix in _options.AlbumStackingPrefixes) { diff --git a/Emby.Naming/TV/SeriesResolver.cs b/Emby.Naming/TV/SeriesResolver.cs index 307a840964..d8fa417436 100644 --- a/Emby.Naming/TV/SeriesResolver.cs +++ b/Emby.Naming/TV/SeriesResolver.cs @@ -7,14 +7,15 @@ namespace Emby.Naming.TV /// /// Used to resolve information about series from path. /// - public static class SeriesResolver + public static partial class SeriesResolver { /// /// Regex that matches strings of at least 2 characters separated by a dot or underscore. /// Used for removing separators between words, i.e turns "The_show" into "The show" while /// preserving namings like "S.H.O.W". /// - private static readonly Regex _seriesNameRegex = new Regex(@"((?[^\._]{2,})[\._]*)|([\._](?[^\._]{2,}))", RegexOptions.Compiled); + [GeneratedRegex(@"((?[^\._]{2,})[\._]*)|([\._](?[^\._]{2,}))")] + private static partial Regex SeriesNameRegex(); /// /// Resolve information about series from path. @@ -37,7 +38,7 @@ namespace Emby.Naming.TV if (!string.IsNullOrEmpty(seriesName)) { - seriesName = _seriesNameRegex.Replace(seriesName, "${a} ${b}").Trim(); + seriesName = SeriesNameRegex().Replace(seriesName, "${a} ${b}").Trim(); } return new SeriesInfo(path) diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index 6209cd46f4..51f29cf088 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -12,9 +12,13 @@ namespace Emby.Naming.Video /// /// Resolves alternative versions and extras from list of video files. /// - public static class VideoListResolver + public static partial class VideoListResolver { - private static readonly Regex _resolutionRegex = new Regex("[0-9]{2}[0-9]+[ip]", RegexOptions.IgnoreCase | RegexOptions.Compiled); + [GeneratedRegex("[0-9]{2}[0-9]+[ip]", RegexOptions.IgnoreCase)] + private static partial Regex ResolutionRegex(); + + [GeneratedRegex(@"^\[([^]]*)\]")] + private static partial Regex CheckMultiVersionRegex(); /// /// Resolves alternative versions and extras from list of video files. @@ -131,7 +135,7 @@ namespace Emby.Naming.Video if (videos.Count > 1) { - var groups = videos.GroupBy(x => _resolutionRegex.IsMatch(x.Files[0].FileNameWithoutExtension)).ToList(); + var groups = videos.GroupBy(x => ResolutionRegex().IsMatch(x.Files[0].FileNameWithoutExtension)).ToList(); videos.Clear(); foreach (var group in groups) { @@ -201,7 +205,7 @@ namespace Emby.Naming.Video // The CleanStringParser should have removed common keywords etc. return testFilename.IsEmpty || testFilename[0] == '-' - || Regex.IsMatch(testFilename, @"^\[([^]]*)\]", RegexOptions.Compiled); + || CheckMultiVersionRegex().IsMatch(testFilename); } } } diff --git a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs index ea980b9929..0b65bf921e 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs @@ -24,7 +24,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies /// /// Class MovieResolver. /// - public class MovieResolver : BaseVideoResolver