Use CompletionHandlers for DelayedReplies
[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
87 NetworkProcessProxy::~NetworkProcessProxy()
88 {
89     ASSERT(m_pendingFetchWebsiteDataCallbacks.isEmpty());
90     ASSERT(m_pendingDeleteWebsiteDataCallbacks.isEmpty());
91     ASSERT(m_pendingDeleteWebsiteDataForOriginsCallbacks.isEmpty());
92 #if ENABLE(CONTENT_EXTENSIONS)
93     for (auto* proxy : m_webUserContentControllerProxies)
94         proxy->removeNetworkProcess(*this);
95 #endif
96 }
97
98 void NetworkProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions)
99 {
100     launchOptions.processType = ProcessLauncher::ProcessType::Network;
101     ChildProcessProxy::getLaunchOptions(launchOptions);
102 }
103
104 void NetworkProcessProxy::connectionWillOpen(IPC::Connection& connection)
105 {
106 #if ENABLE(SEC_ITEM_SHIM)
107     SecItemShimProxy::singleton().initializeConnection(connection);
108 #else
109     UNUSED_PARAM(connection);
110 #endif
111 }
112
113 void NetworkProcessProxy::processWillShutDown(IPC::Connection& connection)
114 {
115     ASSERT_UNUSED(connection, this->connection() == &connection);
116 }
117
118 void NetworkProcessProxy::getNetworkProcessConnection(Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&& reply)
119 {
120     m_pendingConnectionReplies.append(WTFMove(reply));
121
122     if (state() == State::Launching) {
123         m_numPendingConnectionRequests++;
124         return;
125     }
126
127     connection()->send(Messages::NetworkProcess::CreateNetworkConnectionToWebProcess(), 0, IPC::SendOption::DispatchMessageEvenWhenWaitingForSyncReply);
128 }
129
130 DownloadProxy* NetworkProcessProxy::createDownloadProxy(const ResourceRequest& resourceRequest)
131 {
132     if (!m_downloadProxyMap)
133         m_downloadProxyMap = std::make_unique<DownloadProxyMap>(this);
134
135     return m_downloadProxyMap->createDownloadProxy(m_processPool, resourceRequest);
136 }
137
138 void NetworkProcessProxy::fetchWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> dataTypes, OptionSet<WebsiteDataFetchOption> fetchOptions, WTF::Function<void (WebsiteData)>&& completionHandler)
139 {
140     ASSERT(canSendMessage());
141
142     uint64_t callbackID = generateCallbackID();
143     RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is taking a background assertion because the Network process is fetching Website data", this);
144
145     m_pendingFetchWebsiteDataCallbacks.add(callbackID, [this, token = throttler().backgroundActivityToken(), completionHandler = WTFMove(completionHandler), sessionID](WebsiteData websiteData) {
146 #if RELEASE_LOG_DISABLED
147         UNUSED_PARAM(this);
148         UNUSED_PARAM(sessionID);
149 #endif
150         completionHandler(WTFMove(websiteData));
151         RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is releasing a background assertion because the Network process is done fetching Website data", this);
152     });
153
154     send(Messages::NetworkProcess::FetchWebsiteData(sessionID, dataTypes, fetchOptions, callbackID), 0);
155 }
156
157 void NetworkProcessProxy::deleteWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> dataTypes, WallTime modifiedSince, WTF::Function<void ()>&& completionHandler)
158 {
159     auto callbackID = generateCallbackID();
160     RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is taking a background assertion because the Network process is deleting Website data", this);
161
162     m_pendingDeleteWebsiteDataCallbacks.add(callbackID, [this, token = throttler().backgroundActivityToken(), completionHandler = WTFMove(completionHandler), sessionID] {
163 #if RELEASE_LOG_DISABLED
164         UNUSED_PARAM(this);
165         UNUSED_PARAM(sessionID);
166 #endif
167         completionHandler();
168         RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is releasing a background assertion because the Network process is done deleting Website data", this);
169     });
170     send(Messages::NetworkProcess::DeleteWebsiteData(sessionID, dataTypes, modifiedSince, callbackID), 0);
171 }
172
173 void NetworkProcessProxy::deleteWebsiteDataForOrigins(PAL::SessionID sessionID, OptionSet<WebsiteDataType> dataTypes, const Vector<WebCore::SecurityOriginData>& origins, const Vector<String>& cookieHostNames, WTF::Function<void()>&& completionHandler)
174 {
175     ASSERT(canSendMessage());
176
177     uint64_t callbackID = generateCallbackID();
178     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);
179
180     m_pendingDeleteWebsiteDataForOriginsCallbacks.add(callbackID, [this, token = throttler().backgroundActivityToken(), completionHandler = WTFMove(completionHandler), sessionID] {
181 #if RELEASE_LOG_DISABLED
182         UNUSED_PARAM(this);
183         UNUSED_PARAM(sessionID);
184 #endif
185         completionHandler();
186         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);
187     });
188
189     send(Messages::NetworkProcess::DeleteWebsiteDataForOrigins(sessionID, dataTypes, origins, cookieHostNames, callbackID), 0);
190 }
191
192 void NetworkProcessProxy::networkProcessCrashed()
193 {
194     clearCallbackStates();
195
196     Vector<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply> pendingReplies;
197     pendingReplies.reserveInitialCapacity(m_pendingConnectionReplies.size());
198     for (auto& reply : m_pendingConnectionReplies)
199         pendingReplies.append(WTFMove(reply));
200
201     // Tell the network process manager to forget about this network process proxy. This may cause us to be deleted.
202     m_processPool.networkProcessCrashed(*this, WTFMove(pendingReplies));
203 }
204
205 void NetworkProcessProxy::networkProcessFailedToLaunch()
206 {
207     // The network process must have crashed or exited, send any pending sync replies we might have.
208     while (!m_pendingConnectionReplies.isEmpty()) {
209         auto reply = m_pendingConnectionReplies.takeFirst();
210
211 #if USE(UNIX_DOMAIN_SOCKETS)
212         reply(IPC::Attachment());
213 #elif OS(DARWIN)
214         reply(IPC::Attachment(0, MACH_MSG_TYPE_MOVE_SEND));
215 #else
216         notImplemented();
217 #endif
218     }
219     clearCallbackStates();
220     // Tell the network process manager to forget about this network process proxy. This may cause us to be deleted.
221     m_processPool.networkProcessFailedToLaunch(*this);
222 }
223
224 void NetworkProcessProxy::clearCallbackStates()
225 {
226     for (const auto& callback : m_pendingFetchWebsiteDataCallbacks.values())
227         callback(WebsiteData());
228     m_pendingFetchWebsiteDataCallbacks.clear();
229
230     for (const auto& callback : m_pendingDeleteWebsiteDataCallbacks.values())
231         callback();
232     m_pendingDeleteWebsiteDataCallbacks.clear();
233
234     for (const auto& callback : m_pendingDeleteWebsiteDataForOriginsCallbacks.values())
235         callback();
236     m_pendingDeleteWebsiteDataForOriginsCallbacks.clear();
237 }
238
239 void NetworkProcessProxy::didReceiveMessage(IPC::Connection& connection, IPC::Decoder& decoder)
240 {
241     if (dispatchMessage(connection, decoder))
242         return;
243
244     if (m_processPool.dispatchMessage(connection, decoder))
245         return;
246
247     didReceiveNetworkProcessProxyMessage(connection, decoder);
248 }
249
250 void NetworkProcessProxy::didReceiveSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
251 {
252     if (dispatchSyncMessage(connection, decoder, replyEncoder))
253         return;
254
255     ASSERT_NOT_REACHED();
256 }
257
258 void NetworkProcessProxy::didClose(IPC::Connection&)
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     for (auto& callback : m_writeBlobToFilePathCallbackMap.values())
269         callback(false);
270     m_writeBlobToFilePathCallbackMap.clear();
271
272     // This may cause us to be deleted.
273     networkProcessCrashed();
274 }
275
276 void NetworkProcessProxy::didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference, IPC::StringReference)
277 {
278 }
279
280 void NetworkProcessProxy::didCreateNetworkConnectionToWebProcess(const IPC::Attachment& connectionIdentifier)
281 {
282     ASSERT(!m_pendingConnectionReplies.isEmpty());
283
284     // Grab the first pending connection reply.
285     auto reply = m_pendingConnectionReplies.takeFirst();
286
287 #if USE(UNIX_DOMAIN_SOCKETS)
288     reply(connectionIdentifier);
289 #elif OS(DARWIN)
290     reply(IPC::Attachment(connectionIdentifier.port(), MACH_MSG_TYPE_MOVE_SEND));
291 #else
292     notImplemented();
293 #endif
294 }
295
296 void NetworkProcessProxy::didReceiveAuthenticationChallenge(uint64_t pageID, uint64_t frameID, const WebCore::AuthenticationChallenge& coreChallenge, uint64_t challengeID)
297 {
298 #if ENABLE(SERVICE_WORKER)
299     if (auto* serviceWorkerProcessProxy = m_processPool.serviceWorkerProcessProxyFromPageID(pageID)) {
300         auto authenticationChallenge = AuthenticationChallengeProxy::create(coreChallenge, challengeID, connection());
301         serviceWorkerProcessProxy->didReceiveAuthenticationChallenge(pageID, frameID, WTFMove(authenticationChallenge));
302         return;
303     }
304 #endif
305
306     WebPageProxy* page = WebProcessProxy::webPage(pageID);
307     MESSAGE_CHECK(page);
308
309     auto authenticationChallenge = AuthenticationChallengeProxy::create(coreChallenge, challengeID, connection());
310     page->didReceiveAuthenticationChallengeProxy(frameID, WTFMove(authenticationChallenge));
311 }
312
313 void NetworkProcessProxy::didFetchWebsiteData(uint64_t callbackID, const WebsiteData& websiteData)
314 {
315     auto callback = m_pendingFetchWebsiteDataCallbacks.take(callbackID);
316     callback(websiteData);
317 }
318
319 void NetworkProcessProxy::didDeleteWebsiteData(uint64_t callbackID)
320 {
321     auto callback = m_pendingDeleteWebsiteDataCallbacks.take(callbackID);
322     callback();
323 }
324
325 void NetworkProcessProxy::didDeleteWebsiteDataForOrigins(uint64_t callbackID)
326 {
327     auto callback = m_pendingDeleteWebsiteDataForOriginsCallbacks.take(callbackID);
328     callback();
329 }
330
331 void NetworkProcessProxy::grantSandboxExtensionsToStorageProcessForBlobs(uint64_t requestID, const Vector<String>& paths)
332 {
333 #if ENABLE(SANDBOX_EXTENSIONS)
334     SandboxExtension::HandleArray extensions;
335     extensions.allocate(paths.size());
336     for (size_t i = 0; i < paths.size(); ++i) {
337         // ReadWrite is required for creating hard links as well as deleting the temporary file, which the StorageProcess will do.
338         SandboxExtension::createHandle(paths[i], SandboxExtension::Type::ReadWrite, extensions[i]);
339     }
340
341     m_processPool.sendToStorageProcessRelaunchingIfNecessary(Messages::StorageProcess::GrantSandboxExtensionsForBlobs(paths, extensions));
342 #endif
343     connection()->send(Messages::NetworkProcess::DidGrantSandboxExtensionsToStorageProcessForBlobs(requestID), 0);
344 }
345
346 void NetworkProcessProxy::didFinishLaunching(ProcessLauncher* launcher, IPC::Connection::Identifier connectionIdentifier)
347 {
348     ChildProcessProxy::didFinishLaunching(launcher, connectionIdentifier);
349
350     if (!IPC::Connection::identifierIsValid(connectionIdentifier)) {
351         networkProcessFailedToLaunch();
352         return;
353     }
354
355     for (unsigned i = 0; i < m_numPendingConnectionRequests; ++i)
356         connection()->send(Messages::NetworkProcess::CreateNetworkConnectionToWebProcess(), 0);
357     
358     m_numPendingConnectionRequests = 0;
359
360 #if PLATFORM(COCOA)
361     if (m_processPool.processSuppressionEnabled())
362         setProcessSuppressionEnabled(true);
363 #endif
364     
365 #if PLATFORM(IOS)
366     if (xpc_connection_t connection = this->connection()->xpcConnection())
367         m_throttler.didConnectToProcess(xpc_connection_get_pid(connection));
368 #endif
369 }
370
371 void NetworkProcessProxy::logDiagnosticMessage(uint64_t pageID, const String& message, const String& description, WebCore::ShouldSample shouldSample)
372 {
373     WebPageProxy* page = WebProcessProxy::webPage(pageID);
374     // 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,
375     // but for now we simply drop the message in the rare case this happens.
376     if (!page)
377         return;
378
379     page->logDiagnosticMessage(message, description, shouldSample);
380 }
381
382 void NetworkProcessProxy::logDiagnosticMessageWithResult(uint64_t pageID, const String& message, const String& description, uint32_t result, WebCore::ShouldSample shouldSample)
383 {
384     WebPageProxy* page = WebProcessProxy::webPage(pageID);
385     // 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,
386     // but for now we simply drop the message in the rare case this happens.
387     if (!page)
388         return;
389
390     page->logDiagnosticMessageWithResult(message, description, result, shouldSample);
391 }
392
393 void NetworkProcessProxy::logDiagnosticMessageWithValue(uint64_t pageID, const String& message, const String& description, double value, unsigned significantFigures, WebCore::ShouldSample shouldSample)
394 {
395     WebPageProxy* page = WebProcessProxy::webPage(pageID);
396     // 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,
397     // but for now we simply drop the message in the rare case this happens.
398     if (!page)
399         return;
400
401     page->logDiagnosticMessageWithValue(message, description, value, significantFigures, shouldSample);
402 }
403
404 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
405 void NetworkProcessProxy::canAuthenticateAgainstProtectionSpace(uint64_t loaderID, uint64_t pageID, uint64_t frameID, const WebCore::ProtectionSpace& protectionSpace)
406 {
407     // NetworkProcess state cannot asynchronously be kept in sync with these objects
408     // like we expect WebProcess <-> UIProcess state to be kept in sync.
409     // So there's no guarantee the messaged WebPageProxy or WebFrameProxy exist here in the UIProcess.
410     // We need to validate both the page and the frame up front.
411     if (auto* page = WebProcessProxy::webPage(pageID)) {
412         if (page->process().webFrame(frameID)) {
413             page->canAuthenticateAgainstProtectionSpace(loaderID, frameID, protectionSpace);
414             return;
415         }
416 #if ENABLE(SERVICE_WORKER)
417     } else if (m_processPool.serviceWorkerProcessProxyFromPageID(pageID)) {
418         send(Messages::NetworkProcess::ContinueCanAuthenticateAgainstProtectionSpace(loaderID, true), 0);
419         return;
420 #endif
421     }
422     // In the case where we will not be able to reply to this message with a client reply,
423     // we should message back a default to the Networking process.
424     send(Messages::NetworkProcess::ContinueCanAuthenticateAgainstProtectionSpace(loaderID, false), 0);
425 }
426 #endif
427
428 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
429 static uint64_t nextRequestStorageAccessContextId()
430 {
431     static uint64_t nextContextId = 0;
432     return ++nextContextId;
433 }
434
435 void NetworkProcessProxy::hasStorageAccessForFrame(PAL::SessionID sessionID, const String& resourceDomain, const String& firstPartyDomain, uint64_t frameID, uint64_t pageID, WTF::CompletionHandler<void(bool)>&& callback)
436 {
437     auto contextId = nextRequestStorageAccessContextId();
438     auto addResult = m_storageAccessResponseCallbackMap.add(contextId, WTFMove(callback));
439     ASSERT_UNUSED(addResult, addResult.isNewEntry);
440     send(Messages::NetworkProcess::HasStorageAccessForFrame(sessionID, resourceDomain, firstPartyDomain, frameID, pageID, contextId), 0);
441 }
442
443 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)
444 {
445     auto contextId = nextRequestStorageAccessContextId();
446     auto addResult = m_storageAccessResponseCallbackMap.add(contextId, WTFMove(callback));
447     ASSERT_UNUSED(addResult, addResult.isNewEntry);
448     send(Messages::NetworkProcess::GrantStorageAccess(sessionID, resourceDomain, firstPartyDomain, frameID, pageID, contextId), 0);
449 }
450
451 void NetworkProcessProxy::removeAllStorageAccess(PAL::SessionID sessionID)
452 {
453     if (canSendMessage())
454         send(Messages::NetworkProcess::RemoveAllStorageAccess(sessionID), 0);
455 }
456
457 void NetworkProcessProxy::storageAccessRequestResult(bool wasGranted, uint64_t contextId)
458 {
459     auto callback = m_storageAccessResponseCallbackMap.take(contextId);
460     callback(wasGranted);
461 }
462
463 void NetworkProcessProxy::getAllStorageAccessEntries(PAL::SessionID sessionID, CompletionHandler<void(Vector<String>&& domains)>&& callback)
464 {
465     auto contextId = nextRequestStorageAccessContextId();
466     auto addResult = m_allStorageAccessEntriesCallbackMap.add(contextId, WTFMove(callback));
467     ASSERT_UNUSED(addResult, addResult.isNewEntry);
468     send(Messages::NetworkProcess::GetAllStorageAccessEntries(sessionID, contextId), 0);
469 }
470
471 void NetworkProcessProxy::allStorageAccessEntriesResult(Vector<String>&& domains, uint64_t contextId)
472 {
473     auto callback = m_allStorageAccessEntriesCallbackMap.take(contextId);
474     callback(WTFMove(domains));
475 }
476 #endif
477
478 void NetworkProcessProxy::sendProcessWillSuspendImminently()
479 {
480     if (!canSendMessage())
481         return;
482
483     bool handled = false;
484     sendSync(Messages::NetworkProcess::ProcessWillSuspendImminently(), Messages::NetworkProcess::ProcessWillSuspendImminently::Reply(handled), 0, 1_s);
485 }
486     
487 void NetworkProcessProxy::sendPrepareToSuspend()
488 {
489     if (canSendMessage())
490         send(Messages::NetworkProcess::PrepareToSuspend(), 0);
491 }
492
493 void NetworkProcessProxy::sendCancelPrepareToSuspend()
494 {
495     if (canSendMessage())
496         send(Messages::NetworkProcess::CancelPrepareToSuspend(), 0);
497 }
498
499 void NetworkProcessProxy::sendProcessDidResume()
500 {
501     if (canSendMessage())
502         send(Messages::NetworkProcess::ProcessDidResume(), 0);
503 }
504
505 void NetworkProcessProxy::writeBlobToFilePath(const WebCore::URL& url, const String& path, CompletionHandler<void(bool)>&& callback)
506 {
507     if (!canSendMessage()) {
508         callback(false);
509         return;
510     }
511
512     static uint64_t writeBlobToFilePathCallbackIdentifiers = 0;
513     uint64_t callbackID = ++writeBlobToFilePathCallbackIdentifiers;
514     m_writeBlobToFilePathCallbackMap.add(callbackID, WTFMove(callback));
515
516     SandboxExtension::Handle handleForWriting;
517     SandboxExtension::createHandle(path, SandboxExtension::Type::ReadWrite, handleForWriting);
518     send(Messages::NetworkProcess::WriteBlobToFilePath(url, path, handleForWriting, callbackID), 0);
519 }
520
521 void NetworkProcessProxy::didWriteBlobToFilePath(bool success, uint64_t callbackID)
522 {
523     if (auto handler = m_writeBlobToFilePathCallbackMap.take(callbackID))
524         handler(success);
525     else
526         ASSERT_NOT_REACHED();
527 }
528
529 void NetworkProcessProxy::processReadyToSuspend()
530 {
531     m_throttler.processReadyToSuspend();
532 }
533
534 void NetworkProcessProxy::didSetAssertionState(AssertionState)
535 {
536 }
537     
538 void NetworkProcessProxy::setIsHoldingLockedFiles(bool isHoldingLockedFiles)
539 {
540     if (!isHoldingLockedFiles) {
541         RELEASE_LOG(ProcessSuspension, "UIProcess is releasing a background assertion because the Network process is no longer holding locked files");
542         m_tokenForHoldingLockedFiles = nullptr;
543         return;
544     }
545     if (!m_tokenForHoldingLockedFiles) {
546         RELEASE_LOG(ProcessSuspension, "UIProcess is taking a background assertion because the Network process is holding locked files");
547         m_tokenForHoldingLockedFiles = m_throttler.backgroundActivityToken();
548     }
549 }
550
551
552 #if ENABLE(CONTENT_EXTENSIONS)
553 void NetworkProcessProxy::contentExtensionRules(UserContentControllerIdentifier identifier)
554 {
555     if (auto* webUserContentControllerProxy = WebUserContentControllerProxy::get(identifier)) {
556         m_webUserContentControllerProxies.add(webUserContentControllerProxy);
557         webUserContentControllerProxy->addNetworkProcess(*this);
558
559         auto rules = WTF::map(webUserContentControllerProxy->contentExtensionRules(), [](auto&& keyValue) -> std::pair<String, WebCompiledContentRuleListData> {
560             return std::make_pair(keyValue.value->name(), keyValue.value->compiledRuleList().data());
561         });
562         send(Messages::NetworkContentRuleListManager::AddContentRuleLists { identifier, rules }, 0);
563         return;
564     }
565     send(Messages::NetworkContentRuleListManager::AddContentRuleLists { identifier, { } }, 0);
566 }
567
568 void NetworkProcessProxy::didDestroyWebUserContentControllerProxy(WebUserContentControllerProxy& proxy)
569 {
570     send(Messages::NetworkContentRuleListManager::Remove { proxy.identifier() }, 0);
571     m_webUserContentControllerProxies.remove(&proxy);
572 }
573 #endif
574
575 } // namespace WebKit