2 * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
3 * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
4 * Copyright (C) 2009 Torch Mobile Inc. http://www.torchmobile.com/
5 * Copyright (C) 2009 Google Inc. All rights reserved.
6 * Copyright (C) 2011 Apple Inc. All Rights Reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
18 * its contributors may be used to endorse or promote products derived
19 * from this software without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
22 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
25 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
28 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 #include "platform/network/HTTPParsers.h"
36 #include "wtf/DateMath.h"
37 #include "wtf/MathExtras.h"
38 #include "wtf/text/CString.h"
39 #include "wtf/text/StringBuilder.h"
40 #include "wtf/text/WTFString.h"
41 #include "wtf/unicode/CharacterNames.h"
47 // true if there is more to parse, after incrementing pos past whitespace.
48 // Note: Might return pos == str.length()
49 static inline bool skipWhiteSpace(const String& str, unsigned& pos, bool fromHttpEquivMeta)
51 unsigned len = str.length();
53 if (fromHttpEquivMeta) {
54 while (pos < len && str[pos] <= ' ')
57 while (pos < len && (str[pos] == '\t' || str[pos] == ' '))
64 // Returns true if the function can match the whole token (case insensitive)
65 // incrementing pos on match, otherwise leaving pos unchanged.
66 // Note: Might return pos == str.length()
67 static inline bool skipToken(const String& str, unsigned& pos, const char* token)
69 unsigned len = str.length();
70 unsigned current = pos;
72 while (current < len && *token) {
73 if (toASCIILower(str[current]) != *token++)
85 // True if the expected equals sign is seen and there is more to follow.
86 static inline bool skipEquals(const String& str, unsigned &pos)
88 return skipWhiteSpace(str, pos, false) && str[pos++] == '=' && skipWhiteSpace(str, pos, false);
91 // True if a value present, incrementing pos to next space or semicolon, if any.
92 // Note: might return pos == str.length().
93 static inline bool skipValue(const String& str, unsigned& pos)
96 unsigned len = str.length();
98 if (str[pos] == ' ' || str[pos] == '\t' || str[pos] == ';')
105 bool isValidHTTPHeaderValue(const String& name)
107 // FIXME: This should really match name against
108 // field-value in section 4.2 of RFC 2616.
110 return name.containsOnlyLatin1() && !name.contains('\r') && !name.contains('\n');
113 // See RFC 2616, Section 2.2.
114 bool isValidHTTPToken(const String& characters)
116 if (characters.isEmpty())
118 for (unsigned i = 0; i < characters.length(); ++i) {
119 UChar c = characters[i];
120 if (c <= 0x20 || c >= 0x7F
121 || c == '(' || c == ')' || c == '<' || c == '>' || c == '@'
122 || c == ',' || c == ';' || c == ':' || c == '\\' || c == '"'
123 || c == '/' || c == '[' || c == ']' || c == '?' || c == '='
124 || c == '{' || c == '}')
130 static const size_t maxInputSampleSize = 128;
131 static String trimInputSample(const char* p, size_t length)
133 if (length > maxInputSampleSize)
134 return String(p, maxInputSampleSize) + horizontalEllipsis;
135 return String(p, length);
138 ContentDispositionType contentDispositionType(const String& contentDisposition)
140 if (contentDisposition.isEmpty())
141 return ContentDispositionNone;
143 Vector<String> parameters;
144 contentDisposition.split(';', parameters);
146 if (parameters.isEmpty())
147 return ContentDispositionNone;
149 String dispositionType = parameters[0];
150 dispositionType.stripWhiteSpace();
152 if (equalIgnoringCase(dispositionType, "inline"))
153 return ContentDispositionInline;
155 // Some broken sites just send bogus headers like
157 // Content-Disposition: ; filename="file"
158 // Content-Disposition: filename="file"
159 // Content-Disposition: name="file"
161 // without a disposition token... screen those out.
162 if (!isValidHTTPToken(dispositionType))
163 return ContentDispositionNone;
165 // We have a content-disposition of "attachment" or unknown.
166 // RFC 2183, section 2.8 says that an unknown disposition
167 // value should be treated as "attachment"
168 return ContentDispositionAttachment;
171 bool parseHTTPRefresh(const String& refresh, bool fromHttpEquivMeta, double& delay, String& url)
173 unsigned len = refresh.length();
176 if (!skipWhiteSpace(refresh, pos, fromHttpEquivMeta))
179 while (pos != len && refresh[pos] != ',' && refresh[pos] != ';')
182 if (pos == len) { // no URL
185 delay = refresh.stripWhiteSpace().toDouble(&ok);
189 delay = refresh.left(pos).stripWhiteSpace().toDouble(&ok);
194 skipWhiteSpace(refresh, pos, fromHttpEquivMeta);
195 unsigned urlStartPos = pos;
196 if (refresh.find("url", urlStartPos, false) == urlStartPos) {
198 skipWhiteSpace(refresh, urlStartPos, fromHttpEquivMeta);
199 if (refresh[urlStartPos] == '=') {
201 skipWhiteSpace(refresh, urlStartPos, fromHttpEquivMeta);
203 urlStartPos = pos; // e.g. "Refresh: 0; url.html"
207 unsigned urlEndPos = len;
209 if (refresh[urlStartPos] == '"' || refresh[urlStartPos] == '\'') {
210 UChar quotationMark = refresh[urlStartPos];
212 while (urlEndPos > urlStartPos) {
214 if (refresh[urlEndPos] == quotationMark)
218 // https://bugs.webkit.org/show_bug.cgi?id=27868
219 // Sometimes there is no closing quote for the end of the URL even though there was an opening quote.
220 // If we looped over the entire alleged URL string back to the opening quote, just go ahead and use everything
221 // after the opening quote instead.
222 if (urlEndPos == urlStartPos)
226 url = refresh.substring(urlStartPos, urlEndPos - urlStartPos).stripWhiteSpace();
231 double parseDate(const String& value)
233 return parseDateFromNullTerminatedCharacters(value.utf8().data());
236 // FIXME: This function doesn't comply with RFC 6266.
237 // For example, this function doesn't handle the interaction between " and ;
238 // that arises from quoted-string, nor does this function properly unquote
239 // attribute values. Further this function appears to process parameter names
240 // in a case-sensitive manner. (There are likely other bugs as well.)
241 String filenameFromHTTPContentDisposition(const String& value)
243 Vector<String> keyValuePairs;
244 value.split(';', keyValuePairs);
246 unsigned length = keyValuePairs.size();
247 for (unsigned i = 0; i < length; i++) {
248 size_t valueStartPos = keyValuePairs[i].find('=');
249 if (valueStartPos == kNotFound)
252 String key = keyValuePairs[i].left(valueStartPos).stripWhiteSpace();
254 if (key.isEmpty() || key != "filename")
257 String value = keyValuePairs[i].substring(valueStartPos + 1).stripWhiteSpace();
259 // Remove quotes if there are any
260 if (value[0] == '\"')
261 value = value.substring(1, value.length() - 2);
269 AtomicString extractMIMETypeFromMediaType(const AtomicString& mediaType)
271 StringBuilder mimeType;
272 unsigned length = mediaType.length();
273 mimeType.reserveCapacity(length);
274 for (unsigned i = 0; i < length; i++) {
275 UChar c = mediaType[i];
280 // While RFC 2616 does not allow it, other browsers allow multiple values in the HTTP media
281 // type header field, Content-Type. In such cases, the media type string passed here may contain
282 // the multiple values separated by commas. For now, this code ignores text after the first comma,
283 // which prevents it from simply failing to parse such types altogether. Later for better
284 // compatibility we could consider using the first or last valid MIME type instead.
285 // See https://bugs.webkit.org/show_bug.cgi?id=25352 for more discussion.
289 // FIXME: The following is not correct. RFC 2616 allows linear white space before and
290 // after the MIME type, but not within the MIME type itself. And linear white space
291 // includes only a few specific ASCII characters; a small subset of isSpaceOrNewline.
292 // See https://bugs.webkit.org/show_bug.cgi?id=8644 for a bug tracking part of this.
293 if (isSpaceOrNewline(c))
299 if (mimeType.length() == length)
301 return mimeType.toAtomicString();
304 String extractCharsetFromMediaType(const String& mediaType)
307 findCharsetInMediaType(mediaType, pos, len);
308 return mediaType.substring(pos, len);
311 void findCharsetInMediaType(const String& mediaType, unsigned& charsetPos, unsigned& charsetLen, unsigned start)
317 unsigned length = mediaType.length();
319 while (pos < length) {
320 pos = mediaType.find("charset", pos, false);
321 if (pos == kNotFound || !pos) {
326 // is what we found a beginning of a word?
327 if (mediaType[pos-1] > ' ' && mediaType[pos-1] != ';') {
335 while (pos != length && mediaType[pos] <= ' ')
338 if (mediaType[pos++] != '=') // this "charset" substring wasn't a parameter name, but there may be others
341 while (pos != length && (mediaType[pos] <= ' ' || mediaType[pos] == '"' || mediaType[pos] == '\''))
344 // we don't handle spaces within quoted parameter values, because charset names cannot have any
345 unsigned endpos = pos;
346 while (pos != length && mediaType[endpos] > ' ' && mediaType[endpos] != '"' && mediaType[endpos] != '\'' && mediaType[endpos] != ';')
350 charsetLen = endpos - pos;
355 ReflectedXSSDisposition parseXSSProtectionHeader(const String& header, String& failureReason, unsigned& failurePosition, String& reportURL)
357 DEFINE_STATIC_LOCAL(String, failureReasonInvalidToggle, ("expected 0 or 1"));
358 DEFINE_STATIC_LOCAL(String, failureReasonInvalidSeparator, ("expected semicolon"));
359 DEFINE_STATIC_LOCAL(String, failureReasonInvalidEquals, ("expected equals sign"));
360 DEFINE_STATIC_LOCAL(String, failureReasonInvalidMode, ("invalid mode directive"));
361 DEFINE_STATIC_LOCAL(String, failureReasonInvalidReport, ("invalid report directive"));
362 DEFINE_STATIC_LOCAL(String, failureReasonDuplicateMode, ("duplicate mode directive"));
363 DEFINE_STATIC_LOCAL(String, failureReasonDuplicateReport, ("duplicate report directive"));
364 DEFINE_STATIC_LOCAL(String, failureReasonInvalidDirective, ("unrecognized directive"));
368 if (!skipWhiteSpace(header, pos, false))
369 return ReflectedXSSUnset;
371 if (header[pos] == '0')
372 return AllowReflectedXSS;
374 if (header[pos++] != '1') {
375 failureReason = failureReasonInvalidToggle;
376 return ReflectedXSSInvalid;
379 ReflectedXSSDisposition result = FilterReflectedXSS;
380 bool modeDirectiveSeen = false;
381 bool reportDirectiveSeen = false;
384 // At end of previous directive: consume whitespace, semicolon, and whitespace.
385 if (!skipWhiteSpace(header, pos, false))
388 if (header[pos++] != ';') {
389 failureReason = failureReasonInvalidSeparator;
390 failurePosition = pos;
391 return ReflectedXSSInvalid;
394 if (!skipWhiteSpace(header, pos, false))
397 // At start of next directive.
398 if (skipToken(header, pos, "mode")) {
399 if (modeDirectiveSeen) {
400 failureReason = failureReasonDuplicateMode;
401 failurePosition = pos;
402 return ReflectedXSSInvalid;
404 modeDirectiveSeen = true;
405 if (!skipEquals(header, pos)) {
406 failureReason = failureReasonInvalidEquals;
407 failurePosition = pos;
408 return ReflectedXSSInvalid;
410 if (!skipToken(header, pos, "block")) {
411 failureReason = failureReasonInvalidMode;
412 failurePosition = pos;
413 return ReflectedXSSInvalid;
415 result = BlockReflectedXSS;
416 } else if (skipToken(header, pos, "report")) {
417 if (reportDirectiveSeen) {
418 failureReason = failureReasonDuplicateReport;
419 failurePosition = pos;
420 return ReflectedXSSInvalid;
422 reportDirectiveSeen = true;
423 if (!skipEquals(header, pos)) {
424 failureReason = failureReasonInvalidEquals;
425 failurePosition = pos;
426 return ReflectedXSSInvalid;
428 size_t startPos = pos;
429 if (!skipValue(header, pos)) {
430 failureReason = failureReasonInvalidReport;
431 failurePosition = pos;
432 return ReflectedXSSInvalid;
434 reportURL = header.substring(startPos, pos - startPos);
435 failurePosition = startPos; // If later semantic check deems unacceptable.
437 failureReason = failureReasonInvalidDirective;
438 failurePosition = pos;
439 return ReflectedXSSInvalid;
444 ContentTypeOptionsDisposition parseContentTypeOptionsHeader(const String& header)
446 if (header.stripWhiteSpace().lower() == "nosniff")
447 return ContentTypeOptionsNosniff;
448 return ContentTypeOptionsNone;
451 String extractReasonPhraseFromHTTPStatusLine(const String& statusLine)
453 size_t spacePos = statusLine.find(' ');
454 // Remove status code from the status line.
455 spacePos = statusLine.find(' ', spacePos + 1);
456 return statusLine.substring(spacePos + 1);
459 XFrameOptionsDisposition parseXFrameOptionsHeader(const String& header)
461 XFrameOptionsDisposition result = XFrameOptionsNone;
463 if (header.isEmpty())
466 Vector<String> headers;
467 header.split(',', headers);
469 for (size_t i = 0; i < headers.size(); i++) {
470 String currentHeader = headers[i].stripWhiteSpace();
471 XFrameOptionsDisposition currentValue = XFrameOptionsNone;
472 if (equalIgnoringCase(currentHeader, "deny"))
473 currentValue = XFrameOptionsDeny;
474 else if (equalIgnoringCase(currentHeader, "sameorigin"))
475 currentValue = XFrameOptionsSameOrigin;
476 else if (equalIgnoringCase(currentHeader, "allowall"))
477 currentValue = XFrameOptionsAllowAll;
479 currentValue = XFrameOptionsInvalid;
481 if (result == XFrameOptionsNone)
482 result = currentValue;
483 else if (result != currentValue)
484 return XFrameOptionsConflict;
489 bool parseRange(const String& range, long long& rangeOffset, long long& rangeEnd, long long& rangeSuffixLength)
491 // The format of "Range" header is defined in RFC 2616 Section 14.35.1.
492 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.1
493 // We don't support multiple range requests.
495 rangeOffset = rangeEnd = rangeSuffixLength = -1;
497 // The "bytes" unit identifier should be present.
498 static const char bytesStart[] = "bytes=";
499 if (!range.startsWith(bytesStart, false))
501 String byteRange = range.substring(sizeof(bytesStart) - 1);
503 // The '-' character needs to be present.
504 int index = byteRange.find('-');
508 // If the '-' character is at the beginning, the suffix length, which specifies the last N bytes, is provided.
512 String suffixLengthString = byteRange.substring(index + 1).stripWhiteSpace();
514 long long value = suffixLengthString.toInt64Strict(&ok);
516 rangeSuffixLength = value;
520 // Otherwise, the first-byte-position and the last-byte-position are provied.
524 String firstBytePosStr = byteRange.left(index).stripWhiteSpace();
526 long long firstBytePos = firstBytePosStr.toInt64Strict(&ok);
530 String lastBytePosStr = byteRange.substring(index + 1).stripWhiteSpace();
531 long long lastBytePos = -1;
532 if (!lastBytePosStr.isEmpty()) {
533 lastBytePos = lastBytePosStr.toInt64Strict(&ok);
538 if (firstBytePos < 0 || !(lastBytePos == -1 || lastBytePos >= firstBytePos))
541 rangeOffset = firstBytePos;
542 rangeEnd = lastBytePos;
546 // HTTP/1.1 - RFC 2616
547 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1
548 // Request-Line = Method SP Request-URI SP HTTP-Version CRLF
549 size_t parseHTTPRequestLine(const char* data, size_t length, String& failureReason, String& method, String& url, HTTPVersion& httpVersion)
553 httpVersion = Unknown;
555 const char* space1 = 0;
556 const char* space2 = 0;
558 size_t consumedLength;
560 for (p = data, consumedLength = 0; consumedLength < length; p++, consumedLength++) {
566 } else if (*p == '\n') {
571 // Haven't finished header line.
572 if (consumedLength == length) {
573 failureReason = "Incomplete Request Line";
577 // RequestLine does not contain 3 parts.
578 if (!space1 || !space2) {
579 failureReason = "Request Line does not appear to contain: <Method> <Url> <HTTPVersion>.";
583 // The line must end with "\r\n".
584 const char* end = p + 1;
585 if (*(end - 2) != '\r') {
586 failureReason = "Request line does not end with CRLF";
591 method = String(data, space1 - data); // For length subtract 1 for space, but add 1 for data being the first character.
594 url = String(space1 + 1, space2 - space1 - 1); // For length subtract 1 for space.
597 String httpVersionString(space2 + 1, end - space2 - 3); // For length subtract 1 for space, and 2 for "\r\n".
598 if (httpVersionString.length() != 8 || !httpVersionString.startsWith("HTTP/1."))
599 httpVersion = Unknown;
600 else if (httpVersionString[7] == '0')
601 httpVersion = HTTP_1_0;
602 else if (httpVersionString[7] == '1')
603 httpVersion = HTTP_1_1;
605 httpVersion = Unknown;
610 static bool parseHTTPHeaderName(const char* s, size_t start, size_t size, String& failureReason, size_t* position, AtomicString* name)
612 size_t nameBegin = start;
613 for (size_t i = start; i < size; ++i) {
616 failureReason = "Unexpected CR in name at " + trimInputSample(&s[nameBegin], i - nameBegin);
619 failureReason = "Unexpected LF in name at " + trimInputSample(&s[nameBegin], i - nameBegin);
622 if (i == nameBegin) {
623 failureReason = "Header name is missing";
626 *name = AtomicString::fromUTF8(&s[nameBegin], i - nameBegin);
627 if (name->isNull()) {
628 failureReason = "Invalid UTF-8 sequence in header name";
637 failureReason = "Unterminated header name";
641 static bool parseHTTPHeaderValue(const char* s, size_t start, size_t size, String& failureReason, size_t* position, AtomicString* value)
644 for (; i < size && s[i] == ' '; ++i) {
646 size_t valueBegin = i;
648 for (; i < size && s[i] != '\r'; ++i) {
650 failureReason = "Unexpected LF in value at " + trimInputSample(&s[valueBegin], i - valueBegin);
655 failureReason = "Unterminated header value";
659 ASSERT(i < size && s[i] == '\r');
660 if (i + 1 >= size || s[i + 1] != '\n') {
661 failureReason = "LF doesn't follow CR after value at " + trimInputSample(&s[i + 1], size - i - 1);
665 *value = AtomicString::fromUTF8(&s[valueBegin], i - valueBegin);
666 if (i != valueBegin && value->isNull()) {
667 failureReason = "Invalid UTF-8 sequence in header value";
671 // 2 for strlen("\r\n")
676 // Note that the header is already parsed and re-formatted in chromium side.
677 // We assume that the input is more restricted than RFC2616.
678 size_t parseHTTPHeader(const char* s, size_t size, String& failureReason, AtomicString& name, AtomicString& value)
682 if (size >= 1 && s[0] == '\r') {
683 if (size >= 2 && s[1] == '\n') {
684 // Skip an empty line.
687 failureReason = "LF doesn't follow CR at " + trimInputSample(0, size);
691 if (!parseHTTPHeaderName(s, current, size, failureReason, ¤t, &name)) {
694 ASSERT(s[current] == ':');
697 if (!parseHTTPHeaderValue(s, current, size, failureReason, ¤t, &value)) {
704 size_t parseHTTPRequestBody(const char* data, size_t length, Vector<unsigned char>& body)
707 body.append(data, length);
712 static bool isCacheHeaderSeparator(UChar c)
714 // See RFC 2616, Section 2.2
741 static bool isControlCharacter(UChar c)
743 return c < ' ' || c == 127;
746 static inline String trimToNextSeparator(const String& str)
748 return str.substring(0, str.find(isCacheHeaderSeparator));
751 static void parseCacheHeader(const String& header, Vector<pair<String, String> >& result)
753 const String safeHeader = header.removeCharacters(isControlCharacter);
754 unsigned max = safeHeader.length();
755 for (unsigned pos = 0; pos < max; /* pos incremented in loop */) {
756 size_t nextCommaPosition = safeHeader.find(',', pos);
757 size_t nextEqualSignPosition = safeHeader.find('=', pos);
758 if (nextEqualSignPosition != kNotFound && (nextEqualSignPosition < nextCommaPosition || nextCommaPosition == kNotFound)) {
759 // Get directive name, parse right hand side of equal sign, then add to map
760 String directive = trimToNextSeparator(safeHeader.substring(pos, nextEqualSignPosition - pos).stripWhiteSpace());
761 pos += nextEqualSignPosition - pos + 1;
763 String value = safeHeader.substring(pos, max - pos).stripWhiteSpace();
764 if (value[0] == '"') {
765 // The value is a quoted string
766 size_t nextDoubleQuotePosition = value.find('"', 1);
767 if (nextDoubleQuotePosition != kNotFound) {
768 // Store the value as a quoted string without quotes
769 result.append(pair<String, String>(directive, value.substring(1, nextDoubleQuotePosition - 1).stripWhiteSpace()));
770 pos += (safeHeader.find('"', pos) - pos) + nextDoubleQuotePosition + 1;
771 // Move past next comma, if there is one
772 size_t nextCommaPosition2 = safeHeader.find(',', pos);
773 if (nextCommaPosition2 != kNotFound)
774 pos += nextCommaPosition2 - pos + 1;
776 return; // Parse error if there is anything left with no comma
778 // Parse error; just use the rest as the value
779 result.append(pair<String, String>(directive, trimToNextSeparator(value.substring(1, value.length() - 1).stripWhiteSpace())));
783 // The value is a token until the next comma
784 size_t nextCommaPosition2 = value.find(',');
785 if (nextCommaPosition2 != kNotFound) {
786 // The value is delimited by the next comma
787 result.append(pair<String, String>(directive, trimToNextSeparator(value.substring(0, nextCommaPosition2).stripWhiteSpace())));
788 pos += (safeHeader.find(',', pos) - pos) + 1;
790 // The rest is the value; no change to value needed
791 result.append(pair<String, String>(directive, trimToNextSeparator(value)));
795 } else if (nextCommaPosition != kNotFound && (nextCommaPosition < nextEqualSignPosition || nextEqualSignPosition == kNotFound)) {
796 // Add directive to map with empty string as value
797 result.append(pair<String, String>(trimToNextSeparator(safeHeader.substring(pos, nextCommaPosition - pos).stripWhiteSpace()), ""));
798 pos += nextCommaPosition - pos + 1;
800 // Add last directive to map with empty string as value
801 result.append(pair<String, String>(trimToNextSeparator(safeHeader.substring(pos, max - pos).stripWhiteSpace()), ""));
807 CacheControlHeader parseCacheControlDirectives(const AtomicString& cacheControlValue, const AtomicString& pragmaValue)
809 CacheControlHeader cacheControlHeader;
810 cacheControlHeader.parsed = true;
811 cacheControlHeader.maxAge = std::numeric_limits<double>::quiet_NaN();
813 DEFINE_STATIC_LOCAL(const AtomicString, noCacheDirective, ("no-cache", AtomicString::ConstructFromLiteral));
814 DEFINE_STATIC_LOCAL(const AtomicString, noStoreDirective, ("no-store", AtomicString::ConstructFromLiteral));
815 DEFINE_STATIC_LOCAL(const AtomicString, mustRevalidateDirective, ("must-revalidate", AtomicString::ConstructFromLiteral));
816 DEFINE_STATIC_LOCAL(const AtomicString, maxAgeDirective, ("max-age", AtomicString::ConstructFromLiteral));
818 if (!cacheControlValue.isEmpty()) {
819 Vector<pair<String, String> > directives;
820 parseCacheHeader(cacheControlValue, directives);
822 size_t directivesSize = directives.size();
823 for (size_t i = 0; i < directivesSize; ++i) {
824 // RFC2616 14.9.1: A no-cache directive with a value is only meaningful for proxy caches.
825 // It should be ignored by a browser level cache.
826 if (equalIgnoringCase(directives[i].first, noCacheDirective) && directives[i].second.isEmpty()) {
827 cacheControlHeader.containsNoCache = true;
828 } else if (equalIgnoringCase(directives[i].first, noStoreDirective)) {
829 cacheControlHeader.containsNoStore = true;
830 } else if (equalIgnoringCase(directives[i].first, mustRevalidateDirective)) {
831 cacheControlHeader.containsMustRevalidate = true;
832 } else if (equalIgnoringCase(directives[i].first, maxAgeDirective)) {
833 if (!std::isnan(cacheControlHeader.maxAge)) {
834 // First max-age directive wins if there are multiple ones.
838 double maxAge = directives[i].second.toDouble(&ok);
840 cacheControlHeader.maxAge = maxAge;
845 if (!cacheControlHeader.containsNoCache) {
846 // Handle Pragma: no-cache
847 // This is deprecated and equivalent to Cache-control: no-cache
848 // Don't bother tokenizing the value, it is not important
849 cacheControlHeader.containsNoCache = pragmaValue.lower().contains(noCacheDirective);
851 return cacheControlHeader;