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
|
namespace System.Web.Routing {
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
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("{{", "").Replace("}}", "");
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 IsInvalidRouteUrl(string routeUrl) {
return (routeUrl.StartsWith("~", StringComparison.Ordinal) ||
routeUrl.StartsWith("/", StringComparison.Ordinal) ||
(routeUrl.IndexOf('?') != -1));
}
public static ParsedRoute Parse(string routeUrl) {
if (routeUrl == null) {
routeUrl = String.Empty;
}
if (IsInvalidRouteUrl(routeUrl)) {
throw new ArgumentException(SR.GetString(SR.Route_InvalidRouteUrl), "routeUrl");
}
IList<string> urlParts = SplitUrlToPathSegmentStrings(routeUrl);
Exception ex = ValidateUrlParts(urlParts);
if (ex != null) {
throw ex;
}
IList<PathSegment> pathSegments = SplitUrlToPathSegments(urlParts);
Debug.Assert(urlParts.Count == pathSegments.Count, "The number of string segments should be the same as the number of path segments");
return new ParsedRoute(pathSegments);
}
[System.Diagnostics.CodeAnalysis.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 IList<PathSubsegment> ParseUrlSegment(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 = new ArgumentException(
String.Format(
CultureInfo.CurrentUICulture,
SR.GetString(SR.Route_MismatchedParameter),
segment
),
"routeUrl");
return null;
}
if (lastLiteralPart.Length > 0) {
pathSubsegments.Add(new LiteralSubsegment(lastLiteralPart));
}
break;
}
int nextParameterEnd = segment.IndexOf('}', nextParameterStart + 1);
if (nextParameterEnd == -1) {
exception = new ArgumentException(
String.Format(
CultureInfo.CurrentUICulture,
SR.GetString(SR.Route_MismatchedParameter),
segment
),
"routeUrl");
return null;
}
string literalPart = GetLiteral(segment.Substring(startIndex, nextParameterStart - startIndex));
if (literalPart == null) {
exception = new ArgumentException(
String.Format(
CultureInfo.CurrentUICulture,
SR.GetString(SR.Route_MismatchedParameter),
segment
),
"routeUrl");
return null;
}
if (literalPart.Length > 0) {
pathSubsegments.Add(new LiteralSubsegment(literalPart));
}
string parameterName = segment.Substring(nextParameterStart + 1, nextParameterEnd - nextParameterStart - 1);
pathSubsegments.Add(new ParameterSubsegment(parameterName));
startIndex = nextParameterEnd + 1;
}
exception = null;
return pathSubsegments;
}
private static IList<PathSegment> SplitUrlToPathSegments(IList<string> urlParts) {
List<PathSegment> pathSegments = new List<PathSegment>();
foreach (string pathSegment in urlParts) {
bool isCurrentPartSeparator = IsSeparator(pathSegment);
if (isCurrentPartSeparator) {
pathSegments.Add(new SeparatorPathSegment());
}
else {
Exception exception;
IList<PathSubsegment> subsegments = ParseUrlSegment(pathSegment, out exception);
Debug.Assert(exception == null, "This only gets called after the path has been validated, so there should never be an exception here");
pathSegments.Add(new ContentPathSegment(subsegments));
}
}
return pathSegments;
}
internal static IList<string> SplitUrlToPathSegmentStrings(string url) {
List<string> parts = new List<string>();
if (String.IsNullOrEmpty(url)) {
return parts;
}
int currentIndex = 0;
// Split the incoming URL into individual parts
while (currentIndex < url.Length) {
int indexOfNextSeparator = url.IndexOf('/', currentIndex);
if (indexOfNextSeparator == -1) {
// If there are no more separators, the rest of the string is the last part
string finalPart = url.Substring(currentIndex);
if (finalPart.Length > 0) {
parts.Add(finalPart);
}
break;
}
string nextPart = url.Substring(currentIndex, indexOfNextSeparator - currentIndex);
if (nextPart.Length > 0) {
parts.Add(nextPart);
}
Debug.Assert(url[indexOfNextSeparator] == '/', "The separator char itself should always be a '/'.");
parts.Add("/");
currentIndex = indexOfNextSeparator + 1;
}
return parts;
}
[System.Diagnostics.CodeAnalysis.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 ValidateUrlParts(IList<string> pathSegments) {
Debug.Assert(pathSegments != null, "The value should always come from SplitUrl(), 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 URL format.
return new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
SR.GetString(SR.Route_CatchAllMustBeLast)
),
"routeUrl");
}
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 new ArgumentException(SR.GetString(SR.Route_CannotHaveConsecutiveSeparators), "routeUrl");
}
Debug.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;
IList<PathSubsegment> subsegments = ParseUrlSegment(pathSegment, out exception);
if (exception != null) {
return exception;
}
exception = ValidateUrlSegment(subsegments, usedParameterNames, pathSegment);
if (exception != null) {
return exception;
}
foundCatchAllParameter = subsegments.Any<PathSubsegment>(seg => (seg is ParameterSubsegment) && (((ParameterSubsegment)seg).IsCatchAll));
}
}
return null;
}
[System.Diagnostics.CodeAnalysis.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 ValidateUrlSegment(IList<PathSubsegment> pathSubsegments, HashSet<string> usedParameterNames, string pathSegment) {
bool segmentContainsCatchAll = false;
Type previousSegmentType = null;
foreach (PathSubsegment subsegment in pathSubsegments) {
if (previousSegmentType != null) {
if (previousSegmentType == subsegment.GetType()) {
return new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
SR.GetString(SR.Route_CannotHaveConsecutiveParameters)
),
"routeUrl");
}
}
previousSegmentType = subsegment.GetType();
LiteralSubsegment literalSubsegment = subsegment as LiteralSubsegment;
if (literalSubsegment != null) {
// Nothing to validate for literals - everything is valid
}
else {
ParameterSubsegment parameterSubsegment = subsegment as ParameterSubsegment;
if (parameterSubsegment != null) {
string parameterName = parameterSubsegment.ParameterName;
if (parameterSubsegment.IsCatchAll) {
segmentContainsCatchAll = true;
}
// Check for valid characters in the parameter name
if (!IsValidParameterName(parameterName)) {
return new ArgumentException(
String.Format(
CultureInfo.CurrentUICulture,
SR.GetString(SR.Route_InvalidParameterName),
parameterName
),
"routeUrl");
}
if (usedParameterNames.Contains(parameterName)) {
return new ArgumentException(
String.Format(
CultureInfo.CurrentUICulture,
SR.GetString(SR.Route_RepeatedParameter),
parameterName
),
"routeUrl");
}
else {
usedParameterNames.Add(parameterName);
}
}
else {
Debug.Fail("Invalid path subsegment type");
}
}
}
if (segmentContainsCatchAll && (pathSubsegments.Count != 1)) {
return new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
SR.GetString(SR.Route_CannotHaveCatchAllInMultiSegment)
),
"routeUrl");
}
return null;
}
}
}
|