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