| | | 1 | | /******************************************************************************** |
| | | 2 | | * QueryStringParser.cs * |
| | | 3 | | * * |
| | | 4 | | * Author: Denes Solti * |
| | | 5 | | ********************************************************************************/ |
| | | 6 | | using System; |
| | | 7 | | using System.Buffers; |
| | | 8 | | using System.Collections.Generic; |
| | | 9 | | using System.Diagnostics.CodeAnalysis; |
| | | 10 | | using System.Net; |
| | | 11 | | using System.Net.Http; |
| | | 12 | | using System.Threading.Tasks; |
| | | 13 | | |
| | | 14 | | namespace NanoRoute.Internals |
| | | 15 | | { |
| | | 16 | | using Properties; |
| | | 17 | | |
| | 1 | 18 | | internal sealed class QueryStringParser(RequestContext context, IReadOnlyDictionary<ReadOnlyMemory<char>, ParameterP |
| | | 19 | | { |
| | | 20 | | #region Private |
| | 1 | 21 | | private static readonly ArrayPool<char> s_arrayPool = ArrayPool<char>.Create(); |
| | | 22 | | |
| | 1 | 23 | | private readonly ReadOnlyMemory<char> _query = GetRawQuery(context.Request.RequestUri); |
| | | 24 | | |
| | | 25 | | private char[]? _decodedBuffer; |
| | | 26 | | |
| | | 27 | | // Track only query parameters seen during this parse so required checks and duplicate detection |
| | | 28 | | // will not be confused by values that were already present in context.Parameters. |
| | 1 | 29 | | private readonly bool[] _visited = new bool[expectedParameters.Count]; |
| | | 30 | | |
| | | 31 | | // DelimitedSegment is a mutable struct: keep this field non-readonly so MoveNext() updates the _parameter |
| | | 32 | | // itself instead of a defensive copy. |
| | 1 | 33 | | private DelimitedSegment _parameter = new(GetRawQuery(context.Request.RequestUri), '&'); |
| | | 34 | | |
| | | 35 | | private int _nextDecoded; |
| | | 36 | | |
| | | 37 | | // Keep Parse() state-machine-free while all query value parsers complete synchronously. |
| | | 38 | | // If a parser really suspends, this helper resumes the current parameter and finishes the loop. |
| | | 39 | | private async ValueTask ParseAwaitedAsync(ParameterParser expectedParameter, ValueTask<ValueParseResult> parseRe |
| | | 40 | | { |
| | | 41 | | AcceptParameter(expectedParameter.Definition, await parseResult); |
| | | 42 | | await Parse(); |
| | | 43 | | } |
| | | 44 | | |
| | | 45 | | private void AcceptParameter(ParameterDefinition parameterDefinition, ValueParseResult parseResult) |
| | 1 | 46 | | { |
| | 1 | 47 | | if (!parseResult.Success) |
| | 1 | 48 | | ThrowBadRequest(Resources.ERR_QUERY_INVALID_PARAMETER, parameterDefinition.ParameterName!); |
| | | 49 | | |
| | 1 | 50 | | context.Parameters[parameterDefinition.ParameterName!] = parseResult.Parsed; |
| | 1 | 51 | | } |
| | | 52 | | |
| | | 53 | | private ReadOnlyMemory<char> DecodeParameter(ReadOnlyMemory<char> source) |
| | 1 | 54 | | { |
| | 1 | 55 | | if (source.Span.IndexOfAny('%', '+') < 0) |
| | 1 | 56 | | return source; |
| | | 57 | | |
| | 1 | 58 | | char[] decodedBuffer = _decodedBuffer ??= s_arrayPool.Rent(_query.Length); |
| | | 59 | | |
| | 1 | 60 | | if (!UrlUtils.TryDecodeUrl(source.Span, decodedBuffer.AsSpan(_nextDecoded), UrlDecodeMode.Form, out int char |
| | 1 | 61 | | ThrowBadRequest(Resources.ERR_DECODING_FAILED); |
| | | 62 | | |
| | 1 | 63 | | ReadOnlyMemory<char> result = decodedBuffer.AsMemory(_nextDecoded, charsWritten); |
| | 1 | 64 | | _nextDecoded += charsWritten; |
| | | 65 | | |
| | 1 | 66 | | return result; |
| | 1 | 67 | | } |
| | | 68 | | |
| | | 69 | | private static ReadOnlyMemory<char> GetRawQuery(Uri uri) |
| | 1 | 70 | | { |
| | 1 | 71 | | ReadOnlyMemory<char> raw = uri.OriginalString.AsMemory(); |
| | | 72 | | |
| | 1 | 73 | | int fragmentIndex = raw.Span.IndexOf('#'); |
| | 1 | 74 | | if (fragmentIndex >= 0) |
| | 1 | 75 | | raw = raw.Slice(0, fragmentIndex); |
| | | 76 | | |
| | 1 | 77 | | int queryIndex = raw.Span.IndexOf('?'); |
| | 1 | 78 | | return queryIndex >= 0 |
| | 1 | 79 | | ? raw.Slice(queryIndex + 1) |
| | 1 | 80 | | : default; |
| | 1 | 81 | | } |
| | | 82 | | |
| | | 83 | | [DoesNotReturn] |
| | 1 | 84 | | private static void ThrowBadRequest(string? error, params object[] paramz) => HttpRequestException.Throw |
| | 1 | 85 | | ( |
| | 1 | 86 | | HttpStatusCode.BadRequest, |
| | 1 | 87 | | Resources.ERR_BAD_REQUEST, |
| | 1 | 88 | | !string.IsNullOrEmpty(error) ? [string.Format(Resources.Culture, error, paramz)] : [] |
| | 1 | 89 | | ); |
| | | 90 | | #endregion |
| | | 91 | | |
| | | 92 | | public void Dispose() |
| | 1 | 93 | | { |
| | 1 | 94 | | if (_decodedBuffer is not null) |
| | 1 | 95 | | s_arrayPool.Return(_decodedBuffer, clearArray: false); |
| | 1 | 96 | | } |
| | | 97 | | |
| | | 98 | | public ValueTask Parse() |
| | 1 | 99 | | { |
| | 1 | 100 | | while (_parameter.MoveNext()) |
| | 1 | 101 | | { |
| | 1 | 102 | | int separatorIndex = _parameter.Current.Span.IndexOf('='); |
| | 1 | 103 | | if (separatorIndex <= 0) |
| | 1 | 104 | | ThrowBadRequest(null); |
| | | 105 | | |
| | 1 | 106 | | ReadOnlyMemory<char> parameterName = DecodeParameter(_parameter.Current.Slice(0, separatorIndex)); |
| | | 107 | | |
| | 1 | 108 | | if (!expectedParameters.TryGetValue(parameterName, out ParameterParser? expectedParameter)) |
| | 1 | 109 | | continue; |
| | | 110 | | |
| | 1 | 111 | | ParameterDefinition parameterDefinition = expectedParameter.Definition; |
| | | 112 | | |
| | 1 | 113 | | if (_visited[parameterDefinition.Index]) |
| | 1 | 114 | | ThrowBadRequest(Resources.ERR_QUERY_DUPLICATE_PARAMETER, parameterDefinition.ParameterName!); |
| | | 115 | | |
| | 1 | 116 | | _visited[parameterDefinition.Index] = true; |
| | | 117 | | |
| | 1 | 118 | | ValueTask<ValueParseResult> parseResult = expectedParameter.Parse |
| | 1 | 119 | | ( |
| | 1 | 120 | | new ValueParserContext |
| | 1 | 121 | | { |
| | 1 | 122 | | Segment = DecodeParameter(_parameter.Current.Slice(separatorIndex + 1)), |
| | 1 | 123 | | Services = context.Services, |
| | 1 | 124 | | Arguments = expectedParameter.Arguments, |
| | 1 | 125 | | Cancellation = context.Cancellation |
| | 1 | 126 | | } |
| | 1 | 127 | | ); |
| | | 128 | | |
| | 1 | 129 | | if (!parseResult.IsCompletedSuccessfully) |
| | 1 | 130 | | return ParseAwaitedAsync(expectedParameter, parseResult); |
| | | 131 | | |
| | 1 | 132 | | AcceptParameter(parameterDefinition, parseResult.Result); |
| | 1 | 133 | | } |
| | | 134 | | |
| | | 135 | | // FrozenDictionary uses ImmutableArray to access Values so accessing this property is a relative fast opera |
| | | 136 | | // https://learn.microsoft.com/en-us/dotnet/api/system.collections.frozen.frozendictionary-2.values?view=net |
| | 1 | 137 | | foreach (ParameterParser expectedParameter in expectedParameters.Values) |
| | 1 | 138 | | { |
| | 1 | 139 | | ParameterDefinition parameterDefinition = expectedParameter.Definition; |
| | | 140 | | |
| | 1 | 141 | | if (!parameterDefinition.IsOptional && !_visited[parameterDefinition.Index]) |
| | 1 | 142 | | ThrowBadRequest(Resources.ERR_QUERY_MISSING_PARAMETER, parameterDefinition.ParameterName!); |
| | 1 | 143 | | } |
| | | 144 | | |
| | 1 | 145 | | return default; |
| | 1 | 146 | | } |
| | | 147 | | } |
| | | 148 | | } |