1e2212e058eae814454dbfbbd96e3579bec51e87
[WebKit-https.git] / Source / WebKit / WebProcess / Storage / WebSWClientConnection.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 "WebSWClientConnection.h"
28
29 #if ENABLE(SERVICE_WORKER)
30
31 #include "DataReference.h"
32 #include "FormDataReference.h"
33 #include "Logging.h"
34 #include "ServiceWorkerClientFetch.h"
35 #include "StorageToWebProcessConnectionMessages.h"
36 #include "WebCoreArgumentCoders.h"
37 #include "WebProcess.h"
38 #include "WebProcessPoolMessages.h"
39 #include "WebSWOriginTable.h"
40 #include "WebSWServerConnectionMessages.h"
41 #include <WebCore/Document.h>
42 #include <WebCore/SerializedScriptValue.h>
43 #include <WebCore/ServiceWorkerClientData.h>
44 #include <WebCore/ServiceWorkerFetchResult.h>
45 #include <WebCore/ServiceWorkerJobData.h>
46 #include <WebCore/ServiceWorkerRegistrationData.h>
47 #include <WebCore/ServiceWorkerRegistrationKey.h>
48
49 using namespace PAL;
50 using namespace WebCore;
51
52 namespace WebKit {
53
54 WebSWClientConnection::WebSWClientConnection(IPC::Connection& connection, SessionID sessionID)
55     : m_sessionID(sessionID)
56     , m_connection(connection)
57     , m_swOriginTable(makeUniqueRef<WebSWOriginTable>())
58 {
59     ASSERT(sessionID.isValid());
60     bool result = sendSync(Messages::StorageToWebProcessConnection::EstablishSWServerConnection(sessionID), Messages::StorageToWebProcessConnection::EstablishSWServerConnection::Reply(m_identifier), Seconds::infinity(), IPC::SendSyncOption::DoNotProcessIncomingMessagesWhenWaitingForSyncReply);
61
62     ASSERT_UNUSED(result, result);
63 }
64
65 WebSWClientConnection::~WebSWClientConnection()
66 {
67 }
68
69 void WebSWClientConnection::scheduleJobInServer(const ServiceWorkerJobData& jobData)
70 {
71     send(Messages::WebSWServerConnection::ScheduleJobInServer(jobData));
72 }
73
74 void WebSWClientConnection::finishFetchingScriptInServer(const ServiceWorkerFetchResult& result)
75 {
76     send(Messages::WebSWServerConnection::FinishFetchingScriptInServer(result));
77 }
78
79 void WebSWClientConnection::addServiceWorkerRegistrationInServer(ServiceWorkerRegistrationIdentifier identifier)
80 {
81     send(Messages::WebSWServerConnection::AddServiceWorkerRegistrationInServer(identifier));
82 }
83
84 void WebSWClientConnection::removeServiceWorkerRegistrationInServer(ServiceWorkerRegistrationIdentifier identifier)
85 {
86     send(Messages::WebSWServerConnection::RemoveServiceWorkerRegistrationInServer(identifier));
87 }
88
89 void WebSWClientConnection::postMessageToServiceWorker(ServiceWorkerIdentifier destinationIdentifier, MessageWithMessagePorts&& message, const ServiceWorkerOrClientIdentifier& sourceIdentifier)
90 {
91     // FIXME: Temporarily pipe the SW postMessage messages via the UIProcess since this is where the MessagePort registry lives
92     // and this avoids races.
93     WebProcess::singleton().send(Messages::WebProcessPool::PostMessageToServiceWorker(destinationIdentifier, WTFMove(message), sourceIdentifier, serverConnectionIdentifier()), 0);
94 }
95
96 void WebSWClientConnection::registerServiceWorkerClient(const SecurityOrigin& topOrigin, const WebCore::ServiceWorkerClientData& data, const std::optional<WebCore::ServiceWorkerRegistrationIdentifier>& controllingServiceWorkerRegistrationIdentifier)
97 {
98     send(Messages::WebSWServerConnection::RegisterServiceWorkerClient { SecurityOriginData::fromSecurityOrigin(topOrigin), data, controllingServiceWorkerRegistrationIdentifier });
99 }
100
101 void WebSWClientConnection::unregisterServiceWorkerClient(DocumentIdentifier contextIdentifier)
102 {
103     send(Messages::WebSWServerConnection::UnregisterServiceWorkerClient { ServiceWorkerClientIdentifier { serverConnectionIdentifier(), contextIdentifier } });
104 }
105
106 void WebSWClientConnection::didResolveRegistrationPromise(const ServiceWorkerRegistrationKey& key)
107 {
108     send(Messages::WebSWServerConnection::DidResolveRegistrationPromise(key));
109 }
110
111 bool WebSWClientConnection::mayHaveServiceWorkerRegisteredForOrigin(const SecurityOrigin& origin) const
112 {
113     if (!m_swOriginTable->isImported())
114         return true;
115
116     return m_swOriginTable->contains(origin);
117 }
118
119 void WebSWClientConnection::setSWOriginTableSharedMemory(const SharedMemory::Handle& handle)
120 {
121     m_swOriginTable->setSharedMemory(handle);
122 }
123
124 void WebSWClientConnection::setSWOriginTableIsImported()
125 {
126     m_swOriginTable->setIsImported();
127     while (!m_tasksPendingOriginImport.isEmpty())
128         m_tasksPendingOriginImport.takeFirst()();
129 }
130
131 void WebSWClientConnection::didMatchRegistration(uint64_t matchingRequest, std::optional<ServiceWorkerRegistrationData>&& result)
132 {
133     ASSERT(isMainThread());
134
135     if (auto completionHandler = m_ongoingMatchRegistrationTasks.take(matchingRequest))
136         completionHandler(WTFMove(result));
137 }
138
139 void WebSWClientConnection::didGetRegistrations(uint64_t matchingRequest, Vector<ServiceWorkerRegistrationData>&& registrations)
140 {
141     ASSERT(isMainThread());
142
143     if (auto completionHandler = m_ongoingGetRegistrationsTasks.take(matchingRequest))
144         completionHandler(WTFMove(registrations));
145 }
146
147 void WebSWClientConnection::matchRegistration(const SecurityOrigin& topOrigin, const URL& clientURL, RegistrationCallback&& callback)
148 {
149     ASSERT(isMainThread());
150
151     if (!mayHaveServiceWorkerRegisteredForOrigin(topOrigin)) {
152         callback(std::nullopt);
153         return;
154     }
155
156     runOrDelayTaskForImport([this, callback = WTFMove(callback), topOrigin = SecurityOriginData::fromSecurityOrigin(topOrigin), clientURL]() mutable {
157         uint64_t callbackID = ++m_previousCallbackIdentifier;
158         m_ongoingMatchRegistrationTasks.add(callbackID, WTFMove(callback));
159         send(Messages::WebSWServerConnection::MatchRegistration(callbackID, topOrigin, clientURL));
160     });
161 }
162
163 void WebSWClientConnection::runOrDelayTaskForImport(WTF::Function<void()>&& task)
164 {
165     if (m_swOriginTable->isImported())
166         task();
167     else
168         m_tasksPendingOriginImport.append(WTFMove(task));
169 }
170
171 void WebSWClientConnection::whenRegistrationReady(const SecurityOrigin& topOrigin, const URL& clientURL, WhenRegistrationReadyCallback&& callback)
172 {
173     uint64_t callbackID = ++m_previousCallbackIdentifier;
174     m_ongoingRegistrationReadyTasks.add(callbackID, WTFMove(callback));
175     send(Messages::WebSWServerConnection::WhenRegistrationReady(callbackID, SecurityOriginData::fromSecurityOrigin(topOrigin), clientURL));
176 }
177
178 void WebSWClientConnection::registrationReady(uint64_t callbackID, WebCore::ServiceWorkerRegistrationData&& registrationData)
179 {
180     ASSERT(registrationData.activeWorker);
181     if (auto callback = m_ongoingRegistrationReadyTasks.take(callbackID))
182         callback(WTFMove(registrationData));
183 }
184
185 void WebSWClientConnection::getRegistrations(const SecurityOrigin& topOrigin, const URL& clientURL, GetRegistrationsCallback&& callback)
186 {
187     ASSERT(isMainThread());
188
189     if (!mayHaveServiceWorkerRegisteredForOrigin(topOrigin)) {
190         callback({ });
191         return;
192     }
193
194     runOrDelayTaskForImport([this, callback = WTFMove(callback), topOrigin = SecurityOriginData::fromSecurityOrigin(topOrigin), clientURL]() mutable {
195         uint64_t callbackID = ++m_previousCallbackIdentifier;
196         m_ongoingGetRegistrationsTasks.add(callbackID, WTFMove(callback));
197         send(Messages::WebSWServerConnection::GetRegistrations(callbackID, topOrigin, clientURL));
198     });
199 }
200
201 void WebSWClientConnection::startFetch(uint64_t fetchIdentifier, WebCore::ServiceWorkerRegistrationIdentifier serviceWorkerRegistrationIdentifier, const WebCore::ResourceRequest& request, const WebCore::FetchOptions& options, const String& referrer)
202 {
203     send(Messages::WebSWServerConnection::StartFetch { fetchIdentifier, serviceWorkerRegistrationIdentifier, request, options, IPC::FormDataReference { request.httpBody() }, referrer });
204 }
205
206 void WebSWClientConnection::postMessageToServiceWorkerClient(DocumentIdentifier destinationContextIdentifier, MessageWithMessagePorts&& message, ServiceWorkerData&& source, const String& sourceOrigin)
207 {
208     SWClientConnection::postMessageToServiceWorkerClient(destinationContextIdentifier, WTFMove(message), WTFMove(source), sourceOrigin);
209 }
210
211 void WebSWClientConnection::connectionToServerLost()
212 {
213     auto registrationTasks = WTFMove(m_ongoingMatchRegistrationTasks);
214     for (auto& callback : registrationTasks.values())
215         callback(std::nullopt);
216
217     auto getRegistrationTasks = WTFMove(m_ongoingGetRegistrationsTasks);
218     for (auto& callback : getRegistrationTasks.values())
219         callback({ });
220
221     clearPendingJobs();
222 }
223
224 void WebSWClientConnection::syncTerminateWorker(ServiceWorkerIdentifier identifier)
225 {
226     sendSync(Messages::WebSWServerConnection::SyncTerminateWorker(identifier), Messages::WebSWServerConnection::SyncTerminateWorker::Reply());
227 }
228
229 } // namespace WebKit
230
231 #endif // ENABLE(SERVICE_WORKER)