8077d5a5fe8ac58b6e61deb728fec85b3262dbb5
[WebKit-https.git] / Source / WebCore / loader / MediaResourceLoader.cpp
1 /*
2  * Copyright (C) 2014 Igalia S.L
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
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
16  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
18  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
24  * THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28 #include "MediaResourceLoader.h"
29
30 #if ENABLE(VIDEO)
31
32 #include "CachedRawResource.h"
33 #include "CachedResourceLoader.h"
34 #include "CachedResourceRequest.h"
35 #include "CrossOriginAccessControl.h"
36 #include "Document.h"
37 #include "HTMLMediaElement.h"
38 #include "SecurityOrigin.h"
39 #include <wtf/NeverDestroyed.h>
40
41 namespace WebCore {
42
43 MediaResourceLoader::MediaResourceLoader(Document& document, HTMLMediaElement& mediaElement, const String& crossOriginMode)
44     : ContextDestructionObserver(&document)
45     , m_document(&document)
46     , m_mediaElement(makeWeakPtr(mediaElement))
47     , m_crossOriginMode(crossOriginMode)
48 {
49 }
50
51 MediaResourceLoader::~MediaResourceLoader()
52 {
53     ASSERT(m_resources.isEmpty());
54 }
55
56 void MediaResourceLoader::contextDestroyed()
57 {
58     ContextDestructionObserver::contextDestroyed();
59     m_document = nullptr;
60     m_mediaElement = nullptr;
61 }
62
63 RefPtr<PlatformMediaResource> MediaResourceLoader::requestResource(ResourceRequest&& request, LoadOptions options)
64 {
65     if (!m_document)
66         return nullptr;
67
68     DataBufferingPolicy bufferingPolicy = options & LoadOption::BufferData ? WebCore::BufferData : WebCore::DoNotBufferData;
69     auto cachingPolicy = options & LoadOption::DisallowCaching ? CachingPolicy::DisallowCaching : CachingPolicy::AllowCaching;
70
71     request.setRequester(ResourceRequest::Requester::Media);
72 #if HAVE(AVFOUNDATION_LOADER_DELEGATE) && PLATFORM(MAC)
73     // FIXME: Workaround for <rdar://problem/26071607>. We are not able to do CORS checking on 304 responses because they are usually missing the headers we need.
74     if (!m_crossOriginMode.isNull())
75         request.makeUnconditional();
76 #endif
77
78     ContentSecurityPolicyImposition contentSecurityPolicyImposition = m_mediaElement && m_mediaElement->isInUserAgentShadowTree() ? ContentSecurityPolicyImposition::SkipPolicyCheck : ContentSecurityPolicyImposition::DoPolicyCheck;
79     ResourceLoaderOptions loaderOptions { SendCallbacks, DoNotSniffContent, bufferingPolicy, StoredCredentialsPolicy::Use, ClientCredentialPolicy::MayAskClientForCredentials, FetchOptions::Credentials::Include,  DoSecurityCheck, FetchOptions::Mode::NoCors, DoNotIncludeCertificateInfo, contentSecurityPolicyImposition, DefersLoadingPolicy::AllowDefersLoading, cachingPolicy };
80     loaderOptions.destination = m_mediaElement && !m_mediaElement->isVideo() ? FetchOptions::Destination::Audio : FetchOptions::Destination::Video;
81     CachedResourceRequest cacheRequest { WTFMove(request), WTFMove(loaderOptions) };
82     cacheRequest.setAsPotentiallyCrossOrigin(m_crossOriginMode, *m_document);
83     if (m_mediaElement)
84         cacheRequest.setInitiator(*m_mediaElement.get());
85
86     auto resource = m_document->cachedResourceLoader().requestMedia(WTFMove(cacheRequest)).value_or(nullptr);
87     if (!resource)
88         return nullptr;
89
90     Ref<MediaResource> mediaResource = MediaResource::create(*this, resource);
91     m_resources.add(mediaResource.ptr());
92
93     return WTFMove(mediaResource);
94 }
95
96 void MediaResourceLoader::removeResource(MediaResource& mediaResource)
97 {
98     ASSERT(m_resources.contains(&mediaResource));
99     m_resources.remove(&mediaResource);
100 }
101
102 void MediaResourceLoader::addResponseForTesting(const ResourceResponse& response)
103 {
104     const auto maximumResponsesForTesting = 5;
105     if (m_responsesForTesting.size() > maximumResponsesForTesting)
106         return;
107     m_responsesForTesting.append(response);
108 }
109
110 Ref<MediaResource> MediaResource::create(MediaResourceLoader& loader, CachedResourceHandle<CachedRawResource> resource)
111 {
112     return adoptRef(*new MediaResource(loader, resource));
113 }
114
115 MediaResource::MediaResource(MediaResourceLoader& loader, CachedResourceHandle<CachedRawResource> resource)
116     : m_loader(loader)
117     , m_resource(resource)
118 {
119     ASSERT(resource);
120     resource->addClient(*this);
121 }
122
123 MediaResource::~MediaResource()
124 {
125     stop();
126     m_loader->removeResource(*this);
127 }
128
129 void MediaResource::stop()
130 {
131     if (!m_resource)
132         return;
133
134     m_resource->removeClient(*this);
135     m_resource = nullptr;
136 }
137
138 void MediaResource::setDefersLoading(bool defersLoading)
139 {
140     if (m_resource)
141         m_resource->setDefersLoading(defersLoading);
142 }
143
144 void MediaResource::responseReceived(CachedResource& resource, const ResourceResponse& response, CompletionHandler<void()>&& completionHandler)
145 {
146     ASSERT_UNUSED(resource, &resource == m_resource);
147     CompletionHandlerCallingScope completionHandlerCaller(WTFMove(completionHandler));
148
149     if (!m_loader->document())
150         return;
151
152     RefPtr<MediaResource> protectedThis(this);
153     if (m_resource->resourceError().isAccessControl()) {
154         static NeverDestroyed<const String> consoleMessage("Cross-origin media resource load denied by Cross-Origin Resource Sharing policy.");
155         m_loader->document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, consoleMessage.get());
156         m_didPassAccessControlCheck = false;
157         if (m_client)
158             m_client->accessControlCheckFailed(*this, ResourceError(errorDomainWebKitInternal, 0, response.url(), consoleMessage.get()));
159         stop();
160         return;
161     }
162
163     m_didPassAccessControlCheck = m_resource->options().mode == FetchOptions::Mode::Cors;
164     if (m_client)
165         m_client->responseReceived(*this, response);
166
167     m_loader->addResponseForTesting(response);
168 }
169
170 bool MediaResource::shouldCacheResponse(CachedResource& resource, const ResourceResponse& response)
171 {
172     ASSERT_UNUSED(resource, &resource == m_resource);
173
174     RefPtr<MediaResource> protectedThis(this);
175     if (m_client)
176         return m_client->shouldCacheResponse(*this, response);
177     return true;
178 }
179
180 void MediaResource::redirectReceived(CachedResource& resource, ResourceRequest&& request, const ResourceResponse& response, CompletionHandler<void(ResourceRequest&&)>&& completionHandler)
181 {
182     ASSERT_UNUSED(resource, &resource == m_resource);
183
184     RefPtr<MediaResource> protectedThis(this);
185     if (m_client)
186         m_client->redirectReceived(*this, WTFMove(request), response, WTFMove(completionHandler));
187     else
188         completionHandler(WTFMove(request));
189 }
190
191 void MediaResource::dataSent(CachedResource& resource, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
192 {
193     ASSERT_UNUSED(resource, &resource == m_resource);
194
195     RefPtr<MediaResource> protectedThis(this);
196     if (m_client)
197         m_client->dataSent(*this, bytesSent, totalBytesToBeSent);
198 }
199
200 void MediaResource::dataReceived(CachedResource& resource, const char* data, int dataLength)
201 {
202     ASSERT_UNUSED(resource, &resource == m_resource);
203
204     RefPtr<MediaResource> protectedThis(this);
205     if (m_client)
206         m_client->dataReceived(*this, data, dataLength);
207 }
208
209 void MediaResource::notifyFinished(CachedResource& resource)
210 {
211     ASSERT_UNUSED(resource, &resource == m_resource);
212
213     RefPtr<MediaResource> protectedThis(this);
214     if (m_client) {
215         if (m_resource->loadFailedOrCanceled())
216             m_client->loadFailed(*this, m_resource->resourceError());
217         else
218             m_client->loadFinished(*this);
219     }
220     stop();
221 }
222
223 } // namespace WebCore
224
225 #endif