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 Computer, 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 "core/fetch/CSSStyleSheetResource.h"
29
30#include "core/css/StyleSheetContents.h"
31#include "core/fetch/ResourceClientWalker.h"
32#include "core/fetch/StyleSheetResourceClient.h"
33#include "platform/SharedBuffer.h"
34#include "platform/network/HTTPParsers.h"
35#include "wtf/CurrentTime.h"
36
37namespace blink {
38
39CSSStyleSheetResource::CSSStyleSheetResource(const ResourceRequest& resourceRequest, const String& charset)
40    : StyleSheetResource(resourceRequest, CSSStyleSheet, "text/css", charset)
41{
42    DEFINE_STATIC_LOCAL(const AtomicString, acceptCSS, ("text/css,*/*;q=0.1", AtomicString::ConstructFromLiteral));
43
44    // Prefer text/css but accept any type (dell.com serves a stylesheet
45    // as text/html; see <http://bugs.webkit.org/show_bug.cgi?id=11451>).
46    setAccept(acceptCSS);
47}
48
49CSSStyleSheetResource::~CSSStyleSheetResource()
50{
51    // Make sure dispose() was cllaed before destruction.
52    ASSERT(!m_parsedStyleSheetCache);
53}
54
55void CSSStyleSheetResource::dispose()
56{
57    if (m_parsedStyleSheetCache)
58        m_parsedStyleSheetCache->removedFromMemoryCache();
59    m_parsedStyleSheetCache.clear();
60}
61
62void CSSStyleSheetResource::trace(Visitor* visitor)
63{
64    visitor->trace(m_parsedStyleSheetCache);
65    StyleSheetResource::trace(visitor);
66}
67
68void CSSStyleSheetResource::didAddClient(ResourceClient* c)
69{
70    ASSERT(c->resourceClientType() == StyleSheetResourceClient::expectedType());
71    // Resource::didAddClient() must be before setCSSStyleSheet(),
72    // because setCSSStyleSheet() may cause scripts to be executed, which could destroy 'c' if it is an instance of HTMLLinkElement.
73    // see the comment of HTMLLinkElement::setCSSStyleSheet.
74    Resource::didAddClient(c);
75
76    if (!isLoading())
77        static_cast<StyleSheetResourceClient*>(c)->setCSSStyleSheet(m_resourceRequest.url(), m_response.url(), encoding(), this);
78}
79
80const String CSSStyleSheetResource::sheetText(bool enforceMIMEType, bool* hasValidMIMEType) const
81{
82    ASSERT(!isPurgeable());
83
84    if (!m_data || m_data->isEmpty() || !canUseSheet(enforceMIMEType, hasValidMIMEType))
85        return String();
86
87    if (!m_decodedSheetText.isNull())
88        return m_decodedSheetText;
89
90    // Don't cache the decoded text, regenerating is cheap and it can use quite a bit of memory
91    return decodedText();
92}
93
94void CSSStyleSheetResource::checkNotify()
95{
96    // Decode the data to find out the encoding and keep the sheet text around during checkNotify()
97    if (m_data)
98        m_decodedSheetText = decodedText();
99
100    ResourceClientWalker<StyleSheetResourceClient> w(m_clients);
101    while (StyleSheetResourceClient* c = w.next())
102        c->setCSSStyleSheet(m_resourceRequest.url(), m_response.url(), encoding(), this);
103    // Clear the decoded text as it is unlikely to be needed immediately again and is cheap to regenerate.
104    m_decodedSheetText = String();
105}
106
107bool CSSStyleSheetResource::isSafeToUnlock() const
108{
109    return m_data->hasOneRef();
110}
111
112void CSSStyleSheetResource::destroyDecodedDataIfPossible()
113{
114    if (!m_parsedStyleSheetCache)
115        return;
116
117    m_parsedStyleSheetCache->removedFromMemoryCache();
118    m_parsedStyleSheetCache.clear();
119
120    setDecodedSize(0);
121}
122
123bool CSSStyleSheetResource::canUseSheet(bool enforceMIMEType, bool* hasValidMIMEType) const
124{
125    if (errorOccurred())
126        return false;
127
128    if (!enforceMIMEType && !hasValidMIMEType)
129        return true;
130
131    // This check exactly matches Firefox. Note that we grab the Content-Type
132    // header directly because we want to see what the value is BEFORE content
133    // sniffing. Firefox does this by setting a "type hint" on the channel.
134    // This implementation should be observationally equivalent.
135    //
136    // This code defaults to allowing the stylesheet for non-HTTP protocols so
137    // folks can use standards mode for local HTML documents.
138    const AtomicString& mimeType = extractMIMETypeFromMediaType(response().httpHeaderField("Content-Type"));
139    bool typeOK = mimeType.isEmpty() || equalIgnoringCase(mimeType, "text/css") || equalIgnoringCase(mimeType, "application/x-unknown-content-type");
140    if (hasValidMIMEType)
141        *hasValidMIMEType = typeOK;
142    if (!enforceMIMEType)
143        return true;
144    return typeOK;
145}
146
147PassRefPtrWillBeRawPtr<StyleSheetContents> CSSStyleSheetResource::restoreParsedStyleSheet(const CSSParserContext& context)
148{
149    if (!m_parsedStyleSheetCache)
150        return nullptr;
151    if (m_parsedStyleSheetCache->hasFailedOrCanceledSubresources()) {
152        m_parsedStyleSheetCache->removedFromMemoryCache();
153        m_parsedStyleSheetCache.clear();
154        return nullptr;
155    }
156
157    ASSERT(m_parsedStyleSheetCache->isCacheable());
158    ASSERT(m_parsedStyleSheetCache->isInMemoryCache());
159
160    // Contexts must be identical so we know we would get the same exact result if we parsed again.
161    if (m_parsedStyleSheetCache->parserContext() != context)
162        return nullptr;
163
164    didAccessDecodedData();
165
166    return m_parsedStyleSheetCache;
167}
168
169void CSSStyleSheetResource::saveParsedStyleSheet(PassRefPtrWillBeRawPtr<StyleSheetContents> sheet)
170{
171    ASSERT(sheet && sheet->isCacheable());
172
173    if (m_parsedStyleSheetCache)
174        m_parsedStyleSheetCache->removedFromMemoryCache();
175    m_parsedStyleSheetCache = sheet;
176    m_parsedStyleSheetCache->addedToMemoryCache();
177
178    setDecodedSize(m_parsedStyleSheetCache->estimatedSizeInBytes());
179}
180
181}
182