示例#1
0
 private static Task EncodeHeadersToStreamAsync(Stream output, StringBuilder builder, TEntry entry, bool writeDivider, string boundary, EncodingContext context, byte[] buffer)
 {
     builder.Clear();
     if (writeDivider)
     {
         builder.Append(CrLf + DoubleDash).Append(boundary).Append(CrLf);
     }
     //write headers
     WriteHeader(builder, RequestVoteMessage.RecordTermHeader, entry.Term.ToString(InvariantCulture));
     WriteHeader(builder, HeaderNames.LastModified, HeaderUtils.FormatDate(entry.Timestamp));
     // Extra CRLF to end headers (even if there are no headers)
     builder.Append(CrLf);
     return(output.WriteStringAsync(builder.ToString(), context, buffer));
 }
        private static bool TryCreateContentRange(
            string input,
            string unit,
            int fromStartIndex,
            int fromLength,
            int toStartIndex,
            int toLength,
            int lengthStartIndex,
            int lengthLength,
            out ContentRangeHeaderValue parsedValue)
        {
            parsedValue = null;

            long from = 0;

            if ((fromLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(fromStartIndex, fromLength), out from))
            {
                return(false);
            }

            long to = 0;

            if ((toLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(toStartIndex, toLength), out to))
            {
                return(false);
            }

            // 'from' must not be greater than 'to'
            if ((fromLength > 0) && (toLength > 0) && (from > to))
            {
                return(false);
            }

            long length = 0;

            if ((lengthLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(lengthStartIndex, lengthLength),
                                                                     out length))
            {
                return(false);
            }

            // 'from' and 'to' must be less than 'length'
            if ((toLength > 0) && (lengthLength > 0) && (to >= length))
            {
                return(false);
            }

            var result = new ContentRangeHeaderValue();

            result._unit = unit;

            if (fromLength > 0)
            {
                result._from = from;
                result._to   = to;
            }

            if (lengthLength > 0)
            {
                result._length = length;
            }

            parsedValue = result;
            return(true);
        }
示例#3
0
        internal static int GetRangeItemLength(StringSegment input, int startIndex, out RangeItemHeaderValue parsedValue)
        {
            Contract.Requires(startIndex >= 0);

            // This parser parses number ranges: e.g. '1-2', '1-', '-2'.

            parsedValue = null;

            if (StringSegment.IsNullOrEmpty(input) || (startIndex >= input.Length))
            {
                return(0);
            }

            // Caller must remove leading whitespaces. If not, we'll return 0.
            var current = startIndex;

            // Try parse the first value of a value pair.
            var fromStartIndex = current;
            var fromLength     = HttpRuleParser.GetNumberLength(input, current, false);

            if (fromLength > HttpRuleParser.MaxInt64Digits)
            {
                return(0);
            }

            current = current + fromLength;
            current = current + HttpRuleParser.GetWhitespaceLength(input, current);

            // After the first value, the '-' character must follow.
            if ((current == input.Length) || (input[current] != '-'))
            {
                // We need a '-' character otherwise this can't be a valid range.
                return(0);
            }

            current++; // skip the '-' character
            current = current + HttpRuleParser.GetWhitespaceLength(input, current);

            var toStartIndex = current;
            var toLength     = 0;

            // If we didn't reach the end of the string, try parse the second value of the range.
            if (current < input.Length)
            {
                toLength = HttpRuleParser.GetNumberLength(input, current, false);

                if (toLength > HttpRuleParser.MaxInt64Digits)
                {
                    return(0);
                }

                current = current + toLength;
                current = current + HttpRuleParser.GetWhitespaceLength(input, current);
            }

            if ((fromLength == 0) && (toLength == 0))
            {
                return(0); // At least one value must be provided in order to be a valid range.
            }

            // Try convert first value to int64
            long from = 0;

            if ((fromLength > 0) && !HeaderUtilities.TryParseNonNegativeInt64(input.Subsegment(fromStartIndex, fromLength), out from))
            {
                return(0);
            }

            // Try convert second value to int64
            long to = 0;

            if ((toLength > 0) && !HeaderUtilities.TryParseNonNegativeInt64(input.Subsegment(toStartIndex, toLength), out to))
            {
                return(0);
            }

            // 'from' must not be greater than 'to'
            if ((fromLength > 0) && (toLength > 0) && (from > to))
            {
                return(0);
            }

            parsedValue = new RangeItemHeaderValue((fromLength == 0 ? (long?)null : (long?)from),
                                                   (toLength == 0 ? (long?)null : (long?)to));
            return(current - startIndex);
        }
示例#4
0
        public void TryParseSeconds_Fails(string headerValues, string targetValue)
        {
            TimeSpan?value;

            Assert.False(HeaderUtilities.TryParseSeconds(new StringValues(headerValues), targetValue, out value));
        }
示例#5
0
 public void SetAndEscapeValue_ThrowsFormatExceptionOnDelCharacter()
 {
     Assert.Throws <FormatException>(() => { var actual = HeaderUtilities.EscapeAsQuotedString($"{(char)0x7F}"); });
 }
示例#6
0
        // name="value"; expires=Sun, 06 Nov 1994 08:49:37 GMT; max-age=86400; domain=domain1; path=path1; secure; samesite={Strict|Lax}; httponly
        public override string ToString()
        {
            var length = _name.Length + EqualsToken.Length + _value.Length;

            string expires  = null;
            string maxAge   = null;
            string sameSite = null;

            if (Expires.HasValue)
            {
                expires = HeaderUtilities.FormatDate(Expires.GetValueOrDefault());
                length += SeparatorToken.Length + ExpiresToken.Length + EqualsToken.Length + expires.Length;
            }

            if (MaxAge.HasValue)
            {
                maxAge  = HeaderUtilities.FormatNonNegativeInt64((long)MaxAge.GetValueOrDefault().TotalSeconds);
                length += SeparatorToken.Length + MaxAgeToken.Length + EqualsToken.Length + maxAge.Length;
            }

            if (Domain != null)
            {
                length += SeparatorToken.Length + DomainToken.Length + EqualsToken.Length + Domain.Length;
            }

            if (Path != null)
            {
                length += SeparatorToken.Length + PathToken.Length + EqualsToken.Length + Path.Length;
            }

            if (Secure)
            {
                length += SeparatorToken.Length + SecureToken.Length;
            }

            if (SameSite != SameSiteMode.None)
            {
                sameSite = SameSite == SameSiteMode.Lax ? SameSiteLaxToken : SameSiteStrictToken;
                length  += SeparatorToken.Length + SameSiteToken.Length + EqualsToken.Length + sameSite.Length;
            }

            if (HttpOnly)
            {
                length += SeparatorToken.Length + HttpOnlyToken.Length;
            }

            var sb = new InplaceStringBuilder(length);

            sb.Append(_name);
            sb.Append(EqualsToken);
            sb.Append(_value);

            if (expires != null)
            {
                AppendSegment(ref sb, ExpiresToken, expires);
            }

            if (maxAge != null)
            {
                AppendSegment(ref sb, MaxAgeToken, maxAge);
            }

            if (Domain != null)
            {
                AppendSegment(ref sb, DomainToken, Domain);
            }

            if (Path != null)
            {
                AppendSegment(ref sb, PathToken, Path);
            }

            if (Secure)
            {
                AppendSegment(ref sb, SecureToken, null);
            }

            if (SameSite != SameSiteMode.None)
            {
                AppendSegment(ref sb, SameSiteToken, sameSite);
            }

            if (HttpOnly)
            {
                AppendSegment(ref sb, HttpOnlyToken, null);
            }

            return(sb.ToString());
        }
        // name=value; expires=Sun, 06 Nov 1994 08:49:37 GMT; max-age=86400; domain=domain1; path=path1; secure; samesite={Strict|Lax|None}; 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);
                    }
                    // We don't want to include comma, becouse date may contain it (eg. Sun, 06 Nov...)
                    var            dateString = ReadToSemicolonOrEnd(input, ref offset, includeComma: false);
                    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-value
                // samesite-value = "Strict" / "Lax" / "None"
                else if (StringSegment.Equals(token, SameSiteToken, StringComparison.OrdinalIgnoreCase))
                {
                    if (!ReadEqualsSign(input, ref offset))
                    {
                        result.SameSite = SameSiteMode.Unspecified;
                    }
                    else
                    {
                        var enforcementMode = ReadToSemicolonOrEnd(input, ref offset);

                        if (StringSegment.Equals(enforcementMode, SameSiteStrictToken, StringComparison.OrdinalIgnoreCase))
                        {
                            result.SameSite = SameSiteMode.Strict;
                        }
                        else if (StringSegment.Equals(enforcementMode, SameSiteLaxToken, StringComparison.OrdinalIgnoreCase))
                        {
                            result.SameSite = SameSiteMode.Lax;
                        }
                        else if (StringSegment.Equals(enforcementMode, SameSiteNoneToken, StringComparison.OrdinalIgnoreCase))
                        {
                            result.SameSite = SameSiteMode.None;
                        }
                        else
                        {
                            result.SameSite = SameSiteMode.Unspecified;
                        }
                    }
                }
                // httponly-av = "HttpOnly"
                else if (StringSegment.Equals(token, HttpOnlyToken, StringComparison.OrdinalIgnoreCase))
                {
                    result.HttpOnly = true;
                }
                // extension-av = <any CHAR except CTLs or ";">
                else
                {
                    var tokenStart = offset - itemLength;
                    ReadToSemicolonOrEnd(input, ref offset, includeComma: true);
                    result.Extensions.Add(input.Subsegment(tokenStart, offset - tokenStart));
                }
            }

            parsedValue = result;
            return(offset - startIndex);
        }
示例#8
0
 private static void CheckIsValidToken(string item)
 {
     HeaderUtilities.CheckValidToken(item, nameof(item));
 }
示例#9
0
        public void RemoveQuotes_BehaviorCheck(string input, string expected)
        {
            var actual = HeaderUtilities.RemoveQuotes(input);

            Assert.Equal(expected, actual);
        }
示例#10
0
 public void ContainsCacheDirective_MatchesExactValue(string headerValues, string targetValue, bool contains)
 {
     Assert.Equal(contains, HeaderUtilities.ContainsCacheDirective(new StringValues(headerValues), targetValue));
 }
示例#11
0
 public void FormatNonNegativeInt64_Throws_ForNegativeValues(long value)
 {
     Assert.Throws <ArgumentOutOfRangeException>(() => HeaderUtilities.FormatNonNegativeInt64(value));
 }
示例#12
0
 public void FormatNonNegativeInt64_MatchesToString(long value)
 {
     Assert.Equal(value.ToString(CultureInfo.InvariantCulture), HeaderUtilities.FormatNonNegativeInt64(value));
 }
示例#13
0
 public void TryParse_SetOfInvalidValueStrings_ReturnsFalse(string input)
 {
     Assert.False(HeaderUtilities.TryParseDate(input, out var result));
     Assert.Equal(new DateTimeOffset(), result);
 }
示例#14
0
 private static void CheckNameValueFormat(string name, string value)
 {
     HeaderUtilities.CheckValidToken(name, nameof(name));
     CheckValueFormat(value);
 }
        public StringWithQualityHeaderValue(string value)
        {
            HeaderUtilities.CheckValidToken(value, nameof(value));

            _value = value;
        }
示例#16
0
        private static bool TrySetOptionalTokenList(NameValueHeaderValue nameValue, ref bool boolField,
                                                    ref ICollection <string> 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 <string>(CheckIsValidTokenAction);
                }

                destination.Add(valueString.Substring(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);
        }
示例#17
0
        public void IsQuoted_BehaviorCheck(string input, bool expected)
        {
            var actual = HeaderUtilities.IsQuoted(input);

            Assert.Equal(expected, actual);
        }
示例#18
0
        // name="value"; expires=Sun, 06 Nov 1994 08:49:37 GMT; max-age=86400; domain=domain1; path=path1; secure; samesite={strict|lax|none}; httponly
        public override string ToString()
        {
            var length = _name.Length + EqualsToken.Length + _value.Length;

            string?maxAge   = null;
            string?sameSite = null;

            if (Expires.HasValue)
            {
                length += SeparatorToken.Length + ExpiresToken.Length + EqualsToken.Length + ExpiresDateLength;
            }

            if (MaxAge.HasValue)
            {
                maxAge  = HeaderUtilities.FormatNonNegativeInt64((long)MaxAge.GetValueOrDefault().TotalSeconds);
                length += SeparatorToken.Length + MaxAgeToken.Length + EqualsToken.Length + maxAge.Length;
            }

            if (Domain != null)
            {
                length += SeparatorToken.Length + DomainToken.Length + EqualsToken.Length + Domain.Length;
            }

            if (Path != null)
            {
                length += SeparatorToken.Length + PathToken.Length + EqualsToken.Length + Path.Length;
            }

            if (Secure)
            {
                length += SeparatorToken.Length + SecureToken.Length;
            }

            // Allow for Unspecified (-1) to skip SameSite
            if (SameSite == SameSiteMode.None)
            {
                sameSite = SameSiteNoneToken;
                length  += SeparatorToken.Length + SameSiteToken.Length + EqualsToken.Length + sameSite.Length;
            }
            else if (SameSite == SameSiteMode.Lax)
            {
                sameSite = SameSiteLaxToken;
                length  += SeparatorToken.Length + SameSiteToken.Length + EqualsToken.Length + sameSite.Length;
            }
            else if (SameSite == SameSiteMode.Strict)
            {
                sameSite = SameSiteStrictToken;
                length  += SeparatorToken.Length + SameSiteToken.Length + EqualsToken.Length + sameSite.Length;
            }

            if (HttpOnly)
            {
                length += SeparatorToken.Length + HttpOnlyToken.Length;
            }

            foreach (var extension in Extensions)
            {
                length += SeparatorToken.Length + extension.Length;
            }

            return(string.Create(length, (this, maxAge, sameSite), (span, tuple) =>
            {
                var(headerValue, maxAgeValue, sameSite) = tuple;

                Append(ref span, headerValue._name);
                Append(ref span, EqualsToken);
                Append(ref span, headerValue._value);

                if (headerValue.Expires is DateTimeOffset expiresValue)
                {
                    Append(ref span, SeparatorToken);
                    Append(ref span, ExpiresToken);
                    Append(ref span, EqualsToken);

                    var formatted = expiresValue.TryFormat(span, out var charsWritten, ExpiresDateFormat);
                    span = span.Slice(charsWritten);

                    Debug.Assert(formatted);
                }

                if (maxAgeValue != null)
                {
                    AppendSegment(ref span, MaxAgeToken, maxAgeValue);
                }

                if (headerValue.Domain != null)
                {
                    AppendSegment(ref span, DomainToken, headerValue.Domain);
                }

                if (headerValue.Path != null)
                {
                    AppendSegment(ref span, PathToken, headerValue.Path);
                }

                if (headerValue.Secure)
                {
                    AppendSegment(ref span, SecureToken, null);
                }

                if (sameSite != null)
                {
                    AppendSegment(ref span, SameSiteToken, sameSite);
                }

                if (headerValue.HttpOnly)
                {
                    AppendSegment(ref span, HttpOnlyToken, null);
                }

                foreach (var extension in Extensions)
                {
                    AppendSegment(ref span, extension, null);
                }
            }));
        }
示例#19
0
        public void SetAndEscapeValue_BehaviorCheck(string input, string expected)
        {
            var actual = HeaderUtilities.EscapeAsQuotedString(input);

            Assert.Equal(expected, actual);
        }
示例#20
0
 public void SetAndEscapeValue_ControlCharactersThrowFormatException(string input)
 {
     Assert.Throws <FormatException>(() => { var actual = HeaderUtilities.EscapeAsQuotedString(input); });
 }
 private static void CheckNameValueFormat(StringSegment name, StringSegment value)
 {
     HeaderUtilities.CheckValidToken(name, nameof(name));
     CheckValueFormat(value);
 }