コード例 #1
0
ファイル: HeaderUtilities.cs プロジェクト: bclnet/GameNetCore
        private static int AdvanceCacheDirectiveIndex(int current, string headerValue)
        {
            // Skip until the next potential name
            current += ProtoRuleParser.GetWhitespaceLength(headerValue, current);

            // Skip the value if present
            if (current < headerValue.Length && headerValue[current] == '=')
            {
                current++; // skip '='
                current += NameValueHeaderValue.GetValueLength(headerValue, current);
            }

            // Find the next delimiter
            current = headerValue.IndexOf(',', current);

            if (current == -1)
            {
                // If no delimiter found, skip to the end
                return(headerValue.Length);
            }

            current++; // skip ','
            current += ProtoRuleParser.GetWhitespaceLength(headerValue, current);

            return(current);
        }
コード例 #2
0
        private static int GetNextNonEmptyOrWhitespaceIndex(StringSegment input, int startIndex, bool skipEmptyValues, out bool separatorFound)
        {
            Contract.Requires(input != null);
            Contract.Requires(startIndex <= input.Length); // it's OK if index == value.Length.

            separatorFound = false;
            var current = startIndex + ProtoRuleParser.GetWhitespaceLength(input, startIndex);

            if (current == input.Length || (input[current] != ',' && input[current] != ';'))
            {
                return(current);
            }

            // If we have a separator, skip the separator and all following whitespaces. If we support
            // empty values, continue until the current character is neither a separator nor a whitespace.
            separatorFound = true;
            current++; // skip delimiter.
            current += ProtoRuleParser.GetWhitespaceLength(input, current);

            if (skipEmptyValues)
            {
                // Most headers only split on ',', but cookies primarily split on ';'
                while ((current < input.Length) && ((input[current] == ',') || (input[current] == ';')))
                {
                    current++; // skip delimiter.
                    current += ProtoRuleParser.GetWhitespaceLength(input, current);
                }
            }

            return(current);
        }
コード例 #3
0
ファイル: HeaderUtilities.cs プロジェクト: bclnet/GameNetCore
        private static unsafe bool TryParseNonNegativeInt64FromHeaderValue(int startIndex, string headerValue, out long result)
        {
            // Trim leading whitespace
            startIndex += ProtoRuleParser.GetWhitespaceLength(headerValue, startIndex);

            // Match and skip '=', it also can't be the last character in the headerValue
            if (startIndex >= headerValue.Length - 1 || headerValue[startIndex] != '=')
            {
                result = 0;
                return(false);
            }
            startIndex++;

            // Trim trailing whitespace
            startIndex += ProtoRuleParser.GetWhitespaceLength(headerValue, startIndex);

            // Try parse the number
            if (TryParseNonNegativeInt64(new StringSegment(headerValue, startIndex, ProtoRuleParser.GetNumberLength(headerValue, startIndex, false)), out result))
            {
                return(true);
            }

            result = 0;
            return(false);
        }
コード例 #4
0
        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);
        }
コード例 #5
0
        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);
        }
コード例 #6
0
        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);
        }
コード例 #7
0
        private static int GetMediaTypeLength(StringSegment input, int startIndex, out MediaTypeHeaderValue parsedValue)
        {
            Contract.Requires(startIndex >= 0);

            parsedValue = null;

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

            // Caller must remove leading whitespace. If not, we'll return 0.
            var mediaTypeLength = MediaTypeHeaderValue.GetMediaTypeExpressionLength(input, startIndex, out var mediaType);

            if (mediaTypeLength == 0)
            {
                return(0);
            }

            var current = startIndex + mediaTypeLength;

            current = current + ProtoRuleParser.GetWhitespaceLength(input, current);
            MediaTypeHeaderValue mediaTypeHeader = null;

            // If we're not done and we have a parameter delimiter, then we have a list of parameters.
            if ((current < input.Length) && (input[current] == ';'))
            {
                mediaTypeHeader            = new MediaTypeHeaderValue();
                mediaTypeHeader._mediaType = mediaType;

                current++; // skip delimiter.
                var parameterLength = NameValueHeaderValue.GetNameValueListLength(input, current, ';',
                                                                                  mediaTypeHeader.Parameters);

                parsedValue = mediaTypeHeader;
                return(current + parameterLength - startIndex);
            }

            // We have a media type without parameters.
            mediaTypeHeader            = new MediaTypeHeaderValue();
            mediaTypeHeader._mediaType = mediaType;
            parsedValue = mediaTypeHeader;
            return(current - startIndex);
        }
コード例 #8
0
        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);
        }
コード例 #9
0
        // Returns the length of a name/value list, separated by 'delimiter'. E.g. "a=b, c=d, e=f" adds 3
        // name/value pairs to 'nameValueCollection' if 'delimiter' equals ','.
        internal static int GetNameValueListLength(
            StringSegment input,
            int startIndex,
            char delimiter,
            IList <NameValueHeaderValue> nameValueCollection)
        {
            Contract.Requires(nameValueCollection != null);
            Contract.Requires(startIndex >= 0);

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

            var current = startIndex + ProtoRuleParser.GetWhitespaceLength(input, startIndex);

            while (true)
            {
                NameValueHeaderValue parameter = null;
                var nameValueLength            = GetNameValueLength(input, current, out parameter);

                if (nameValueLength == 0)
                {
                    // There may be a trailing ';'
                    return(current - startIndex);
                }

                nameValueCollection.Add(parameter);
                current = current + nameValueLength;
                current = current + ProtoRuleParser.GetWhitespaceLength(input, current);

                if ((current == input.Length) || (input[current] != delimiter))
                {
                    // We're done and we have at least one valid name/value pair.
                    return(current - startIndex);
                }

                // input[current] is 'delimiter'. Skip the delimiter and whitespaces and try to parse again.
                current++; // skip delimiter.
                current = current + ProtoRuleParser.GetWhitespaceLength(input, current);
            }
        }
コード例 #10
0
ファイル: HeaderUtilities.cs プロジェクト: bclnet/GameNetCore
        /// <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);
        }
コード例 #11
0
        private static bool TryReadQuality(StringSegment input, StringWithQualityHeaderValue result, ref int index)
        {
            var current = index;

            // See if we have a quality value by looking for "q"
            if ((current == input.Length) || ((input[current] != 'q') && (input[current] != 'Q')))
            {
                return(false);
            }

            current++; // skip 'q' identifier
            current = current + ProtoRuleParser.GetWhitespaceLength(input, current);

            // If we found "q" it must be followed by "="
            if ((current == input.Length) || (input[current] != '='))
            {
                return(false);
            }

            current++; // skip '=' separator
            current = current + ProtoRuleParser.GetWhitespaceLength(input, current);

            if (current == input.Length)
            {
                return(false);
            }

            if (!HeaderUtilities.TryParseQualityDouble(input, current, out var quality, out var qualityLength))
            {
                return(false);
            }

            result._quality = quality;

            current = current + qualityLength;
            current = current + ProtoRuleParser.GetWhitespaceLength(input, current);

            index = current;
            return(true);
        }
コード例 #12
0
ファイル: HeaderUtilities.cs プロジェクト: bclnet/GameNetCore
        /// <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);
        }
コード例 #13
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     = ProtoRuleParser.GetNumberLength(input, current, false);

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

            current = current + fromLength;
            current = current + ProtoRuleParser.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 + ProtoRuleParser.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 = ProtoRuleParser.GetNumberLength(input, current, false);

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

                current = current + toLength;
                current = current + ProtoRuleParser.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);
        }
コード例 #14
0
        // 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);
        }
コード例 #15
0
        internal static int GetEntityTagLength(StringSegment input, int startIndex, out EntityTagHeaderValue parsedValue)
        {
            Contract.Requires(startIndex >= 0);

            parsedValue = null;

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

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

            var firstChar = input[startIndex];

            if (firstChar == '*')
            {
                // We have '*' value, indicating "any" ETag.
                parsedValue = Any;
                current++;
            }
            else
            {
                // The RFC defines 'W/' as prefix, but we'll be flexible and also accept lower-case 'w'.
                if ((firstChar == 'W') || (firstChar == 'w'))
                {
                    current++;
                    // We need at least 3 more chars: the '/' character followed by two quotes.
                    if ((current + 2 >= input.Length) || (input[current] != '/'))
                    {
                        return(0);
                    }
                    isWeak = true;
                    current++; // we have a weak-entity tag.
                    current = current + ProtoRuleParser.GetWhitespaceLength(input, current);
                }

                var tagStartIndex = current;
                var tagLength     = 0;
                if (ProtoRuleParser.GetQuotedStringLength(input, current, out tagLength) != ProtoParseResult.Parsed)
                {
                    return(0);
                }

                parsedValue = new EntityTagHeaderValue();
                if (tagLength == input.Length)
                {
                    // Most of the time we'll have strong ETags without leading/trailing whitespaces.
                    Contract.Assert(startIndex == 0);
                    Contract.Assert(!isWeak);
                    parsedValue._tag    = input;
                    parsedValue._isWeak = false;
                }
                else
                {
                    parsedValue._tag    = input.Subsegment(tagStartIndex, tagLength);
                    parsedValue._isWeak = isWeak;
                }

                current = current + tagLength;
            }
            current = current + ProtoRuleParser.GetWhitespaceLength(input, current);

            return(current - startIndex);
        }