1/*
2    Copyright (C) 1998 Lars Knoll (knoll@mpi-hd.mpg.de)
3    Copyright (C) 2001 Dirk Mueller (mueller@kde.org)
4    Copyright (C) 2002 Waldo Bastian (bastian@kde.org)
5    Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
6    Copyright (C) 2004, 2005, 2006 Apple Inc.
7
8    This library is free software; you can redistribute it and/or
9    modify it under the terms of the GNU Library General Public
10    License as published by the Free Software Foundation; either
11    version 2 of the License, or (at your option) any later version.
12
13    This library is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16    Library General Public License for more details.
17
18    You should have received a copy of the GNU Library General Public License
19    along with this library; see the file COPYING.LIB.  If not, write to
20    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21    Boston, MA 02110-1301, USA.
22
23    This class provides all functionality needed for loading images, style sheets and html
24    pages from the web. It has a memory cache for these objects.
25*/
26
27#include "config.h"
28#include "CachedCSSStyleSheet.h"
29
30#include "CSSStyleSheet.h"
31#include "CachedResourceClientWalker.h"
32#include "CachedStyleSheetClient.h"
33#include "HTTPHeaderNames.h"
34#include "HTTPParsers.h"
35#include "MemoryCache.h"
36#include "ResourceBuffer.h"
37#include "StyleSheetContents.h"
38#include "TextResourceDecoder.h"
39#include <wtf/CurrentTime.h>
40#include <wtf/Vector.h>
41
42namespace WebCore {
43
44CachedCSSStyleSheet::CachedCSSStyleSheet(const ResourceRequest& resourceRequest, const String& charset, SessionID sessionID)
45    : CachedResource(resourceRequest, CSSStyleSheet, sessionID)
46    , m_decoder(TextResourceDecoder::create("text/css", charset))
47{
48    // Prefer text/css but accept any type (dell.com serves a stylesheet
49    // as text/html; see <http://bugs.webkit.org/show_bug.cgi?id=11451>).
50    setAccept("text/css,*/*;q=0.1");
51}
52
53CachedCSSStyleSheet::~CachedCSSStyleSheet()
54{
55    if (m_parsedStyleSheetCache)
56        m_parsedStyleSheetCache->removedFromMemoryCache();
57}
58
59void CachedCSSStyleSheet::didAddClient(CachedResourceClient* c)
60{
61    ASSERT(c->resourceClientType() == CachedStyleSheetClient::expectedType());
62    // CachedResource::didAddClient() must be before setCSSStyleSheet(),
63    // because setCSSStyleSheet() may cause scripts to be executed, which could destroy 'c' if it is an instance of HTMLLinkElement.
64    // see the comment of HTMLLinkElement::setCSSStyleSheet.
65    CachedResource::didAddClient(c);
66
67    if (!isLoading())
68        static_cast<CachedStyleSheetClient*>(c)->setCSSStyleSheet(m_resourceRequest.url(), m_response.url(), m_decoder->encoding().name(), this);
69}
70
71void CachedCSSStyleSheet::setEncoding(const String& chs)
72{
73    m_decoder->setEncoding(chs, TextResourceDecoder::EncodingFromHTTPHeader);
74}
75
76String CachedCSSStyleSheet::encoding() const
77{
78    return m_decoder->encoding().name();
79}
80
81const String CachedCSSStyleSheet::sheetText(bool enforceMIMEType, bool* hasValidMIMEType) const
82{
83    ASSERT(!isPurgeable());
84
85    if (!m_data || m_data->isEmpty() || !canUseSheet(enforceMIMEType, hasValidMIMEType))
86        return String();
87
88    if (!m_decodedSheetText.isNull())
89        return m_decodedSheetText;
90
91    // Don't cache the decoded text, regenerating is cheap and it can use quite a bit of memory
92    return m_decoder->decodeAndFlush(m_data->data(), m_data->size());
93}
94
95void CachedCSSStyleSheet::finishLoading(ResourceBuffer* data)
96{
97    m_data = data;
98    setEncodedSize(m_data.get() ? m_data->size() : 0);
99    // Decode the data to find out the encoding and keep the sheet text around during checkNotify()
100    if (m_data)
101        m_decodedSheetText = m_decoder->decodeAndFlush(m_data->data(), m_data->size());
102    setLoading(false);
103    checkNotify();
104    // Clear the decoded text as it is unlikely to be needed immediately again and is cheap to regenerate.
105    m_decodedSheetText = String();
106}
107
108void CachedCSSStyleSheet::checkNotify()
109{
110    if (isLoading())
111        return;
112
113    CachedResourceClientWalker<CachedStyleSheetClient> w(m_clients);
114    while (CachedStyleSheetClient* c = w.next())
115        c->setCSSStyleSheet(m_resourceRequest.url(), m_response.url(), m_decoder->encoding().name(), this);
116}
117
118bool CachedCSSStyleSheet::canUseSheet(bool enforceMIMEType, bool* hasValidMIMEType) const
119{
120    if (errorOccurred())
121        return false;
122
123    if (!enforceMIMEType && !hasValidMIMEType)
124        return true;
125
126    // This check exactly matches Firefox.  Note that we grab the Content-Type
127    // header directly because we want to see what the value is BEFORE content
128    // sniffing.  Firefox does this by setting a "type hint" on the channel.
129    // This implementation should be observationally equivalent.
130    //
131    // This code defaults to allowing the stylesheet for non-HTTP protocols so
132    // folks can use standards mode for local HTML documents.
133    String mimeType = extractMIMETypeFromMediaType(response().httpHeaderField(HTTPHeaderName::ContentType));
134    bool typeOK = mimeType.isEmpty() || equalIgnoringCase(mimeType, "text/css") || equalIgnoringCase(mimeType, "application/x-unknown-content-type");
135    if (hasValidMIMEType)
136        *hasValidMIMEType = typeOK;
137    if (!enforceMIMEType)
138        return true;
139    return typeOK;
140}
141
142void CachedCSSStyleSheet::destroyDecodedData()
143{
144    if (!m_parsedStyleSheetCache)
145        return;
146
147    m_parsedStyleSheetCache->removedFromMemoryCache();
148    m_parsedStyleSheetCache.clear();
149
150    setDecodedSize(0);
151
152    if (!MemoryCache::shouldMakeResourcePurgeableOnEviction() && isSafeToMakePurgeable())
153        makePurgeable(true);
154}
155
156PassRefPtr<StyleSheetContents> CachedCSSStyleSheet::restoreParsedStyleSheet(const CSSParserContext& context)
157{
158    if (!m_parsedStyleSheetCache)
159        return 0;
160    if (m_parsedStyleSheetCache->hasFailedOrCanceledSubresources()) {
161        m_parsedStyleSheetCache->removedFromMemoryCache();
162        m_parsedStyleSheetCache.clear();
163        return 0;
164    }
165
166    ASSERT(m_parsedStyleSheetCache->isCacheable());
167    ASSERT(m_parsedStyleSheetCache->isInMemoryCache());
168
169    // Contexts must be identical so we know we would get the same exact result if we parsed again.
170    if (m_parsedStyleSheetCache->parserContext() != context)
171        return 0;
172
173    didAccessDecodedData(monotonicallyIncreasingTime());
174
175    return m_parsedStyleSheetCache;
176}
177
178void CachedCSSStyleSheet::saveParsedStyleSheet(PassRef<StyleSheetContents> sheet)
179{
180    ASSERT(sheet.get().isCacheable());
181
182    if (m_parsedStyleSheetCache)
183        m_parsedStyleSheetCache->removedFromMemoryCache();
184    m_parsedStyleSheetCache = WTF::move(sheet);
185    m_parsedStyleSheetCache->addedToMemoryCache();
186
187    setDecodedSize(m_parsedStyleSheetCache->estimatedSizeInBytes());
188}
189
190}
191