[WTF] Add makeUnique<T>, which ensures T is fast-allocated, makeUnique / makeUniqueWi...
[WebKit-https.git] / Source / WebCore / loader / LinkLoader.cpp
1 /*
2  * Copyright (C) 2011 Google Inc. All rights reserved.
3  * Copyright (C) 2016-2017 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 "HTMLSrcsetParser.h"
48 #include "LinkHeader.h"
49 #include "LinkPreloadResourceClients.h"
50 #include "LinkRelAttribute.h"
51 #include "LoaderStrategy.h"
52 #include "MIMETypeRegistry.h"
53 #include "MediaList.h"
54 #include "MediaQueryEvaluator.h"
55 #include "PlatformStrategies.h"
56 #include "ResourceError.h"
57 #include "RuntimeEnabledFeatures.h"
58 #include "Settings.h"
59 #include "SizesAttributeParser.h"
60 #include "StyleResolver.h"
61
62 namespace WebCore {
63
64 LinkLoader::LinkLoader(LinkLoaderClient& client)
65     : m_client(client)
66 {
67 }
68
69 LinkLoader::~LinkLoader()
70 {
71     if (m_cachedLinkResource)
72         m_cachedLinkResource->removeClient(*this);
73     if (m_preloadResourceClient)
74         m_preloadResourceClient->clear();
75 }
76
77 void LinkLoader::triggerEvents(const CachedResource& resource)
78 {
79     if (resource.errorOccurred())
80         m_client.linkLoadingErrored();
81     else
82         m_client.linkLoaded();
83 }
84
85 void LinkLoader::notifyFinished(CachedResource& resource)
86 {
87     ASSERT_UNUSED(resource, m_cachedLinkResource.get() == &resource);
88
89     triggerEvents(*m_cachedLinkResource);
90
91     m_cachedLinkResource->removeClient(*this);
92     m_cachedLinkResource = nullptr;
93 }
94
95 void LinkLoader::loadLinksFromHeader(const String& headerValue, const URL& baseURL, Document& document, MediaAttributeCheck mediaAttributeCheck)
96 {
97     if (headerValue.isEmpty())
98         return;
99     LinkHeaderSet headerSet(headerValue);
100     for (auto& header : headerSet) {
101         if (!header.valid() || header.url().isEmpty() || header.rel().isEmpty())
102             continue;
103         if ((mediaAttributeCheck == MediaAttributeCheck::MediaAttributeNotEmpty && !header.isViewportDependent())
104             || (mediaAttributeCheck == MediaAttributeCheck::MediaAttributeEmpty && header.isViewportDependent())) {
105                 continue;
106         }
107
108         LinkRelAttribute relAttribute(document, header.rel());
109         URL url(baseURL, header.url());
110         // Sanity check to avoid re-entrancy here.
111         if (equalIgnoringFragmentIdentifier(url, baseURL))
112             continue;
113
114         LinkLoadParameters params { relAttribute, url, header.as(), header.media(), header.mimeType(), header.crossOrigin(), header.imageSrcSet(), header.imageSizes() };
115         preconnectIfNeeded(params, document);
116         preloadIfNeeded(params, document, nullptr);
117     }
118 }
119
120 Optional<CachedResource::Type> LinkLoader::resourceTypeFromAsAttribute(const String& as)
121 {
122     if (equalLettersIgnoringASCIICase(as, "fetch"))
123         return CachedResource::Type::RawResource;
124     if (equalLettersIgnoringASCIICase(as, "image"))
125         return CachedResource::Type::ImageResource;
126     if (equalLettersIgnoringASCIICase(as, "script"))
127         return CachedResource::Type::Script;
128     if (equalLettersIgnoringASCIICase(as, "style"))
129         return CachedResource::Type::CSSStyleSheet;
130     if (RuntimeEnabledFeatures::sharedFeatures().mediaPreloadingEnabled() && (equalLettersIgnoringASCIICase(as, "video") || equalLettersIgnoringASCIICase(as, "audio")))
131         return CachedResource::Type::MediaResource;
132     if (equalLettersIgnoringASCIICase(as, "font"))
133         return CachedResource::Type::FontResource;
134 #if ENABLE(VIDEO_TRACK)
135     if (equalLettersIgnoringASCIICase(as, "track"))
136         return CachedResource::Type::TextTrackResource;
137 #endif
138     return WTF::nullopt;
139 }
140
141 static std::unique_ptr<LinkPreloadResourceClient> createLinkPreloadResourceClient(CachedResource& resource, LinkLoader& loader)
142 {
143     switch (resource.type()) {
144     case CachedResource::Type::ImageResource:
145         return makeUnique<LinkPreloadImageResourceClient>(loader, downcast<CachedImage>(resource));
146     case CachedResource::Type::Script:
147         return makeUnique<LinkPreloadDefaultResourceClient>(loader, downcast<CachedScript>(resource));
148     case CachedResource::Type::CSSStyleSheet:
149         return makeUnique<LinkPreloadStyleResourceClient>(loader, downcast<CachedCSSStyleSheet>(resource));
150     case CachedResource::Type::FontResource:
151         return makeUnique<LinkPreloadFontResourceClient>(loader, downcast<CachedFont>(resource));
152 #if ENABLE(VIDEO_TRACK)
153     case CachedResource::Type::TextTrackResource:
154         return makeUnique<LinkPreloadDefaultResourceClient>(loader, downcast<CachedTextTrack>(resource));
155 #endif
156     case CachedResource::Type::MediaResource:
157         ASSERT(RuntimeEnabledFeatures::sharedFeatures().mediaPreloadingEnabled());
158         FALLTHROUGH;
159     case CachedResource::Type::RawResource:
160         return makeUnique<LinkPreloadRawResourceClient>(loader, downcast<CachedRawResource>(resource));
161     case CachedResource::Type::MainResource:
162     case CachedResource::Type::Icon:
163 #if ENABLE(SVG_FONTS)
164     case CachedResource::Type::SVGFontResource:
165 #endif
166     case CachedResource::Type::SVGDocumentResource:
167 #if ENABLE(XSLT)
168     case CachedResource::Type::XSLStyleSheet:
169 #endif
170     case CachedResource::Type::Beacon:
171     case CachedResource::Type::Ping:
172     case CachedResource::Type::LinkPrefetch:
173 #if ENABLE(APPLICATION_MANIFEST)
174     case CachedResource::Type::ApplicationManifest:
175 #endif
176         // None of these values is currently supported as an `as` value.
177         ASSERT_NOT_REACHED();
178     }
179     return nullptr;
180 }
181
182 bool LinkLoader::isSupportedType(CachedResource::Type resourceType, const String& mimeType)
183 {
184     if (mimeType.isEmpty())
185         return true;
186     switch (resourceType) {
187     case CachedResource::Type::ImageResource:
188         return MIMETypeRegistry::isSupportedImageVideoOrSVGMIMEType(mimeType);
189     case CachedResource::Type::Script:
190         return MIMETypeRegistry::isSupportedJavaScriptMIMEType(mimeType);
191     case CachedResource::Type::CSSStyleSheet:
192         return MIMETypeRegistry::isSupportedStyleSheetMIMEType(mimeType);
193     case CachedResource::Type::FontResource:
194         return MIMETypeRegistry::isSupportedFontMIMEType(mimeType);
195     case CachedResource::Type::MediaResource:
196         if (!RuntimeEnabledFeatures::sharedFeatures().mediaPreloadingEnabled())
197             ASSERT_NOT_REACHED();
198         return MIMETypeRegistry::isSupportedMediaMIMEType(mimeType);
199
200 #if ENABLE(VIDEO_TRACK)
201     case CachedResource::Type::TextTrackResource:
202         return MIMETypeRegistry::isSupportedTextTrackMIMEType(mimeType);
203 #endif
204     case CachedResource::Type::RawResource:
205 #if ENABLE(APPLICATION_MANIFEST)
206     case CachedResource::Type::ApplicationManifest:
207 #endif
208         return true;
209     default:
210         ASSERT_NOT_REACHED();
211     }
212     return false;
213 }
214
215 void LinkLoader::preconnectIfNeeded(const LinkLoadParameters& params, Document& document)
216 {
217     const URL href = params.href;
218     if (!params.relAttribute.isLinkPreconnect || !href.isValid() || !params.href.protocolIsInHTTPFamily() || !document.frame())
219         return;
220     ASSERT(document.settings().linkPreconnectEnabled());
221     StoredCredentialsPolicy storageCredentialsPolicy = StoredCredentialsPolicy::Use;
222     if (equalIgnoringASCIICase(params.crossOrigin, "anonymous") && document.securityOrigin().canAccess(SecurityOrigin::create(href)))
223         storageCredentialsPolicy = StoredCredentialsPolicy::DoNotUse;
224     ASSERT(document.frame()->loader().networkingContext());
225     platformStrategies()->loaderStrategy()->preconnectTo(document.frame()->loader(), href, storageCredentialsPolicy, [weakDocument = makeWeakPtr(document), href](ResourceError error) {
226         if (!weakDocument)
227             return;
228
229         if (!error.isNull())
230             weakDocument->addConsoleMessage(MessageSource::Network, MessageLevel::Error, makeString("Failed to preconnect to "_s, href.string(), ". Error: "_s, error.localizedDescription()));
231         else
232             weakDocument->addConsoleMessage(MessageSource::Network, MessageLevel::Info, makeString("Successfuly preconnected to "_s, href.string()));
233     });
234 }
235
236 std::unique_ptr<LinkPreloadResourceClient> LinkLoader::preloadIfNeeded(const LinkLoadParameters& params, Document& document, LinkLoader* loader)
237 {
238     if (!document.loader() || !params.relAttribute.isLinkPreload)
239         return nullptr;
240
241     ASSERT(RuntimeEnabledFeatures::sharedFeatures().linkPreloadEnabled());
242     auto type = LinkLoader::resourceTypeFromAsAttribute(params.as);
243     if (!type) {
244         document.addConsoleMessage(MessageSource::Other, MessageLevel::Error, "<link rel=preload> must have a valid `as` value"_s);
245         return nullptr;
246     }
247     URL url;
248     if (RuntimeEnabledFeatures::sharedFeatures().linkPreloadResponsiveImagesEnabled() && type == CachedResource::Type::ImageResource && !params.imageSrcSet.isEmpty()) {
249         auto sourceSize = SizesAttributeParser(params.imageSizes, document).length();
250         auto candidate = bestFitSourceForImageAttributes(document.deviceScaleFactor(), params.href.string(), params.imageSrcSet, sourceSize);
251         url = document.completeURL(URL({ }, candidate.string.toString()));
252     } else
253         url = document.completeURL(params.href);
254
255     if (!url.isValid()) {
256         if (params.imageSrcSet.isEmpty())
257             document.addConsoleMessage(MessageSource::Other, MessageLevel::Error, "<link rel=preload> has an invalid `href` value"_s);
258         else
259             document.addConsoleMessage(MessageSource::Other, MessageLevel::Error, "<link rel=preload> has an invalid `imagesrcset` value"_s);
260         return nullptr;
261     }
262     if (!MediaQueryEvaluator::mediaAttributeMatches(document, params.media))
263         return nullptr;
264     if (!isSupportedType(type.value(), params.mimeType))
265         return nullptr;
266
267     auto options = CachedResourceLoader::defaultCachedResourceOptions();
268     auto linkRequest = createPotentialAccessControlRequest(url, document, params.crossOrigin, WTFMove(options));
269     linkRequest.setPriority(CachedResource::defaultPriorityForResourceType(type.value()));
270     linkRequest.setInitiator("link");
271     linkRequest.setIgnoreForRequestCount(true);
272     linkRequest.setIsLinkPreload();
273
274     auto cachedLinkResource = document.cachedResourceLoader().preload(type.value(), WTFMove(linkRequest)).value_or(nullptr);
275
276     if (cachedLinkResource && cachedLinkResource->type() != *type)
277         return nullptr;
278
279     if (cachedLinkResource && loader)
280         return createLinkPreloadResourceClient(*cachedLinkResource, *loader);
281     return nullptr;
282 }
283
284 void LinkLoader::prefetchIfNeeded(const LinkLoadParameters& params, Document& document)
285 {
286     if (!params.href.isValid() || !document.frame())
287         return;
288
289     ASSERT(RuntimeEnabledFeatures::sharedFeatures().linkPrefetchEnabled());
290     Optional<ResourceLoadPriority> priority;
291     CachedResource::Type type = CachedResource::Type::LinkPrefetch;
292
293     if (m_cachedLinkResource) {
294         m_cachedLinkResource->removeClient(*this);
295         m_cachedLinkResource = nullptr;
296     }
297     // FIXME: Add further prefetch restrictions/limitations:
298     // - third-party iframes cannot trigger prefetches
299     // - Number of prefetches of a given page is limited (to 1 maybe?)
300     ResourceLoaderOptions options = CachedResourceLoader::defaultCachedResourceOptions();
301     options.contentSecurityPolicyImposition = ContentSecurityPolicyImposition::SkipPolicyCheck;
302     options.certificateInfoPolicy = CertificateInfoPolicy::IncludeCertificateInfo;
303     options.credentials = FetchOptions::Credentials::SameOrigin;
304     options.redirect = FetchOptions::Redirect::Manual;
305     options.mode = FetchOptions::Mode::Navigate;
306     options.serviceWorkersMode = ServiceWorkersMode::None;
307     options.cachingPolicy = CachingPolicy::DisallowCaching;
308     m_cachedLinkResource = document.cachedResourceLoader().requestLinkResource(type, CachedResourceRequest(ResourceRequest { document.completeURL(params.href) }, options, priority)).value_or(nullptr);
309     if (m_cachedLinkResource)
310         m_cachedLinkResource->addClient(*this);
311 }
312
313 void LinkLoader::cancelLoad()
314 {
315     if (m_preloadResourceClient)
316         m_preloadResourceClient->clear();
317 }
318
319 void LinkLoader::loadLink(const LinkLoadParameters& params, Document& document)
320 {
321     if (params.relAttribute.isDNSPrefetch) {
322         // FIXME: The href attribute of the link element can be in "//hostname" form, and we shouldn't attempt
323         // to complete that as URL <https://bugs.webkit.org/show_bug.cgi?id=48857>.
324         if (document.settings().dnsPrefetchingEnabled() && params.href.isValid() && !params.href.isEmpty() && document.frame())
325             document.frame()->loader().client().prefetchDNS(params.href.host().toString());
326     }
327
328     preconnectIfNeeded(params, document);
329
330     if (params.relAttribute.isLinkPrefetch) {
331         prefetchIfNeeded(params, document);
332         return;
333     }
334
335     if (m_client.shouldLoadLink()) {
336         auto resourceClient = preloadIfNeeded(params, document, this);
337         if (m_preloadResourceClient)
338             m_preloadResourceClient->clear();
339         if (resourceClient)
340             m_preloadResourceClient = WTFMove(resourceClient);
341     }
342 }
343
344 }