Deal better with the network process crashing on startup
[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 "StorageProcessMessages.h"
41 #include "WebCompiledContentRuleList.h"
42 #include "WebPageProxy.h"
43 #include "WebProcessMessages.h"
44 #include "WebProcessPool.h"
45 #include "WebUserContentControllerProxy.h"
46 #include "WebsiteData.h"
47 #include <wtf/CompletionHandler.h>
48
49 #if ENABLE(SEC_ITEM_SHIM)
50 #include "SecItemShimProxy.h"
51 #endif
52
53 #if PLATFORM(IOS)
54 #include <wtf/spi/darwin/XPCSPI.h>
55 #endif
56
57 #define MESSAGE_CHECK(assertion) MESSAGE_CHECK_BASE(assertion, connection())
58
59 using namespace WebCore;
60
61 namespace WebKit {
62
63 static uint64_t generateCallbackID()
64 {
65     static uint64_t callbackID;
66
67     return ++callbackID;
68 }
69
70 Ref<NetworkProcessProxy> NetworkProcessProxy::create(WebProcessPool& processPool)
71 {
72     return adoptRef(*new NetworkProcessProxy(processPool));
73 }
74
75 NetworkProcessProxy::NetworkProcessProxy(WebProcessPool& processPool)
76     : ChildProcessProxy(processPool.alwaysRunsAtBackgroundPriority())
77     , m_processPool(processPool)
78     , m_numPendingConnectionRequests(0)
79 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
80     , m_customProtocolManagerProxy(*this)
81 #endif
82     , m_throttler(*this, processPool.shouldTakeUIBackgroundAssertion())
83 {
84     connect();
85
86     if (auto* websiteDataStore = m_processPool.websiteDataStore())
87         m_websiteDataStores.set(websiteDataStore->websiteDataStore().sessionID(), makeRef(websiteDataStore->websiteDataStore()));
88 }
89
90 NetworkProcessProxy::~NetworkProcessProxy()
91 {
92     ASSERT(m_pendingFetchWebsiteDataCallbacks.isEmpty());
93     ASSERT(m_pendingDeleteWebsiteDataCallbacks.isEmpty());
94     ASSERT(m_pendingDeleteWebsiteDataForOriginsCallbacks.isEmpty());
95 #if ENABLE(CONTENT_EXTENSIONS)
96     for (auto* proxy : m_webUserContentControllerProxies)
97         proxy->removeNetworkProcess(*this);
98 #endif
99 }
100
101 void NetworkProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions)
102 {
103     launchOptions.processType = ProcessLauncher::ProcessType::Network;
104     ChildProcessProxy::getLaunchOptions(launchOptions);
105
106     if (processPool().shouldMakeNextNetworkProcessLaunchFailForTesting()) {
107         processPool().setShouldMakeNextNetworkProcessLaunchFailForTesting(false);
108         launchOptions.shouldMakeProcessLaunchFailForTesting = true;
109     }
110 }
111
112 void NetworkProcessProxy::connectionWillOpen(IPC::Connection& connection)
113 {
114 #if ENABLE(SEC_ITEM_SHIM)
115     SecItemShimProxy::singleton().initializeConnection(connection);
116 #else
117     UNUSED_PARAM(connection);
118 #endif
119 }
120
121 void NetworkProcessProxy::processWillShutDown(IPC::Connection& connection)
122 {
123     ASSERT_UNUSED(connection, this->connection() == &connection);
124 }
125
126 void NetworkProcessProxy::getNetworkProcessConnection(Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&& reply)
127 {
128     m_pendingConnectionReplies.append(WTFMove(reply));
129
130     if (state() == State::Launching) {
131         m_numPendingConnectionRequests++;
132         return;
133     }
134
135     connection()->send(Messages::NetworkProcess::CreateNetworkConnectionToWebProcess(), 0, IPC::SendOption::DispatchMessageEvenWhenWaitingForSyncReply);
136 }
137
138 DownloadProxy* NetworkProcessProxy::createDownloadProxy(const ResourceRequest& resourceRequest)
139 {
140     if (!m_downloadProxyMap)
141         m_downloadProxyMap = std::make_unique<DownloadProxyMap>(this);
142
143     return m_downloadProxyMap->createDownloadProxy(m_processPool, resourceRequest);
144 }
145
146 void NetworkProcessProxy::fetchWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> dataTypes, OptionSet<WebsiteDataFetchOption> fetchOptions, WTF::Function<void (WebsiteData)>&& completionHandler)
147 {
148     ASSERT(canSendMessage());
149
150     uint64_t callbackID = generateCallbackID();
151     RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is taking a background assertion because the Network process is fetching Website data", this);
152
153     m_pendingFetchWebsiteDataCallbacks.add(callbackID, [this, token = throttler().backgroundActivityToken(), completionHandler = WTFMove(completionHandler), sessionID](WebsiteData websiteData) {
154 #if RELEASE_LOG_DISABLED
155         UNUSED_PARAM(this);
156         UNUSED_PARAM(sessionID);
157 #endif
158         completionHandler(WTFMove(websiteData));
159         RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is releasing a background assertion because the Network process is done fetching Website data", this);
160     });
161
162     send(Messages::NetworkProcess::FetchWebsiteData(sessionID, dataTypes, fetchOptions, callbackID), 0);
163 }
164
165 void NetworkProcessProxy::deleteWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> dataTypes, WallTime modifiedSince, WTF::Function<void ()>&& completionHandler)
166 {
167     auto callbackID = generateCallbackID();
168     RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is taking a background assertion because the Network process is deleting Website data", this);
169
170     m_pendingDeleteWebsiteDataCallbacks.add(callbackID, [this, token = throttler().backgroundActivityToken(), completionHandler = WTFMove(completionHandler), sessionID] {
171 #if RELEASE_LOG_DISABLED
172         UNUSED_PARAM(this);
173         UNUSED_PARAM(sessionID);
174 #endif
175         completionHandler();
176         RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is releasing a background assertion because the Network process is done deleting Website data", this);
177     });
178     send(Messages::NetworkProcess::DeleteWebsiteData(sessionID, dataTypes, modifiedSince, callbackID), 0);
179 }
180
181 void NetworkProcessProxy::deleteWebsiteDataForOrigins(PAL::SessionID sessionID, OptionSet<WebsiteDataType> dataTypes, const Vector<WebCore::SecurityOriginData>& origins, const Vector<String>& cookieHostNames, WTF::Function<void()>&& completionHandler)
182 {
183     ASSERT(canSendMessage());
184
185     uint64_t callbackID = generateCallbackID();
186     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);
187
188     m_pendingDeleteWebsiteDataForOriginsCallbacks.add(callbackID, [this, token = throttler().backgroundActivityToken(), completionHandler = WTFMove(completionHandler), sessionID] {
189 #if RELEASE_LOG_DISABLED
190         UNUSED_PARAM(this);
191         UNUSED_PARAM(sessionID);
192 #endif
193         completionHandler();
194         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);
195     });
196
197     send(Messages::NetworkProcess::DeleteWebsiteDataForOrigins(sessionID, dataTypes, origins, cookieHostNames, callbackID), 0);
198 }
199
200 void NetworkProcessProxy::networkProcessCrashed()
201 {
202     clearCallbackStates();
203
204     Vector<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply> pendingReplies;
205     pendingReplies.reserveInitialCapacity(m_pendingConnectionReplies.size());
206     for (auto& reply : m_pendingConnectionReplies)
207         pendingReplies.append(WTFMove(reply));
208
209     // Tell the network process manager to forget about this network process proxy. This may cause us to be deleted.
210     m_processPool.networkProcessCrashed(*this, WTFMove(pendingReplies));
211 }
212
213 void NetworkProcessProxy::clearCallbackStates()
214 {
215     while (!m_pendingFetchWebsiteDataCallbacks.isEmpty())
216         m_pendingFetchWebsiteDataCallbacks.take(m_pendingFetchWebsiteDataCallbacks.begin()->key)(WebsiteData { });
217
218     while (!m_pendingDeleteWebsiteDataCallbacks.isEmpty())
219         m_pendingDeleteWebsiteDataCallbacks.take(m_pendingDeleteWebsiteDataCallbacks.begin()->key)();
220
221     while (!m_pendingDeleteWebsiteDataForOriginsCallbacks.isEmpty())
222         m_pendingDeleteWebsiteDataForOriginsCallbacks.take(m_pendingDeleteWebsiteDataForOriginsCallbacks.begin()->key)();
223
224     while (!m_updatePartitionOrBlockCookiesCallbackMap.isEmpty())
225         m_updatePartitionOrBlockCookiesCallbackMap.take(m_updatePartitionOrBlockCookiesCallbackMap.begin()->key)();
226     
227     while (!m_storageAccessResponseCallbackMap.isEmpty())
228         m_storageAccessResponseCallbackMap.take(m_storageAccessResponseCallbackMap.begin()->key)(false);
229 }
230
231 void NetworkProcessProxy::didReceiveMessage(IPC::Connection& connection, IPC::Decoder& decoder)
232 {
233     if (dispatchMessage(connection, decoder))
234         return;
235
236     if (m_processPool.dispatchMessage(connection, decoder))
237         return;
238
239     didReceiveNetworkProcessProxyMessage(connection, decoder);
240 }
241
242 void NetworkProcessProxy::didReceiveSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
243 {
244     if (dispatchSyncMessage(connection, decoder, replyEncoder))
245         return;
246
247     ASSERT_NOT_REACHED();
248 }
249
250 void NetworkProcessProxy::didClose(IPC::Connection&)
251 {
252     auto protectedProcessPool = makeRef(m_processPool);
253
254     if (m_downloadProxyMap)
255         m_downloadProxyMap->processDidClose();
256 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
257     m_customProtocolManagerProxy.invalidate();
258 #endif
259
260     m_tokenForHoldingLockedFiles = nullptr;
261     
262     m_syncAllCookiesToken = nullptr;
263     m_syncAllCookiesCounter = 0;
264
265     for (auto& callback : m_writeBlobToFilePathCallbackMap.values())
266         callback(false);
267     m_writeBlobToFilePathCallbackMap.clear();
268
269     // This may cause us to be deleted.
270     networkProcessCrashed();
271 }
272
273 void NetworkProcessProxy::didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference, IPC::StringReference)
274 {
275 }
276
277 void NetworkProcessProxy::didCreateNetworkConnectionToWebProcess(const IPC::Attachment& connectionIdentifier)
278 {
279     ASSERT(!m_pendingConnectionReplies.isEmpty());
280
281     // Grab the first pending connection reply.
282     auto reply = m_pendingConnectionReplies.takeFirst();
283
284 #if USE(UNIX_DOMAIN_SOCKETS) || OS(WINDOWS)
285     reply(connectionIdentifier);
286 #elif OS(DARWIN)
287     reply(IPC::Attachment(connectionIdentifier.port(), MACH_MSG_TYPE_MOVE_SEND));
288 #else
289     notImplemented();
290 #endif
291 }
292
293 void NetworkProcessProxy::didReceiveAuthenticationChallenge(uint64_t pageID, uint64_t frameID, WebCore::AuthenticationChallenge&& coreChallenge, uint64_t challengeID)
294 {
295 #if ENABLE(SERVICE_WORKER)
296     if (auto* serviceWorkerProcessProxy = m_processPool.serviceWorkerProcessProxyFromPageID(pageID)) {
297         auto authenticationChallenge = AuthenticationChallengeProxy::create(WTFMove(coreChallenge), challengeID, connection());
298         serviceWorkerProcessProxy->didReceiveAuthenticationChallenge(pageID, frameID, WTFMove(authenticationChallenge));
299         return;
300     }
301 #endif
302
303     WebPageProxy* page = WebProcessProxy::webPage(pageID);
304     MESSAGE_CHECK(page);
305
306     auto authenticationChallenge = AuthenticationChallengeProxy::create(WTFMove(coreChallenge), challengeID, connection());
307     page->didReceiveAuthenticationChallengeProxy(frameID, WTFMove(authenticationChallenge));
308 }
309
310 void NetworkProcessProxy::didFetchWebsiteData(uint64_t callbackID, const WebsiteData& websiteData)
311 {
312     auto callback = m_pendingFetchWebsiteDataCallbacks.take(callbackID);
313     callback(websiteData);
314 }
315
316 void NetworkProcessProxy::didDeleteWebsiteData(uint64_t callbackID)
317 {
318     auto callback = m_pendingDeleteWebsiteDataCallbacks.take(callbackID);
319     callback();
320 }
321
322 void NetworkProcessProxy::didDeleteWebsiteDataForOrigins(uint64_t callbackID)
323 {
324     auto callback = m_pendingDeleteWebsiteDataForOriginsCallbacks.take(callbackID);
325     callback();
326 }
327
328 void NetworkProcessProxy::grantSandboxExtensionsToStorageProcessForBlobs(uint64_t requestID, const Vector<String>& paths)
329 {
330 #if ENABLE(SANDBOX_EXTENSIONS)
331     SandboxExtension::HandleArray extensions;
332     extensions.allocate(paths.size());
333     for (size_t i = 0; i < paths.size(); ++i) {
334         // ReadWrite is required for creating hard links as well as deleting the temporary file, which the StorageProcess will do.
335         SandboxExtension::createHandle(paths[i], SandboxExtension::Type::ReadWrite, extensions[i]);
336     }
337
338     m_processPool.sendToStorageProcessRelaunchingIfNecessary(Messages::StorageProcess::GrantSandboxExtensionsForBlobs(paths, extensions));
339 #endif
340     connection()->send(Messages::NetworkProcess::DidGrantSandboxExtensionsToStorageProcessForBlobs(requestID), 0);
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(), 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)
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 USE(PROTECTION_SPACE_AUTH_CALLBACK)
402 void NetworkProcessProxy::canAuthenticateAgainstProtectionSpace(uint64_t loaderID, uint64_t pageID, uint64_t frameID, const WebCore::ProtectionSpace& protectionSpace)
403 {
404     // NetworkProcess state cannot asynchronously be kept in sync with these objects
405     // like we expect WebProcess <-> UIProcess state to be kept in sync.
406     // So there's no guarantee the messaged WebPageProxy or WebFrameProxy exist here in the UIProcess.
407     // We need to validate both the page and the frame up front.
408     if (auto* page = WebProcessProxy::webPage(pageID)) {
409         if (page->process().webFrame(frameID)) {
410             page->canAuthenticateAgainstProtectionSpace(loaderID, frameID, protectionSpace);
411             return;
412         }
413 #if ENABLE(SERVICE_WORKER)
414     } else if (m_processPool.serviceWorkerProcessProxyFromPageID(pageID)) {
415         send(Messages::NetworkProcess::ContinueCanAuthenticateAgainstProtectionSpace(loaderID, true), 0);
416         return;
417 #endif
418     }
419     // In the case where we will not be able to reply to this message with a client reply,
420     // we should message back a default to the Networking process.
421     send(Messages::NetworkProcess::ContinueCanAuthenticateAgainstProtectionSpace(loaderID, false), 0);
422 }
423 #endif
424
425 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
426 void NetworkProcessProxy::updatePrevalentDomainsToPartitionOrBlockCookies(PAL::SessionID sessionID, const Vector<String>& domainsToPartition, const Vector<String>& domainsToBlock, const Vector<String>& domainsToNeitherPartitionNorBlock, ShouldClearFirst shouldClearFirst, CompletionHandler<void()>&& callback)
427 {
428     if (!canSendMessage()) {
429         callback();
430         return;
431     }
432     
433     auto callbackId = generateCallbackID();
434     auto addResult = m_updatePartitionOrBlockCookiesCallbackMap.add(callbackId, [protectedThis = makeRef(*this), token = throttler().backgroundActivityToken(), callback = WTFMove(callback)] {
435         callback();
436     });
437     ASSERT_UNUSED(addResult, addResult.isNewEntry);
438     send(Messages::NetworkProcess::UpdatePrevalentDomainsToPartitionOrBlockCookies(sessionID, domainsToPartition, domainsToBlock, domainsToNeitherPartitionNorBlock, shouldClearFirst == ShouldClearFirst::Yes, callbackId), 0);
439 }
440
441 void NetworkProcessProxy::didUpdatePartitionOrBlockCookies(uint64_t callbackId)
442 {
443     m_updatePartitionOrBlockCookiesCallbackMap.take(callbackId)();
444 }
445
446 static uint64_t nextRequestStorageAccessContextId()
447 {
448     static uint64_t nextContextId = 0;
449     return ++nextContextId;
450 }
451
452 void NetworkProcessProxy::hasStorageAccessForFrame(PAL::SessionID sessionID, const String& resourceDomain, const String& firstPartyDomain, uint64_t frameID, uint64_t pageID, WTF::CompletionHandler<void(bool)>&& callback)
453 {
454     auto contextId = nextRequestStorageAccessContextId();
455     auto addResult = m_storageAccessResponseCallbackMap.add(contextId, WTFMove(callback));
456     ASSERT_UNUSED(addResult, addResult.isNewEntry);
457     send(Messages::NetworkProcess::HasStorageAccessForFrame(sessionID, resourceDomain, firstPartyDomain, frameID, pageID, contextId), 0);
458 }
459
460 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)
461 {
462     auto contextId = nextRequestStorageAccessContextId();
463     auto addResult = m_storageAccessResponseCallbackMap.add(contextId, WTFMove(callback));
464     ASSERT_UNUSED(addResult, addResult.isNewEntry);
465     send(Messages::NetworkProcess::GrantStorageAccess(sessionID, resourceDomain, firstPartyDomain, frameID, pageID, contextId), 0);
466 }
467
468 void NetworkProcessProxy::removeAllStorageAccess(PAL::SessionID sessionID)
469 {
470     if (canSendMessage())
471         send(Messages::NetworkProcess::RemoveAllStorageAccess(sessionID), 0);
472 }
473
474 void NetworkProcessProxy::storageAccessRequestResult(bool wasGranted, uint64_t contextId)
475 {
476     auto callback = m_storageAccessResponseCallbackMap.take(contextId);
477     callback(wasGranted);
478 }
479
480 void NetworkProcessProxy::getAllStorageAccessEntries(PAL::SessionID sessionID, CompletionHandler<void(Vector<String>&& domains)>&& callback)
481 {
482     auto contextId = nextRequestStorageAccessContextId();
483     auto addResult = m_allStorageAccessEntriesCallbackMap.add(contextId, WTFMove(callback));
484     ASSERT_UNUSED(addResult, addResult.isNewEntry);
485     send(Messages::NetworkProcess::GetAllStorageAccessEntries(sessionID, contextId), 0);
486 }
487
488 void NetworkProcessProxy::allStorageAccessEntriesResult(Vector<String>&& domains, uint64_t contextId)
489 {
490     auto callback = m_allStorageAccessEntriesCallbackMap.take(contextId);
491     callback(WTFMove(domains));
492 }
493 #endif
494
495 void NetworkProcessProxy::sendProcessWillSuspendImminently()
496 {
497     if (!canSendMessage())
498         return;
499
500     bool handled = false;
501     sendSync(Messages::NetworkProcess::ProcessWillSuspendImminently(), Messages::NetworkProcess::ProcessWillSuspendImminently::Reply(handled), 0, 1_s);
502 }
503     
504 void NetworkProcessProxy::sendPrepareToSuspend()
505 {
506     if (canSendMessage())
507         send(Messages::NetworkProcess::PrepareToSuspend(), 0);
508 }
509
510 void NetworkProcessProxy::sendCancelPrepareToSuspend()
511 {
512     if (canSendMessage())
513         send(Messages::NetworkProcess::CancelPrepareToSuspend(), 0);
514 }
515
516 void NetworkProcessProxy::sendProcessDidResume()
517 {
518     if (canSendMessage())
519         send(Messages::NetworkProcess::ProcessDidResume(), 0);
520 }
521
522 void NetworkProcessProxy::writeBlobToFilePath(const WebCore::URL& url, const String& path, CompletionHandler<void(bool)>&& callback)
523 {
524     if (!canSendMessage()) {
525         callback(false);
526         return;
527     }
528
529     static uint64_t writeBlobToFilePathCallbackIdentifiers = 0;
530     uint64_t callbackID = ++writeBlobToFilePathCallbackIdentifiers;
531     m_writeBlobToFilePathCallbackMap.add(callbackID, WTFMove(callback));
532
533     SandboxExtension::Handle handleForWriting;
534     SandboxExtension::createHandle(path, SandboxExtension::Type::ReadWrite, handleForWriting);
535     send(Messages::NetworkProcess::WriteBlobToFilePath(url, path, handleForWriting, callbackID), 0);
536 }
537
538 void NetworkProcessProxy::didWriteBlobToFilePath(bool success, uint64_t callbackID)
539 {
540     if (auto handler = m_writeBlobToFilePathCallbackMap.take(callbackID))
541         handler(success);
542     else
543         ASSERT_NOT_REACHED();
544 }
545
546 void NetworkProcessProxy::processReadyToSuspend()
547 {
548     m_throttler.processReadyToSuspend();
549 }
550
551 void NetworkProcessProxy::didSetAssertionState(AssertionState)
552 {
553 }
554     
555 void NetworkProcessProxy::setIsHoldingLockedFiles(bool isHoldingLockedFiles)
556 {
557     if (!isHoldingLockedFiles) {
558         RELEASE_LOG(ProcessSuspension, "UIProcess is releasing a background assertion because the Network process is no longer holding locked files");
559         m_tokenForHoldingLockedFiles = nullptr;
560         return;
561     }
562     if (!m_tokenForHoldingLockedFiles) {
563         RELEASE_LOG(ProcessSuspension, "UIProcess is taking a background assertion because the Network process is holding locked files");
564         m_tokenForHoldingLockedFiles = m_throttler.backgroundActivityToken();
565     }
566 }
567
568 void NetworkProcessProxy::syncAllCookies()
569 {
570     send(Messages::NetworkProcess::SyncAllCookies(), 0);
571     
572     ++m_syncAllCookiesCounter;
573     if (m_syncAllCookiesToken)
574         return;
575     
576     RELEASE_LOG(ProcessSuspension, "%p - NetworkProcessProxy is taking a background assertion because the Network process is syncing cookies", this);
577     m_syncAllCookiesToken = throttler().backgroundActivityToken();
578 }
579     
580 void NetworkProcessProxy::didSyncAllCookies()
581 {
582     ASSERT(m_syncAllCookiesCounter);
583
584     --m_syncAllCookiesCounter;
585     if (!m_syncAllCookiesCounter) {
586         RELEASE_LOG(ProcessSuspension, "%p - NetworkProcessProxy is releasing a background assertion because the Network process is done syncing cookies", this);
587         m_syncAllCookiesToken = nullptr;
588     }
589 }
590
591 void NetworkProcessProxy::addSession(Ref<WebsiteDataStore>&& store)
592 {
593     if (canSendMessage())
594         send(Messages::NetworkProcess::AddWebsiteDataStore { store->parameters() }, 0);
595     auto sessionID = store->sessionID();
596     if (!sessionID.isEphemeral())
597         m_websiteDataStores.set(sessionID, WTFMove(store));
598 }
599
600 void NetworkProcessProxy::removeSession(PAL::SessionID sessionID)
601 {
602     if (canSendMessage())
603         send(Messages::NetworkProcess::DestroySession { sessionID }, 0);
604     if (!sessionID.isEphemeral())
605         m_websiteDataStores.remove(sessionID);
606 }
607
608 void NetworkProcessProxy::retrieveCacheStorageParameters(PAL::SessionID sessionID)
609 {
610     auto iterator = m_websiteDataStores.find(sessionID);
611     if (iterator == m_websiteDataStores.end()) {
612         auto quota = m_processPool.websiteDataStore() ? m_processPool.websiteDataStore()->websiteDataStore().cacheStoragePerOriginQuota() : WebsiteDataStore::defaultCacheStoragePerOriginQuota;
613         send(Messages::NetworkProcess::SetCacheStorageParameters { sessionID, quota, { }, { } }, 0);
614         return;
615     }
616
617     auto& store = *iterator->value;
618     auto& cacheStorageDirectory = store.cacheStorageDirectory();
619     SandboxExtension::Handle cacheStorageDirectoryExtensionHandle;
620     if (!cacheStorageDirectory.isEmpty())
621         SandboxExtension::createHandleForReadWriteDirectory(cacheStorageDirectory, cacheStorageDirectoryExtensionHandle);
622
623     send(Messages::NetworkProcess::SetCacheStorageParameters { sessionID, store.cacheStoragePerOriginQuota(), cacheStorageDirectory, cacheStorageDirectoryExtensionHandle }, 0);
624 }
625
626 #if ENABLE(CONTENT_EXTENSIONS)
627 void NetworkProcessProxy::contentExtensionRules(UserContentControllerIdentifier identifier)
628 {
629     if (auto* webUserContentControllerProxy = WebUserContentControllerProxy::get(identifier)) {
630         m_webUserContentControllerProxies.add(webUserContentControllerProxy);
631         webUserContentControllerProxy->addNetworkProcess(*this);
632
633         auto rules = WTF::map(webUserContentControllerProxy->contentExtensionRules(), [](auto&& keyValue) -> std::pair<String, WebCompiledContentRuleListData> {
634             return std::make_pair(keyValue.value->name(), keyValue.value->compiledRuleList().data());
635         });
636         send(Messages::NetworkContentRuleListManager::AddContentRuleLists { identifier, rules }, 0);
637         return;
638     }
639     send(Messages::NetworkContentRuleListManager::AddContentRuleLists { identifier, { } }, 0);
640 }
641
642 void NetworkProcessProxy::didDestroyWebUserContentControllerProxy(WebUserContentControllerProxy& proxy)
643 {
644     send(Messages::NetworkContentRuleListManager::Remove { proxy.identifier() }, 0);
645     m_webUserContentControllerProxies.remove(&proxy);
646 }
647 #endif
648
649 } // namespace WebKit