Skip to content

Removed bound checks in SharedUrlHelper.IsLocalUrl and use JIT unrolling for checks #61361

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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
@@ -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;
@@ -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.