aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Emby.Dlna/Eventing/DlnaEventManager.cs2
-rw-r--r--Jellyfin.Networking/HappyEyeballs/HttpClientExtension.cs117
-rw-r--r--Jellyfin.Networking/Manager/NetworkManager.cs17
-rw-r--r--Jellyfin.Server/Startup.cs20
-rw-r--r--MediaBrowser.Common/Net/NamedClient.cs9
5 files changed, 158 insertions, 7 deletions
diff --git a/Emby.Dlna/Eventing/DlnaEventManager.cs b/Emby.Dlna/Eventing/DlnaEventManager.cs
index d17e23871..d2c0017ec 100644
--- a/Emby.Dlna/Eventing/DlnaEventManager.cs
+++ b/Emby.Dlna/Eventing/DlnaEventManager.cs
@@ -165,7 +165,7 @@ namespace Emby.Dlna.Eventing
try
{
- using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
+ using var response = await _httpClientFactory.CreateClient(NamedClient.DirectIp)
.SendAsync(options, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
}
catch (OperationCanceledException)
diff --git a/Jellyfin.Networking/HappyEyeballs/HttpClientExtension.cs b/Jellyfin.Networking/HappyEyeballs/HttpClientExtension.cs
new file mode 100644
index 000000000..12b42cc6e
--- /dev/null
+++ b/Jellyfin.Networking/HappyEyeballs/HttpClientExtension.cs
@@ -0,0 +1,117 @@
+using System.Diagnostics.Metrics;
+using System.IO;
+using System.Net.Http;
+using System.Net.Sockets;
+using System.Threading;
+using System.Threading.Tasks;
+
+/*
+ Copyright (c) 2021 ppy Pty Ltd <contact@ppy.sh>.
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+*/
+
+namespace Jellyfin.Networking.HappyEyeballs
+{
+ /// <summary>
+ /// Defines the <see cref="HttpClientExtension"/> class.
+ ///
+ /// Implementation taken from https://github.com/ppy/osu-framework/pull/4191 .
+ /// </summary>
+ public static class HttpClientExtension
+ {
+ private const int ConnectionEstablishTimeout = 2000;
+
+ /// <summary>
+ /// Gets a value indicating whether the initial IPv6 check has been performed (to determine whether v6 is available or not).
+ /// </summary>
+ private static bool _hasResolvedIPv6Availability;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether IPv6 should be preferred. Value may change based on runtime failures.
+ /// </summary>
+ public static bool? UseIPv6 { get; set; } = null;
+
+ /// <summary>
+ /// Implements the httpclient callback method.
+ /// </summary>
+ /// <param name="context">The <see cref="SocketsHttpConnectionContext"/> instance.</param>
+ /// <param name="cancellationToken">The <see cref="CancellationToken"/> instance.</param>
+ /// <returns>The http steam.</returns>
+ public static async ValueTask<Stream> OnConnect(SocketsHttpConnectionContext context, CancellationToken cancellationToken)
+ {
+ // Until .NET supports an implementation of Happy Eyeballs (https://tools.ietf.org/html/rfc8305#section-2),
+ // let's make IPv4 fallback work in a simple way. This issue is being tracked at https://github.com/dotnet/runtime/issues/26177
+ // and expected to be fixed in .NET 6.
+ if (UseIPv6 == true)
+ {
+ try
+ {
+ var localToken = cancellationToken;
+
+ if (!_hasResolvedIPv6Availability)
+ {
+ // to make things move fast, use a very low timeout for the initial ipv6 attempt.
+ using var quickFailCts = new CancellationTokenSource(ConnectionEstablishTimeout);
+ using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, quickFailCts.Token);
+
+ localToken = linkedTokenSource.Token;
+ }
+
+ return await AttemptConnection(AddressFamily.InterNetworkV6, context, localToken).ConfigureAwait(false);
+ }
+#pragma warning disable CA1031 // Do not catch general exception types
+ catch
+#pragma warning restore CA1031 // Do not catch general exception types
+ {
+ // very naively fallback to ipv4 permanently for this execution based on the response of the first connection attempt.
+ // Network manager will reset this value in the case of physical network changes / interruptions.
+ UseIPv6 = false;
+ }
+ finally
+ {
+ _hasResolvedIPv6Availability = true;
+ }
+ }
+
+ // fallback to IPv4.
+ return await AttemptConnection(AddressFamily.InterNetwork, context, cancellationToken).ConfigureAwait(false);
+ }
+
+ private static async ValueTask<Stream> AttemptConnection(AddressFamily addressFamily, SocketsHttpConnectionContext context, CancellationToken cancellationToken)
+ {
+ // The following socket constructor will create a dual-mode socket on systems where IPV6 is available.
+ var socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp)
+ {
+ // Turn off Nagle's algorithm since it degrades performance in most HttpClient scenarios.
+ NoDelay = true
+ };
+
+ try
+ {
+ await socket.ConnectAsync(context.DnsEndPoint, cancellationToken).ConfigureAwait(false);
+ // The stream should take the ownership of the underlying socket,
+ // closing it when it's disposed.
+ return new NetworkStream(socket, ownsSocket: true);
+ }
+ catch
+ {
+ socket.Dispose();
+ throw;
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs
index 9e06cdfe7..631e9cdb8 100644
--- a/Jellyfin.Networking/Manager/NetworkManager.cs
+++ b/Jellyfin.Networking/Manager/NetworkManager.cs
@@ -594,6 +594,7 @@ namespace Jellyfin.Networking.Manager
IsIP4Enabled = Socket.OSSupportsIPv4 && config.EnableIPV4;
IsIP6Enabled = Socket.OSSupportsIPv6 && config.EnableIPV6;
+ HappyEyeballs.HttpClientExtension.UseIPv6 = IsIP6Enabled;
if (!IsIP6Enabled && !IsIP4Enabled)
{
@@ -838,9 +839,19 @@ namespace Jellyfin.Networking.Manager
try
{
await Task.Delay(2000).ConfigureAwait(false);
- InitialiseInterfaces();
- // Recalculate LAN caches.
- InitialiseLAN(_configurationManager.GetNetworkConfiguration());
+
+ var config = _configurationManager.GetNetworkConfiguration();
+ // Have we lost IPv6 capability?
+ if (IsIP6Enabled && !Socket.OSSupportsIPv6)
+ {
+ UpdateSettings(config);
+ }
+ else
+ {
+ InitialiseInterfaces();
+ // Recalculate LAN caches.
+ InitialiseLAN(config);
+ }
NetworkChanged?.Invoke(this, EventArgs.Empty);
}
diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs
index 1954a5c55..4417bb722 100644
--- a/Jellyfin.Server/Startup.cs
+++ b/Jellyfin.Server/Startup.cs
@@ -7,6 +7,7 @@ using System.Net.Mime;
using System.Text;
using Jellyfin.MediaEncoding.Hls.Extensions;
using Jellyfin.Networking.Configuration;
+using Jellyfin.Networking.HappyEyeballs;
using Jellyfin.Server.Extensions;
using Jellyfin.Server.Implementations;
using Jellyfin.Server.Infrastructure;
@@ -24,6 +25,7 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
+using Microsoft.VisualBasic;
using Prometheus;
namespace Jellyfin.Server
@@ -79,6 +81,13 @@ namespace Jellyfin.Server
var acceptJsonHeader = new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json, 1.0);
var acceptXmlHeader = new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Xml, 0.9);
var acceptAnyHeader = new MediaTypeWithQualityHeaderValue("*/*", 0.8);
+ Func<IServiceProvider, HttpMessageHandler> eyeballsHttpClientHandlerDelegate = (_) => new SocketsHttpHandler()
+ {
+ AutomaticDecompression = DecompressionMethods.All,
+ RequestHeaderEncodingSelector = (_, _) => Encoding.UTF8,
+ ConnectCallback = HttpClientExtension.OnConnect
+ };
+
Func<IServiceProvider, HttpMessageHandler> defaultHttpClientHandlerDelegate = (_) => new SocketsHttpHandler()
{
AutomaticDecompression = DecompressionMethods.All,
@@ -93,7 +102,7 @@ namespace Jellyfin.Server
c.DefaultRequestHeaders.Accept.Add(acceptXmlHeader);
c.DefaultRequestHeaders.Accept.Add(acceptAnyHeader);
})
- .ConfigurePrimaryHttpMessageHandler(defaultHttpClientHandlerDelegate);
+ .ConfigurePrimaryHttpMessageHandler(eyeballsHttpClientHandlerDelegate);
services.AddHttpClient(NamedClient.MusicBrainz, c =>
{
@@ -102,6 +111,15 @@ namespace Jellyfin.Server
c.DefaultRequestHeaders.Accept.Add(acceptXmlHeader);
c.DefaultRequestHeaders.Accept.Add(acceptAnyHeader);
})
+ .ConfigurePrimaryHttpMessageHandler(eyeballsHttpClientHandlerDelegate);
+
+ services.AddHttpClient(NamedClient.DirectIp, c =>
+ {
+ c.DefaultRequestHeaders.UserAgent.Add(productHeader);
+ c.DefaultRequestHeaders.Accept.Add(acceptJsonHeader);
+ c.DefaultRequestHeaders.Accept.Add(acceptXmlHeader);
+ c.DefaultRequestHeaders.Accept.Add(acceptAnyHeader);
+ })
.ConfigurePrimaryHttpMessageHandler(defaultHttpClientHandlerDelegate);
services.AddHttpClient(NamedClient.Dlna, c =>
diff --git a/MediaBrowser.Common/Net/NamedClient.cs b/MediaBrowser.Common/Net/NamedClient.cs
index a6cacd4f1..9c5544b0f 100644
--- a/MediaBrowser.Common/Net/NamedClient.cs
+++ b/MediaBrowser.Common/Net/NamedClient.cs
@@ -1,4 +1,4 @@
-namespace MediaBrowser.Common.Net
+namespace MediaBrowser.Common.Net
{
/// <summary>
/// Registered http client names.
@@ -6,7 +6,7 @@
public static class NamedClient
{
/// <summary>
- /// Gets the value for the default named http client.
+ /// Gets the value for the default named http client which implements happy eyeballs.
/// </summary>
public const string Default = nameof(Default);
@@ -19,5 +19,10 @@
/// Gets the value for the DLNA named http client.
/// </summary>
public const string Dlna = nameof(Dlna);
+
+ /// <summary>
+ /// Non happy eyeballs implementation.
+ /// </summary>
+ public const string DirectIp = nameof(DirectIp);
}
}