[preload] Add media and type attribute support.
[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 "FrameLoaderClient.h"
45 #include "FrameView.h"
46 #include "LinkHeader.h"
47 #include "LinkPreloadResourceClients.h"
48 #include "LinkRelAttribute.h"
49 #include "MIMETypeRegistry.h"
50 #include "MediaQueryEvaluator.h"
51 #include "RuntimeEnabledFeatures.h"
52 #include "Settings.h"
53 #include "StyleResolver.h"
54
55 namespace WebCore {
56
57 LinkLoader::LinkLoader(LinkLoaderClient& client)
58     : m_client(client)
59     , m_weakPtrFactory(this)
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, nullptr);
111     }
112 }
113
114 std::optional<CachedResource::Type> LinkLoader::resourceTypeFromAsAttribute(const String& as)
115 {
116     if (as.isEmpty())
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 (equalLettersIgnoringASCIICase(as, "media"))
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 ENABLE(VIDEO_TRACK)
148     case CachedResource::TextTrackResource:
149 #endif
150     case CachedResource::RawResource:
151         return LinkPreloadRawResourceClient::create(loader, static_cast<CachedRawResource&>(resource));
152     case CachedResource::MainResource:
153 #if ENABLE(SVG_FONTS)
154     case CachedResource::SVGFontResource:
155 #endif
156     case CachedResource::SVGDocumentResource:
157 #if ENABLE(XSLT)
158     case CachedResource::XSLStyleSheet:
159 #endif
160 #if ENABLE(LINK_PREFETCH)
161     case CachedResource::LinkSubresource:
162     case CachedResource::LinkPrefetch:
163 #endif
164         // None of these values is currently supported as an `as` value.
165         ASSERT_NOT_REACHED();
166     }
167     return nullptr;
168 }
169
170 bool LinkLoader::isSupportedType(CachedResource::Type resourceType, const String& mimeType)
171 {
172     if (mimeType.isEmpty())
173         return true;
174     switch (resourceType) {
175     case CachedResource::ImageResource:
176         return MIMETypeRegistry::isSupportedImageOrSVGMIMEType(mimeType);
177     case CachedResource::Script:
178         return MIMETypeRegistry::isSupportedJavaScriptMIMEType(mimeType);
179     case CachedResource::CSSStyleSheet:
180         return MIMETypeRegistry::isSupportedStyleSheetMIMEType(mimeType);
181     case CachedResource::FontResource:
182         return MIMETypeRegistry::isSupportedFontMIMEType(mimeType);
183     case CachedResource::MediaResource:
184         return MIMETypeRegistry::isSupportedMediaMIMEType(mimeType);
185 #if ENABLE(VIDEO_TRACK)
186     case CachedResource::TextTrackResource:
187         return MIMETypeRegistry::isSupportedTextTrackMIMEType(mimeType);
188 #endif
189     case CachedResource::RawResource:
190         return true;
191     default:
192         ASSERT_NOT_REACHED();
193     }
194     return false;
195 }
196
197 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, LinkLoaderClient* client)
198 {
199     if (!document.loader() || !relAttribute.isLinkPreload)
200         return nullptr;
201
202     ASSERT(RuntimeEnabledFeatures::sharedFeatures().linkPreloadEnabled());
203     if (!href.isValid()) {
204         document.addConsoleMessage(MessageSource::Other, MessageLevel::Error, String("<link rel=preload> has an invalid `href` value"));
205         return nullptr;
206     }
207     auto type = LinkLoader::resourceTypeFromAsAttribute(as);
208     if (!type) {
209         document.addConsoleMessage(MessageSource::Other, MessageLevel::Error, String("<link rel=preload> must have a valid `as` value"));
210         if (client)
211             client->linkLoadingErrored();
212         return nullptr;
213     }
214     if (!MediaQueryEvaluator::mediaAttributeMatches(document, media))
215         return nullptr;
216     if (!isSupportedType(type.value(), mimeType))
217         return nullptr;
218
219     ResourceRequest resourceRequest(document.completeURL(href));
220     resourceRequest.setIgnoreForRequestCount(true);
221     CachedResourceRequest linkRequest(WTFMove(resourceRequest), CachedResourceLoader::defaultCachedResourceOptions(), CachedResource::defaultPriorityForResourceType(type.value()));
222     linkRequest.setInitiator("link");
223     linkRequest.setIsLinkPreload();
224
225     linkRequest.setAsPotentiallyCrossOrigin(crossOriginMode, document);
226     CachedResourceHandle<CachedResource> cachedLinkResource = document.cachedResourceLoader().preload(type.value(), WTFMove(linkRequest));
227
228     if (cachedLinkResource && loader)
229         return createLinkPreloadResourceClient(*cachedLinkResource, *loader, type.value());
230     return nullptr;
231 }
232
233 void LinkLoader::cancelLoad()
234 {
235     if (m_preloadResourceClient)
236         m_preloadResourceClient->clear();
237 }
238
239 bool LinkLoader::loadLink(const LinkRelAttribute& relAttribute, const URL& href, const String& as, const String& media, const String& mimeType, const String& crossOrigin, Document& document)
240 {
241     if (relAttribute.isDNSPrefetch) {
242         // FIXME: The href attribute of the link element can be in "//hostname" form, and we shouldn't attempt
243         // to complete that as URL <https://bugs.webkit.org/show_bug.cgi?id=48857>.
244         if (document.settings().dnsPrefetchingEnabled() && href.isValid() && !href.isEmpty() && document.frame())
245             document.frame()->loader().client().prefetchDNS(href.host());
246     }
247
248     if (m_client.shouldLoadLink()) {
249         auto resourceClient = preloadIfNeeded(relAttribute, href, document, as, media, mimeType, crossOrigin, this, &m_client);
250         if (resourceClient)
251             m_preloadResourceClient = WTFMove(resourceClient);
252         else if (m_preloadResourceClient)
253             m_preloadResourceClient->clear();
254     }
255
256 #if ENABLE(LINK_PREFETCH)
257     if ((relAttribute.isLinkPrefetch || relAttribute.isLinkSubresource) && href.isValid() && document.frame()) {
258         if (!m_client.shouldLoadLink())
259             return false;
260
261         std::optional<ResourceLoadPriority> priority;
262         CachedResource::Type type = CachedResource::LinkPrefetch;
263         if (relAttribute.isLinkSubresource) {
264             // We only make one request to the cached resource loader if multiple rel types are specified;
265             // this is the higher priority, which should overwrite the lower priority.
266             priority = ResourceLoadPriority::Low;
267             type = CachedResource::LinkSubresource;
268         }
269
270         if (m_cachedLinkResource) {
271             m_cachedLinkResource->removeClient(*this);
272             m_cachedLinkResource = nullptr;
273         }
274         ResourceLoaderOptions options = CachedResourceLoader::defaultCachedResourceOptions();
275         options.contentSecurityPolicyImposition = ContentSecurityPolicyImposition::SkipPolicyCheck;
276         m_cachedLinkResource = document.cachedResourceLoader().requestLinkResource(type, CachedResourceRequest(ResourceRequest(document.completeURL(href)), options, priority));
277         if (m_cachedLinkResource)
278             m_cachedLinkResource->addClient(*this);
279     }
280 #endif
281
282     return true;
283 }
284
285 }