Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 13 additions & 11 deletions src/Shared/ResultsHelpers/SharedUrlHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Internal;
Expand Down Expand Up @@ -32,49 +33,50 @@ internal static class SharedUrlHelper

internal static bool IsLocalUrl([NotNullWhen(true)] string? url)
{
if (string.IsNullOrEmpty(url))
var urlSpan = url.AsSpan();

if (urlSpan.IsEmpty)
{
return false;
}

// Allows "/" or "/foo" but not "//" or "/\".
if (url[0] == '/')
if (urlSpan[0] == '/')
{
// url is exactly "/"
if (url.Length == 1)
if (urlSpan.Length < 2)
{
return true;
}

// url doesn't start with "//" or "/\"
if (url[1] != '/' && url[1] != '\\')
if (urlSpan[1] is not '/' and '\\')
{
return !HasControlCharacter(url.AsSpan(1));
return !HasControlCharacter(urlSpan.Slice(1));
}

return false;
}

// Allows "~/" or "~/foo" but not "~//" or "~/\".
if (url[0] == '~' && url.Length > 1 && url[1] == '/')
if (urlSpan.StartsWith("~/"))
{
// url is exactly "~/"
if (url.Length == 2)
if (urlSpan.Length < 3)
{
return true;
}

// url doesn't start with "~//" or "~/\"
if (url[2] != '/' && url[2] != '\\')
if (urlSpan[2] is not '/' and '\\')
{
return !HasControlCharacter(url.AsSpan(2));
return !HasControlCharacter(urlSpan.Slice(2));
}

return false;
}

return false;

[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool HasControlCharacter(ReadOnlySpan<char> readOnlySpan)
{
// URLs may not contain ASCII control characters.
Expand Down
Loading