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);
string serverAddress = _appHost.GetSmartApiUrl(info.RemoteIpAddress);
string serverAddress = _appHost.GetSmartApiUrl(info.RemoteIPAddress);
controller = new PlayToController(
sessionInfo,

View file

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

View file

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

View file

@ -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);

View file

@ -48,10 +48,10 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
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();
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);

View file

@ -30,7 +30,7 @@ namespace Jellyfin.Api.Auth.AnonymousLanAccessPolicy
/// <inheritdoc />
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))

View file

@ -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)
{

View file

@ -31,7 +31,7 @@ namespace Jellyfin.Api.Auth.LocalAccessOrRequiresElevationPolicy
/// <inheritdoc />
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))

View file

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

View file

@ -179,7 +179,7 @@ public class SystemController : BaseJellyfinApiController
return new EndPointInfo
{
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,
Request.HttpContext.GetNormalizedRemoteIp());
Request.HttpContext.GetNormalizedRemoteIP());
}
_mediaInfoHelper.SortMediaSources(info, maxStreamingBitrate);

View file

@ -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<ActionResult<ForgotPasswordResult>> 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;
}

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;

View file

@ -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);

View file

@ -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)

View file

@ -9,15 +9,15 @@ namespace Jellyfin.Api.Middleware;
/// <summary>
/// Validates the IP of requests coming from local networks wrt. remote access.
/// </summary>
public class IpBasedAccessValidationMiddleware
public class IPBasedAccessValidationMiddleware
{
private readonly RequestDelegate _next;
/// <summary>
/// Initializes a new instance of the <see cref="IpBasedAccessValidationMiddleware"/> class.
/// Initializes a new instance of the <see cref="IPBasedAccessValidationMiddleware"/> class.
/// </summary>
/// <param name="next">The next delegate in the pipeline.</param>
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;
}

View file

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

View file

@ -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);
}

View file

@ -122,7 +122,7 @@ namespace Jellyfin.Networking.Manager
/// <summary>
/// Gets a value indicating whether is all IPv6 interfaces are trusted as internal.
/// </summary>
public bool TrustAllIpv6Interfaces { get; private set; }
public bool TrustAllIPv6Interfaces { get; private set; }
/// <summary>
/// Gets the Published server override list.
@ -596,17 +596,17 @@ namespace Jellyfin.Networking.Manager
}
/// <inheritdoc/>
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;
}

View file

@ -63,9 +63,9 @@ namespace Jellyfin.Server.Extensions
/// </summary>
/// <param name="appBuilder">The application builder.</param>
/// <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>

View file

@ -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))
{

View file

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

View file

@ -25,7 +25,7 @@ namespace MediaBrowser.Common.Extensions
/// </summary>
/// <param name="context">The HTTP context.</param>
/// <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)
var ip = context.Connection.RemoteIpAddress ?? IPAddress.Loopback;

View file

@ -130,10 +130,10 @@ namespace MediaBrowser.Common.Net
IReadOnlyList<IPData> GetInternalBindAddresses();
/// <summary>
/// Checks if <paramref name="remoteIp"/> has access to the server.
/// Checks if <paramref name="remoteIP"/> has access to the server.
/// </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>
bool HasRemoteAccess(IPAddress remoteIp);
bool HasRemoteAccess(IPAddress remoteIP);
}
}

View file

@ -126,11 +126,11 @@ namespace MediaBrowser.Common.Net
/// <summary>
/// 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>
/// <param name="address">Address to convert.</param>
/// <returns>URI safe conversion of the address.</returns>
public static string FormatIpString(IPAddress? address)
public static string FormatIPString(IPAddress? address)
{
if (address is null)
{
@ -252,10 +252,10 @@ namespace MediaBrowser.Common.Net
/// </summary>
/// <param name="host">Host name to parse.</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="isIpv6Enabled"><c>true</c> if IPv6 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>
/// <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))
{
@ -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<IPAddress>();
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));
}
}
}

View file

@ -13,10 +13,10 @@ namespace MediaBrowser.Model.Dlna
public Dictionary<string, string> 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; }
}
}

View file

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

View file

@ -33,13 +33,13 @@ namespace Rssdp.Infrastructure
/// <summary>
/// Sends a message to a particular address (uni or multicast) and port.
/// </summary>
Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken);
Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIPAddress, CancellationToken cancellationToken);
/// <summary>
/// Sends a message to the SSDP multicast address and port.
/// </summary>
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);
/// <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.

View file

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

View file

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

View file

@ -155,7 +155,7 @@ namespace Rssdp.Infrastructure
/// <summary>
/// Sends a message to a particular address (uni or multicast) and port.
/// </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)
{
@ -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<Socket> GetSendSockets(IPAddress fromLocalIpAddress, IPEndPoint destination)
private List<Socket> 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);
}
/// <summary>
/// Sends a message to the SSDP multicast address and port.
/// </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)
{
@ -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
});
}
}

View file

@ -240,7 +240,7 @@ namespace Rssdp.Infrastructure
/// Raises the <see cref="DeviceAvailable"/> event.
/// </summary>
/// <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)
{
@ -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)

View file

@ -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);
}
}

View file

@ -97,7 +97,7 @@ namespace Jellyfin.Networking.Tests
/// Checks if IPv4 address is within a defined subnet.
/// </summary>
/// <param name="netMask">Network mask.</param>
/// <param name="ipAddress">IP Address.</param>
/// <param name="IPAddress">IP Address.</param>
[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<NetworkManager>());
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<NetworkManager>());
Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIp)), denied);
Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIP)), denied);
}
[Theory]