• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
3  * Copyright (C) 2009 Google Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include "config.h"
28 #include "ResourceResponseBase.h"
29 
30 #include "HTTPParsers.h"
31 #include "ResourceResponse.h"
32 #include <wtf/CurrentTime.h>
33 #include <wtf/MathExtras.h>
34 #include <wtf/StdLibExtras.h>
35 
36 using namespace std;
37 
38 namespace WebCore {
39 
40 static void parseCacheHeader(const String& header, Vector<pair<String, String> >& result);
41 
ResourceResponseBase()42 ResourceResponseBase::ResourceResponseBase()
43     : m_expectedContentLength(0)
44     , m_httpStatusCode(0)
45     , m_lastModifiedDate(0)
46     , m_isNull(true)
47     , m_haveParsedCacheControlHeader(false)
48     , m_haveParsedAgeHeader(false)
49     , m_haveParsedDateHeader(false)
50     , m_haveParsedExpiresHeader(false)
51     , m_haveParsedLastModifiedHeader(false)
52     , m_cacheControlContainsNoCache(false)
53     , m_cacheControlContainsNoStore(false)
54     , m_cacheControlContainsMustRevalidate(false)
55     , m_cacheControlMaxAge(0.0)
56     , m_age(0.0)
57     , m_date(0.0)
58     , m_expires(0.0)
59     , m_lastModified(0.0)
60 {
61 }
62 
ResourceResponseBase(const KURL & url,const String & mimeType,long long expectedLength,const String & textEncodingName,const String & filename)63 ResourceResponseBase::ResourceResponseBase(const KURL& url, const String& mimeType, long long expectedLength, const String& textEncodingName, const String& filename)
64     : m_url(url)
65     , m_mimeType(mimeType)
66     , m_expectedContentLength(expectedLength)
67     , m_textEncodingName(textEncodingName)
68     , m_suggestedFilename(filename)
69     , m_httpStatusCode(0)
70     , m_lastModifiedDate(0)
71     , m_isNull(false)
72     , m_haveParsedCacheControlHeader(false)
73     , m_haveParsedAgeHeader(false)
74     , m_haveParsedDateHeader(false)
75     , m_haveParsedExpiresHeader(false)
76     , m_haveParsedLastModifiedHeader(false)
77     , m_cacheControlContainsNoCache(false)
78     , m_cacheControlContainsNoStore(false)
79     , m_cacheControlContainsMustRevalidate(false)
80     , m_cacheControlMaxAge(0.0)
81     , m_age(0.0)
82     , m_date(0.0)
83     , m_expires(0.0)
84     , m_lastModified(0.0)
85 {
86 }
87 
adopt(auto_ptr<CrossThreadResourceResponseData> data)88 auto_ptr<ResourceResponse> ResourceResponseBase::adopt(auto_ptr<CrossThreadResourceResponseData> data)
89 {
90     auto_ptr<ResourceResponse> response(new ResourceResponse());
91     response->setURL(data->m_url);
92     response->setMimeType(data->m_mimeType);
93     response->setExpectedContentLength(data->m_expectedContentLength);
94     response->setTextEncodingName(data->m_textEncodingName);
95     response->setSuggestedFilename(data->m_suggestedFilename);
96 
97     response->setHTTPStatusCode(data->m_httpStatusCode);
98     response->setHTTPStatusText(data->m_httpStatusText);
99 
100     response->lazyInit();
101     response->m_httpHeaderFields.adopt(std::auto_ptr<CrossThreadHTTPHeaderMapData>(data->m_httpHeaders.release()));
102     response->setLastModifiedDate(data->m_lastModifiedDate);
103 
104     return response;
105 }
106 
copyData() const107 auto_ptr<CrossThreadResourceResponseData> ResourceResponseBase::copyData() const
108 {
109     auto_ptr<CrossThreadResourceResponseData> data(new CrossThreadResourceResponseData());
110     data->m_url = url().copy();
111     data->m_mimeType = mimeType().copy();
112     data->m_expectedContentLength = expectedContentLength();
113     data->m_textEncodingName = textEncodingName().copy();
114     data->m_suggestedFilename = suggestedFilename().copy();
115     data->m_httpStatusCode = httpStatusCode();
116     data->m_httpStatusText = httpStatusText().copy();
117     data->m_httpHeaders.adopt(httpHeaderFields().copyData());
118     data->m_lastModifiedDate = lastModifiedDate();
119     return data;
120 }
121 
isHTTP() const122 bool ResourceResponseBase::isHTTP() const
123 {
124     lazyInit();
125 
126     String protocol = m_url.protocol();
127 
128     return equalIgnoringCase(protocol, "http")  || equalIgnoringCase(protocol, "https");
129 }
130 
url() const131 const KURL& ResourceResponseBase::url() const
132 {
133     lazyInit();
134 
135     return m_url;
136 }
137 
setURL(const KURL & url)138 void ResourceResponseBase::setURL(const KURL& url)
139 {
140     lazyInit();
141     m_isNull = false;
142 
143     m_url = url;
144 }
145 
mimeType() const146 const String& ResourceResponseBase::mimeType() const
147 {
148     lazyInit();
149 
150     return m_mimeType;
151 }
152 
setMimeType(const String & mimeType)153 void ResourceResponseBase::setMimeType(const String& mimeType)
154 {
155     lazyInit();
156     m_isNull = false;
157 
158     m_mimeType = mimeType;
159 }
160 
expectedContentLength() const161 long long ResourceResponseBase::expectedContentLength() const
162 {
163     lazyInit();
164 
165     return m_expectedContentLength;
166 }
167 
setExpectedContentLength(long long expectedContentLength)168 void ResourceResponseBase::setExpectedContentLength(long long expectedContentLength)
169 {
170     lazyInit();
171     m_isNull = false;
172 
173     m_expectedContentLength = expectedContentLength;
174 }
175 
textEncodingName() const176 const String& ResourceResponseBase::textEncodingName() const
177 {
178     lazyInit();
179 
180     return m_textEncodingName;
181 }
182 
setTextEncodingName(const String & encodingName)183 void ResourceResponseBase::setTextEncodingName(const String& encodingName)
184 {
185     lazyInit();
186     m_isNull = false;
187 
188     m_textEncodingName = encodingName;
189 }
190 
191 // FIXME should compute this on the fly
suggestedFilename() const192 const String& ResourceResponseBase::suggestedFilename() const
193 {
194     lazyInit();
195 
196     return m_suggestedFilename;
197 }
198 
setSuggestedFilename(const String & suggestedName)199 void ResourceResponseBase::setSuggestedFilename(const String& suggestedName)
200 {
201     lazyInit();
202     m_isNull = false;
203 
204     m_suggestedFilename = suggestedName;
205 }
206 
httpStatusCode() const207 int ResourceResponseBase::httpStatusCode() const
208 {
209     lazyInit();
210 
211     return m_httpStatusCode;
212 }
213 
setHTTPStatusCode(int statusCode)214 void ResourceResponseBase::setHTTPStatusCode(int statusCode)
215 {
216     lazyInit();
217 
218     m_httpStatusCode = statusCode;
219 }
220 
httpStatusText() const221 const String& ResourceResponseBase::httpStatusText() const
222 {
223     lazyInit();
224 
225     return m_httpStatusText;
226 }
227 
setHTTPStatusText(const String & statusText)228 void ResourceResponseBase::setHTTPStatusText(const String& statusText)
229 {
230     lazyInit();
231 
232     m_httpStatusText = statusText;
233 }
234 
httpHeaderField(const AtomicString & name) const235 String ResourceResponseBase::httpHeaderField(const AtomicString& name) const
236 {
237     lazyInit();
238 
239     return m_httpHeaderFields.get(name);
240 }
241 
setHTTPHeaderField(const AtomicString & name,const String & value)242 void ResourceResponseBase::setHTTPHeaderField(const AtomicString& name, const String& value)
243 {
244     lazyInit();
245 
246     DEFINE_STATIC_LOCAL(const AtomicString, ageHeader, ("age"));
247     DEFINE_STATIC_LOCAL(const AtomicString, cacheControlHeader, ("cache-control"));
248     DEFINE_STATIC_LOCAL(const AtomicString, dateHeader, ("date"));
249     DEFINE_STATIC_LOCAL(const AtomicString, expiresHeader, ("expires"));
250     DEFINE_STATIC_LOCAL(const AtomicString, lastModifiedHeader, ("last-modified"));
251     DEFINE_STATIC_LOCAL(const AtomicString, pragmaHeader, ("pragma"));
252     if (equalIgnoringCase(name, ageHeader))
253         m_haveParsedAgeHeader = false;
254     else if (equalIgnoringCase(name, cacheControlHeader) || equalIgnoringCase(name, pragmaHeader))
255         m_haveParsedCacheControlHeader = false;
256     else if (equalIgnoringCase(name, dateHeader))
257         m_haveParsedDateHeader = false;
258     else if (equalIgnoringCase(name, expiresHeader))
259         m_haveParsedExpiresHeader = false;
260     else if (equalIgnoringCase(name, lastModifiedHeader))
261         m_haveParsedLastModifiedHeader = false;
262 
263     m_httpHeaderFields.set(name, value);
264 }
265 
httpHeaderFields() const266 const HTTPHeaderMap& ResourceResponseBase::httpHeaderFields() const
267 {
268     lazyInit();
269 
270     return m_httpHeaderFields;
271 }
272 
parseCacheControlDirectives() const273 void ResourceResponseBase::parseCacheControlDirectives() const
274 {
275     ASSERT(!m_haveParsedCacheControlHeader);
276 
277     lazyInit();
278 
279     m_haveParsedCacheControlHeader = true;
280 
281     m_cacheControlContainsMustRevalidate = false;
282     m_cacheControlContainsNoCache = false;
283     m_cacheControlMaxAge = numeric_limits<double>::quiet_NaN();
284 
285     DEFINE_STATIC_LOCAL(const AtomicString, cacheControlString, ("cache-control"));
286     DEFINE_STATIC_LOCAL(const AtomicString, noCacheDirective, ("no-cache"));
287     DEFINE_STATIC_LOCAL(const AtomicString, noStoreDirective, ("no-store"));
288     DEFINE_STATIC_LOCAL(const AtomicString, mustRevalidateDirective, ("must-revalidate"));
289     DEFINE_STATIC_LOCAL(const AtomicString, maxAgeDirective, ("max-age"));
290 
291     String cacheControlValue = m_httpHeaderFields.get(cacheControlString);
292     if (!cacheControlValue.isEmpty()) {
293         Vector<pair<String, String> > directives;
294         parseCacheHeader(cacheControlValue, directives);
295 
296         size_t directivesSize = directives.size();
297         for (size_t i = 0; i < directivesSize; ++i) {
298             // RFC2616 14.9.1: A no-cache directive with a value is only meaningful for proxy caches.
299             // It should be ignored by a browser level cache.
300             if (equalIgnoringCase(directives[i].first, noCacheDirective) && directives[i].second.isEmpty())
301                 m_cacheControlContainsNoCache = true;
302             else if (equalIgnoringCase(directives[i].first, noStoreDirective))
303                 m_cacheControlContainsNoStore = true;
304             else if (equalIgnoringCase(directives[i].first, mustRevalidateDirective))
305                 m_cacheControlContainsMustRevalidate = true;
306             else if (equalIgnoringCase(directives[i].first, maxAgeDirective)) {
307                 bool ok;
308                 double maxAge = directives[i].second.toDouble(&ok);
309                 if (ok)
310                     m_cacheControlMaxAge = maxAge;
311             }
312         }
313     }
314 
315     if (!m_cacheControlContainsNoCache) {
316         // Handle Pragma: no-cache
317         // This is deprecated and equivalent to Cache-control: no-cache
318         // Don't bother tokenizing the value, it is not important
319         DEFINE_STATIC_LOCAL(const AtomicString, pragmaHeader, ("pragma"));
320         String pragmaValue = m_httpHeaderFields.get(pragmaHeader);
321         m_cacheControlContainsNoCache = pragmaValue.lower().contains(noCacheDirective);
322     }
323 }
324 
cacheControlContainsNoCache() const325 bool ResourceResponseBase::cacheControlContainsNoCache() const
326 {
327     if (!m_haveParsedCacheControlHeader)
328         parseCacheControlDirectives();
329     return m_cacheControlContainsNoCache;
330 }
331 
cacheControlContainsNoStore() const332 bool ResourceResponseBase::cacheControlContainsNoStore() const
333 {
334     if (!m_haveParsedCacheControlHeader)
335         parseCacheControlDirectives();
336     return m_cacheControlContainsNoStore;
337 }
338 
cacheControlContainsMustRevalidate() const339 bool ResourceResponseBase::cacheControlContainsMustRevalidate() const
340 {
341     if (!m_haveParsedCacheControlHeader)
342         parseCacheControlDirectives();
343     return m_cacheControlContainsMustRevalidate;
344 }
345 
cacheControlMaxAge() const346 double ResourceResponseBase::cacheControlMaxAge() const
347 {
348     if (!m_haveParsedCacheControlHeader)
349         parseCacheControlDirectives();
350     return m_cacheControlMaxAge;
351 }
352 
parseDateValueInHeader(const HTTPHeaderMap & headers,const AtomicString & headerName)353 static double parseDateValueInHeader(const HTTPHeaderMap& headers, const AtomicString& headerName)
354 {
355     String headerValue = headers.get(headerName);
356     if (headerValue.isEmpty())
357         return std::numeric_limits<double>::quiet_NaN();
358     // This handles all date formats required by RFC2616:
359     // Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
360     // Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
361     // Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
362     double dateInMilliseconds = parseDate(headerValue);
363     if (!isfinite(dateInMilliseconds))
364         return std::numeric_limits<double>::quiet_NaN();
365     return dateInMilliseconds / 1000;
366 }
367 
date() const368 double ResourceResponseBase::date() const
369 {
370     lazyInit();
371 
372     if (!m_haveParsedDateHeader) {
373         DEFINE_STATIC_LOCAL(const AtomicString, headerName, ("date"));
374         m_date = parseDateValueInHeader(m_httpHeaderFields, headerName);
375         m_haveParsedDateHeader = true;
376     }
377     return m_date;
378 }
379 
age() const380 double ResourceResponseBase::age() const
381 {
382     lazyInit();
383 
384     if (!m_haveParsedAgeHeader) {
385         DEFINE_STATIC_LOCAL(const AtomicString, headerName, ("age"));
386         String headerValue = m_httpHeaderFields.get(headerName);
387         bool ok;
388         m_age = headerValue.toDouble(&ok);
389         if (!ok)
390             m_age = std::numeric_limits<double>::quiet_NaN();
391         m_haveParsedAgeHeader = true;
392     }
393     return m_age;
394 }
395 
expires() const396 double ResourceResponseBase::expires() const
397 {
398     lazyInit();
399 
400     if (!m_haveParsedExpiresHeader) {
401         DEFINE_STATIC_LOCAL(const AtomicString, headerName, ("expires"));
402         m_expires = parseDateValueInHeader(m_httpHeaderFields, headerName);
403         m_haveParsedExpiresHeader = true;
404     }
405     return m_expires;
406 }
407 
lastModified() const408 double ResourceResponseBase::lastModified() const
409 {
410     lazyInit();
411 
412     if (!m_haveParsedLastModifiedHeader) {
413         DEFINE_STATIC_LOCAL(const AtomicString, headerName, ("last-modified"));
414         m_lastModified = parseDateValueInHeader(m_httpHeaderFields, headerName);
415         m_haveParsedLastModifiedHeader = true;
416     }
417     return m_lastModified;
418 }
419 
isAttachment() const420 bool ResourceResponseBase::isAttachment() const
421 {
422     lazyInit();
423 
424     DEFINE_STATIC_LOCAL(const AtomicString, headerName, ("content-disposition"));
425     String value = m_httpHeaderFields.get(headerName);
426     int loc = value.find(';');
427     if (loc != -1)
428         value = value.left(loc);
429     value = value.stripWhiteSpace();
430     DEFINE_STATIC_LOCAL(const AtomicString, attachmentString, ("attachment"));
431     return equalIgnoringCase(value, attachmentString);
432 }
433 
setLastModifiedDate(time_t lastModifiedDate)434 void ResourceResponseBase::setLastModifiedDate(time_t lastModifiedDate)
435 {
436     lazyInit();
437 
438     m_lastModifiedDate = lastModifiedDate;
439 }
440 
lastModifiedDate() const441 time_t ResourceResponseBase::lastModifiedDate() const
442 {
443     lazyInit();
444 
445     return m_lastModifiedDate;
446 }
447 
lazyInit() const448 void ResourceResponseBase::lazyInit() const
449 {
450     const_cast<ResourceResponse*>(static_cast<const ResourceResponse*>(this))->platformLazyInit();
451 }
452 
compare(const ResourceResponse & a,const ResourceResponse & b)453 bool ResourceResponseBase::compare(const ResourceResponse& a, const ResourceResponse& b)
454 {
455     if (a.isNull() != b.isNull())
456         return false;
457     if (a.url() != b.url())
458         return false;
459     if (a.mimeType() != b.mimeType())
460         return false;
461     if (a.expectedContentLength() != b.expectedContentLength())
462         return false;
463     if (a.textEncodingName() != b.textEncodingName())
464         return false;
465     if (a.suggestedFilename() != b.suggestedFilename())
466         return false;
467     if (a.httpStatusCode() != b.httpStatusCode())
468         return false;
469     if (a.httpStatusText() != b.httpStatusText())
470         return false;
471     if (a.httpHeaderFields() != b.httpHeaderFields())
472         return false;
473     return ResourceResponse::platformCompare(a, b);
474 }
475 
isCacheHeaderSeparator(UChar c)476 static bool isCacheHeaderSeparator(UChar c)
477 {
478     // See RFC 2616, Section 2.2
479     switch (c) {
480         case '(':
481         case ')':
482         case '<':
483         case '>':
484         case '@':
485         case ',':
486         case ';':
487         case ':':
488         case '\\':
489         case '"':
490         case '/':
491         case '[':
492         case ']':
493         case '?':
494         case '=':
495         case '{':
496         case '}':
497         case ' ':
498         case '\t':
499             return true;
500         default:
501             return false;
502     }
503 }
504 
isControlCharacter(UChar c)505 static bool isControlCharacter(UChar c)
506 {
507     return c < ' ' || c == 127;
508 }
509 
trimToNextSeparator(const String & str)510 static inline String trimToNextSeparator(const String& str)
511 {
512     return str.substring(0, str.find(isCacheHeaderSeparator, 0));
513 }
514 
parseCacheHeader(const String & header,Vector<pair<String,String>> & result)515 static void parseCacheHeader(const String& header, Vector<pair<String, String> >& result)
516 {
517     const String safeHeader = header.removeCharacters(isControlCharacter);
518     unsigned max = safeHeader.length();
519     for (unsigned pos = 0; pos < max; /* pos incremented in loop */) {
520         int nextCommaPosition = safeHeader.find(',', pos);
521         int nextEqualSignPosition = safeHeader.find('=', pos);
522         if (nextEqualSignPosition >= 0 && (nextEqualSignPosition < nextCommaPosition || nextCommaPosition < 0)) {
523             // Get directive name, parse right hand side of equal sign, then add to map
524             String directive = trimToNextSeparator(safeHeader.substring(pos, nextEqualSignPosition - pos).stripWhiteSpace());
525             pos += nextEqualSignPosition - pos + 1;
526 
527             String value = safeHeader.substring(pos, max - pos).stripWhiteSpace();
528             if (value[0] == '"') {
529                 // The value is a quoted string
530                 int nextDoubleQuotePosition = value.find('"', 1);
531                 if (nextDoubleQuotePosition >= 0) {
532                     // Store the value as a quoted string without quotes
533                     result.append(pair<String, String>(directive, value.substring(1, nextDoubleQuotePosition - 1).stripWhiteSpace()));
534                     pos += (safeHeader.find('"', pos) - pos) + nextDoubleQuotePosition + 1;
535                     // Move past next comma, if there is one
536                     int nextCommaPosition2 = safeHeader.find(',', pos);
537                     if (nextCommaPosition2 >= 0)
538                         pos += nextCommaPosition2 - pos + 1;
539                     else
540                         return; // Parse error if there is anything left with no comma
541                 } else {
542                     // Parse error; just use the rest as the value
543                     result.append(pair<String, String>(directive, trimToNextSeparator(value.substring(1, value.length() - 1).stripWhiteSpace())));
544                     return;
545                 }
546             } else {
547                 // The value is a token until the next comma
548                 int nextCommaPosition2 = value.find(',', 0);
549                 if (nextCommaPosition2 >= 0) {
550                     // The value is delimited by the next comma
551                     result.append(pair<String, String>(directive, trimToNextSeparator(value.substring(0, nextCommaPosition2).stripWhiteSpace())));
552                     pos += (safeHeader.find(',', pos) - pos) + 1;
553                 } else {
554                     // The rest is the value; no change to value needed
555                     result.append(pair<String, String>(directive, trimToNextSeparator(value)));
556                     return;
557                 }
558             }
559         } else if (nextCommaPosition >= 0 && (nextCommaPosition < nextEqualSignPosition || nextEqualSignPosition < 0)) {
560             // Add directive to map with empty string as value
561             result.append(pair<String, String>(trimToNextSeparator(safeHeader.substring(pos, nextCommaPosition - pos).stripWhiteSpace()), ""));
562             pos += nextCommaPosition - pos + 1;
563         } else {
564             // Add last directive to map with empty string as value
565             result.append(pair<String, String>(trimToNextSeparator(safeHeader.substring(pos, max - pos).stripWhiteSpace()), ""));
566             return;
567         }
568     }
569 }
570 
571 }
572