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