Add event support for link preload.
[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 "LinkPreloadResourceClients.h"
47 #include "LinkRelAttribute.h"
48 #include "RuntimeEnabledFeatures.h"
49 #include "Settings.h"
50 #include "StyleResolver.h"
51
52 namespace WebCore {
53
54 LinkLoader::LinkLoader(LinkLoaderClient& client)
55     : m_client(client)
56     , m_weakPtrFactory(this)
57 {
58 }
59
60 LinkLoader::~LinkLoader()
61 {
62     if (m_cachedLinkResource)
63         m_cachedLinkResource->removeClient(this);
64     if (m_preloadResourceClient)
65         m_preloadResourceClient->clear();
66 }
67
68 void LinkLoader::triggerEvents(const CachedResource* resource)
69 {
70     if (resource->errorOccurred())
71         m_client.linkLoadingErrored();
72     else
73         m_client.linkLoaded();
74 }
75
76 void LinkLoader::notifyFinished(CachedResource* resource)
77 {
78     ASSERT_UNUSED(resource, m_cachedLinkResource.get() == resource);
79
80     triggerEvents(m_cachedLinkResource.get());
81
82     m_cachedLinkResource->removeClient(this);
83     m_cachedLinkResource = nullptr;
84 }
85
86 Optional<CachedResource::Type> LinkLoader::resourceTypeFromAsAttribute(const String& as)
87 {
88     if (as.isEmpty())
89         return CachedResource::RawResource;
90     if (equalLettersIgnoringASCIICase(as, "image"))
91         return CachedResource::ImageResource;
92     if (equalLettersIgnoringASCIICase(as, "script"))
93         return CachedResource::Script;
94     if (equalLettersIgnoringASCIICase(as, "style"))
95         return CachedResource::CSSStyleSheet;
96     if (equalLettersIgnoringASCIICase(as, "media"))
97         return CachedResource::MediaResource;
98     if (equalLettersIgnoringASCIICase(as, "font"))
99         return CachedResource::FontResource;
100 #if ENABLE(VIDEO_TRACK)
101     if (equalLettersIgnoringASCIICase(as, "track"))
102         return CachedResource::TextTrackResource;
103 #endif
104     return Nullopt;
105 }
106
107 static std::unique_ptr<LinkPreloadResourceClient> createLinkPreloadResourceClient(CachedResource& resource, LinkLoader& loader, CachedResource::Type type)
108 {
109     switch (type) {
110     case CachedResource::ImageResource:
111         return LinkPreloadImageResourceClient::create(loader, static_cast<CachedImage&>(resource));
112     case CachedResource::Script:
113         return LinkPreloadScriptResourceClient::create(loader, static_cast<CachedScript&>(resource));
114     case CachedResource::CSSStyleSheet:
115         return LinkPreloadStyleResourceClient::create(loader, static_cast<CachedCSSStyleSheet&>(resource));
116     case CachedResource::FontResource:
117         return LinkPreloadFontResourceClient::create(loader, static_cast<CachedFont&>(resource));
118     case CachedResource::MediaResource:
119 #if ENABLE(VIDEO_TRACK)
120     case CachedResource::TextTrackResource:
121 #endif
122     case CachedResource::RawResource:
123         return LinkPreloadRawResourceClient::create(loader, static_cast<CachedRawResource&>(resource));
124     case CachedResource::MainResource:
125     case CachedResource::SVGFontResource:
126     case CachedResource::SVGDocumentResource:
127     case CachedResource::XSLStyleSheet:
128 #if ENABLE(LINK_PREFETCH)
129     case CachedResource::LinkSubresource:
130     case CachedResource::LinkPrefetch:
131 #endif
132         // None of these values is currently supported as an `as` value.
133         ASSERT_NOT_REACHED();
134     }
135     return nullptr;
136 }
137
138 void LinkLoader::preloadIfNeeded(const LinkRelAttribute& relAttribute, const URL& href, Document& document, const String& as, const String& crossOriginMode)
139 {
140     if (!document.loader() || !relAttribute.isLinkPreload)
141         return;
142
143     ASSERT(RuntimeEnabledFeatures::sharedFeatures().linkPreloadEnabled());
144     if (!href.isValid()) {
145         document.addConsoleMessage(MessageSource::Other, MessageLevel::Error, String("<link rel=preload> has an invalid `href` value"));
146         return;
147     }
148     auto type = LinkLoader::resourceTypeFromAsAttribute(as);
149     if (!type) {
150         document.addConsoleMessage(MessageSource::Other, MessageLevel::Error, String("<link rel=preload> must have a valid `as` value"));
151         m_client.linkLoadingErrored();
152         return;
153     }
154
155     ResourceRequest resourceRequest(document.completeURL(href));
156     resourceRequest.setIgnoreForRequestCount(true);
157     CachedResourceRequest linkRequest(resourceRequest, CachedResource::defaultPriorityForResourceType(type.value()));
158     linkRequest.setInitiator("link");
159
160     if (!crossOriginMode.isNull()) {
161         ASSERT(document.securityOrigin());
162         StoredCredentials allowCredentials = equalLettersIgnoringASCIICase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials;
163         updateRequestForAccessControl(linkRequest.mutableResourceRequest(), *document.securityOrigin(), allowCredentials);
164     }
165     linkRequest.setForPreload(true);
166     CachedResourceHandle<CachedResource> cachedLinkResource = document.cachedResourceLoader().preload(type.value(), linkRequest, emptyString(), CachedResourceLoader::ExplicitPreload);
167
168     if (cachedLinkResource)
169         m_preloadResourceClient = createLinkPreloadResourceClient(*cachedLinkResource, *this, type.value());
170 }
171
172 bool LinkLoader::loadLink(const LinkRelAttribute& relAttribute, const URL& href, const String& as, const String& crossOrigin, Document& document)
173 {
174     if (relAttribute.isDNSPrefetch) {
175         Settings* settings = document.settings();
176         // FIXME: The href attribute of the link element can be in "//hostname" form, and we shouldn't attempt
177         // to complete that as URL <https://bugs.webkit.org/show_bug.cgi?id=48857>.
178         if (settings && settings->dnsPrefetchingEnabled() && href.isValid() && !href.isEmpty() && document.frame())
179             document.frame()->loader().client().prefetchDNS(href.host());
180     }
181
182     if (m_client.shouldLoadLink())
183         preloadIfNeeded(relAttribute, href, document, as, crossOrigin);
184
185 #if ENABLE(LINK_PREFETCH)
186     if ((relAttribute.isLinkPrefetch || relAttribute.isLinkSubresource) && href.isValid() && document.frame()) {
187         if (!m_client.shouldLoadLink())
188             return false;
189
190         Optional<ResourceLoadPriority> priority;
191         CachedResource::Type type = CachedResource::LinkPrefetch;
192         if (relAttribute.isLinkSubresource) {
193             // We only make one request to the cached resource loader if multiple rel types are specified;
194             // this is the higher priority, which should overwrite the lower priority.
195             priority = ResourceLoadPriority::Low;
196             type = CachedResource::LinkSubresource;
197         }
198         CachedResourceRequest linkRequest(ResourceRequest(document.completeURL(href)), priority);
199
200         if (m_cachedLinkResource) {
201             m_cachedLinkResource->removeClient(this);
202             m_cachedLinkResource = nullptr;
203         }
204         m_cachedLinkResource = document.cachedResourceLoader().requestLinkResource(type, linkRequest);
205         if (m_cachedLinkResource)
206             m_cachedLinkResource->addClient(this);
207     }
208 #endif
209
210     return true;
211 }
212
213 }