2b161326430c10d592428d15b48772bef6a6903d
[WebKit-https.git] / Source / WebCore / loader / LinkLoader.cpp
1 /*
2  * Copyright (C) 2011 Google Inc. All rights reserved.
3  * Copyright (C) 2016 Apple 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 are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *     * Redistributions in binary form must reproduce the above
12  * copyright notice, this list of conditions and the following disclaimer
13  * in the documentation and/or other materials provided with the
14  * distribution.
15  *     * Neither the name of Google Inc. nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  *
31  */
32
33 #include "config.h"
34 #include "LinkLoader.h"
35
36 #include "CSSStyleSheet.h"
37 #include "CachedCSSStyleSheet.h"
38 #include "CachedResourceLoader.h"
39 #include "CachedResourceRequest.h"
40 #include "ContainerNode.h"
41 #include "CrossOriginAccessControl.h"
42 #include "Document.h"
43 #include "Frame.h"
44 #include "FrameLoader.h"
45 #include "FrameLoaderClient.h"
46 #include "FrameView.h"
47 #include "LinkHeader.h"
48 #include "LinkPreloadResourceClients.h"
49 #include "LinkRelAttribute.h"
50 #include "MIMETypeRegistry.h"
51 #include "MediaQueryEvaluator.h"
52 #include "RuntimeEnabledFeatures.h"
53 #include "Settings.h"
54 #include "StyleResolver.h"
55
56 namespace WebCore {
57
58 LinkLoader::LinkLoader(LinkLoaderClient& client)
59     : m_client(client)
60 {
61 }
62
63 LinkLoader::~LinkLoader()
64 {
65     if (m_cachedLinkResource)
66         m_cachedLinkResource->removeClient(*this);
67     if (m_preloadResourceClient)
68         m_preloadResourceClient->clear();
69 }
70
71 void LinkLoader::triggerEvents(const CachedResource& resource)
72 {
73     if (resource.errorOccurred())
74         m_client.linkLoadingErrored();
75     else
76         m_client.linkLoaded();
77 }
78
79 void LinkLoader::notifyFinished(CachedResource& resource)
80 {
81     ASSERT_UNUSED(resource, m_cachedLinkResource.get() == &resource);
82
83     triggerEvents(*m_cachedLinkResource);
84
85     m_cachedLinkResource->removeClient(*this);
86     m_cachedLinkResource = nullptr;
87 }
88
89 void LinkLoader::loadLinksFromHeader(const String& headerValue, const URL& baseURL, Document& document, MediaAttributeCheck mediaAttributeCheck)
90 {
91     if (headerValue.isEmpty())
92         return;
93     LinkHeaderSet headerSet(headerValue);
94     for (auto& header : headerSet) {
95         if (!header.valid() || header.url().isEmpty() || header.rel().isEmpty())
96             continue;
97         if (mediaAttributeCheck == MediaAttributeCheck::MediaAttributeNotEmpty) {
98             if (header.media().isEmpty())
99                 continue;
100         } else {
101             if (!header.media().isEmpty())
102                 continue;
103         }
104
105         LinkRelAttribute relAttribute(header.rel());
106         URL url(baseURL, header.url());
107         // Sanity check to avoid re-entrancy here.
108         if (equalIgnoringFragmentIdentifier(url, baseURL))
109             continue;
110         preloadIfNeeded(relAttribute, url, document, header.as(), header.media(), header.mimeType(), header.crossOrigin(), nullptr);
111     }
112 }
113
114 std::optional<CachedResource::Type> LinkLoader::resourceTypeFromAsAttribute(const String& as)
115 {
116     if (equalLettersIgnoringASCIICase(as, "fetch"))
117         return CachedResource::RawResource;
118     if (equalLettersIgnoringASCIICase(as, "image"))
119         return CachedResource::ImageResource;
120     if (equalLettersIgnoringASCIICase(as, "script"))
121         return CachedResource::Script;
122     if (equalLettersIgnoringASCIICase(as, "style"))
123         return CachedResource::CSSStyleSheet;
124     if (RuntimeEnabledFeatures::sharedFeatures().mediaPreloadingEnabled() && (equalLettersIgnoringASCIICase(as, "video") || equalLettersIgnoringASCIICase(as, "audio")))
125         return CachedResource::MediaResource;
126     if (equalLettersIgnoringASCIICase(as, "font"))
127         return CachedResource::FontResource;
128 #if ENABLE(VIDEO_TRACK)
129     if (equalLettersIgnoringASCIICase(as, "track"))
130         return CachedResource::TextTrackResource;
131 #endif
132     return std::nullopt;
133 }
134
135 static std::unique_ptr<LinkPreloadResourceClient> createLinkPreloadResourceClient(CachedResource& resource, LinkLoader& loader, CachedResource::Type type)
136 {
137     switch (type) {
138     case CachedResource::ImageResource:
139         return LinkPreloadImageResourceClient::create(loader, static_cast<CachedImage&>(resource));
140     case CachedResource::Script:
141         return LinkPreloadScriptResourceClient::create(loader, static_cast<CachedScript&>(resource));
142     case CachedResource::CSSStyleSheet:
143         return LinkPreloadStyleResourceClient::create(loader, static_cast<CachedCSSStyleSheet&>(resource));
144     case CachedResource::FontResource:
145         return LinkPreloadFontResourceClient::create(loader, static_cast<CachedFont&>(resource));
146     case CachedResource::MediaResource:
147         if (!RuntimeEnabledFeatures::sharedFeatures().mediaPreloadingEnabled())
148             ASSERT_NOT_REACHED();
149         FALLTHROUGH;
150 #if ENABLE(VIDEO_TRACK)
151     case CachedResource::TextTrackResource:
152 #endif
153     case CachedResource::RawResource:
154         return LinkPreloadRawResourceClient::create(loader, static_cast<CachedRawResource&>(resource));
155     case CachedResource::MainResource:
156     case CachedResource::Icon:
157 #if ENABLE(SVG_FONTS)
158     case CachedResource::SVGFontResource:
159 #endif
160     case CachedResource::SVGDocumentResource:
161 #if ENABLE(XSLT)
162     case CachedResource::XSLStyleSheet:
163 #endif
164     case CachedResource::Beacon:
165 #if ENABLE(LINK_PREFETCH)
166     case CachedResource::LinkSubresource:
167     case CachedResource::LinkPrefetch:
168 #endif
169         // None of these values is currently supported as an `as` value.
170         ASSERT_NOT_REACHED();
171     }
172     return nullptr;
173 }
174
175 bool LinkLoader::isSupportedType(CachedResource::Type resourceType, const String& mimeType)
176 {
177     if (mimeType.isEmpty())
178         return true;
179     switch (resourceType) {
180     case CachedResource::ImageResource:
181         return MIMETypeRegistry::isSupportedImageOrSVGMIMEType(mimeType);
182     case CachedResource::Script:
183         return MIMETypeRegistry::isSupportedJavaScriptMIMEType(mimeType);
184     case CachedResource::CSSStyleSheet:
185         return MIMETypeRegistry::isSupportedStyleSheetMIMEType(mimeType);
186     case CachedResource::FontResource:
187         return MIMETypeRegistry::isSupportedFontMIMEType(mimeType);
188     case CachedResource::MediaResource:
189         if (!RuntimeEnabledFeatures::sharedFeatures().mediaPreloadingEnabled())
190             ASSERT_NOT_REACHED();
191         return MIMETypeRegistry::isSupportedMediaMIMEType(mimeType);
192
193 #if ENABLE(VIDEO_TRACK)
194     case CachedResource::TextTrackResource:
195         return MIMETypeRegistry::isSupportedTextTrackMIMEType(mimeType);
196 #endif
197     case CachedResource::RawResource:
198         return true;
199     default:
200         ASSERT_NOT_REACHED();
201     }
202     return false;
203 }
204
205 std::unique_ptr<LinkPreloadResourceClient> LinkLoader::preloadIfNeeded(const LinkRelAttribute& relAttribute, const URL& href, Document& document, const String& as, const String& media, const String& mimeType, const String& crossOriginMode, LinkLoader* loader)
206 {
207     if (!document.loader() || !relAttribute.isLinkPreload)
208         return nullptr;
209
210     ASSERT(RuntimeEnabledFeatures::sharedFeatures().linkPreloadEnabled());
211     if (!href.isValid()) {
212         document.addConsoleMessage(MessageSource::Other, MessageLevel::Error, String("<link rel=preload> has an invalid `href` value"));
213         return nullptr;
214     }
215     auto type = LinkLoader::resourceTypeFromAsAttribute(as);
216     if (!type) {
217         document.addConsoleMessage(MessageSource::Other, MessageLevel::Error, String("<link rel=preload> must have a valid `as` value"));
218         return nullptr;
219     }
220     if (!MediaQueryEvaluator::mediaAttributeMatches(document, media))
221         return nullptr;
222     if (!isSupportedType(type.value(), mimeType))
223         return nullptr;
224
225     CachedResourceRequest linkRequest(document.completeURL(href), CachedResourceLoader::defaultCachedResourceOptions(), CachedResource::defaultPriorityForResourceType(type.value()));
226     linkRequest.setInitiator("link");
227     linkRequest.setIgnoreForRequestCount(true);
228     linkRequest.setIsLinkPreload();
229
230     linkRequest.setAsPotentiallyCrossOrigin(crossOriginMode, document);
231     auto cachedLinkResource = document.cachedResourceLoader().preload(type.value(), WTFMove(linkRequest)).valueOr(nullptr);
232
233     if (cachedLinkResource && loader)
234         return createLinkPreloadResourceClient(*cachedLinkResource, *loader, type.value());
235     return nullptr;
236 }
237
238 void LinkLoader::cancelLoad()
239 {
240     if (m_preloadResourceClient)
241         m_preloadResourceClient->clear();
242 }
243
244 bool LinkLoader::loadLink(const LinkRelAttribute& relAttribute, const URL& href, const String& as, const String& media, const String& mimeType, const String& crossOrigin, Document& document)
245 {
246     if (relAttribute.isDNSPrefetch) {
247         // FIXME: The href attribute of the link element can be in "//hostname" form, and we shouldn't attempt
248         // to complete that as URL <https://bugs.webkit.org/show_bug.cgi?id=48857>.
249         if (document.settings().dnsPrefetchingEnabled() && href.isValid() && !href.isEmpty() && document.frame())
250             document.frame()->loader().client().prefetchDNS(href.host());
251     }
252
253     if (m_client.shouldLoadLink()) {
254         auto resourceClient = preloadIfNeeded(relAttribute, href, document, as, media, mimeType, crossOrigin, this);
255         if (resourceClient)
256             m_preloadResourceClient = WTFMove(resourceClient);
257         else if (m_preloadResourceClient)
258             m_preloadResourceClient->clear();
259     }
260
261 #if ENABLE(LINK_PREFETCH)
262     if ((relAttribute.isLinkPrefetch || relAttribute.isLinkSubresource) && href.isValid() && document.frame()) {
263         if (!m_client.shouldLoadLink())
264             return false;
265
266         std::optional<ResourceLoadPriority> priority;
267         CachedResource::Type type = CachedResource::LinkPrefetch;
268         if (relAttribute.isLinkSubresource) {
269             // We only make one request to the cached resource loader if multiple rel types are specified;
270             // this is the higher priority, which should overwrite the lower priority.
271             priority = ResourceLoadPriority::Low;
272             type = CachedResource::LinkSubresource;
273         }
274
275         if (m_cachedLinkResource) {
276             m_cachedLinkResource->removeClient(*this);
277             m_cachedLinkResource = nullptr;
278         }
279         ResourceLoaderOptions options = CachedResourceLoader::defaultCachedResourceOptions();
280         options.contentSecurityPolicyImposition = ContentSecurityPolicyImposition::SkipPolicyCheck;
281         m_cachedLinkResource = document.cachedResourceLoader().requestLinkResource(type, CachedResourceRequest(ResourceRequest(document.completeURL(href)), options, priority)).valueOr(nullptr);
282         if (m_cachedLinkResource)
283             m_cachedLinkResource->addClient(*this);
284     }
285 #endif
286
287     return true;
288 }
289
290 }