18d841d46fb3708baddf3fe2030c093ae3915cb8
[WebKit-https.git] / Source / WebKit / StorageProcess / ServiceWorker / WebSWServerConnection.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 "WebSWServerConnection.h"
28
29 #if ENABLE(SERVICE_WORKER)
30
31 #include "DataReference.h"
32 #include "Logging.h"
33 #include "ServiceWorkerClientFetchMessages.h"
34 #include "StorageProcess.h"
35 #include "StorageToWebProcessConnectionMessages.h"
36 #include "WebCoreArgumentCoders.h"
37 #include "WebProcess.h"
38 #include "WebProcessMessages.h"
39 #include "WebSWClientConnectionMessages.h"
40 #include "WebSWContextManagerConnectionMessages.h"
41 #include "WebSWServerConnectionMessages.h"
42 #include "WebSWServerToContextConnection.h"
43 #include "WebToStorageProcessConnection.h"
44 #include <WebCore/ExceptionData.h>
45 #include <WebCore/NotImplemented.h>
46 #include <WebCore/SWServerRegistration.h>
47 #include <WebCore/SecurityOrigin.h>
48 #include <WebCore/ServiceWorkerClientData.h>
49 #include <WebCore/ServiceWorkerClientIdentifier.h>
50 #include <WebCore/ServiceWorkerContextData.h>
51 #include <WebCore/ServiceWorkerJobData.h>
52 #include <wtf/MainThread.h>
53
54 using namespace PAL;
55 using namespace WebCore;
56
57 namespace WebKit {
58
59 WebSWServerConnection::WebSWServerConnection(SWServer& server, IPC::Connection& connection, SessionID sessionID)
60     : SWServer::Connection(server)
61     , m_sessionID(sessionID)
62     , m_contentConnection(connection)
63 {
64     StorageProcess::singleton().registerSWServerConnection(*this);
65 }
66
67 WebSWServerConnection::~WebSWServerConnection()
68 {
69     StorageProcess::singleton().unregisterSWServerConnection(*this);
70     for (auto keyValue : m_clientOrigins)
71         server().unregisterServiceWorkerClient(keyValue.value, keyValue.key);
72 }
73
74 void WebSWServerConnection::disconnectedFromWebProcess()
75 {
76     notImplemented();
77 }
78
79 void WebSWServerConnection::rejectJobInClient(ServiceWorkerJobIdentifier jobIdentifier, const ExceptionData& exceptionData)
80 {
81     send(Messages::WebSWClientConnection::JobRejectedInServer(jobIdentifier, exceptionData));
82 }
83
84 void WebSWServerConnection::resolveRegistrationJobInClient(ServiceWorkerJobIdentifier jobIdentifier, const ServiceWorkerRegistrationData& registrationData, ShouldNotifyWhenResolved shouldNotifyWhenResolved)
85 {
86     send(Messages::WebSWClientConnection::RegistrationJobResolvedInServer(jobIdentifier, registrationData, shouldNotifyWhenResolved));
87 }
88
89 void WebSWServerConnection::resolveUnregistrationJobInClient(ServiceWorkerJobIdentifier jobIdentifier, const ServiceWorkerRegistrationKey& registrationKey, bool unregistrationResult)
90 {
91     send(Messages::WebSWClientConnection::UnregistrationJobResolvedInServer(jobIdentifier, unregistrationResult));
92 }
93
94 void WebSWServerConnection::startScriptFetchInClient(ServiceWorkerJobIdentifier jobIdentifier, const ServiceWorkerRegistrationKey& registrationKey, FetchOptions::Cache cachePolicy)
95 {
96     send(Messages::WebSWClientConnection::StartScriptFetchForServer(jobIdentifier, registrationKey, cachePolicy));
97 }
98
99 void WebSWServerConnection::updateRegistrationStateInClient(ServiceWorkerRegistrationIdentifier identifier, ServiceWorkerRegistrationState state, const std::optional<ServiceWorkerData>& serviceWorkerData)
100 {
101     send(Messages::WebSWClientConnection::UpdateRegistrationState(identifier, state, serviceWorkerData));
102 }
103
104 void WebSWServerConnection::fireUpdateFoundEvent(ServiceWorkerRegistrationIdentifier identifier)
105 {
106     send(Messages::WebSWClientConnection::FireUpdateFoundEvent(identifier));
107 }
108
109 void WebSWServerConnection::setRegistrationLastUpdateTime(ServiceWorkerRegistrationIdentifier identifier, WallTime lastUpdateTime)
110 {
111     send(Messages::WebSWClientConnection::SetRegistrationLastUpdateTime(identifier, lastUpdateTime));
112 }
113
114 void WebSWServerConnection::setRegistrationUpdateViaCache(ServiceWorkerRegistrationIdentifier identifier, ServiceWorkerUpdateViaCache updateViaCache)
115 {
116     send(Messages::WebSWClientConnection::SetRegistrationUpdateViaCache(identifier, updateViaCache));
117 }
118
119 void WebSWServerConnection::notifyClientsOfControllerChange(const HashSet<DocumentIdentifier>& contextIdentifiers, const ServiceWorkerData& newController)
120 {
121     send(Messages::WebSWClientConnection::NotifyClientsOfControllerChange(contextIdentifiers, newController));
122 }
123
124 void WebSWServerConnection::updateWorkerStateInClient(ServiceWorkerIdentifier worker, ServiceWorkerState state)
125 {
126     send(Messages::WebSWClientConnection::UpdateWorkerState(worker, state));
127 }
128
129 void WebSWServerConnection::startFetch(uint64_t fetchIdentifier, ServiceWorkerRegistrationIdentifier serviceWorkerRegistrationIdentifier, ResourceRequest&& request, FetchOptions&& options, IPC::FormDataReference&& formData, String&& referrer)
130 {
131     auto* worker = server().activeWorkerFromRegistrationID(serviceWorkerRegistrationIdentifier);
132     if (!worker) {
133         m_contentConnection->send(Messages::ServiceWorkerClientFetch::DidNotHandle { }, fetchIdentifier);
134         return;
135     }
136     auto serviceWorkerIdentifier = worker->identifier();
137
138     auto runServerWorkerAndStartFetch = [weakThis = makeWeakPtr(this), this, fetchIdentifier, serviceWorkerIdentifier, request = WTFMove(request), options = WTFMove(options), formData = WTFMove(formData), referrer = WTFMove(referrer)](bool success) mutable {
139         if (!weakThis)
140             return;
141
142         if (!success) {
143             m_contentConnection->send(Messages::ServiceWorkerClientFetch::DidNotHandle { }, fetchIdentifier);
144             return;
145         }
146
147         server().runServiceWorkerIfNecessary(serviceWorkerIdentifier, [weakThis = WTFMove(weakThis), this, fetchIdentifier, serviceWorkerIdentifier, request = WTFMove(request), options = WTFMove(options), formData = WTFMove(formData), referrer = WTFMove(referrer)](bool success, auto& contextConnection) {
148             if (!weakThis)
149                 return;
150
151             if (success)
152                 sendToContextProcess(contextConnection, Messages::WebSWContextManagerConnection::StartFetch { identifier(), fetchIdentifier, serviceWorkerIdentifier, request, options, formData, referrer });
153             else
154                 m_contentConnection->send(Messages::ServiceWorkerClientFetch::DidNotHandle { }, fetchIdentifier);
155         });
156     };
157
158     if (worker->state() == ServiceWorkerState::Activating) {
159         worker->whenActivated(WTFMove(runServerWorkerAndStartFetch));
160         return;
161     }
162     ASSERT(worker->state() == ServiceWorkerState::Activated);
163     runServerWorkerAndStartFetch(true);
164 }
165
166 void WebSWServerConnection::postMessageToServiceWorker(ServiceWorkerIdentifier destinationIdentifier, IPC::DataReference&& message, const ServiceWorkerOrClientIdentifier& sourceIdentifier)
167 {
168     std::optional<ServiceWorkerOrClientData> sourceData;
169     WTF::switchOn(sourceIdentifier, [&](ServiceWorkerIdentifier identifier) {
170         if (auto* sourceWorker = server().workerByID(identifier))
171             sourceData = ServiceWorkerOrClientData { sourceWorker->data() };
172     }, [&](ServiceWorkerClientIdentifier identifier) {
173         if (auto clientData = server().serviceWorkerClientByID(identifier))
174             sourceData = ServiceWorkerOrClientData { *clientData };
175     });
176
177     if (!sourceData)
178         return;
179
180     // It's possible this specific worker cannot be re-run (e.g. its registration has been removed)
181     server().runServiceWorkerIfNecessary(destinationIdentifier, [destinationIdentifier, message = message.vector(), sourceData = WTFMove(*sourceData)](bool success, auto& contextConnection) mutable {
182         if (success)
183             sendToContextProcess(contextConnection, Messages::WebSWContextManagerConnection::PostMessageToServiceWorker { destinationIdentifier, message, WTFMove(sourceData) });
184     });
185 }
186
187 void WebSWServerConnection::didReceiveFetchResponse(uint64_t fetchIdentifier, const ResourceResponse& response)
188 {
189     m_contentConnection->send(Messages::ServiceWorkerClientFetch::DidReceiveResponse { response }, fetchIdentifier);
190 }
191
192 void WebSWServerConnection::didReceiveFetchData(uint64_t fetchIdentifier, const IPC::DataReference& data, int64_t encodedDataLength)
193 {
194     m_contentConnection->send(Messages::ServiceWorkerClientFetch::DidReceiveData { data, encodedDataLength }, fetchIdentifier);
195 }
196
197 void WebSWServerConnection::didReceiveFetchFormData(uint64_t fetchIdentifier, const IPC::FormDataReference& formData)
198 {
199     m_contentConnection->send(Messages::ServiceWorkerClientFetch::DidReceiveFormData { formData }, fetchIdentifier);
200 }
201
202 void WebSWServerConnection::didFinishFetch(uint64_t fetchIdentifier)
203 {
204     m_contentConnection->send(Messages::ServiceWorkerClientFetch::DidFinish { }, fetchIdentifier);
205 }
206
207 void WebSWServerConnection::didFailFetch(uint64_t fetchIdentifier)
208 {
209     m_contentConnection->send(Messages::ServiceWorkerClientFetch::DidFail { }, fetchIdentifier);
210 }
211
212 void WebSWServerConnection::didNotHandleFetch(uint64_t fetchIdentifier)
213 {
214     m_contentConnection->send(Messages::ServiceWorkerClientFetch::DidNotHandle { }, fetchIdentifier);
215 }
216
217 void WebSWServerConnection::postMessageToServiceWorkerClient(DocumentIdentifier destinationContextIdentifier, const IPC::DataReference& message, ServiceWorkerIdentifier sourceIdentifier, const String& sourceOrigin)
218 {
219     auto* sourceServiceWorker = server().workerByID(sourceIdentifier);
220     if (!sourceServiceWorker)
221         return;
222
223     send(Messages::WebSWClientConnection::PostMessageToServiceWorkerClient { destinationContextIdentifier, message, sourceServiceWorker->data(), sourceOrigin });
224 }
225
226 void WebSWServerConnection::matchRegistration(uint64_t registrationMatchRequestIdentifier, const SecurityOriginData& topOrigin, const URL& clientURL)
227 {
228     if (auto* registration = doRegistrationMatching(topOrigin, clientURL)) {
229         send(Messages::WebSWClientConnection::DidMatchRegistration { registrationMatchRequestIdentifier, registration->data() });
230         return;
231     }
232     send(Messages::WebSWClientConnection::DidMatchRegistration { registrationMatchRequestIdentifier, std::nullopt });
233 }
234
235 void WebSWServerConnection::registrationReady(uint64_t registrationReadyRequestIdentifier, ServiceWorkerRegistrationData&& registrationData)
236 {
237     send(Messages::WebSWClientConnection::RegistrationReady { registrationReadyRequestIdentifier, WTFMove(registrationData) });
238 }
239
240 void WebSWServerConnection::getRegistrations(uint64_t registrationMatchRequestIdentifier, const SecurityOriginData& topOrigin, const URL& clientURL)
241 {
242     auto registrations = server().getRegistrations(topOrigin, clientURL);
243     send(Messages::WebSWClientConnection::DidGetRegistrations { registrationMatchRequestIdentifier, registrations });
244 }
245
246 void WebSWServerConnection::registerServiceWorkerClient(SecurityOriginData&& topOrigin, ServiceWorkerClientData&& data, const std::optional<ServiceWorkerIdentifier>& controllingServiceWorkerIdentifier)
247 {
248     auto clientOrigin = ClientOrigin { WTFMove(topOrigin), SecurityOriginData::fromSecurityOrigin(SecurityOrigin::create(data.url)) };
249     m_clientOrigins.add(data.identifier, clientOrigin);
250     server().registerServiceWorkerClient(WTFMove(clientOrigin), WTFMove(data), controllingServiceWorkerIdentifier);
251 }
252
253 void WebSWServerConnection::unregisterServiceWorkerClient(const ServiceWorkerClientIdentifier& clientIdentifier)
254 {
255     auto iterator = m_clientOrigins.find(clientIdentifier);
256     if (iterator == m_clientOrigins.end())
257         return;
258
259     server().unregisterServiceWorkerClient(iterator->value, clientIdentifier);
260     m_clientOrigins.remove(iterator);
261 }
262
263 template<typename U> void WebSWServerConnection::sendToContextProcess(U&& message)
264 {
265     if (auto* connection = StorageProcess::singleton().globalServerToContextConnection())
266         connection->send(WTFMove(message));
267 }
268
269 template<typename U> void WebSWServerConnection::sendToContextProcess(WebCore::SWServerToContextConnection& connection, U&& message)
270 {
271     static_cast<WebSWServerToContextConnection&>(connection).send(WTFMove(message));
272 }
273
274 } // namespace WebKit
275
276 #endif // ENABLE(SERVICE_WORKER)