private static int GetDispositionTypeExpressionLength(StringSegment input, int startIndex, out StringSegment dispositionType) { Contract.Requires((input != null) && (input.Length > 0) && (startIndex < input.Length)); // This method just parses the disposition type string, it does not parse parameters. dispositionType = null; // Parse the disposition type, i.e. <dispositiontype> in content-disposition string // "<dispositiontype>; param1=value1; param2=value2" var typeLength = HttpRuleParser.GetTokenLength(input, startIndex); if (typeLength == 0) { return(0); } dispositionType = input.Subsegment(startIndex, typeLength); return(typeLength); }
/// <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> /// <see langword="true" /> if <paramref name="targetValue"/> is found and successfully parsed; otherwise, /// <see langword="false" />. /// </returns> // e.g. { "headerValue=10, targetHeaderValue=30" } public static bool TryParseSeconds(StringValues headerValues, string targetValue, [NotNullWhen(true)] out TimeSpan?value) { if (StringValues.IsNullOrEmpty(headerValues) || string.IsNullOrEmpty(targetValue)) { value = null; return(false); } for (var i = 0; i < headerValues.Count; i++) { var segment = headerValues[i] !; // Trim leading white space var current = HttpRuleParser.GetWhitespaceLength(segment, 0); while (current < segment.Length) { long seconds; var initial = current; var tokenLength = HttpRuleParser.GetTokenLength(headerValues[i], current); if (tokenLength == targetValue.Length && string.Compare(headerValues[i], current, targetValue, 0, tokenLength, StringComparison.OrdinalIgnoreCase) == 0 && TryParseNonNegativeInt64FromHeaderValue(current + tokenLength, segment, out seconds)) { // Token matches target value and seconds were parsed value = TimeSpan.FromSeconds(seconds); return(true); } current = AdvanceCacheDirectiveIndex(current + tokenLength, segment); // 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) { if (startIndex >= input.Length) { return(0); } var valueLength = HttpRuleParser.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 (HttpRuleParser.GetQuotedStringLength(input, startIndex, out valueLength) != HttpParseResult.Parsed) { // We have an invalid value. Reset the name and return. return(0); } } return(valueLength); }
// name=value; name="value" internal static bool TryGetCookieLength(StringSegment input, ref int offset, [NotNullWhen(true)] out CookieHeaderValue?parsedValue) { Contract.Requires(offset >= 0); parsedValue = null; if (StringSegment.IsNullOrEmpty(input) || (offset >= input.Length)) { return(false); } var result = new CookieHeaderValue(); // The caller should have already consumed any leading whitespace, commas, etc.. // Name=value; // Name var itemLength = HttpRuleParser.GetTokenLength(input, offset); if (itemLength == 0) { return(false); } result._name = input.Subsegment(offset, itemLength); offset += itemLength; // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return(false); } // value or "quoted value" // The value may be empty result._value = GetCookieValue(input, ref offset); parsedValue = result; return(true); }
/// <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> /// <see langword="true" /> if <paramref name="targetDirectives"/> is contained in <paramref name="cacheControlDirectives"/>; /// otherwise, <see langword="false" />. /// </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++) { var segment = cacheControlDirectives[i] !; // Trim leading white space var current = HttpRuleParser.GetWhitespaceLength(segment, 0); while (current < segment.Length) { var initial = current; var tokenLength = HttpRuleParser.GetTokenLength(segment, current); if (tokenLength == targetDirectives.Length && string.Compare(segment, current, targetDirectives, 0, tokenLength, StringComparison.OrdinalIgnoreCase) == 0) { // Token matches target value return(true); } current = AdvanceCacheDirectiveIndex(current + tokenLength, segment); // Ensure index was advanced if (current <= initial) { Debug.Assert(false, $"Index '{nameof(current)}' not advanced, this is a bug."); return(false); } } } return(false); }
// Returns input for decoding failures, as the content might not be encoded private StringSegment EncodeAndQuoteMime(StringSegment input) { var result = input; var needsQuotes = false; // Remove bounding quotes, they'll get re-added later if (IsQuoted(result)) { result = result.Subsegment(1, result.Length - 2); needsQuotes = true; } if (RequiresEncoding(result)) { // EncodeMimeWithQuotes will Base64 encode any quotes in the input, and surround the payload in quotes // so there is no need to add quotes needsQuotes = false; result = EncodeMimeWithQuotes(result); // "=?utf-8?B?asdfasdfaesdf?=" } else if (!needsQuotes && HttpRuleParser.GetTokenLength(result, 0) != result.Length) { needsQuotes = true; } if (needsQuotes) { if (result.IndexOfAny(EscapeChars) != -1) { // '\' and '"' must be escaped in a quoted string result = result.ToString().Replace(@"\", @"\\").Replace(@"""", @"\"""); } // Re-add quotes "value" result = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", result); } return(result); }
private static int GetContentRangeLength(StringSegment input, int startIndex, out ContentRangeHeaderValue?parsedValue) { Contract.Requires(startIndex >= 0); parsedValue = null; if (StringSegment.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return(0); } // Parse the unit string: <unit> in '<unit> <from>-<to>/<length>' var unitLength = HttpRuleParser.GetTokenLength(input, startIndex); if (unitLength == 0) { return(0); } var unit = input.Subsegment(startIndex, unitLength); var current = startIndex + unitLength; var separatorLength = HttpRuleParser.GetWhitespaceLength(input, current); if (separatorLength == 0) { return(0); } current = current + separatorLength; if (current == input.Length) { return(0); } // Read range values <from> and <to> in '<unit> <from>-<to>/<length>' var fromStartIndex = current; var fromLength = 0; var toStartIndex = 0; var toLength = 0; if (!TryGetRangeLength(input, ref current, out fromLength, out toStartIndex, out toLength)) { return(0); } // After the range is read we expect the length separator '/' if ((current == input.Length) || (input[current] != '/')) { return(0); } current++; // Skip '/' separator current = current + HttpRuleParser.GetWhitespaceLength(input, current); if (current == input.Length) { return(0); } // We may not have a length (e.g. 'bytes 1-2/*'). But if we do, parse the length now. var lengthStartIndex = current; var lengthLength = 0; if (!TryGetLengthLength(input, ref current, out lengthLength)) { return(0); } if (!TryCreateContentRange(input, unit, fromStartIndex, fromLength, toStartIndex, toLength, lengthStartIndex, lengthLength, out parsedValue)) { return(0); } return(current - startIndex); }
// 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 = HttpRuleParser.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 += HttpRuleParser.GetWhitespaceLength(input, offset); // cookie-av = expires-av / max-age-av / domain-av / path-av / secure-av / samesite-av / httponly-av / extension-av itemLength = HttpRuleParser.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 (!HttpRuleParser.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 = HttpRuleParser.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 = "HttpOnly" else if (StringSegment.Equals(token, HttpOnlyToken, StringComparison.OrdinalIgnoreCase)) { result.HttpOnly = true; } // extension-av = <any CHAR except CTLs or ";"> else { // TODO: skip it? Store it in a list? } } parsedValue = result; return(offset - startIndex); }
private static bool TrySetOptionalTokenList( NameValueHeaderValue nameValue, ref bool boolField, ref ICollection <StringSegment> destination) { Contract.Requires(nameValue != null); if (nameValue.Value == null) { boolField = true; return(true); } // We need the string to be at least 3 chars long: 2x quotes and at least 1 character. Also make sure we // have a quoted string. Note that NameValueHeaderValue will never have leading/trailing whitespaces. var valueString = nameValue.Value; if ((valueString.Length < 3) || (valueString[0] != '\"') || (valueString[valueString.Length - 1] != '\"')) { return(false); } // We have a quoted string. Now verify that the string contains a list of valid tokens separated by ','. var current = 1; // skip the initial '"' character. var maxLength = valueString.Length - 1; // -1 because we don't want to parse the final '"'. var separatorFound = false; var originalValueCount = destination == null ? 0 : destination.Count; while (current < maxLength) { current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(valueString, current, true, out separatorFound); if (current == maxLength) { break; } var tokenLength = HttpRuleParser.GetTokenLength(valueString, current); if (tokenLength == 0) { // We already skipped whitespaces and separators. If we don't have a token it must be an invalid // character. return(false); } if (destination == null) { destination = new ObjectCollection <StringSegment>(CheckIsValidTokenAction); } destination.Add(valueString.Subsegment(current, tokenLength)); current = current + tokenLength; } // After parsing a valid token list, we expect to have at least one value if ((destination != null) && (destination.Count > originalValueCount)) { boolField = true; return(true); } return(false); }