f0b6132a4cc237b7ca79aea66c407146db54eadc
[WebKit-https.git] / Source / WebKit / UIProcess / Network / NetworkProcessProxy.cpp
1 /*
2  * Copyright (C) 2012-2018 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 "NetworkProcessProxy.h"
28
29 #include "APIContentRuleList.h"
30 #include "AuthenticationChallengeProxy.h"
31 #include "DownloadProxyMessages.h"
32 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
33 #include "LegacyCustomProtocolManagerProxyMessages.h"
34 #endif
35 #include "Logging.h"
36 #include "NetworkContentRuleListManagerMessages.h"
37 #include "NetworkProcessCreationParameters.h"
38 #include "NetworkProcessMessages.h"
39 #include "SandboxExtension.h"
40 #include "WebCompiledContentRuleList.h"
41 #include "WebPageProxy.h"
42 #include "WebProcessMessages.h"
43 #include "WebProcessPool.h"
44 #include "WebUserContentControllerProxy.h"
45 #include "WebsiteData.h"
46 #include <wtf/CompletionHandler.h>
47
48 #if ENABLE(SEC_ITEM_SHIM)
49 #include "SecItemShimProxy.h"
50 #endif
51
52 #if PLATFORM(IOS_FAMILY)
53 #include <wtf/spi/darwin/XPCSPI.h>
54 #endif
55
56 #define MESSAGE_CHECK(assertion) MESSAGE_CHECK_BASE(assertion, connection())
57
58 namespace WebKit {
59 using namespace WebCore;
60
61 static uint64_t generateCallbackID()
62 {
63     static uint64_t callbackID;
64
65     return ++callbackID;
66 }
67
68 NetworkProcessProxy::NetworkProcessProxy(WebProcessPool& processPool)
69     : ChildProcessProxy(processPool.alwaysRunsAtBackgroundPriority())
70     , m_processPool(processPool)
71     , m_numPendingConnectionRequests(0)
72 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
73     , m_customProtocolManagerProxy(*this)
74 #endif
75     , m_throttler(*this, processPool.shouldTakeUIBackgroundAssertion())
76 {
77     connect();
78
79     if (auto* websiteDataStore = m_processPool.websiteDataStore())
80         m_websiteDataStores.set(websiteDataStore->websiteDataStore().sessionID(), makeRef(websiteDataStore->websiteDataStore()));
81 }
82
83 NetworkProcessProxy::~NetworkProcessProxy()
84 {
85     ASSERT(m_pendingFetchWebsiteDataCallbacks.isEmpty());
86     ASSERT(m_pendingDeleteWebsiteDataCallbacks.isEmpty());
87     ASSERT(m_pendingDeleteWebsiteDataForOriginsCallbacks.isEmpty());
88 #if ENABLE(CONTENT_EXTENSIONS)
89     for (auto* proxy : m_webUserContentControllerProxies)
90         proxy->removeNetworkProcess(*this);
91 #endif
92 }
93
94 void NetworkProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions)
95 {
96     launchOptions.processType = ProcessLauncher::ProcessType::Network;
97     ChildProcessProxy::getLaunchOptions(launchOptions);
98
99     if (processPool().shouldMakeNextNetworkProcessLaunchFailForTesting()) {
100         processPool().setShouldMakeNextNetworkProcessLaunchFailForTesting(false);
101         launchOptions.shouldMakeProcessLaunchFailForTesting = true;
102     }
103 }
104
105 void NetworkProcessProxy::connectionWillOpen(IPC::Connection& connection)
106 {
107 #if ENABLE(SEC_ITEM_SHIM)
108     SecItemShimProxy::singleton().initializeConnection(connection);
109 #else
110     UNUSED_PARAM(connection);
111 #endif
112 }
113
114 void NetworkProcessProxy::processWillShutDown(IPC::Connection& connection)
115 {
116     ASSERT_UNUSED(connection, this->connection() == &connection);
117 }
118
119 void NetworkProcessProxy::getNetworkProcessConnection(WebProcessProxy& webProcessProxy, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&& reply)
120 {
121     m_pendingConnectionReplies.append(std::make_pair(makeWeakPtr(webProcessProxy), WTFMove(reply)));
122
123     if (state() == State::Launching) {
124         m_numPendingConnectionRequests++;
125         return;
126     }
127
128     bool isServiceWorkerProcess = false;
129     SecurityOriginData securityOrigin;
130 #if ENABLE(SERVICE_WORKER)
131     if (is<ServiceWorkerProcessProxy>(webProcessProxy)) {
132         isServiceWorkerProcess = true;
133         securityOrigin = downcast<ServiceWorkerProcessProxy>(webProcessProxy).securityOrigin();
134     }
135 #endif
136
137     connection()->send(Messages::NetworkProcess::CreateNetworkConnectionToWebProcess(isServiceWorkerProcess, securityOrigin), 0, IPC::SendOption::DispatchMessageEvenWhenWaitingForSyncReply);
138 }
139
140 DownloadProxy* NetworkProcessProxy::createDownloadProxy(const ResourceRequest& resourceRequest)
141 {
142     if (!m_downloadProxyMap)
143         m_downloadProxyMap = std::make_unique<DownloadProxyMap>(this);
144
145     return m_downloadProxyMap->createDownloadProxy(m_processPool, resourceRequest);
146 }
147
148 void NetworkProcessProxy::fetchWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> dataTypes, OptionSet<WebsiteDataFetchOption> fetchOptions, CompletionHandler<void (WebsiteData)>&& completionHandler)
149 {
150     ASSERT(canSendMessage());
151
152     uint64_t callbackID = generateCallbackID();
153     RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is taking a background assertion because the Network process is fetching Website data", this);
154
155     m_pendingFetchWebsiteDataCallbacks.add(callbackID, [this, token = throttler().backgroundActivityToken(), completionHandler = WTFMove(completionHandler), sessionID] (WebsiteData websiteData) mutable {
156 #if RELEASE_LOG_DISABLED
157         UNUSED_PARAM(this);
158         UNUSED_PARAM(sessionID);
159 #endif
160         completionHandler(WTFMove(websiteData));
161         RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is releasing a background assertion because the Network process is done fetching Website data", this);
162     });
163
164     send(Messages::NetworkProcess::FetchWebsiteData(sessionID, dataTypes, fetchOptions, callbackID), 0);
165 }
166
167 void NetworkProcessProxy::deleteWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> dataTypes, WallTime modifiedSince, CompletionHandler<void ()>&& completionHandler)
168 {
169     auto callbackID = generateCallbackID();
170     RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is taking a background assertion because the Network process is deleting Website data", this);
171
172     m_pendingDeleteWebsiteDataCallbacks.add(callbackID, [this, token = throttler().backgroundActivityToken(), completionHandler = WTFMove(completionHandler), sessionID] () mutable {
173 #if RELEASE_LOG_DISABLED
174         UNUSED_PARAM(this);
175         UNUSED_PARAM(sessionID);
176 #endif
177         completionHandler();
178         RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is releasing a background assertion because the Network process is done deleting Website data", this);
179     });
180     send(Messages::NetworkProcess::DeleteWebsiteData(sessionID, dataTypes, modifiedSince, callbackID), 0);
181 }
182
183 void NetworkProcessProxy::deleteWebsiteDataForOrigins(PAL::SessionID sessionID, OptionSet<WebsiteDataType> dataTypes, const Vector<WebCore::SecurityOriginData>& origins, const Vector<String>& cookieHostNames, const Vector<String>& HSTSCacheHostNames, CompletionHandler<void()>&& completionHandler)
184 {
185     ASSERT(canSendMessage());
186
187     uint64_t callbackID = generateCallbackID();
188     RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is taking a background assertion because the Network process is deleting Website data for several origins", this);
189
190     m_pendingDeleteWebsiteDataForOriginsCallbacks.add(callbackID, [this, token = throttler().backgroundActivityToken(), completionHandler = WTFMove(completionHandler), sessionID] () mutable {
191 #if RELEASE_LOG_DISABLED
192         UNUSED_PARAM(this);
193         UNUSED_PARAM(sessionID);
194 #endif
195         completionHandler();
196         RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is releasing a background assertion because the Network process is done deleting Website data for several origins", this);
197     });
198
199     send(Messages::NetworkProcess::DeleteWebsiteDataForOrigins(sessionID, dataTypes, origins, cookieHostNames, HSTSCacheHostNames, callbackID), 0);
200 }
201
202 void NetworkProcessProxy::networkProcessCrashed()
203 {
204     clearCallbackStates();
205
206     Vector<std::pair<RefPtr<WebProcessProxy>, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>> pendingReplies;
207     pendingReplies.reserveInitialCapacity(m_pendingConnectionReplies.size());
208     for (auto& reply : m_pendingConnectionReplies) {
209         if (reply.first)
210             pendingReplies.append(std::make_pair(makeRefPtr(reply.first.get()), WTFMove(reply.second)));
211         else
212             reply.second({ });
213     }
214
215     // Tell the network process manager to forget about this network process proxy. This will cause us to be deleted.
216     m_processPool.networkProcessCrashed(*this, WTFMove(pendingReplies));
217 }
218
219 void NetworkProcessProxy::clearCallbackStates()
220 {
221     while (!m_pendingFetchWebsiteDataCallbacks.isEmpty())
222         m_pendingFetchWebsiteDataCallbacks.take(m_pendingFetchWebsiteDataCallbacks.begin()->key)(WebsiteData { });
223
224     while (!m_pendingDeleteWebsiteDataCallbacks.isEmpty())
225         m_pendingDeleteWebsiteDataCallbacks.take(m_pendingDeleteWebsiteDataCallbacks.begin()->key)();
226
227     while (!m_pendingDeleteWebsiteDataForOriginsCallbacks.isEmpty())
228         m_pendingDeleteWebsiteDataForOriginsCallbacks.take(m_pendingDeleteWebsiteDataForOriginsCallbacks.begin()->key)();
229
230     while (!m_updateBlockCookiesCallbackMap.isEmpty())
231         m_updateBlockCookiesCallbackMap.take(m_updateBlockCookiesCallbackMap.begin()->key)();
232     
233     while (!m_storageAccessResponseCallbackMap.isEmpty())
234         m_storageAccessResponseCallbackMap.take(m_storageAccessResponseCallbackMap.begin()->key)(false);
235 }
236
237 void NetworkProcessProxy::didReceiveMessage(IPC::Connection& connection, IPC::Decoder& decoder)
238 {
239     if (dispatchMessage(connection, decoder))
240         return;
241
242     if (m_processPool.dispatchMessage(connection, decoder))
243         return;
244
245     didReceiveNetworkProcessProxyMessage(connection, decoder);
246 }
247
248 void NetworkProcessProxy::didReceiveSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
249 {
250     if (dispatchSyncMessage(connection, decoder, replyEncoder))
251         return;
252
253     ASSERT_NOT_REACHED();
254 }
255
256 void NetworkProcessProxy::didClose(IPC::Connection&)
257 {
258     auto protectedProcessPool = makeRef(m_processPool);
259
260     if (m_downloadProxyMap)
261         m_downloadProxyMap->processDidClose();
262 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
263     m_customProtocolManagerProxy.invalidate();
264 #endif
265
266     m_tokenForHoldingLockedFiles = nullptr;
267     
268     m_syncAllCookiesToken = nullptr;
269     m_syncAllCookiesCounter = 0;
270
271     for (auto& callback : m_writeBlobToFilePathCallbackMap.values())
272         callback(false);
273     m_writeBlobToFilePathCallbackMap.clear();
274
275     for (auto& callback : m_removeAllStorageAccessCallbackMap.values())
276         callback();
277     m_removeAllStorageAccessCallbackMap.clear();
278
279     for (auto& callback : m_updateBlockCookiesCallbackMap.values())
280         callback();
281     m_updateBlockCookiesCallbackMap.clear();
282     
283     // This will cause us to be deleted.
284     networkProcessCrashed();
285 }
286
287 void NetworkProcessProxy::didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference, IPC::StringReference)
288 {
289 }
290
291 void NetworkProcessProxy::didCreateNetworkConnectionToWebProcess(const IPC::Attachment& connectionIdentifier)
292 {
293     ASSERT(!m_pendingConnectionReplies.isEmpty());
294
295     // Grab the first pending connection reply.
296     auto reply = m_pendingConnectionReplies.takeFirst().second;
297
298 #if USE(UNIX_DOMAIN_SOCKETS) || OS(WINDOWS)
299     reply(connectionIdentifier);
300 #elif OS(DARWIN)
301     MESSAGE_CHECK(MACH_PORT_VALID(connectionIdentifier.port()));
302     reply(IPC::Attachment(connectionIdentifier.port(), MACH_MSG_TYPE_MOVE_SEND));
303 #else
304     notImplemented();
305 #endif
306 }
307
308 void NetworkProcessProxy::didReceiveAuthenticationChallenge(uint64_t pageID, uint64_t frameID, WebCore::AuthenticationChallenge&& coreChallenge, uint64_t challengeID)
309 {
310 #if ENABLE(SERVICE_WORKER)
311     if (auto* serviceWorkerProcessProxy = m_processPool.serviceWorkerProcessProxyFromPageID(pageID)) {
312         auto authenticationChallenge = AuthenticationChallengeProxy::create(WTFMove(coreChallenge), challengeID, makeRef(*connection()), nullptr);
313         serviceWorkerProcessProxy->didReceiveAuthenticationChallenge(pageID, frameID, WTFMove(authenticationChallenge));
314         return;
315     }
316 #endif
317
318     WebPageProxy* page = WebProcessProxy::webPage(pageID);
319     MESSAGE_CHECK(page);
320
321     auto authenticationChallenge = AuthenticationChallengeProxy::create(WTFMove(coreChallenge), challengeID, makeRef(*connection()), page->secKeyProxyStore(coreChallenge));
322     page->didReceiveAuthenticationChallengeProxy(frameID, WTFMove(authenticationChallenge));
323 }
324
325 void NetworkProcessProxy::didFetchWebsiteData(uint64_t callbackID, const WebsiteData& websiteData)
326 {
327     auto callback = m_pendingFetchWebsiteDataCallbacks.take(callbackID);
328     callback(websiteData);
329 }
330
331 void NetworkProcessProxy::didDeleteWebsiteData(uint64_t callbackID)
332 {
333     auto callback = m_pendingDeleteWebsiteDataCallbacks.take(callbackID);
334     callback();
335 }
336
337 void NetworkProcessProxy::didDeleteWebsiteDataForOrigins(uint64_t callbackID)
338 {
339     auto callback = m_pendingDeleteWebsiteDataForOriginsCallbacks.take(callbackID);
340     callback();
341 }
342
343 void NetworkProcessProxy::didFinishLaunching(ProcessLauncher* launcher, IPC::Connection::Identifier connectionIdentifier)
344 {
345     ChildProcessProxy::didFinishLaunching(launcher, connectionIdentifier);
346
347     if (!IPC::Connection::identifierIsValid(connectionIdentifier)) {
348         networkProcessCrashed();
349         return;
350     }
351
352     for (unsigned i = 0; i < m_numPendingConnectionRequests; ++i)
353         connection()->send(Messages::NetworkProcess::CreateNetworkConnectionToWebProcess(false, { }), 0);
354     
355     m_numPendingConnectionRequests = 0;
356
357 #if PLATFORM(COCOA)
358     if (m_processPool.processSuppressionEnabled())
359         setProcessSuppressionEnabled(true);
360 #endif
361     
362 #if PLATFORM(IOS_FAMILY)
363     if (xpc_connection_t connection = this->connection()->xpcConnection())
364         m_throttler.didConnectToProcess(xpc_connection_get_pid(connection));
365 #endif
366 }
367
368 void NetworkProcessProxy::logDiagnosticMessage(uint64_t pageID, const String& message, const String& description, WebCore::ShouldSample shouldSample)
369 {
370     WebPageProxy* page = WebProcessProxy::webPage(pageID);
371     // FIXME: We do this null-check because by the time the decision to log is made, the page may be gone. We should refactor to avoid this,
372     // but for now we simply drop the message in the rare case this happens.
373     if (!page)
374         return;
375
376     page->logDiagnosticMessage(message, description, shouldSample);
377 }
378
379 void NetworkProcessProxy::logDiagnosticMessageWithResult(uint64_t pageID, const String& message, const String& description, uint32_t result, WebCore::ShouldSample shouldSample)
380 {
381     WebPageProxy* page = WebProcessProxy::webPage(pageID);
382     // FIXME: We do this null-check because by the time the decision to log is made, the page may be gone. We should refactor to avoid this,
383     // but for now we simply drop the message in the rare case this happens.
384     if (!page)
385         return;
386
387     page->logDiagnosticMessageWithResult(message, description, result, shouldSample);
388 }
389
390 void NetworkProcessProxy::logDiagnosticMessageWithValue(uint64_t pageID, const String& message, const String& description, double value, unsigned significantFigures, WebCore::ShouldSample shouldSample)
391 {
392     WebPageProxy* page = WebProcessProxy::webPage(pageID);
393     // FIXME: We do this null-check because by the time the decision to log is made, the page may be gone. We should refactor to avoid this,
394     // but for now we simply drop the message in the rare case this happens.
395     if (!page)
396         return;
397
398     page->logDiagnosticMessageWithValue(message, description, value, significantFigures, shouldSample);
399 }
400
401 #if ENABLE(RESOURCE_LOAD_STATISTICS)
402 void NetworkProcessProxy::updatePrevalentDomainsToBlockCookiesFor(PAL::SessionID sessionID, const Vector<String>& domainsToBlock, CompletionHandler<void()>&& completionHandler)
403 {
404     if (!canSendMessage()) {
405         completionHandler();
406         return;
407     }
408     
409     auto callbackId = generateCallbackID();
410     auto addResult = m_updateBlockCookiesCallbackMap.add(callbackId, [protectedProcessPool = makeRef(m_processPool), token = throttler().backgroundActivityToken(), completionHandler = WTFMove(completionHandler)]() mutable {
411         completionHandler();
412     });
413     ASSERT_UNUSED(addResult, addResult.isNewEntry);
414     send(Messages::NetworkProcess::UpdatePrevalentDomainsToBlockCookiesFor(sessionID, domainsToBlock, callbackId), 0);
415 }
416
417 void NetworkProcessProxy::didUpdateBlockCookies(uint64_t callbackId)
418 {
419     m_updateBlockCookiesCallbackMap.take(callbackId)();
420 }
421
422 void NetworkProcessProxy::setAgeCapForClientSideCookies(PAL::SessionID sessionID, std::optional<Seconds> seconds, CompletionHandler<void()>&& completionHandler)
423 {
424     if (!canSendMessage()) {
425         completionHandler();
426         return;
427     }
428     
429     auto callbackId = generateCallbackID();
430     auto addResult = m_updateBlockCookiesCallbackMap.add(callbackId, [protectedProcessPool = makeRef(m_processPool), token = throttler().backgroundActivityToken(), completionHandler = WTFMove(completionHandler)]() mutable {
431         completionHandler();
432     });
433     ASSERT_UNUSED(addResult, addResult.isNewEntry);
434     send(Messages::NetworkProcess::SetAgeCapForClientSideCookies(sessionID, seconds, callbackId), 0);
435 }
436
437 void NetworkProcessProxy::didSetAgeCapForClientSideCookies(uint64_t callbackId)
438 {
439     m_updateBlockCookiesCallbackMap.take(callbackId)();
440 }
441
442 void NetworkProcessProxy::hasStorageAccessForFrame(PAL::SessionID sessionID, const String& resourceDomain, const String& firstPartyDomain, uint64_t frameID, uint64_t pageID, WTF::CompletionHandler<void(bool)>&& callback)
443 {
444     auto contextId = generateCallbackID();
445     auto addResult = m_storageAccessResponseCallbackMap.add(contextId, WTFMove(callback));
446     ASSERT_UNUSED(addResult, addResult.isNewEntry);
447     send(Messages::NetworkProcess::HasStorageAccessForFrame(sessionID, resourceDomain, firstPartyDomain, frameID, pageID, contextId), 0);
448 }
449
450 void NetworkProcessProxy::grantStorageAccess(PAL::SessionID sessionID, const String& resourceDomain, const String& firstPartyDomain, std::optional<uint64_t> frameID, uint64_t pageID, WTF::CompletionHandler<void(bool)>&& callback)
451 {
452     auto contextId = generateCallbackID();
453     auto addResult = m_storageAccessResponseCallbackMap.add(contextId, WTFMove(callback));
454     ASSERT_UNUSED(addResult, addResult.isNewEntry);
455     send(Messages::NetworkProcess::GrantStorageAccess(sessionID, resourceDomain, firstPartyDomain, frameID, pageID, contextId), 0);
456 }
457
458 void NetworkProcessProxy::storageAccessRequestResult(bool wasGranted, uint64_t contextId)
459 {
460     auto callback = m_storageAccessResponseCallbackMap.take(contextId);
461     callback(wasGranted);
462 }
463
464 void NetworkProcessProxy::removeAllStorageAccess(PAL::SessionID sessionID, CompletionHandler<void()>&& completionHandler)
465 {
466     if (!canSendMessage()) {
467         completionHandler();
468         return;
469     }
470
471     auto contextId = generateCallbackID();
472     auto addResult = m_removeAllStorageAccessCallbackMap.add(contextId, WTFMove(completionHandler));
473     ASSERT_UNUSED(addResult, addResult.isNewEntry);
474     send(Messages::NetworkProcess::RemoveAllStorageAccess(sessionID, contextId), 0);
475 }
476
477 void NetworkProcessProxy::didRemoveAllStorageAccess(uint64_t contextId)
478 {
479     auto completionHandler = m_removeAllStorageAccessCallbackMap.take(contextId);
480     completionHandler();
481 }
482
483 void NetworkProcessProxy::getAllStorageAccessEntries(PAL::SessionID sessionID, CompletionHandler<void(Vector<String>&& domains)>&& callback)
484 {
485     auto contextId = generateCallbackID();
486     auto addResult = m_allStorageAccessEntriesCallbackMap.add(contextId, WTFMove(callback));
487     ASSERT_UNUSED(addResult, addResult.isNewEntry);
488     send(Messages::NetworkProcess::GetAllStorageAccessEntries(sessionID, contextId), 0);
489 }
490
491 void NetworkProcessProxy::allStorageAccessEntriesResult(Vector<String>&& domains, uint64_t contextId)
492 {
493     auto callback = m_allStorageAccessEntriesCallbackMap.take(contextId);
494     callback(WTFMove(domains));
495 }
496
497 void NetworkProcessProxy::setCacheMaxAgeCapForPrevalentResources(PAL::SessionID sessionID, Seconds seconds, CompletionHandler<void()>&& completionHandler)
498 {
499     if (!canSendMessage()) {
500         completionHandler();
501         return;
502     }
503     
504     auto contextId = generateCallbackID();
505     auto addResult = m_updateRuntimeSettingsCallbackMap.add(contextId, WTFMove(completionHandler));
506     ASSERT_UNUSED(addResult, addResult.isNewEntry);
507     send(Messages::NetworkProcess::SetCacheMaxAgeCapForPrevalentResources(sessionID, seconds, contextId), 0);
508 }
509
510 void NetworkProcessProxy::didSetCacheMaxAgeCapForPrevalentResources(uint64_t contextId)
511 {
512     auto completionHandler = m_updateRuntimeSettingsCallbackMap.take(contextId);
513     completionHandler();
514 }
515
516 void NetworkProcessProxy::resetCacheMaxAgeCapForPrevalentResources(PAL::SessionID sessionID, CompletionHandler<void()>&& completionHandler)
517 {
518     if (!canSendMessage()) {
519         completionHandler();
520         return;
521     }
522     
523     auto contextId = generateCallbackID();
524     auto addResult = m_updateRuntimeSettingsCallbackMap.add(contextId, WTFMove(completionHandler));
525     ASSERT_UNUSED(addResult, addResult.isNewEntry);
526     send(Messages::NetworkProcess::ResetCacheMaxAgeCapForPrevalentResources(sessionID, contextId), 0);
527 }
528
529 void NetworkProcessProxy::didResetCacheMaxAgeCapForPrevalentResources(uint64_t contextId)
530 {
531     auto completionHandler = m_updateRuntimeSettingsCallbackMap.take(contextId);
532     completionHandler();
533 }
534 #endif // ENABLE(RESOURCE_LOAD_STATISTICS)
535
536 void NetworkProcessProxy::sendProcessWillSuspendImminently()
537 {
538     if (!canSendMessage())
539         return;
540
541     bool handled = false;
542     sendSync(Messages::NetworkProcess::ProcessWillSuspendImminently(), Messages::NetworkProcess::ProcessWillSuspendImminently::Reply(handled), 0, 1_s);
543 }
544     
545 void NetworkProcessProxy::sendPrepareToSuspend()
546 {
547     if (canSendMessage())
548         send(Messages::NetworkProcess::PrepareToSuspend(), 0);
549 }
550
551 void NetworkProcessProxy::sendCancelPrepareToSuspend()
552 {
553     if (canSendMessage())
554         send(Messages::NetworkProcess::CancelPrepareToSuspend(), 0);
555 }
556
557 void NetworkProcessProxy::sendProcessDidResume()
558 {
559     if (canSendMessage())
560         send(Messages::NetworkProcess::ProcessDidResume(), 0);
561 }
562
563 void NetworkProcessProxy::writeBlobToFilePath(const WebCore::URL& url, const String& path, CompletionHandler<void(bool)>&& callback)
564 {
565     if (!canSendMessage()) {
566         callback(false);
567         return;
568     }
569
570     static uint64_t writeBlobToFilePathCallbackIdentifiers = 0;
571     uint64_t callbackID = ++writeBlobToFilePathCallbackIdentifiers;
572     m_writeBlobToFilePathCallbackMap.add(callbackID, WTFMove(callback));
573
574     SandboxExtension::Handle handleForWriting;
575     SandboxExtension::createHandle(path, SandboxExtension::Type::ReadWrite, handleForWriting);
576     send(Messages::NetworkProcess::WriteBlobToFilePath(url, path, handleForWriting, callbackID), 0);
577 }
578
579 void NetworkProcessProxy::didWriteBlobToFilePath(bool success, uint64_t callbackID)
580 {
581     if (auto handler = m_writeBlobToFilePathCallbackMap.take(callbackID))
582         handler(success);
583     else
584         ASSERT_NOT_REACHED();
585 }
586
587 void NetworkProcessProxy::processReadyToSuspend()
588 {
589     m_throttler.processReadyToSuspend();
590 }
591
592 void NetworkProcessProxy::didSetAssertionState(AssertionState)
593 {
594 }
595     
596 void NetworkProcessProxy::setIsHoldingLockedFiles(bool isHoldingLockedFiles)
597 {
598     if (!isHoldingLockedFiles) {
599         RELEASE_LOG(ProcessSuspension, "UIProcess is releasing a background assertion because the Network process is no longer holding locked files");
600         m_tokenForHoldingLockedFiles = nullptr;
601         return;
602     }
603     if (!m_tokenForHoldingLockedFiles) {
604         RELEASE_LOG(ProcessSuspension, "UIProcess is taking a background assertion because the Network process is holding locked files");
605         m_tokenForHoldingLockedFiles = m_throttler.backgroundActivityToken();
606     }
607 }
608
609 void NetworkProcessProxy::syncAllCookies()
610 {
611     send(Messages::NetworkProcess::SyncAllCookies(), 0);
612     
613     ++m_syncAllCookiesCounter;
614     if (m_syncAllCookiesToken)
615         return;
616     
617     RELEASE_LOG(ProcessSuspension, "%p - NetworkProcessProxy is taking a background assertion because the Network process is syncing cookies", this);
618     m_syncAllCookiesToken = throttler().backgroundActivityToken();
619 }
620     
621 void NetworkProcessProxy::didSyncAllCookies()
622 {
623     ASSERT(m_syncAllCookiesCounter);
624
625     --m_syncAllCookiesCounter;
626     if (!m_syncAllCookiesCounter) {
627         RELEASE_LOG(ProcessSuspension, "%p - NetworkProcessProxy is releasing a background assertion because the Network process is done syncing cookies", this);
628         m_syncAllCookiesToken = nullptr;
629     }
630 }
631
632 void NetworkProcessProxy::addSession(Ref<WebsiteDataStore>&& store)
633 {
634     if (canSendMessage())
635         send(Messages::NetworkProcess::AddWebsiteDataStore { store->parameters() }, 0);
636     auto sessionID = store->sessionID();
637     if (!sessionID.isEphemeral())
638         m_websiteDataStores.set(sessionID, WTFMove(store));
639 }
640
641 void NetworkProcessProxy::removeSession(PAL::SessionID sessionID)
642 {
643     if (canSendMessage())
644         send(Messages::NetworkProcess::DestroySession { sessionID }, 0);
645     if (!sessionID.isEphemeral())
646         m_websiteDataStores.remove(sessionID);
647 }
648
649 WebsiteDataStore* NetworkProcessProxy::websiteDataStoreFromSessionID(PAL::SessionID sessionID)
650 {
651     auto iterator = m_websiteDataStores.find(sessionID);
652     if (iterator != m_websiteDataStores.end())
653         return iterator->value.get();
654
655     if (auto* websiteDataStore = m_processPool.websiteDataStore()) {
656         if (sessionID == websiteDataStore->websiteDataStore().sessionID())
657             return &websiteDataStore->websiteDataStore();
658     }
659
660     if (sessionID != PAL::SessionID::defaultSessionID())
661         return nullptr;
662
663     return &API::WebsiteDataStore::defaultDataStore()->websiteDataStore();
664 }
665
666 void NetworkProcessProxy::retrieveCacheStorageParameters(PAL::SessionID sessionID)
667 {
668     auto* store = websiteDataStoreFromSessionID(sessionID);
669
670     if (!store) {
671         RELEASE_LOG_ERROR(CacheStorage, "%p - NetworkProcessProxy is unable to retrieve CacheStorage parameters from the given session ID %" PRIu64, this, sessionID.sessionID());
672         auto quota = m_processPool.websiteDataStore() ? m_processPool.websiteDataStore()->websiteDataStore().cacheStoragePerOriginQuota() : WebsiteDataStore::defaultCacheStoragePerOriginQuota;
673         send(Messages::NetworkProcess::SetCacheStorageParameters { sessionID, quota, { }, { } }, 0);
674         return;
675     }
676
677     auto& cacheStorageDirectory = store->cacheStorageDirectory();
678     SandboxExtension::Handle cacheStorageDirectoryExtensionHandle;
679     if (!cacheStorageDirectory.isEmpty())
680         SandboxExtension::createHandleForReadWriteDirectory(cacheStorageDirectory, cacheStorageDirectoryExtensionHandle);
681
682     send(Messages::NetworkProcess::SetCacheStorageParameters { sessionID, store->cacheStoragePerOriginQuota(), cacheStorageDirectory, cacheStorageDirectoryExtensionHandle }, 0);
683 }
684
685 #if ENABLE(CONTENT_EXTENSIONS)
686 void NetworkProcessProxy::contentExtensionRules(UserContentControllerIdentifier identifier)
687 {
688     if (auto* webUserContentControllerProxy = WebUserContentControllerProxy::get(identifier)) {
689         m_webUserContentControllerProxies.add(webUserContentControllerProxy);
690         webUserContentControllerProxy->addNetworkProcess(*this);
691
692         auto rules = WTF::map(webUserContentControllerProxy->contentExtensionRules(), [](auto&& keyValue) -> std::pair<String, WebCompiledContentRuleListData> {
693             return std::make_pair(keyValue.value->name(), keyValue.value->compiledRuleList().data());
694         });
695         send(Messages::NetworkContentRuleListManager::AddContentRuleLists { identifier, rules }, 0);
696         return;
697     }
698     send(Messages::NetworkContentRuleListManager::AddContentRuleLists { identifier, { } }, 0);
699 }
700
701 void NetworkProcessProxy::didDestroyWebUserContentControllerProxy(WebUserContentControllerProxy& proxy)
702 {
703     send(Messages::NetworkContentRuleListManager::Remove { proxy.identifier() }, 0);
704     m_webUserContentControllerProxies.remove(&proxy);
705 }
706 #endif
707     
708 void NetworkProcessProxy::sendProcessDidTransitionToForeground()
709 {
710     send(Messages::NetworkProcess::ProcessDidTransitionToForeground(), 0);
711 }
712
713 void NetworkProcessProxy::sendProcessDidTransitionToBackground()
714 {
715     send(Messages::NetworkProcess::ProcessDidTransitionToBackground(), 0);
716 }
717
718 #if ENABLE(SANDBOX_EXTENSIONS)
719 void NetworkProcessProxy::getSandboxExtensionsForBlobFiles(const Vector<String>& paths, Messages::NetworkProcessProxy::GetSandboxExtensionsForBlobFiles::AsyncReply&& reply)
720 {
721     SandboxExtension::HandleArray extensions;
722     extensions.allocate(paths.size());
723     for (size_t i = 0; i < paths.size(); ++i) {
724         // ReadWrite is required for creating hard links, which is something that might be done with these extensions.
725         SandboxExtension::createHandle(paths[i], SandboxExtension::Type::ReadWrite, extensions[i]);
726     }
727     reply(WTFMove(extensions));
728 }
729 #endif
730
731 #if ENABLE(SERVICE_WORKER)
732 void NetworkProcessProxy::establishWorkerContextConnectionToNetworkProcess(SecurityOriginData&& origin)
733 {
734     m_processPool.establishWorkerContextConnectionToNetworkProcess(*this, WTFMove(origin), std::nullopt);
735 }
736
737 void NetworkProcessProxy::establishWorkerContextConnectionToNetworkProcessForExplicitSession(SecurityOriginData&& origin, PAL::SessionID sessionID)
738 {
739     m_processPool.establishWorkerContextConnectionToNetworkProcess(*this, WTFMove(origin), sessionID);
740 }
741 #endif
742
743 } // namespace WebKit
744
745 #undef MESSAGE_CHECK
746 #undef MESSAGE_CHECK_URL