Consistently write IP in upercase

This commit is contained in:
Shadowghost 2023-02-17 19:27:36 +01:00
parent bedee7922f
commit 20fd05b050
34 changed files with 132 additions and 132 deletions

View File

@ -189,7 +189,7 @@ namespace Emby.Dlna.PlayTo
_sessionManager.UpdateDeviceName(sessionInfo.Id, deviceName); _sessionManager.UpdateDeviceName(sessionInfo.Id, deviceName);
string serverAddress = _appHost.GetSmartApiUrl(info.RemoteIpAddress); string serverAddress = _appHost.GetSmartApiUrl(info.RemoteIPAddress);
controller = new PlayToController( controller = new PlayToController(
sessionInfo, sessionInfo,

View File

@ -110,7 +110,7 @@ namespace Emby.Dlna.Ssdp
{ {
Location = e.DiscoveredDevice.DescriptionLocation, Location = e.DiscoveredDevice.DescriptionLocation,
Headers = headers, Headers = headers,
RemoteIpAddress = e.RemoteIpAddress RemoteIPAddress = e.RemoteIPAddress
}); });
DeviceDiscoveredInternal?.Invoke(this, args); DeviceDiscoveredInternal?.Invoke(this, args);

View File

@ -51,7 +51,7 @@ namespace Emby.Server.Implementations.HttpServer
using var connection = new WebSocketConnection( using var connection = new WebSocketConnection(
_loggerFactory.CreateLogger<WebSocketConnection>(), _loggerFactory.CreateLogger<WebSocketConnection>(),
webSocket, webSocket,
context.GetNormalizedRemoteIp()) context.GetNormalizedRemoteIP())
{ {
OnReceive = ProcessWebSocketMessageReceived OnReceive = ProcessWebSocketMessageReceived
}; };

View File

@ -667,12 +667,12 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
while (!cancellationToken.IsCancellationRequested) while (!cancellationToken.IsCancellationRequested)
{ {
var response = await udpClient.ReceiveMessageFromAsync(receiveBuffer, new IPEndPoint(IPAddress.Any, 0), cancellationToken).ConfigureAwait(false); 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 // 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) if (response.ReceivedBytes > 13 && receiveBuffer[1] == 3)
{ {
var deviceAddress = "http://" + deviceIp; var deviceAddress = "http://" + deviceIP;
var info = await TryGetTunerHostInfo(deviceAddress, cancellationToken).ConfigureAwait(false); var info = await TryGetTunerHostInfo(deviceAddress, cancellationToken).ConfigureAwait(false);

View File

@ -48,10 +48,10 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
public async Task<bool> CheckTunerAvailability(IPAddress remoteIp, int tuner, CancellationToken cancellationToken) public async Task<bool> CheckTunerAvailability(IPAddress remoteIP, int tuner, CancellationToken cancellationToken)
{ {
using var client = new TcpClient(); using var client = new TcpClient();
await client.ConnectAsync(remoteIp, HdHomeRunPort).ConfigureAwait(false); await client.ConnectAsync(remoteIP, HdHomeRunPort).ConfigureAwait(false);
using var stream = client.GetStream(); using var stream = client.GetStream();
return await CheckTunerAvailability(stream, tuner, cancellationToken).ConfigureAwait(false); 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(); _tcpClient = new TcpClient();
await _tcpClient.ConnectAsync(_remoteEndPoint, cancellationToken).ConfigureAwait(false); 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); var targetMsgLen = WriteSetMessage(buffer, i, "target", targetValue, lockKeyValue);
await stream.WriteAsync(buffer.AsMemory(0, targetMsgLen), cancellationToken).ConfigureAwait(false); await stream.WriteAsync(buffer.AsMemory(0, targetMsgLen), cancellationToken).ConfigureAwait(false);

View File

@ -30,7 +30,7 @@ namespace Jellyfin.Api.Auth.AnonymousLanAccessPolicy
/// <inheritdoc /> /// <inheritdoc />
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AnonymousLanAccessRequirement requirement) 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. // Loopback will be on LAN, so we can accept null.
if (ip is null || _networkManager.IsInLocalNetwork(ip)) if (ip is null || _networkManager.IsInLocalNetwork(ip))

View File

@ -47,7 +47,7 @@ namespace Jellyfin.Api.Auth.DefaultAuthorizationPolicy
} }
var isInLocalNetwork = _httpContextAccessor.HttpContext is not null var isInLocalNetwork = _httpContextAccessor.HttpContext is not null
&& _networkManager.IsInLocalNetwork(_httpContextAccessor.HttpContext.GetNormalizedRemoteIp()); && _networkManager.IsInLocalNetwork(_httpContextAccessor.HttpContext.GetNormalizedRemoteIP());
var user = _userManager.GetUserById(userId); var user = _userManager.GetUserById(userId);
if (user is null) if (user is null)
{ {

View File

@ -31,7 +31,7 @@ namespace Jellyfin.Api.Auth.LocalAccessOrRequiresElevationPolicy
/// <inheritdoc /> /// <inheritdoc />
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, LocalAccessOrRequiresElevationRequirement requirement) 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. // Loopback will be on LAN, so we can accept null.
if (ip is null || _networkManager.IsInLocalNetwork(ip)) if (ip is null || _networkManager.IsInLocalNetwork(ip))

View File

@ -183,7 +183,7 @@ public class MediaInfoController : BaseJellyfinApiController
enableTranscoding.Value, enableTranscoding.Value,
allowVideoStreamCopy.Value, allowVideoStreamCopy.Value,
allowAudioStreamCopy.Value, allowAudioStreamCopy.Value,
Request.HttpContext.GetNormalizedRemoteIp()); Request.HttpContext.GetNormalizedRemoteIP());
} }
_mediaInfoHelper.SortMediaSources(info, maxStreamingBitrate); _mediaInfoHelper.SortMediaSources(info, maxStreamingBitrate);

View File

@ -179,7 +179,7 @@ public class SystemController : BaseJellyfinApiController
return new EndPointInfo return new EndPointInfo
{ {
IsLocal = HttpContext.IsLocal(), IsLocal = HttpContext.IsLocal(),
IsInNetwork = _network.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp()) IsInNetwork = _network.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIP())
}; };
} }

View File

@ -143,7 +143,7 @@ public class UniversalAudioController : BaseJellyfinApiController
true, true,
true, true,
true, true,
Request.HttpContext.GetNormalizedRemoteIp()); Request.HttpContext.GetNormalizedRemoteIP());
} }
_mediaInfoHelper.SortMediaSources(info, maxStreamingBitrate); _mediaInfoHelper.SortMediaSources(info, maxStreamingBitrate);

View File

@ -129,7 +129,7 @@ public class UserController : BaseJellyfinApiController
return NotFound("User not found"); return NotFound("User not found");
} }
var result = _userManager.GetUserDto(user, HttpContext.GetNormalizedRemoteIp().ToString()); var result = _userManager.GetUserDto(user, HttpContext.GetNormalizedRemoteIP().ToString());
return result; return result;
} }
@ -211,7 +211,7 @@ public class UserController : BaseJellyfinApiController
DeviceId = auth.DeviceId, DeviceId = auth.DeviceId,
DeviceName = auth.Device, DeviceName = auth.Device,
Password = request.Pw, Password = request.Pw,
RemoteEndPoint = HttpContext.GetNormalizedRemoteIp().ToString(), RemoteEndPoint = HttpContext.GetNormalizedRemoteIP().ToString(),
Username = request.Username Username = request.Username
}).ConfigureAwait(false); }).ConfigureAwait(false);
@ -220,7 +220,7 @@ public class UserController : BaseJellyfinApiController
catch (SecurityException e) catch (SecurityException e)
{ {
// rethrow adding IP address to message // 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) catch (SecurityException e)
{ {
// rethrow adding IP address to message // 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, user.Username,
request.CurrentPw ?? string.Empty, request.CurrentPw ?? string.Empty,
request.CurrentPw ?? string.Empty, request.CurrentPw ?? string.Empty,
HttpContext.GetNormalizedRemoteIp().ToString(), HttpContext.GetNormalizedRemoteIP().ToString(),
false).ConfigureAwait(false); false).ConfigureAwait(false);
if (success is null) if (success is null)
@ -489,7 +489,7 @@ public class UserController : BaseJellyfinApiController
await _userManager.ChangePassword(newUser, request.Password).ConfigureAwait(false); 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; return result;
} }
@ -504,7 +504,7 @@ public class UserController : BaseJellyfinApiController
[ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult<ForgotPasswordResult>> ForgotPassword([FromBody, Required] ForgotPasswordDto forgotPasswordRequest) public async Task<ActionResult<ForgotPasswordResult>> ForgotPassword([FromBody, Required] ForgotPasswordDto forgotPasswordRequest)
{ {
var ip = HttpContext.GetNormalizedRemoteIp(); var ip = HttpContext.GetNormalizedRemoteIP();
var isLocal = HttpContext.IsLocal() var isLocal = HttpContext.IsLocal()
|| _networkManager.IsInLocalNetwork(ip); || _networkManager.IsInLocalNetwork(ip);
@ -585,7 +585,7 @@ public class UserController : BaseJellyfinApiController
if (filterByNetwork) if (filterByNetwork)
{ {
if (!_networkManager.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp())) if (!_networkManager.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIP()))
{ {
users = users.Where(i => i.HasPermission(PermissionKind.EnableRemoteAccess)); users = users.Where(i => i.HasPermission(PermissionKind.EnableRemoteAccess));
} }
@ -593,7 +593,7 @@ public class UserController : BaseJellyfinApiController
var result = users var result = users
.OrderBy(u => u.Username) .OrderBy(u => u.Username)
.Select(i => _userManager.GetUserDto(i, HttpContext.GetNormalizedRemoteIp().ToString())); .Select(i => _userManager.GetUserDto(i, HttpContext.GetNormalizedRemoteIP().ToString()));
return result; return result;
} }

View File

@ -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; var requestedVideoBitrate = state.VideoRequest is null ? 0 : state.VideoRequest.VideoBitRate ?? 0;

View File

@ -421,7 +421,7 @@ public class MediaInfoHelper
true, true,
true, true,
true, true,
httpContext.GetNormalizedRemoteIp()); httpContext.GetNormalizedRemoteIP());
} }
else else
{ {
@ -487,7 +487,7 @@ public class MediaInfoHelper
{ {
var isInLocalNetwork = _networkManager.IsInLocalNetwork(ipAddress); 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) if (!isInLocalNetwork)
{ {
maxBitrate = Math.Min(maxBitrate ?? remoteClientMaxBitrate, remoteClientMaxBitrate); maxBitrate = Math.Min(maxBitrate ?? remoteClientMaxBitrate, remoteClientMaxBitrate);

View File

@ -98,7 +98,7 @@ public static class RequestHelpers
httpContext.User.GetVersion(), httpContext.User.GetVersion(),
httpContext.User.GetDeviceId(), httpContext.User.GetDeviceId(),
httpContext.User.GetDevice(), httpContext.User.GetDevice(),
httpContext.GetNormalizedRemoteIp().ToString(), httpContext.GetNormalizedRemoteIP().ToString(),
user).ConfigureAwait(false); user).ConfigureAwait(false);
if (session is null) if (session is null)

View File

@ -9,15 +9,15 @@ namespace Jellyfin.Api.Middleware;
/// <summary> /// <summary>
/// Validates the IP of requests coming from local networks wrt. remote access. /// Validates the IP of requests coming from local networks wrt. remote access.
/// </summary> /// </summary>
public class IpBasedAccessValidationMiddleware public class IPBasedAccessValidationMiddleware
{ {
private readonly RequestDelegate _next; private readonly RequestDelegate _next;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="IpBasedAccessValidationMiddleware"/> class. /// Initializes a new instance of the <see cref="IPBasedAccessValidationMiddleware"/> class.
/// </summary> /// </summary>
/// <param name="next">The next delegate in the pipeline.</param> /// <param name="next">The next delegate in the pipeline.</param>
public IpBasedAccessValidationMiddleware(RequestDelegate next) public IPBasedAccessValidationMiddleware(RequestDelegate next)
{ {
_next = next; _next = next;
} }
@ -37,9 +37,9 @@ public class IpBasedAccessValidationMiddleware
return; return;
} }
var remoteIp = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback; var remoteIP = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback;
if (!networkManager.HasRemoteAccess(remoteIp)) if (!networkManager.HasRemoteAccess(remoteIP))
{ {
return; return;
} }

View File

@ -38,7 +38,7 @@ public class LanFilteringMiddleware
return; return;
} }
var host = httpContext.GetNormalizedRemoteIp(); var host = httpContext.GetNormalizedRemoteIP();
if (!networkManager.IsInLocalNetwork(host)) if (!networkManager.IsInLocalNetwork(host))
{ {
return; return;

View File

@ -51,9 +51,9 @@ public class ResponseTimeMiddleware
if (enableWarning && responseTimeMs > warningThreshold && _logger.IsEnabled(LogLevel.Debug)) if (enableWarning && responseTimeMs > warningThreshold && _logger.IsEnabled(LogLevel.Debug))
{ {
_logger.LogDebug( _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.Request.GetDisplayUrl(),
context.GetNormalizedRemoteIp(), context.GetNormalizedRemoteIP(),
responseTime, responseTime,
context.Response.StatusCode); context.Response.StatusCode);
} }

View File

@ -122,7 +122,7 @@ namespace Jellyfin.Networking.Manager
/// <summary> /// <summary>
/// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal.
/// </summary> /// </summary>
public bool TrustAllIpv6Interfaces { get; private set; } public bool TrustAllIPv6Interfaces { get; private set; }
/// <summary> /// <summary>
/// Gets the Published server override list. /// Gets the Published server override list.
@ -596,17 +596,17 @@ namespace Jellyfin.Networking.Manager
} }
/// <inheritdoc/> /// <inheritdoc/>
public bool HasRemoteAccess(IPAddress remoteIp) public bool HasRemoteAccess(IPAddress remoteIP)
{ {
var config = _configurationManager.GetNetworkConfiguration(); var config = _configurationManager.GetNetworkConfiguration();
if (config.EnableRemoteAccess) if (config.EnableRemoteAccess)
{ {
// Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely. // 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 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. // 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) if ((!config.IsRemoteIPFilterBlacklist && matches > 0)
|| (config.IsRemoteIPFilterBlacklist && matches == 0)) || (config.IsRemoteIPFilterBlacklist && matches == 0))
{ {
@ -616,7 +616,7 @@ namespace Jellyfin.Networking.Manager
return false; 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. // Remote not enabled. So everyone should be LAN.
return false; return false;
@ -771,7 +771,7 @@ namespace Jellyfin.Networking.Manager
// If no source address is given, use the preferred (first) interface // If no source address is given, use the preferred (first) interface
if (source is null) 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); _logger.LogDebug("{Source}: Using first internal interface as bind address: {Result}", source, result);
return result; return result;
} }
@ -782,14 +782,14 @@ namespace Jellyfin.Networking.Manager
{ {
if (intf.Subnet.Contains(source)) 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); _logger.LogDebug("{Source}: Found interface with matching subnet, using it as bind address: {Result}", source, result);
return result; return result;
} }
} }
// Fallback to first available interface // 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); _logger.LogDebug("{Source}: No matching interfaces found, using preferred interface as bind address: {Result}", source, result);
return result; return result;
} }
@ -842,7 +842,7 @@ namespace Jellyfin.Networking.Manager
ArgumentNullException.ThrowIfNull(address); ArgumentNullException.ThrowIfNull(address);
// See conversation at https://github.com/jellyfin/jellyfin/pull/3515. // 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.Loopback)
|| address.Equals(IPAddress.IPv6Loopback)) || address.Equals(IPAddress.IPv6Loopback))
{ {
@ -995,7 +995,7 @@ namespace Jellyfin.Networking.Manager
if (bindAddress is not null) 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); _logger.LogDebug("{Source}: External request received, matching external bind address found: {Result}", source, result);
return true; return true;
} }
@ -1015,7 +1015,7 @@ namespace Jellyfin.Networking.Manager
if (bindAddress is not null) 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); _logger.LogDebug("{Source}: Internal request received, matching internal bind address found: {Result}", source, result);
return true; return true;
} }
@ -1049,14 +1049,14 @@ namespace Jellyfin.Networking.Manager
{ {
if (!IsInLocalNetwork(intf.Address) && intf.Subnet.Contains(source)) 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); _logger.LogDebug("{Source}: Found external interface with matching subnet, using it as bind address: {Result}", source, result);
return true; return true;
} }
} }
// Fallback to first external interface. // 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); _logger.LogDebug("{Source}: Using first external interface as bind address: {Result}", source, result);
return true; return true;
} }

View File

@ -63,9 +63,9 @@ namespace Jellyfin.Server.Extensions
/// </summary> /// </summary>
/// <param name="appBuilder">The application builder.</param> /// <param name="appBuilder">The application builder.</param>
/// <returns>The updated application builder.</returns> /// <returns>The updated application builder.</returns>
public static IApplicationBuilder UseIpBasedAccessValidation(this IApplicationBuilder appBuilder) public static IApplicationBuilder UseIPBasedAccessValidation(this IApplicationBuilder appBuilder)
{ {
return appBuilder.UseMiddleware<IpBasedAccessValidationMiddleware>(); return appBuilder.UseMiddleware<IPBasedAccessValidationMiddleware>();
} }
/// <summary> /// <summary>

View File

@ -271,26 +271,26 @@ namespace Jellyfin.Server.Extensions
{ {
if (IPAddress.TryParse(allowedProxies[i], out var addr)) 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)) else if (NetworkExtensions.TryParseToSubnet(allowedProxies[i], out var subnet))
{ {
if (subnet != null) 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)) else if (NetworkExtensions.TryParseHost(allowedProxies[i], out var addresses))
{ {
foreach (var address in 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)) if ((!config.EnableIPv4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPv6 && addr.AddressFamily == AddressFamily.InterNetworkV6))
{ {

View File

@ -190,7 +190,7 @@ namespace Jellyfin.Server
mainApp.UseAuthorization(); mainApp.UseAuthorization();
mainApp.UseLanFiltering(); mainApp.UseLanFiltering();
mainApp.UseIpBasedAccessValidation(); mainApp.UseIPBasedAccessValidation();
mainApp.UseWebSocketHandler(); mainApp.UseWebSocketHandler();
mainApp.UseServerStartupMessage(); mainApp.UseServerStartupMessage();

View File

@ -25,7 +25,7 @@ namespace MediaBrowser.Common.Extensions
/// </summary> /// </summary>
/// <param name="context">The HTTP context.</param> /// <param name="context">The HTTP context.</param>
/// <returns>The remote caller IP address.</returns> /// <returns>The remote caller IP address.</returns>
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) // Default to the loopback address if no RemoteIpAddress is specified (i.e. during integration tests)
var ip = context.Connection.RemoteIpAddress ?? IPAddress.Loopback; var ip = context.Connection.RemoteIpAddress ?? IPAddress.Loopback;

View File

@ -130,10 +130,10 @@ namespace MediaBrowser.Common.Net
IReadOnlyList<IPData> GetInternalBindAddresses(); IReadOnlyList<IPData> GetInternalBindAddresses();
/// <summary> /// <summary>
/// Checks if <paramref name="remoteIp"/> has access to the server. /// Checks if <paramref name="remoteIP"/> has access to the server.
/// </summary> /// </summary>
/// <param name="remoteIp">IP address of the client.</param> /// <param name="remoteIP">IP address of the client.</param>
/// <returns><b>True</b> if it has access, otherwise <b>false</b>.</returns> /// <returns><b>True</b> if it has access, otherwise <b>false</b>.</returns>
bool HasRemoteAccess(IPAddress remoteIp); bool HasRemoteAccess(IPAddress remoteIP);
} }
} }

View File

@ -126,11 +126,11 @@ namespace MediaBrowser.Common.Net
/// <summary> /// <summary>
/// Converts an IPAddress into a string. /// Converts an IPAddress into a string.
/// Ipv6 addresses are returned in [ ], with their scope removed. /// IPv6 addresses are returned in [ ], with their scope removed.
/// </summary> /// </summary>
/// <param name="address">Address to convert.</param> /// <param name="address">Address to convert.</param>
/// <returns>URI safe conversion of the address.</returns> /// <returns>URI safe conversion of the address.</returns>
public static string FormatIpString(IPAddress? address) public static string FormatIPString(IPAddress? address)
{ {
if (address is null) if (address is null)
{ {
@ -252,10 +252,10 @@ namespace MediaBrowser.Common.Net
/// </summary> /// </summary>
/// <param name="host">Host name to parse.</param> /// <param name="host">Host name to parse.</param>
/// <param name="addresses">Object representing the string, if it has successfully been parsed.</param> /// <param name="addresses">Object representing the string, if it has successfully been parsed.</param>
/// <param name="isIpv4Enabled"><c>true</c> if IPv4 is enabled.</param> /// <param name="isIPv4Enabled"><c>true</c> if IPv4 is enabled.</param>
/// <param name="isIpv6Enabled"><c>true</c> if IPv6 is enabled.</param> /// <param name="isIPv6Enabled"><c>true</c> if IPv6 is enabled.</param>
/// <returns><c>true</c> if the parsing is successful, <c>false</c> if not.</returns> /// <returns><c>true</c> if the parsing is successful, <c>false</c> if not.</returns>
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)) if (string.IsNullOrWhiteSpace(host))
{ {
@ -302,8 +302,8 @@ namespace MediaBrowser.Common.Net
if (IPAddress.TryParse(host, out var address)) if (IPAddress.TryParse(host, out var address))
{ {
if (((address.AddressFamily == AddressFamily.InterNetwork) && (!isIpv4Enabled && isIpv6Enabled)) || if (((address.AddressFamily == AddressFamily.InterNetwork) && (!isIPv4Enabled && isIPv6Enabled)) ||
((address.AddressFamily == AddressFamily.InterNetworkV6) && (isIpv4Enabled && !isIpv6Enabled))) ((address.AddressFamily == AddressFamily.InterNetworkV6) && (isIPv4Enabled && !isIPv6Enabled)))
{ {
addresses = Array.Empty<IPAddress>(); addresses = Array.Empty<IPAddress>();
return false; return false;
@ -338,11 +338,11 @@ namespace MediaBrowser.Common.Net
addressBytes.Reverse(); 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 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));
} }
} }
} }

View File

@ -13,10 +13,10 @@ namespace MediaBrowser.Model.Dlna
public Dictionary<string, string> Headers { get; set; } public Dictionary<string, string> Headers { get; set; }
public IPAddress LocalIpAddress { get; set; } public IPAddress LocalIPAddress { get; set; }
public int LocalPort { get; set; } public int LocalPort { get; set; }
public IPAddress RemoteIpAddress { get; set; } public IPAddress RemoteIPAddress { get; set; }
} }
} }

View File

@ -8,7 +8,7 @@ namespace Rssdp
/// </summary> /// </summary>
public sealed class DeviceAvailableEventArgs : EventArgs public sealed class DeviceAvailableEventArgs : EventArgs
{ {
public IPAddress RemoteIpAddress { get; set; } public IPAddress RemoteIPAddress { get; set; }
private readonly DiscoveredSsdpDevice _DiscoveredDevice; private readonly DiscoveredSsdpDevice _DiscoveredDevice;

View File

@ -33,13 +33,13 @@ namespace Rssdp.Infrastructure
/// <summary> /// <summary>
/// Sends a message to a particular address (uni or multicast) and port. /// Sends a message to a particular address (uni or multicast) and port.
/// </summary> /// </summary>
Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken); Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIPAddress, CancellationToken cancellationToken);
/// <summary> /// <summary>
/// Sends a message to the SSDP multicast address and port. /// Sends a message to the SSDP multicast address and port.
/// </summary> /// </summary>
Task SendMulticastMessage(string message, IPAddress fromLocalIpAddress, CancellationToken cancellationToken); Task SendMulticastMessage(string message, IPAddress fromLocalIPAddress, CancellationToken cancellationToken);
Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIpAddress, CancellationToken cancellationToken); Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIPAddress, CancellationToken cancellationToken);
/// <summary> /// <summary>
/// Gets or sets a boolean value indicating whether or not this instance is shared amongst multiple <see cref="SsdpDeviceLocator"/> and/or <see cref="ISsdpDevicePublisher"/> instances. /// Gets or sets a boolean value indicating whether or not this instance is shared amongst multiple <see cref="SsdpDeviceLocator"/> and/or <see cref="ISsdpDevicePublisher"/> instances.

View File

@ -13,16 +13,16 @@ namespace Rssdp.Infrastructure
private readonly IPEndPoint _ReceivedFrom; private readonly IPEndPoint _ReceivedFrom;
public IPAddress LocalIpAddress { get; private set; } public IPAddress LocalIPAddress { get; private set; }
/// <summary> /// <summary>
/// Full constructor. /// Full constructor.
/// </summary> /// </summary>
public RequestReceivedEventArgs(HttpRequestMessage message, IPEndPoint receivedFrom, IPAddress localIpAddress) public RequestReceivedEventArgs(HttpRequestMessage message, IPEndPoint receivedFrom, IPAddress localIPAddress)
{ {
_Message = message; _Message = message;
_ReceivedFrom = receivedFrom; _ReceivedFrom = receivedFrom;
LocalIpAddress = localIpAddress; LocalIPAddress = localIPAddress;
} }
/// <summary> /// <summary>

View File

@ -9,7 +9,7 @@ namespace Rssdp.Infrastructure
/// </summary> /// </summary>
public sealed class ResponseReceivedEventArgs : EventArgs public sealed class ResponseReceivedEventArgs : EventArgs
{ {
public IPAddress LocalIpAddress { get; set; } public IPAddress LocalIPAddress { get; set; }
private readonly HttpResponseMessage _Message; private readonly HttpResponseMessage _Message;

View File

@ -155,7 +155,7 @@ namespace Rssdp.Infrastructure
/// <summary> /// <summary>
/// Sends a message to a particular address (uni or multicast) and port. /// Sends a message to a particular address (uni or multicast) and port.
/// </summary> /// </summary>
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) if (messageData is null)
{ {
@ -164,7 +164,7 @@ namespace Rssdp.Infrastructure
ThrowIfDisposed(); ThrowIfDisposed();
var sockets = GetSendSockets(fromLocalIpAddress, destination); var sockets = GetSendSockets(fromlocalIPAddress, destination);
if (sockets.Count == 0) if (sockets.Count == 0)
{ {
@ -200,19 +200,19 @@ namespace Rssdp.Infrastructure
} }
} }
private List<Socket> GetSendSockets(IPAddress fromLocalIpAddress, IPEndPoint destination) private List<Socket> GetSendSockets(IPAddress fromlocalIPAddress, IPEndPoint destination)
{ {
EnsureSendSocketCreated(); EnsureSendSocketCreated();
lock (_SendSocketSynchroniser) 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 // 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) 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 sending to the loopback address, filter the socket list as well
if (destination.Address.Equals(IPAddress.Loopback)) if (destination.Address.Equals(IPAddress.Loopback))
@ -221,10 +221,10 @@ namespace Rssdp.Infrastructure
|| ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Loopback)); || ((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) 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 sending to the loopback address, filter the socket list as well
if (destination.Address.Equals(IPAddress.IPv6Loopback)) 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);
} }
/// <summary> /// <summary>
/// Sends a message to the SSDP multicast address and port. /// Sends a message to the SSDP multicast address and port.
/// </summary> /// </summary>
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) if (message is null)
{ {
@ -269,7 +269,7 @@ namespace Rssdp.Infrastructure
new IPEndPoint( new IPEndPoint(
IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress), IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress),
SsdpConstants.MulticastPort), SsdpConstants.MulticastPort),
fromLocalIpAddress, fromlocalIPAddress,
cancellationToken).ConfigureAwait(false); cancellationToken).ConfigureAwait(false);
await Task.Delay(100, 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; var sockets = _sendSockets;
if (sockets is not null) if (sockets is not null)
{ {
sockets = sockets.ToList(); 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)); .Select(s => SendFromSocket(s, messageData, destination, cancellationToken));
return Task.WhenAll(tasks); 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 // 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 // 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 // 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. // 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)) if (data.StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase))
{ {
HttpResponseMessage responseMessage = null; HttpResponseMessage responseMessage = null;
@ -479,7 +479,7 @@ namespace Rssdp.Infrastructure
if (responseMessage is not null) if (responseMessage is not null)
{ {
OnResponseReceived(responseMessage, endPoint, receivedOnLocalIpAddress); OnResponseReceived(responseMessage, endPoint, receivedOnlocalIPAddress);
} }
} }
else else
@ -496,12 +496,12 @@ namespace Rssdp.Infrastructure
if (requestMessage is not null) 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 // SSDP specification says only * is currently used but other uri's might
// be implemented in the future and should be ignored unless understood. // be implemented in the future and should be ignored unless understood.
@ -514,18 +514,18 @@ namespace Rssdp.Infrastructure
var handlers = this.RequestReceived; var handlers = this.RequestReceived;
if (handlers is not null) 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; var handlers = this.ResponseReceived;
if (handlers is not null) if (handlers is not null)
{ {
handlers(this, new ResponseReceivedEventArgs(data, endPoint) handlers(this, new ResponseReceivedEventArgs(data, endPoint)
{ {
LocalIpAddress = localIpAddress LocalIPAddress = localIPAddress
}); });
} }
} }

View File

@ -240,7 +240,7 @@ namespace Rssdp.Infrastructure
/// Raises the <see cref="DeviceAvailable"/> event. /// Raises the <see cref="DeviceAvailable"/> event.
/// </summary> /// </summary>
/// <seealso cref="DeviceAvailable"/> /// <seealso cref="DeviceAvailable"/>
protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress IpAddress) protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress IPAddress)
{ {
if (this.IsDisposed) if (this.IsDisposed)
{ {
@ -252,7 +252,7 @@ namespace Rssdp.Infrastructure
{ {
handlers(this, new DeviceAvailableEventArgs(device, isNewDevice) 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; bool isNewDevice = false;
lock (_Devices) 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)) if (!NotificationTypeMatchesFilter(device))
{ {
return; return;
} }
OnDeviceAvailable(device, isNewDevice, IpAddress); OnDeviceAvailable(device, isNewDevice, IPAddress);
} }
private bool NotificationTypeMatchesFilter(DiscoveredSsdpDevice device) private bool NotificationTypeMatchesFilter(DiscoveredSsdpDevice device)
@ -378,7 +378,7 @@ namespace Rssdp.Infrastructure
return _CommunicationsServer.SendMulticastMessage(message, null, cancellationToken); return _CommunicationsServer.SendMulticastMessage(message, null, cancellationToken);
} }
private void ProcessSearchResponseMessage(HttpResponseMessage message, IPAddress IpAddress) private void ProcessSearchResponseMessage(HttpResponseMessage message, IPAddress IPAddress)
{ {
if (!message.IsSuccessStatusCode) if (!message.IsSuccessStatusCode)
{ {
@ -398,11 +398,11 @@ namespace Rssdp.Infrastructure
ResponseHeaders = message.Headers 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) if (String.Compare(message.Method.Method, "Notify", StringComparison.OrdinalIgnoreCase) != 0)
{ {
@ -412,7 +412,7 @@ namespace Rssdp.Infrastructure
var notificationType = GetFirstHeaderStringValue("NTS", message); var notificationType = GetFirstHeaderStringValue("NTS", message);
if (String.Compare(notificationType, SsdpConstants.SsdpKeepAliveNotification, StringComparison.OrdinalIgnoreCase) == 0) 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) 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); var location = GetFirstHeaderUriValue("Location", message);
if (location is not null) if (location is not null)
@ -435,7 +435,7 @@ namespace Rssdp.Infrastructure
ResponseHeaders = message.Headers ResponseHeaders = message.Headers
}; };
AddOrUpdateDiscoveredDevice(device, IpAddress); AddOrUpdateDiscoveredDevice(device, IPAddress);
} }
} }
@ -651,7 +651,7 @@ namespace Rssdp.Infrastructure
private void CommsServer_ResponseReceived(object sender, ResponseReceivedEventArgs e) 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) private void CommsServer_RequestReceived(object sender, RequestReceivedEventArgs e)

View File

@ -224,7 +224,7 @@ namespace Rssdp.Infrastructure
string mx, string mx,
string searchTarget, string searchTarget,
IPEndPoint remoteEndPoint, IPEndPoint remoteEndPoint,
IPAddress receivedOnlocalIpAddress, IPAddress receivedOnlocalIPAddress,
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
if (String.IsNullOrEmpty(searchTarget)) if (String.IsNullOrEmpty(searchTarget))
@ -297,9 +297,9 @@ namespace Rssdp.Infrastructure
{ {
var root = device.ToRootDevice(); 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( private void SendDeviceSearchResponses(
SsdpDevice device, SsdpDevice device,
IPEndPoint endPoint, IPEndPoint endPoint,
IPAddress receivedOnlocalIpAddress, IPAddress receivedOnlocalIPAddress,
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
bool isRootDevice = (device as SsdpRootDevice) is not null; bool isRootDevice = (device as SsdpRootDevice) is not null;
if (isRootDevice) 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) 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) private string GetUsn(string udn, string fullDeviceType)
@ -342,7 +342,7 @@ namespace Rssdp.Infrastructure
SsdpDevice device, SsdpDevice device,
string uniqueServiceName, string uniqueServiceName,
IPEndPoint endPoint, IPEndPoint endPoint,
IPAddress receivedOnlocalIpAddress, IPAddress receivedOnlocalIPAddress,
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
const string header = "HTTP/1.1 200 OK"; const string header = "HTTP/1.1 200 OK";
@ -366,7 +366,7 @@ namespace Rssdp.Infrastructure
await _CommsServer.SendMessage( await _CommsServer.SendMessage(
Encoding.UTF8.GetBytes(message), Encoding.UTF8.GetBytes(message),
endPoint, endPoint,
receivedOnlocalIpAddress, receivedOnlocalIPAddress,
cancellationToken) cancellationToken)
.ConfigureAwait(false); .ConfigureAwait(false);
} }
@ -625,7 +625,7 @@ namespace Rssdp.Infrastructure
// else if (!e.Message.Headers.Contains("MAN")) // else if (!e.Message.Headers.Contains("MAN"))
// WriteTrace("Ignoring search request - missing MAN header."); // WriteTrace("Ignoring search request - missing MAN header.");
// else // 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);
} }
} }

View File

@ -97,7 +97,7 @@ namespace Jellyfin.Networking.Tests
/// Checks if IPv4 address is within a defined subnet. /// Checks if IPv4 address is within a defined subnet.
/// </summary> /// </summary>
/// <param name="netMask">Network mask.</param> /// <param name="netMask">Network mask.</param>
/// <param name="ipAddress">IP Address.</param> /// <param name="IPAddress">IP Address.</param>
[Theory] [Theory]
[InlineData("192.168.5.85/24", "192.168.5.1")] [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/24", "192.168.5.254")]
@ -282,7 +282,7 @@ namespace Jellyfin.Networking.Tests
[InlineData("185.10.10.10", "185.10.10.10", false)] [InlineData("185.10.10.10", "185.10.10.10", false)]
[InlineData("", "100.100.100.100", 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. // 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 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<NetworkManager>()); using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIp)), denied); Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIP)), denied);
} }
[Theory] [Theory]
@ -302,7 +302,7 @@ namespace Jellyfin.Networking.Tests
[InlineData("185.10.10.10", "185.10.10.10", true)] [InlineData("185.10.10.10", "185.10.10.10", true)]
[InlineData("", "100.100.100.100", false)] [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. // 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 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<NetworkManager>()); using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIp)), denied); Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIP)), denied);
} }
[Theory] [Theory]