1f72a30f3b35a21a4a76dcbdf38e64cc5eb4827a
[WebKit-https.git] / Source / WebKit / WebProcess / Storage / ServiceWorkerClientFetch.cpp
1 /*
2  * Copyright (C) 2017 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "ServiceWorkerClientFetch.h"
28
29 #if ENABLE(SERVICE_WORKER)
30
31 #include "DataReference.h"
32 #include "WebSWClientConnection.h"
33 #include "WebServiceWorkerProvider.h"
34 #include <WebCore/CrossOriginAccessControl.h>
35 #include <WebCore/MIMETypeRegistry.h>
36 #include <WebCore/NotImplemented.h>
37 #include <WebCore/ResourceError.h>
38
39 using namespace WebCore;
40
41 namespace WebKit {
42
43 Ref<ServiceWorkerClientFetch> ServiceWorkerClientFetch::create(WebServiceWorkerProvider& serviceWorkerProvider, Ref<WebCore::ResourceLoader>&& loader, uint64_t identifier, Ref<WebSWClientConnection>&& connection, bool shouldClearReferrerOnHTTPSToHTTPRedirect, Callback&& callback)
44 {
45     auto fetch = adoptRef(*new ServiceWorkerClientFetch { serviceWorkerProvider, WTFMove(loader), identifier, WTFMove(connection), shouldClearReferrerOnHTTPSToHTTPRedirect, WTFMove(callback) });
46     fetch->start();
47     return fetch;
48 }
49
50 ServiceWorkerClientFetch::~ServiceWorkerClientFetch()
51 {
52 }
53
54 ServiceWorkerClientFetch::ServiceWorkerClientFetch(WebServiceWorkerProvider& serviceWorkerProvider, Ref<WebCore::ResourceLoader>&& loader, uint64_t identifier, Ref<WebSWClientConnection>&& connection, bool shouldClearReferrerOnHTTPSToHTTPRedirect, Callback&& callback)
55     : m_serviceWorkerProvider(serviceWorkerProvider)
56     , m_loader(WTFMove(loader))
57     , m_identifier(identifier)
58     , m_connection(WTFMove(connection))
59     , m_callback(WTFMove(callback))
60     , m_shouldClearReferrerOnHTTPSToHTTPRedirect(shouldClearReferrerOnHTTPSToHTTPRedirect)
61 {
62 }
63
64 void ServiceWorkerClientFetch::start()
65 {
66     auto request = m_loader->request();
67     auto& options = m_loader->options();
68
69     auto referrer = request.httpReferrer();
70
71     // We are intercepting fetch calls after going through the HTTP layer, which may add some specific headers.
72     cleanHTTPRequestHeadersForAccessControl(request, options.httpHeadersToKeep);
73
74     ASSERT(options.serviceWorkersMode != ServiceWorkersMode::None);
75     m_connection->startFetch(m_loader->identifier(), options.serviceWorkerRegistrationIdentifier.value(), request, options, referrer);
76
77     m_redirectionStatus = RedirectionStatus::None;
78 }
79
80 // https://fetch.spec.whatwg.org/#http-fetch step 3.3
81 std::optional<ResourceError> ServiceWorkerClientFetch::validateResponse(const ResourceResponse& response)
82 {
83     // FIXME: make a better error reporting.
84     if (response.type() == ResourceResponse::Type::Error)
85         return ResourceError { ResourceError::Type::General };
86
87     auto& options = m_loader->options();
88     if (options.mode != FetchOptions::Mode::NoCors && response.tainting() == ResourceResponse::Tainting::Opaque)
89         return ResourceError { errorDomainWebKitInternal, 0, response.url(), ASCIILiteral("Response served by service worker is opaque"), ResourceError::Type::AccessControl };
90
91     // Navigate mode induces manual redirect.
92     if (options.redirect != FetchOptions::Redirect::Manual && options.mode != FetchOptions::Mode::Navigate && response.tainting() == ResourceResponse::Tainting::Opaqueredirect)
93         return ResourceError { errorDomainWebKitInternal, 0, response.url(), ASCIILiteral("Response served by service worker is opaque redirect"), ResourceError::Type::AccessControl };
94
95     if ((options.redirect != FetchOptions::Redirect::Follow || options.mode == FetchOptions::Mode::Navigate) && response.isRedirected())
96         return ResourceError { errorDomainWebKitInternal, 0, response.url(), ASCIILiteral("Response served by service worker has redirections"), ResourceError::Type::AccessControl };
97
98     return std::nullopt;
99 }
100
101 void ServiceWorkerClientFetch::didReceiveResponse(ResourceResponse&& response)
102 {
103     callOnMainThread([this, protectedThis = makeRef(*this), response = WTFMove(response)]() mutable {
104         if (!m_loader)
105             return;
106
107         if (auto error = validateResponse(response)) {
108             m_loader->didFail(error.value());
109             if (auto callback = WTFMove(m_callback))
110                 callback(Result::Succeeded);
111             return;
112         }
113         response.setSource(ResourceResponse::Source::ServiceWorker);
114
115         if (response.isRedirection() && response.httpHeaderFields().contains(HTTPHeaderName::Location)) {
116             m_redirectionStatus = RedirectionStatus::Receiving;
117             m_loader->willSendRequest(m_loader->request().redirectedRequest(response, m_shouldClearReferrerOnHTTPSToHTTPRedirect), response, [protectedThis = makeRef(*this), this](ResourceRequest&& request) {
118                 if (request.isNull() || !m_callback)
119                     return;
120
121                 ASSERT(request == m_loader->request());
122                 if (m_redirectionStatus == RedirectionStatus::Received) {
123                     start();
124                     return;
125                 }
126                 m_redirectionStatus = RedirectionStatus::Following;
127             });
128             return;
129         }
130
131         // In case of main resource and mime type is the default one, we set it to text/html to pass more service worker WPT tests.
132         // FIXME: We should refine our MIME type sniffing strategy for synthetic responses.
133         if (m_loader->originalRequest().requester() == ResourceRequest::Requester::Main) {
134             if (response.mimeType() == defaultMIMEType()) {
135                 response.setMimeType(ASCIILiteral("text/html"));
136                 response.setTextEncodingName(ASCIILiteral("UTF-8"));
137             }
138         }
139
140         // As per https://fetch.spec.whatwg.org/#main-fetch step 9, copy request's url list in response's url list if empty.
141         if (response.url().isNull())
142             response.setURL(m_loader->request().url());
143
144         m_loader->didReceiveResponse(response, [this, protectedThis = WTFMove(protectedThis)] {
145             if (auto callback = WTFMove(m_callback))
146                 callback(Result::Succeeded);
147         });
148     });
149 }
150
151 void ServiceWorkerClientFetch::didReceiveData(const IPC::DataReference& data, int64_t encodedDataLength)
152 {
153     callOnMainThread([this, protectedThis = makeRef(*this), data = data.vector(), encodedDataLength] {
154         if (!m_loader)
155             return;
156
157         m_loader->didReceiveData(reinterpret_cast<const char*>(data.data()), data.size(), encodedDataLength, DataPayloadBytes);
158     });
159 }
160
161 void ServiceWorkerClientFetch::didReceiveFormData(const IPC::FormDataReference&)
162 {
163     // FIXME: Implement form data reading.
164 }
165
166 void ServiceWorkerClientFetch::didFinish()
167 {
168     callOnMainThread([this, protectedThis = makeRef(*this)] {
169         if (!m_loader)
170             return;
171
172         switch (m_redirectionStatus) {
173         case RedirectionStatus::None:
174             break;
175         case RedirectionStatus::Receiving:
176             m_redirectionStatus = RedirectionStatus::Received;
177             return;
178         case RedirectionStatus::Following:
179             start();
180             return;
181         case RedirectionStatus::Received:
182             ASSERT_NOT_REACHED();
183             m_redirectionStatus = RedirectionStatus::None;
184         }
185
186         ASSERT(!m_callback);
187
188         m_loader->didFinishLoading(NetworkLoadMetrics { });
189         m_serviceWorkerProvider.fetchFinished(m_identifier);
190     });
191 }
192
193 void ServiceWorkerClientFetch::didFail()
194 {
195     callOnMainThread([this, protectedThis = makeRef(*this)] {
196         if (!m_loader)
197             return;
198
199         m_loader->didFail({ ResourceError::Type::General });
200
201         if (auto callback = WTFMove(m_callback))
202             callback(Result::Succeeded);
203
204         m_serviceWorkerProvider.fetchFinished(m_identifier);
205     });
206 }
207
208 void ServiceWorkerClientFetch::didNotHandle()
209 {
210     callOnMainThread([this, protectedThis = makeRef(*this)] {
211         if (!m_loader)
212             return;
213
214         if (auto callback = WTFMove(m_callback))
215             callback(Result::Unhandled);
216
217         m_serviceWorkerProvider.fetchFinished(m_identifier);
218     });
219 }
220
221 void ServiceWorkerClientFetch::cancel()
222 {
223     if (auto callback = WTFMove(m_callback))
224         callback(Result::Cancelled);
225     m_loader = nullptr;
226 }
227
228 } // namespace WebKit
229
230 #endif // ENABLE(SERVICE_WORKER)