internal static void CheckValidToken(StringSegment value, string parameterName) { if (StringSegment.IsNullOrEmpty(value)) { throw new ArgumentException("An empty string is not allowed.", parameterName); } if (ProtoRuleParser.GetTokenLength(value, 0) != value.Length) { throw new FormatException(string.Format(CultureInfo.InvariantCulture, "Invalid token '{0}.", value)); } }
private static int GetNameValueLength(StringSegment input, int startIndex, out NameValueHeaderValue parsedValue) { Contract.Requires(input != null); Contract.Requires(startIndex >= 0); parsedValue = null; if (StringSegment.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return(0); } // Parse the name, i.e. <name> in name/value string "<name>=<value>". Caller must remove // leading whitespaces. var nameLength = ProtoRuleParser.GetTokenLength(input, startIndex); if (nameLength == 0) { return(0); } var name = input.Subsegment(startIndex, nameLength); var current = startIndex + nameLength; current = current + ProtoRuleParser.GetWhitespaceLength(input, current); // Parse the separator between name and value if ((current == input.Length) || (input[current] != '=')) { // We only have a name and that's OK. Return. parsedValue = new NameValueHeaderValue(); parsedValue._name = name; current = current + ProtoRuleParser.GetWhitespaceLength(input, current); // skip whitespaces return(current - startIndex); } current++; // skip delimiter. current = current + ProtoRuleParser.GetWhitespaceLength(input, current); // Parse the value, i.e. <value> in name/value string "<name>=<value>" int valueLength = GetValueLength(input, current); // Value after the '=' may be empty // Use parameterless ctor to avoid double-parsing of name and value, i.e. skip public ctor validation. parsedValue = new NameValueHeaderValue(); parsedValue._name = name; parsedValue._value = input.Subsegment(current, valueLength); current = current + valueLength; current = current + ProtoRuleParser.GetWhitespaceLength(input, current); // skip whitespaces return(current - startIndex); }
private static int GetMediaTypeExpressionLength(StringSegment input, int startIndex, out StringSegment mediaType) { Contract.Requires((input != null) && (input.Length > 0) && (startIndex < input.Length)); // This method just parses the "type/subtype" string, it does not parse parameters. mediaType = null; // Parse the type, i.e. <type> in media type string "<type>/<subtype>; param1=value1; param2=value2" var typeLength = ProtoRuleParser.GetTokenLength(input, startIndex); if (typeLength == 0) { return(0); } var current = startIndex + typeLength; current = current + ProtoRuleParser.GetWhitespaceLength(input, current); // Parse the separator between type and subtype if ((current >= input.Length) || (input[current] != '/')) { return(0); } current++; // skip delimiter. current = current + ProtoRuleParser.GetWhitespaceLength(input, current); // Parse the subtype, i.e. <subtype> in media type string "<type>/<subtype>; param1=value1; param2=value2" var subtypeLength = ProtoRuleParser.GetTokenLength(input, current); if (subtypeLength == 0) { return(0); } // If there is no whitespace between <type> and <subtype> in <type>/<subtype> get the media type using // one Substring call. Otherwise get substrings for <type> and <subtype> and combine them. var mediaTypeLength = current + subtypeLength - startIndex; if (typeLength + subtypeLength + 1 == mediaTypeLength) { mediaType = input.Subsegment(startIndex, mediaTypeLength); } else { mediaType = input.Substring(startIndex, typeLength) + ForwardSlashCharacter + input.Substring(current, subtypeLength); } return(mediaTypeLength); }
private static int GetRangeLength(StringSegment input, int startIndex, out RangeHeaderValue parsedValue) { Contract.Requires(startIndex >= 0); parsedValue = null; if (StringSegment.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return(0); } // Parse the unit string: <unit> in '<unit>=<from1>-<to1>, <from2>-<to2>' var unitLength = ProtoRuleParser.GetTokenLength(input, startIndex); if (unitLength == 0) { return(0); } RangeHeaderValue result = new RangeHeaderValue(); result._unit = input.Subsegment(startIndex, unitLength); var current = startIndex + unitLength; current = current + ProtoRuleParser.GetWhitespaceLength(input, current); if ((current == input.Length) || (input[current] != '=')) { return(0); } current++; // skip '=' separator current = current + ProtoRuleParser.GetWhitespaceLength(input, current); var rangesLength = RangeItemHeaderValue.GetRangeItemListLength(input, current, result.Ranges); if (rangesLength == 0) { return(0); } current = current + rangesLength; Contract.Assert(current == input.Length, "GetRangeItemListLength() should consume the whole string or fail."); parsedValue = result; return(current - startIndex); }
private static int GetStringWithQualityLength(StringSegment input, int startIndex, out StringWithQualityHeaderValue parsedValue) { Contract.Requires(startIndex >= 0); parsedValue = null; if (StringSegment.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return(0); } // Parse the value string: <value> in '<value>; q=<quality>' var valueLength = ProtoRuleParser.GetTokenLength(input, startIndex); if (valueLength == 0) { return(0); } StringWithQualityHeaderValue result = new StringWithQualityHeaderValue(); result._value = input.Subsegment(startIndex, valueLength); var current = startIndex + valueLength; current = current + ProtoRuleParser.GetWhitespaceLength(input, current); if ((current == input.Length) || (input[current] != ';')) { parsedValue = result; return(current - startIndex); // we have a valid token, but no quality. } current++; // skip ';' separator current = current + ProtoRuleParser.GetWhitespaceLength(input, current); // If we found a ';' separator, it must be followed by a quality information if (!TryReadQuality(input, result, ref current)) { return(0); } parsedValue = result; return(current - startIndex); }
/// <summary> /// Try to find a target header value among the set of given header values and parse it as a /// <see cref="TimeSpan"/>. /// </summary> /// <param name="headerValues"> /// The <see cref="StringValues"/> containing the set of header values to search. /// </param> /// <param name="targetValue"> /// The target header value to look for. /// </param> /// <param name="value"> /// When this method returns, contains the parsed <see cref="TimeSpan"/>, if the parsing succeeded, or /// null if the parsing failed. The conversion fails if the <paramref name="targetValue"/> was not /// found or could not be parsed as a <see cref="TimeSpan"/>. This parameter is passed uninitialized; /// any value originally supplied in result will be overwritten. /// </param> /// <returns> /// <code>true</code> if <paramref name="targetValue"/> is found and successfully parsed; otherwise, /// <code>false</code>. /// </returns> // e.g. { "headerValue=10, targetHeaderValue=30" } public static bool TryParseSeconds(StringValues headerValues, string targetValue, out TimeSpan?value) { if (StringValues.IsNullOrEmpty(headerValues) || string.IsNullOrEmpty(targetValue)) { value = null; return(false); } for (var i = 0; i < headerValues.Count; i++) { // Trim leading white space var current = ProtoRuleParser.GetWhitespaceLength(headerValues[i], 0); while (current < headerValues[i].Length) { long seconds; var initial = current; var tokenLength = ProtoRuleParser.GetTokenLength(headerValues[i], current); if (tokenLength == targetValue.Length && string.Compare(headerValues[i], current, targetValue, 0, tokenLength, StringComparison.OrdinalIgnoreCase) == 0 && TryParseNonNegativeInt64FromHeaderValue(current + tokenLength, headerValues[i], out seconds)) { // Token matches target value and seconds were parsed value = TimeSpan.FromSeconds(seconds); return(true); } current = AdvanceCacheDirectiveIndex(current + tokenLength, headerValues[i]); // Ensure index was advanced if (current <= initial) { Debug.Assert(false, $"Index '{nameof(current)}' not advanced, this is a bug."); value = null; return(false); } } } value = null; return(false); }
internal static int GetValueLength(StringSegment input, int startIndex) { Contract.Requires(input != null); if (startIndex >= input.Length) { return(0); } var valueLength = ProtoRuleParser.GetTokenLength(input, startIndex); if (valueLength == 0) { // A value can either be a token or a quoted string. Check if it is a quoted string. if (ProtoRuleParser.GetQuotedStringLength(input, startIndex, out valueLength) != ProtoParseResult.Parsed) { // We have an invalid value. Reset the name and return. return(0); } } return(valueLength); }
/// <summary> /// Check if a target directive exists among the set of given cache control directives. /// </summary> /// <param name="cacheControlDirectives"> /// The <see cref="StringValues"/> containing the set of cache control directives. /// </param> /// <param name="targetDirectives"> /// The target cache control directives to look for. /// </param> /// <returns> /// <code>true</code> if <paramref name="targetDirectives"/> is contained in <paramref name="cacheControlDirectives"/>; /// otherwise, <code>false</code>. /// </returns> public static bool ContainsCacheDirective(StringValues cacheControlDirectives, string targetDirectives) { if (StringValues.IsNullOrEmpty(cacheControlDirectives) || string.IsNullOrEmpty(targetDirectives)) { return(false); } for (var i = 0; i < cacheControlDirectives.Count; i++) { // Trim leading white space var current = ProtoRuleParser.GetWhitespaceLength(cacheControlDirectives[i], 0); while (current < cacheControlDirectives[i].Length) { var initial = current; var tokenLength = ProtoRuleParser.GetTokenLength(cacheControlDirectives[i], current); if (tokenLength == targetDirectives.Length && string.Compare(cacheControlDirectives[i], current, targetDirectives, 0, tokenLength, StringComparison.OrdinalIgnoreCase) == 0) { // Token matches target value return(true); } current = AdvanceCacheDirectiveIndex(current + tokenLength, cacheControlDirectives[i]); // Ensure index was advanced if (current <= initial) { Debug.Assert(false, $"Index '{nameof(current)}' not advanced, this is a bug."); return(false); } } } return(false); }
// name=value; expires=Sun, 06 Nov 1994 08:49:37 GMT; max-age=86400; domain=domain1; path=path1; secure; samesite={Strict|Lax}; httponly private static int GetSetCookieLength(StringSegment input, int startIndex, out SetCookieHeaderValue parsedValue) { Contract.Requires(startIndex >= 0); var offset = startIndex; parsedValue = null; if (StringSegment.IsNullOrEmpty(input) || (offset >= input.Length)) { return(0); } var result = new SetCookieHeaderValue(); // The caller should have already consumed any leading whitespace, commas, etc.. // Name=value; // Name var itemLength = ProtoRuleParser.GetTokenLength(input, offset); if (itemLength == 0) { return(0); } result._name = input.Subsegment(offset, itemLength); offset += itemLength; // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return(0); } // value or "quoted value" // The value may be empty result._value = CookieHeaderValue.GetCookieValue(input, ref offset); // *(';' SP cookie-av) while (offset < input.Length) { if (input[offset] == ',') { // Divider between headers break; } if (input[offset] != ';') { // Expecting a ';' between parameters return(0); } offset++; offset += ProtoRuleParser.GetWhitespaceLength(input, offset); // cookie-av = expires-av / max-age-av / domain-av / path-av / secure-av / samesite-av / httponly-av / extension-av itemLength = ProtoRuleParser.GetTokenLength(input, offset); if (itemLength == 0) { // Trailing ';' or leading into garbage. Let the next parser fail. break; } var token = input.Subsegment(offset, itemLength); offset += itemLength; // expires-av = "Expires=" sane-cookie-date if (StringSegment.Equals(token, ExpiresToken, StringComparison.OrdinalIgnoreCase)) { // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return(0); } var dateString = ReadToSemicolonOrEnd(input, ref offset); DateTimeOffset expirationDate; if (!ProtoRuleParser.TryStringToDate(dateString, out expirationDate)) { // Invalid expiration date, abort return(0); } result.Expires = expirationDate; } // max-age-av = "Max-Age=" non-zero-digit *DIGIT else if (StringSegment.Equals(token, MaxAgeToken, StringComparison.OrdinalIgnoreCase)) { // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return(0); } itemLength = ProtoRuleParser.GetNumberLength(input, offset, allowDecimal: false); if (itemLength == 0) { return(0); } var numberString = input.Subsegment(offset, itemLength); long maxAge; if (!HeaderUtilities.TryParseNonNegativeInt64(numberString, out maxAge)) { // Invalid expiration date, abort return(0); } result.MaxAge = TimeSpan.FromSeconds(maxAge); offset += itemLength; } // domain-av = "Domain=" domain-value // domain-value = <subdomain> ; defined in [RFC1034], Section 3.5, as enhanced by [RFC1123], Section 2.1 else if (StringSegment.Equals(token, DomainToken, StringComparison.OrdinalIgnoreCase)) { // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return(0); } // We don't do any detailed validation on the domain. result.Domain = ReadToSemicolonOrEnd(input, ref offset); } // path-av = "Path=" path-value // path-value = <any CHAR except CTLs or ";"> else if (StringSegment.Equals(token, PathToken, StringComparison.OrdinalIgnoreCase)) { // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return(0); } // We don't do any detailed validation on the path. result.Path = ReadToSemicolonOrEnd(input, ref offset); } // secure-av = "Secure" else if (StringSegment.Equals(token, SecureToken, StringComparison.OrdinalIgnoreCase)) { result.Secure = true; } // samesite-av = "SameSite" / "SameSite=" samesite-value // samesite-value = "Strict" / "Lax" else if (StringSegment.Equals(token, SameSiteToken, StringComparison.OrdinalIgnoreCase)) { if (!ReadEqualsSign(input, ref offset)) { result.SameSite = SameSiteMode.Strict; } else { var enforcementMode = ReadToSemicolonOrEnd(input, ref offset); if (StringSegment.Equals(enforcementMode, SameSiteLaxToken, StringComparison.OrdinalIgnoreCase)) { result.SameSite = SameSiteMode.Lax; } else { result.SameSite = SameSiteMode.Strict; } } } // httponly-av = "ProtoOnly" else if (StringSegment.Equals(token, ProtoOnlyToken, StringComparison.OrdinalIgnoreCase)) { result.ProtoOnly = true; } // extension-av = <any CHAR except CTLs or ";"> else { // TODO: skiping it for now to avoid parsing failure? Store it in a list? // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return(0); } ReadToSemicolonOrEnd(input, ref offset); } } parsedValue = result; return(offset - startIndex); }