Repository navigation
Expand file tree
/
Copy pathRouteParser.cs
More file actions
375 lines (321 loc) · 15.2 KB
/
Copy pathRouteParser.cs
File metadata and controls
375 lines (321 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
#if ASPNETWEBAPI
using ErrorResources = System.Web.Http.Properties.SRResources;
using TParsedRoute = System.Web.Http.Routing.HttpParsedRoute;
#else
using ErrorResources = System.Web.Mvc.Properties.MvcResources;
using TParsedRoute = System.Web.Mvc.Routing.ParsedRoute;
#endif
#if ASPNETWEBAPI
namespace System.Web.Http.Routing
#else
namespace System.Web.Mvc.Routing
#endif
{
// in the MVC case, route parsing is done for AttributeRouting's sake, so that
// it could order the discovered routes before pushing them into the routeCollection,
// where, unfortunately, they would be parsed again.
internal static class RouteParser
{
private static string GetLiteral(string segmentLiteral)
{
// Scan for errant single { and } and convert double {{ to { and double }} to }
// First we eliminate all escaped braces and then check if any other braces are remaining
string newLiteral = segmentLiteral.Replace("{{", String.Empty).Replace("}}", String.Empty);
if (newLiteral.Contains("{") || newLiteral.Contains("}"))
{
return null;
}
// If it's a valid format, we unescape the braces
return segmentLiteral.Replace("{{", "{").Replace("}}", "}");
}
private static int IndexOfFirstOpenParameter(string segment, int startIndex)
{
// Find the first unescaped open brace
while (true)
{
startIndex = segment.IndexOf('{', startIndex);
if (startIndex == -1)
{
// If there are no more open braces, stop
return -1;
}
if ((startIndex + 1 == segment.Length) ||
((startIndex + 1 < segment.Length) && (segment[startIndex + 1] != '{')))
{
// If we found an open brace that is followed by a non-open brace, it's
// a parameter delimiter.
// It's also a delimiter if the open brace is the last character - though
// it ends up being being called out as invalid later on.
return startIndex;
}
// Increment by two since we want to skip both the open brace that
// we're on as well as the subsequent character since we know for
// sure that it is part of an escape sequence.
startIndex += 2;
}
}
internal static bool IsSeparator(string s)
{
return String.Equals(s, "/", StringComparison.Ordinal);
}
private static bool IsValidParameterName(string parameterName)
{
if (parameterName.Length == 0)
{
return false;
}
for (int i = 0; i < parameterName.Length; i++)
{
char c = parameterName[i];
if (c == '/' || c == '{' || c == '}')
{
return false;
}
}
return true;
}
internal static bool IsInvalidRouteTemplate(string routeTemplate)
{
return routeTemplate.StartsWith("~", StringComparison.Ordinal) ||
routeTemplate.StartsWith("/", StringComparison.Ordinal) ||
(routeTemplate.IndexOf('?') != -1);
}
public static TParsedRoute Parse(string routeTemplate)
{
if (routeTemplate == null)
{
routeTemplate = String.Empty;
}
if (IsInvalidRouteTemplate(routeTemplate))
{
throw Error.Argument("routeTemplate", ErrorResources.Route_InvalidRouteTemplate);
}
List<string> uriParts = SplitUriToPathSegmentStrings(routeTemplate);
Exception ex = ValidateUriParts(uriParts);
if (ex != null)
{
throw ex;
}
List<PathSegment> pathSegments = SplitUriToPathSegments(uriParts);
Contract.Assert(uriParts.Count == pathSegments.Count, "The number of string segments should be the same as the number of path segments");
return new TParsedRoute(pathSegments);
}
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly",
Justification = "The exceptions are just constructed here, but they are thrown from a method that does have those parameter names.")]
private static List<PathSubsegment> ParseUriSegment(string segment, out Exception exception)
{
int startIndex = 0;
List<PathSubsegment> pathSubsegments = new List<PathSubsegment>();
while (startIndex < segment.Length)
{
int nextParameterStart = IndexOfFirstOpenParameter(segment, startIndex);
if (nextParameterStart == -1)
{
// If there are no more parameters in the segment, capture the remainder as a literal and stop
string lastLiteralPart = GetLiteral(segment.Substring(startIndex));
if (lastLiteralPart == null)
{
exception = Error.Argument("routeTemplate", ErrorResources.Route_MismatchedParameter, segment);
return null;
}
if (lastLiteralPart.Length > 0)
{
pathSubsegments.Add(new PathLiteralSubsegment(lastLiteralPart));
}
break;
}
int nextParameterEnd = segment.IndexOf('}', nextParameterStart + 1);
if (nextParameterEnd == -1)
{
exception = Error.Argument("routeTemplate", ErrorResources.Route_MismatchedParameter, segment);
return null;
}
string literalPart = GetLiteral(segment.Substring(startIndex, nextParameterStart - startIndex));
if (literalPart == null)
{
exception = Error.Argument("routeTemplate", ErrorResources.Route_MismatchedParameter, segment);
return null;
}
if (literalPart.Length > 0)
{
pathSubsegments.Add(new PathLiteralSubsegment(literalPart));
}
string parameterName = segment.Substring(nextParameterStart + 1, nextParameterEnd - nextParameterStart - 1);
pathSubsegments.Add(new PathParameterSubsegment(parameterName));
startIndex = nextParameterEnd + 1;
}
exception = null;
return pathSubsegments;
}
private static List<PathSegment> SplitUriToPathSegments(List<string> uriParts)
{
List<PathSegment> pathSegments = new List<PathSegment>();
foreach (string pathSegment in uriParts)
{
bool isCurrentPartSeparator = IsSeparator(pathSegment);
if (isCurrentPartSeparator)
{
pathSegments.Add(new PathSeparatorSegment());
}
else
{
Exception exception;
List<PathSubsegment> subsegments = ParseUriSegment(pathSegment, out exception);
Contract.Assert(exception == null, "This only gets called after the path has been validated, so there should never be an exception here");
pathSegments.Add(new PathContentSegment(subsegments));
}
}
return pathSegments;
}
internal static List<string> SplitUriToPathSegmentStrings(string uri)
{
List<string> parts = new List<string>();
if (String.IsNullOrEmpty(uri))
{
return parts;
}
int currentIndex = 0;
// Split the incoming URI into individual parts
while (currentIndex < uri.Length)
{
int indexOfNextSeparator = uri.IndexOf('/', currentIndex);
if (indexOfNextSeparator == -1)
{
// If there are no more separators, the rest of the string is the last part
string finalPart = uri.Substring(currentIndex);
if (finalPart.Length > 0)
{
parts.Add(finalPart);
}
break;
}
string nextPart = uri.Substring(currentIndex, indexOfNextSeparator - currentIndex);
if (nextPart.Length > 0)
{
parts.Add(nextPart);
}
Contract.Assert(uri[indexOfNextSeparator] == '/', "The separator char itself should always be a '/'.");
parts.Add("/");
currentIndex = indexOfNextSeparator + 1;
}
return parts;
}
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Not changing original algorithm")]
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly",
Justification = "The exceptions are just constructed here, but they are thrown from a method that does have those parameter names.")]
private static Exception ValidateUriParts(List<string> pathSegments)
{
Contract.Assert(pathSegments != null, "The value should always come from SplitUri(), and that function should never return null.");
HashSet<string> usedParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
bool? isPreviousPartSeparator = null;
bool foundCatchAllParameter = false;
foreach (string pathSegment in pathSegments)
{
if (foundCatchAllParameter)
{
// If we ever start an iteration of the loop and we've already found a
// catchall parameter then we have an invalid URI format.
return Error.Argument("routeTemplate", ErrorResources.Route_CatchAllMustBeLast, "routeTemplate");
}
bool isCurrentPartSeparator;
if (isPreviousPartSeparator == null)
{
// Prime the loop with the first value
isPreviousPartSeparator = IsSeparator(pathSegment);
isCurrentPartSeparator = isPreviousPartSeparator.Value;
}
else
{
isCurrentPartSeparator = IsSeparator(pathSegment);
// If both the previous part and the current part are separators, it's invalid
if (isCurrentPartSeparator && isPreviousPartSeparator.Value)
{
return Error.Argument("routeTemplate", ErrorResources.Route_CannotHaveConsecutiveSeparators);
}
Contract.Assert(isCurrentPartSeparator != isPreviousPartSeparator.Value, "This assert should only happen if both the current and previous parts are non-separators. This should never happen because consecutive non-separators are always parsed as a single part.");
isPreviousPartSeparator = isCurrentPartSeparator;
}
// If it's not a separator, parse the segment for parameters and validate it
if (!isCurrentPartSeparator)
{
Exception exception;
List<PathSubsegment> subsegments = ParseUriSegment(pathSegment, out exception);
if (exception != null)
{
return exception;
}
exception = ValidateUriSegment(subsegments, usedParameterNames);
if (exception != null)
{
return exception;
}
foundCatchAllParameter = subsegments.Any<PathSubsegment>(seg => (seg is PathParameterSubsegment) && ((PathParameterSubsegment)seg).IsCatchAll);
}
}
return null;
}
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly",
Justification = "The exceptions are just constructed here, but they are thrown from a method that does have those parameter names.")]
private static Exception ValidateUriSegment(List<PathSubsegment> pathSubsegments, HashSet<string> usedParameterNames)
{
bool segmentContainsCatchAll = false;
Type previousSegmentType = null;
foreach (PathSubsegment subsegment in pathSubsegments)
{
if (previousSegmentType != null)
{
if (previousSegmentType == subsegment.GetType())
{
return Error.Argument("routeTemplate", ErrorResources.Route_CannotHaveConsecutiveParameters);
}
}
previousSegmentType = subsegment.GetType();
PathLiteralSubsegment literalSubsegment = subsegment as PathLiteralSubsegment;
if (literalSubsegment != null)
{
// Nothing to validate for literals - everything is valid
}
else
{
PathParameterSubsegment parameterSubsegment = subsegment as PathParameterSubsegment;
if (parameterSubsegment != null)
{
string parameterName = parameterSubsegment.ParameterName;
if (parameterSubsegment.IsCatchAll)
{
segmentContainsCatchAll = true;
}
// Check for valid characters in the parameter name
if (!IsValidParameterName(parameterName))
{
return Error.Argument("routeTemplate", ErrorResources.Route_InvalidParameterName, parameterName);
}
if (usedParameterNames.Contains(parameterName))
{
return Error.Argument("routeTemplate", ErrorResources.Route_RepeatedParameter, parameterName);
}
else
{
usedParameterNames.Add(parameterName);
}
}
else
{
Contract.Assert(false, "Invalid path subsegment type");
}
}
}
if (segmentContainsCatchAll && (pathSubsegments.Count != 1))
{
return Error.Argument("routeTemplate", ErrorResources.Route_CannotHaveCatchAllInMultiSegment);
}
return null;
}
}
}