74811f479efdb081fba8f29ff0df94cbb3c23c06
[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, ServiceWorkerClientIdentifier { identifier(), keyValue.key });
72 }
73
74 void WebSWServerConnection::disconnectedFromWebProcess()
75 {
76     notImplemented();
77 }
78
79 void WebSWServerConnection::rejectJobInClient(const ServiceWorkerJobDataIdentifier& jobDataIdentifier, const ExceptionData& exceptionData)
80 {
81     send(Messages::WebSWClientConnection::JobRejectedInServer(jobDataIdentifier, exceptionData));
82 }
83
84 void WebSWServerConnection::resolveRegistrationJobInClient(const ServiceWorkerJobDataIdentifier& jobDataIdentifier, const ServiceWorkerRegistrationData& registrationData, ShouldNotifyWhenResolved shouldNotifyWhenResolved)
85 {
86     send(Messages::WebSWClientConnection::RegistrationJobResolvedInServer(jobDataIdentifier, registrationData, shouldNotifyWhenResolved));
87 }
88
89 void WebSWServerConnection::resolveUnregistrationJobInClient(const ServiceWorkerJobDataIdentifier& jobDataIdentifier, const ServiceWorkerRegistrationKey& registrationKey, bool unregistrationResult)
90 {
91     send(Messages::WebSWClientConnection::UnregistrationJobResolvedInServer(jobDataIdentifier, unregistrationResult));
92 }
93
94 void WebSWServerConnection::startScriptFetchInClient(const ServiceWorkerJobDataIdentifier& jobDataIdentifier)
95 {
96     send(Messages::WebSWClientConnection::StartScriptFetchForServer(jobDataIdentifier));
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::notifyClientsOfControllerChange(const HashSet<DocumentIdentifier>& contextIdentifiers, const ServiceWorkerData& newController)
110 {
111     send(Messages::WebSWClientConnection::NotifyClientsOfControllerChange(contextIdentifiers, newController));
112 }
113
114 void WebSWServerConnection::updateWorkerStateInClient(ServiceWorkerIdentifier worker, ServiceWorkerState state)
115 {
116     send(Messages::WebSWClientConnection::UpdateWorkerState(worker, state));
117 }
118
119 void WebSWServerConnection::startFetch(uint64_t fetchIdentifier, ServiceWorkerIdentifier serviceWorkerIdentifier, ResourceRequest&& request, FetchOptions&& options, IPC::FormDataReference&& formData)
120 {
121     // It's possible this specific worker cannot be re-run (e.g. its registration has been removed)
122     server().runServiceWorkerIfNecessary(serviceWorkerIdentifier, [contentConnection = m_contentConnection.copyRef(), connectionIdentifier = identifier(), fetchIdentifier, serviceWorkerIdentifier = serviceWorkerIdentifier, request = WTFMove(request), options = WTFMove(options), formData = WTFMove(formData)](bool success, auto& contextConnection) {
123         if (success)
124             sendToContextProcess(contextConnection, Messages::WebSWContextManagerConnection::StartFetch { connectionIdentifier, fetchIdentifier, serviceWorkerIdentifier, request, options, formData });
125         else
126             contentConnection->send(Messages::ServiceWorkerClientFetch::DidNotHandle { }, fetchIdentifier);
127     });
128 }
129
130 void WebSWServerConnection::postMessageToServiceWorkerFromClient(ServiceWorkerIdentifier destinationIdentifier, IPC::DataReference&& message, ServiceWorkerClientIdentifier sourceIdentifier, ServiceWorkerClientData&& sourceData)
131 {
132     // It's possible this specific worker cannot be re-run (e.g. its registration has been removed)
133     server().runServiceWorkerIfNecessary(destinationIdentifier, [destinationIdentifier, message = WTFMove(message), sourceIdentifier, sourceData = WTFMove(sourceData)](bool success, auto& contextConnection) mutable {
134         if (success)
135             sendToContextProcess(contextConnection, Messages::WebSWContextManagerConnection::PostMessageToServiceWorkerFromClient { destinationIdentifier, message, sourceIdentifier, WTFMove(sourceData) });
136     });
137 }
138
139 void WebSWServerConnection::postMessageToServiceWorkerFromServiceWorker(ServiceWorkerIdentifier destinationIdentifier, IPC::DataReference&& message, ServiceWorkerIdentifier sourceIdentifier)
140 {
141     auto* sourceWorker = server().workerByID(sourceIdentifier);
142     if (!sourceWorker)
143         return;
144
145     // It's possible this specific worker cannot be re-run (e.g. its registration has been removed)
146     server().runServiceWorkerIfNecessary(destinationIdentifier, [destinationIdentifier, message = WTFMove(message), sourceData = sourceWorker->data()](bool success, auto& contextConnection) mutable {
147         if (!success)
148             return;
149
150         sendToContextProcess(contextConnection, Messages::WebSWContextManagerConnection::PostMessageToServiceWorkerFromServiceWorker { destinationIdentifier, message, WTFMove(sourceData) });
151     });
152 }
153
154 void WebSWServerConnection::didReceiveFetchResponse(uint64_t fetchIdentifier, const ResourceResponse& response)
155 {
156     m_contentConnection->send(Messages::ServiceWorkerClientFetch::DidReceiveResponse { response }, fetchIdentifier);
157 }
158
159 void WebSWServerConnection::didReceiveFetchData(uint64_t fetchIdentifier, const IPC::DataReference& data, int64_t encodedDataLength)
160 {
161     m_contentConnection->send(Messages::ServiceWorkerClientFetch::DidReceiveData { data, encodedDataLength }, fetchIdentifier);
162 }
163
164 void WebSWServerConnection::didReceiveFetchFormData(uint64_t fetchIdentifier, const IPC::FormDataReference& formData)
165 {
166     m_contentConnection->send(Messages::ServiceWorkerClientFetch::DidReceiveFormData { formData }, fetchIdentifier);
167 }
168
169 void WebSWServerConnection::didFinishFetch(uint64_t fetchIdentifier)
170 {
171     m_contentConnection->send(Messages::ServiceWorkerClientFetch::DidFinish { }, fetchIdentifier);
172 }
173
174 void WebSWServerConnection::didFailFetch(uint64_t fetchIdentifier)
175 {
176     m_contentConnection->send(Messages::ServiceWorkerClientFetch::DidFail { }, fetchIdentifier);
177 }
178
179 void WebSWServerConnection::didNotHandleFetch(uint64_t fetchIdentifier)
180 {
181     m_contentConnection->send(Messages::ServiceWorkerClientFetch::DidNotHandle { }, fetchIdentifier);
182 }
183
184 void WebSWServerConnection::postMessageToServiceWorkerClient(DocumentIdentifier destinationContextIdentifier, const IPC::DataReference& message, ServiceWorkerIdentifier sourceIdentifier, const String& sourceOrigin)
185 {
186     auto* sourceServiceWorker = server().workerByID(sourceIdentifier);
187     if (!sourceServiceWorker)
188         return;
189
190     send(Messages::WebSWClientConnection::PostMessageToServiceWorkerClient { destinationContextIdentifier, message, sourceServiceWorker->data(), sourceOrigin });
191 }
192
193 void WebSWServerConnection::matchRegistration(uint64_t registrationMatchRequestIdentifier, const SecurityOriginData& topOrigin, const URL& clientURL)
194 {
195     if (auto* registration = doRegistrationMatching(topOrigin, clientURL)) {
196         send(Messages::WebSWClientConnection::DidMatchRegistration { registrationMatchRequestIdentifier, registration->data() });
197         return;
198     }
199     send(Messages::WebSWClientConnection::DidMatchRegistration { registrationMatchRequestIdentifier, std::nullopt });
200 }
201
202 void WebSWServerConnection::registrationReady(uint64_t registrationReadyRequestIdentifier, ServiceWorkerRegistrationData&& registrationData)
203 {
204     send(Messages::WebSWClientConnection::RegistrationReady { registrationReadyRequestIdentifier, WTFMove(registrationData) });
205 }
206
207 void WebSWServerConnection::getRegistrations(uint64_t registrationMatchRequestIdentifier, const SecurityOriginData& topOrigin, const URL& clientURL)
208 {
209     auto registrations = server().getRegistrations(topOrigin, clientURL);
210     send(Messages::WebSWClientConnection::DidGetRegistrations { registrationMatchRequestIdentifier, registrations });
211 }
212
213 void WebSWServerConnection::registerServiceWorkerClient(SecurityOriginData&& topOrigin, DocumentIdentifier contextIdentifier, ServiceWorkerClientData&& data, const std::optional<ServiceWorkerIdentifier>& controllingServiceWorkerIdentifier)
214 {
215     auto clientOrigin = ClientOrigin { WTFMove(topOrigin), SecurityOriginData::fromSecurityOrigin(SecurityOrigin::create(data.url)) };
216     m_clientOrigins.add(contextIdentifier, clientOrigin);
217     server().registerServiceWorkerClient(WTFMove(clientOrigin), ServiceWorkerClientIdentifier { this->identifier(), contextIdentifier } , WTFMove(data), controllingServiceWorkerIdentifier);
218 }
219
220 void WebSWServerConnection::unregisterServiceWorkerClient(DocumentIdentifier contextIdentifier)
221 {
222     auto iterator = m_clientOrigins.find(contextIdentifier);
223     if (iterator == m_clientOrigins.end())
224         return;
225
226     server().unregisterServiceWorkerClient(iterator->value, ServiceWorkerClientIdentifier { this->identifier(), contextIdentifier });
227     m_clientOrigins.remove(iterator);
228 }
229
230 template<typename U> void WebSWServerConnection::sendToContextProcess(U&& message)
231 {
232     if (auto* connection = StorageProcess::singleton().globalServerToContextConnection())
233         connection->send(WTFMove(message));
234 }
235
236 template<typename U> void WebSWServerConnection::sendToContextProcess(WebCore::SWServerToContextConnection& connection, U&& message)
237 {
238     static_cast<WebSWServerToContextConnection&>(connection).send(WTFMove(message));
239 }
240
241 } // namespace WebKit
242
243 #endif // ENABLE(SERVICE_WORKER)