51c879a228fdcd05f00701b301f421b448bbd984
[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     auto protectedThis = makeRef(*this);
104
105     if (auto error = validateResponse(response)) {
106         m_loader->didFail(error.value());
107         if (auto callback = WTFMove(m_callback))
108             callback(Result::Succeeded);
109         return;
110     }
111
112     if (response.isRedirection()) {
113         m_redirectionStatus = RedirectionStatus::Receiving;
114         // FIXME: Get shouldClearReferrerOnHTTPSToHTTPRedirect value from
115         m_loader->willSendRequest(m_loader->request().redirectedRequest(response, m_shouldClearReferrerOnHTTPSToHTTPRedirect), response, [protectedThis = makeRef(*this), this](ResourceRequest&& request) {
116             if (request.isNull() || !m_callback)
117                 return;
118
119             ASSERT(request == m_loader->request());
120             if (m_redirectionStatus == RedirectionStatus::Received) {
121                 start();
122                 return;
123             }
124             m_redirectionStatus = RedirectionStatus::Following;
125         });
126         return;
127     }
128
129     // 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.
130     // FIXME: We should refine our MIME type sniffing strategy for synthetic responses.
131     if (m_loader->originalRequest().requester() == ResourceRequest::Requester::Main) {
132         if (response.mimeType() == defaultMIMEType()) {
133             response.setMimeType(ASCIILiteral("text/html"));
134             response.setTextEncodingName(ASCIILiteral("UTF-8"));
135         }
136     }
137     response.setSource(ResourceResponse::Source::ServiceWorker);
138
139     // As per https://fetch.spec.whatwg.org/#main-fetch step 9, copy request's url list in response's url list if empty.
140     if (response.url().isNull())
141         response.setURL(m_loader->request().url());
142
143     m_loader->didReceiveResponse(response);
144     if (auto callback = WTFMove(m_callback))
145         callback(Result::Succeeded);
146 }
147
148 void ServiceWorkerClientFetch::didReceiveData(const IPC::DataReference& data, int64_t encodedDataLength)
149 {
150     m_loader->didReceiveData(reinterpret_cast<const char*>(data.data()), data.size(), encodedDataLength, DataPayloadBytes);
151 }
152
153 void ServiceWorkerClientFetch::didReceiveFormData(const IPC::FormDataReference&)
154 {
155     // FIXME: Implement form data reading.
156 }
157
158 void ServiceWorkerClientFetch::didFinish()
159 {
160     switch (m_redirectionStatus) {
161     case RedirectionStatus::None:
162         break;
163     case RedirectionStatus::Receiving:
164         m_redirectionStatus = RedirectionStatus::Received;
165         return;
166     case RedirectionStatus::Following:
167         start();
168         return;
169     case RedirectionStatus::Received:
170         ASSERT_NOT_REACHED();
171         m_redirectionStatus = RedirectionStatus::None;
172     }
173
174     ASSERT(!m_callback);
175
176     auto protectedThis = makeRef(*this);
177     m_loader->didFinishLoading(NetworkLoadMetrics { });
178     m_serviceWorkerProvider.fetchFinished(m_identifier);
179 }
180
181 void ServiceWorkerClientFetch::didFail()
182 {
183     auto protectedThis = makeRef(*this);
184     m_loader->didFail({ ResourceError::Type::General });
185
186     if (auto callback = WTFMove(m_callback))
187         callback(Result::Succeeded);
188
189     m_serviceWorkerProvider.fetchFinished(m_identifier);
190 }
191
192 void ServiceWorkerClientFetch::didNotHandle()
193 {
194     if (auto callback = WTFMove(m_callback))
195         callback(Result::Unhandled);
196
197     m_serviceWorkerProvider.fetchFinished(m_identifier);
198 }
199
200 void ServiceWorkerClientFetch::cancel()
201 {
202     if (auto callback = WTFMove(m_callback))
203         callback(Result::Cancelled);
204 }
205
206 } // namespace WebKit
207
208 #endif // ENABLE(SERVICE_WORKER)