2 * Copyright (C) 2012-2017 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
27 #include "NetworkProcess.h"
29 #include "ArgumentCoders.h"
30 #include "Attachment.h"
31 #include "AuthenticationManager.h"
32 #include "ChildProcessMessages.h"
33 #include "DataReference.h"
34 #include "DownloadProxyMessages.h"
35 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
36 #include "LegacyCustomProtocolManager.h"
39 #include "NetworkBlobRegistry.h"
40 #include "NetworkConnectionToWebProcess.h"
41 #include "NetworkProcessCreationParameters.h"
42 #include "NetworkProcessPlatformStrategies.h"
43 #include "NetworkProcessProxyMessages.h"
44 #include "NetworkResourceLoader.h"
45 #include "NetworkSession.h"
46 #include "PreconnectTask.h"
47 #include "RemoteNetworkingContext.h"
48 #include "SessionTracker.h"
49 #include "StatisticsData.h"
50 #include "WebCookieManager.h"
51 #include "WebCoreArgumentCoders.h"
52 #include "WebPageProxyMessages.h"
53 #include "WebProcessPoolMessages.h"
54 #include "WebsiteData.h"
55 #include "WebsiteDataFetchOption.h"
56 #include "WebsiteDataStore.h"
57 #include "WebsiteDataStoreParameters.h"
58 #include "WebsiteDataType.h"
59 #include <WebCore/DNS.h>
60 #include <WebCore/DeprecatedGlobalSettings.h>
61 #include <WebCore/DiagnosticLoggingClient.h>
62 #include <WebCore/LogInitialization.h>
63 #include <WebCore/MIMETypeRegistry.h>
64 #include <WebCore/NetworkStorageSession.h>
65 #include <WebCore/PlatformCookieJar.h>
66 #include <WebCore/ResourceRequest.h>
67 #include <WebCore/RuntimeApplicationChecks.h>
68 #include <WebCore/SecurityOriginData.h>
69 #include <WebCore/SecurityOriginHash.h>
70 #include <WebCore/Settings.h>
71 #include <WebCore/URLParser.h>
72 #include <pal/SessionID.h>
73 #include <wtf/CallbackAggregator.h>
74 #include <wtf/OptionSet.h>
75 #include <wtf/RunLoop.h>
76 #include <wtf/text/AtomicString.h>
77 #include <wtf/text/CString.h>
79 #if ENABLE(SEC_ITEM_SHIM)
80 #include "SecItemShim.h"
83 #include "NetworkCache.h"
84 #include "NetworkCacheCoders.h"
86 #if ENABLE(NETWORK_CAPTURE)
87 #include "NetworkCaptureManager.h"
91 #include "NetworkSessionCocoa.h"
94 using namespace WebCore;
98 NetworkProcess& NetworkProcess::singleton()
100 static NeverDestroyed<NetworkProcess> networkProcess;
101 return networkProcess;
104 NetworkProcess::NetworkProcess()
105 : m_hasSetCacheModel(false)
106 , m_cacheModel(CacheModelDocumentViewer)
107 , m_diskCacheIsDisabledForTesting(false)
108 , m_canHandleHTTPSServerTrustEvaluation(true)
110 , m_clearCacheDispatchGroup(0)
113 , m_webSQLiteDatabaseTracker(*this)
116 NetworkProcessPlatformStrategies::initialize();
118 addSupplement<AuthenticationManager>();
119 addSupplement<WebCookieManager>();
120 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
121 addSupplement<LegacyCustomProtocolManager>();
125 NetworkProcess::~NetworkProcess()
129 AuthenticationManager& NetworkProcess::authenticationManager()
131 return *supplement<AuthenticationManager>();
134 DownloadManager& NetworkProcess::downloadManager()
136 static NeverDestroyed<DownloadManager> downloadManager(*this);
137 return downloadManager;
140 void NetworkProcess::removeNetworkConnectionToWebProcess(NetworkConnectionToWebProcess* connection)
142 size_t vectorIndex = m_webProcessConnections.find(connection);
143 ASSERT(vectorIndex != notFound);
145 m_webProcessConnections.remove(vectorIndex);
148 bool NetworkProcess::shouldTerminate()
150 // Network process keeps session cookies and credentials, so it should never terminate (as long as UI process connection is alive).
154 void NetworkProcess::didReceiveMessage(IPC::Connection& connection, IPC::Decoder& decoder)
156 if (messageReceiverMap().dispatchMessage(connection, decoder))
159 if (decoder.messageReceiverName() == Messages::ChildProcess::messageReceiverName()) {
160 ChildProcess::didReceiveMessage(connection, decoder);
164 didReceiveNetworkProcessMessage(connection, decoder);
167 void NetworkProcess::didReceiveSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
169 if (messageReceiverMap().dispatchSyncMessage(connection, decoder, replyEncoder))
172 didReceiveSyncNetworkProcessMessage(connection, decoder, replyEncoder);
175 void NetworkProcess::didClose(IPC::Connection&)
177 // The UIProcess just exited.
181 void NetworkProcess::didCreateDownload()
183 disableTermination();
186 void NetworkProcess::didDestroyDownload()
191 IPC::Connection* NetworkProcess::downloadProxyConnection()
193 return parentProcessConnection();
196 AuthenticationManager& NetworkProcess::downloadsAuthenticationManager()
198 return authenticationManager();
201 void NetworkProcess::lowMemoryHandler(Critical critical)
203 if (m_suppressMemoryPressureHandler)
206 WTF::releaseFastMallocFreeMemory();
209 void NetworkProcess::initializeNetworkProcess(NetworkProcessCreationParameters&& parameters)
211 WebCore::setPresentingApplicationPID(parameters.presentingApplicationPID);
212 platformInitializeNetworkProcess(parameters);
214 WTF::Thread::setCurrentThreadIsUserInitiated();
215 AtomicString::init();
217 m_suppressMemoryPressureHandler = parameters.shouldSuppressMemoryPressureHandler;
218 m_loadThrottleLatency = parameters.loadThrottleLatency;
219 if (!m_suppressMemoryPressureHandler) {
220 auto& memoryPressureHandler = MemoryPressureHandler::singleton();
222 if (parameters.memoryPressureMonitorHandle.fileDescriptor() != -1)
223 memoryPressureHandler.setMemoryPressureMonitorHandle(parameters.memoryPressureMonitorHandle.releaseFileDescriptor());
225 memoryPressureHandler.setLowMemoryHandler([this] (Critical critical, Synchronous) {
226 lowMemoryHandler(critical);
228 memoryPressureHandler.install();
231 #if ENABLE(NETWORK_CAPTURE)
232 NetworkCapture::Manager::singleton().initialize(
233 parameters.recordReplayMode,
234 parameters.recordReplayCacheLocation);
237 m_diskCacheIsDisabledForTesting = parameters.shouldUseTestingNetworkSession;
239 m_diskCacheSizeOverride = parameters.diskCacheSizeOverride;
240 setCacheModel(static_cast<uint32_t>(parameters.cacheModel));
242 setCanHandleHTTPSServerTrustEvaluation(parameters.canHandleHTTPSServerTrustEvaluation);
244 // FIXME: instead of handling this here, a message should be sent later (scales to multiple sessions)
245 if (parameters.privateBrowsingEnabled)
246 RemoteNetworkingContext::ensureWebsiteDataStoreSession(WebsiteDataStoreParameters::legacyPrivateSessionParameters());
248 if (parameters.shouldUseTestingNetworkSession)
249 NetworkStorageSession::switchToNewTestingSession();
251 #if HAVE(CFNETWORK_STORAGE_PARTITIONING) && !RELEASE_LOG_DISABLED
252 m_logCookieInformation = parameters.logCookieInformation;
255 #if USE(NETWORK_SESSION)
256 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
257 parameters.defaultSessionParameters.legacyCustomProtocolManager = supplement<LegacyCustomProtocolManager>();
259 SessionTracker::setSession(PAL::SessionID::defaultSessionID(), NetworkSession::create(WTFMove(parameters.defaultSessionParameters)));
262 for (auto& supplement : m_supplements.values())
263 supplement->initialize(parameters);
266 void NetworkProcess::initializeConnection(IPC::Connection* connection)
268 ChildProcess::initializeConnection(connection);
270 for (auto& supplement : m_supplements.values())
271 supplement->initializeConnection(connection);
274 void NetworkProcess::createNetworkConnectionToWebProcess()
276 #if USE(UNIX_DOMAIN_SOCKETS)
277 IPC::Connection::SocketPair socketPair = IPC::Connection::createPlatformConnection();
279 auto connection = NetworkConnectionToWebProcess::create(socketPair.server);
280 m_webProcessConnections.append(WTFMove(connection));
282 IPC::Attachment clientSocket(socketPair.client);
283 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidCreateNetworkConnectionToWebProcess(clientSocket), 0);
285 // Create the listening port.
286 mach_port_t listeningPort;
287 mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &listeningPort);
289 // Create a listening connection.
290 auto connection = NetworkConnectionToWebProcess::create(IPC::Connection::Identifier(listeningPort));
291 m_webProcessConnections.append(WTFMove(connection));
293 IPC::Attachment clientPort(listeningPort, MACH_MSG_TYPE_MAKE_SEND);
294 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidCreateNetworkConnectionToWebProcess(clientPort), 0);
300 void NetworkProcess::clearCachedCredentials()
302 NetworkStorageSession::defaultStorageSession().credentialStorage().clearCredentials();
303 #if USE(NETWORK_SESSION)
304 if (auto* networkSession = SessionTracker::networkSession(PAL::SessionID::defaultSessionID()))
305 networkSession->clearCredentials();
307 ASSERT_NOT_REACHED();
311 void NetworkProcess::addWebsiteDataStore(WebsiteDataStoreParameters&& parameters)
313 RemoteNetworkingContext::ensureWebsiteDataStoreSession(WTFMove(parameters));
316 void NetworkProcess::destroySession(PAL::SessionID sessionID)
318 SessionTracker::destroySession(sessionID);
321 void NetworkProcess::grantSandboxExtensionsToStorageProcessForBlobs(const Vector<String>& filenames, Function<void ()>&& completionHandler)
323 static uint64_t lastRequestID;
325 uint64_t requestID = ++lastRequestID;
326 m_sandboxExtensionForBlobsCompletionHandlers.set(requestID, WTFMove(completionHandler));
327 parentProcessConnection()->send(Messages::NetworkProcessProxy::GrantSandboxExtensionsToStorageProcessForBlobs(requestID, filenames), 0);
330 void NetworkProcess::didGrantSandboxExtensionsToStorageProcessForBlobs(uint64_t requestID)
332 if (auto handler = m_sandboxExtensionForBlobsCompletionHandlers.take(requestID))
336 void NetworkProcess::writeBlobToFilePath(const WebCore::URL& url, const String& path, SandboxExtension::Handle&& handleForWriting, uint64_t requestID)
338 auto extension = SandboxExtension::create(WTFMove(handleForWriting));
340 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidWriteBlobToFilePath(false, requestID), 0);
344 extension->consume();
345 NetworkBlobRegistry::singleton().writeBlobToFilePath(url, path, [this, extension = WTFMove(extension), requestID] (bool success) {
347 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidWriteBlobToFilePath(success, requestID), 0);
351 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
352 void NetworkProcess::updatePrevalentDomainsToPartitionOrBlockCookies(PAL::SessionID sessionID, const Vector<String>& domainsToPartition, const Vector<String>& domainsToBlock, const Vector<String>& domainsToNeitherPartitionNorBlock, bool shouldClearFirst)
354 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
355 networkStorageSession->setPrevalentDomainsToPartitionOrBlockCookies(domainsToPartition, domainsToBlock, domainsToNeitherPartitionNorBlock, shouldClearFirst);
358 void NetworkProcess::hasStorageAccessForPrevalentDomains(PAL::SessionID sessionID, const String& resourceDomain, const String& firstPartyDomain, uint64_t frameID, uint64_t pageID, uint64_t contextId)
360 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
361 parentProcessConnection()->send(Messages::NetworkProcessProxy::StorageAccessRequestResult(networkStorageSession->isStorageAccessGranted(resourceDomain, firstPartyDomain, frameID, pageID), contextId), 0);
363 ASSERT_NOT_REACHED();
366 void NetworkProcess::updateStorageAccessForPrevalentDomains(PAL::SessionID sessionID, const String& resourceDomain, const String& firstPartyDomain, uint64_t frameID, uint64_t pageID, bool shouldGrantStorage, uint64_t contextId)
368 bool isStorageGranted = false;
369 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID)) {
370 networkStorageSession->setStorageAccessGranted(resourceDomain, firstPartyDomain, frameID, pageID, shouldGrantStorage);
371 ASSERT(networkStorageSession->isStorageAccessGranted(resourceDomain, firstPartyDomain, frameID, pageID) == shouldGrantStorage);
372 isStorageGranted = shouldGrantStorage;
374 ASSERT_NOT_REACHED();
376 parentProcessConnection()->send(Messages::NetworkProcessProxy::StorageAccessRequestResult(isStorageGranted, contextId), 0);
379 void NetworkProcess::removePrevalentDomains(PAL::SessionID sessionID, const Vector<String>& domains)
381 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
382 networkStorageSession->removePrevalentDomains(domains);
386 static void fetchDiskCacheEntries(PAL::SessionID sessionID, OptionSet<WebsiteDataFetchOption> fetchOptions, Function<void (Vector<WebsiteData::Entry>)>&& completionHandler)
388 if (auto* cache = NetworkProcess::singleton().cache()) {
389 HashMap<SecurityOriginData, uint64_t> originsAndSizes;
390 cache->traverse([fetchOptions, completionHandler = WTFMove(completionHandler), originsAndSizes = WTFMove(originsAndSizes)](auto* traversalEntry) mutable {
391 if (!traversalEntry) {
392 Vector<WebsiteData::Entry> entries;
394 for (auto& originAndSize : originsAndSizes)
395 entries.append(WebsiteData::Entry { originAndSize.key, WebsiteDataType::DiskCache, originAndSize.value });
397 RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler), entries = WTFMove(entries)] {
398 completionHandler(entries);
404 auto url = traversalEntry->entry.response().url();
405 auto result = originsAndSizes.add({url.protocol().toString(), url.host(), url.port()}, 0);
407 if (fetchOptions.contains(WebsiteDataFetchOption::ComputeSizes))
408 result.iterator->value += traversalEntry->entry.sourceStorageRecord().header.size() + traversalEntry->recordInfo.bodySize;
414 RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler)] {
415 completionHandler({ });
419 void NetworkProcess::fetchWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, OptionSet<WebsiteDataFetchOption> fetchOptions, uint64_t callbackID)
421 struct CallbackAggregator final : public RefCounted<CallbackAggregator> {
422 explicit CallbackAggregator(Function<void (WebsiteData)>&& completionHandler)
423 : m_completionHandler(WTFMove(completionHandler))
427 ~CallbackAggregator()
429 ASSERT(RunLoop::isMain());
431 RunLoop::main().dispatch([completionHandler = WTFMove(m_completionHandler), websiteData = WTFMove(m_websiteData)] {
432 completionHandler(websiteData);
436 Function<void (WebsiteData)> m_completionHandler;
437 WebsiteData m_websiteData;
440 auto callbackAggregator = adoptRef(*new CallbackAggregator([this, callbackID] (WebsiteData websiteData) {
441 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidFetchWebsiteData(callbackID, websiteData), 0);
444 if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
445 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
446 getHostnamesWithCookies(*networkStorageSession, callbackAggregator->m_websiteData.hostNamesWithCookies);
449 if (websiteDataTypes.contains(WebsiteDataType::Credentials)) {
450 if (NetworkStorageSession::storageSession(sessionID))
451 callbackAggregator->m_websiteData.originsWithCredentials = NetworkStorageSession::storageSession(sessionID)->credentialStorage().originsWithCredentials();
454 if (websiteDataTypes.contains(WebsiteDataType::DOMCache)) {
455 CacheStorage::Engine::fetchEntries(sessionID, fetchOptions.contains(WebsiteDataFetchOption::ComputeSizes), [callbackAggregator = callbackAggregator.copyRef()](auto entries) mutable {
456 callbackAggregator->m_websiteData.entries.appendVector(entries);
460 if (websiteDataTypes.contains(WebsiteDataType::DiskCache)) {
461 fetchDiskCacheEntries(sessionID, fetchOptions, [callbackAggregator = WTFMove(callbackAggregator)](auto entries) mutable {
462 callbackAggregator->m_websiteData.entries.appendVector(entries);
467 void NetworkProcess::deleteWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, WallTime modifiedSince, uint64_t callbackID)
470 if (websiteDataTypes.contains(WebsiteDataType::HSTSCache)) {
471 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
472 clearHSTSCache(*networkStorageSession, modifiedSince);
476 if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
477 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
478 deleteAllCookiesModifiedSince(*networkStorageSession, modifiedSince);
481 if (websiteDataTypes.contains(WebsiteDataType::Credentials)) {
482 if (NetworkStorageSession::storageSession(sessionID))
483 NetworkStorageSession::storageSession(sessionID)->credentialStorage().clearCredentials();
486 auto clearTasksHandler = WTF::CallbackAggregator::create([this, callbackID] {
487 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidDeleteWebsiteData(callbackID), 0);
490 if (websiteDataTypes.contains(WebsiteDataType::DOMCache))
491 CacheStorage::Engine::from(sessionID).clearAllCaches(clearTasksHandler);
493 if (websiteDataTypes.contains(WebsiteDataType::DiskCache) && !sessionID.isEphemeral())
494 clearDiskCache(modifiedSince, [clearTasksHandler = WTFMove(clearTasksHandler)] { });
497 static void clearDiskCacheEntries(const Vector<SecurityOriginData>& origins, Function<void ()>&& completionHandler)
499 if (auto* cache = NetworkProcess::singleton().cache()) {
500 HashSet<RefPtr<SecurityOrigin>> originsToDelete;
501 for (auto& origin : origins)
502 originsToDelete.add(origin.securityOrigin());
504 Vector<NetworkCache::Key> cacheKeysToDelete;
505 cache->traverse([cache, completionHandler = WTFMove(completionHandler), originsToDelete = WTFMove(originsToDelete), cacheKeysToDelete = WTFMove(cacheKeysToDelete)](auto* traversalEntry) mutable {
506 if (traversalEntry) {
507 if (originsToDelete.contains(SecurityOrigin::create(traversalEntry->entry.response().url())))
508 cacheKeysToDelete.append(traversalEntry->entry.key());
512 cache->remove(cacheKeysToDelete, WTFMove(completionHandler));
519 RunLoop::main().dispatch(WTFMove(completionHandler));
522 void NetworkProcess::deleteWebsiteDataForOrigins(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, const Vector<SecurityOriginData>& originDatas, const Vector<String>& cookieHostNames, uint64_t callbackID)
524 if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
525 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
526 deleteCookiesForHostnames(*networkStorageSession, cookieHostNames);
529 auto clearTasksHandler = WTF::CallbackAggregator::create([this, callbackID] {
530 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidDeleteWebsiteDataForOrigins(callbackID), 0);
533 if (websiteDataTypes.contains(WebsiteDataType::DOMCache)) {
534 for (auto& originData : originDatas) {
535 auto origin = originData.securityOrigin()->toString();
536 CacheStorage::Engine::from(sessionID).clearCachesForOrigin(origin, clearTasksHandler);
540 if (websiteDataTypes.contains(WebsiteDataType::DiskCache) && !sessionID.isEphemeral())
541 clearDiskCacheEntries(originDatas, [clearTasksHandler = WTFMove(clearTasksHandler)] { });
544 void NetworkProcess::downloadRequest(PAL::SessionID sessionID, DownloadID downloadID, const ResourceRequest& request, const String& suggestedFilename)
546 downloadManager().startDownload(nullptr, sessionID, downloadID, request, suggestedFilename);
549 void NetworkProcess::resumeDownload(PAL::SessionID sessionID, DownloadID downloadID, const IPC::DataReference& resumeData, const String& path, WebKit::SandboxExtension::Handle&& sandboxExtensionHandle)
551 downloadManager().resumeDownload(sessionID, downloadID, resumeData, path, WTFMove(sandboxExtensionHandle));
554 void NetworkProcess::cancelDownload(DownloadID downloadID)
556 downloadManager().cancelDownload(downloadID);
559 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
560 static uint64_t generateCanAuthenticateIdentifier()
562 static uint64_t lastLoaderID = 0;
563 return ++lastLoaderID;
566 void NetworkProcess::canAuthenticateAgainstProtectionSpace(NetworkResourceLoader& loader, const WebCore::ProtectionSpace& protectionSpace)
568 uint64_t loaderID = generateCanAuthenticateIdentifier();
569 m_waitingNetworkResourceLoaders.set(loaderID, loader);
570 parentProcessConnection()->send(Messages::NetworkProcessProxy::CanAuthenticateAgainstProtectionSpace(loaderID, loader.pageID(), loader.frameID(), protectionSpace), 0);
573 #if ENABLE(SERVER_PRECONNECT)
574 void NetworkProcess::canAuthenticateAgainstProtectionSpace(PreconnectTask& preconnectTask, const WebCore::ProtectionSpace& protectionSpace)
576 uint64_t loaderID = generateCanAuthenticateIdentifier();
577 m_waitingPreconnectTasks.set(loaderID, preconnectTask.createWeakPtr());
578 parentProcessConnection()->send(Messages::NetworkProcessProxy::CanAuthenticateAgainstProtectionSpace(loaderID, preconnectTask.pageID(), preconnectTask.frameID(), protectionSpace), 0);
582 void NetworkProcess::continueCanAuthenticateAgainstProtectionSpace(uint64_t loaderID, bool canAuthenticate)
584 if (auto resourceLoader = m_waitingNetworkResourceLoaders.take(loaderID)) {
585 resourceLoader.value()->continueCanAuthenticateAgainstProtectionSpace(canAuthenticate);
588 #if ENABLE(SERVER_PRECONNECT)
589 if (auto preconnectTask = m_waitingPreconnectTasks.take(loaderID)) {
590 preconnectTask->continueCanAuthenticateAgainstProtectionSpace(canAuthenticate);
598 #if USE(NETWORK_SESSION)
599 void NetworkProcess::continueWillSendRequest(DownloadID downloadID, WebCore::ResourceRequest&& request)
601 downloadManager().continueWillSendRequest(downloadID, WTFMove(request));
604 void NetworkProcess::pendingDownloadCanceled(DownloadID downloadID)
606 downloadProxyConnection()->send(Messages::DownloadProxy::DidCancel({ }), downloadID.downloadID());
609 void NetworkProcess::findPendingDownloadLocation(NetworkDataTask& networkDataTask, ResponseCompletionHandler&& completionHandler, const ResourceResponse& response)
611 uint64_t destinationID = networkDataTask.pendingDownloadID().downloadID();
612 downloadProxyConnection()->send(Messages::DownloadProxy::DidReceiveResponse(response), destinationID);
614 downloadManager().willDecidePendingDownloadDestination(networkDataTask, WTFMove(completionHandler));
616 // As per https://html.spec.whatwg.org/#as-a-download (step 2), the filename from the Content-Disposition header
617 // should override the suggested filename from the download attribute.
618 String suggestedFilename = response.isAttachmentWithFilename() ? response.suggestedFilename() : networkDataTask.suggestedFilename();
619 suggestedFilename = MIMETypeRegistry::appendFileExtensionIfNecessary(suggestedFilename, response.mimeType());
621 downloadProxyConnection()->send(Messages::DownloadProxy::DecideDestinationWithSuggestedFilenameAsync(networkDataTask.pendingDownloadID(), suggestedFilename), destinationID);
625 void NetworkProcess::continueDecidePendingDownloadDestination(DownloadID downloadID, String destination, SandboxExtension::Handle&& sandboxExtensionHandle, bool allowOverwrite)
627 if (destination.isEmpty())
628 downloadManager().cancelDownload(downloadID);
630 downloadManager().continueDecidePendingDownloadDestination(downloadID, destination, WTFMove(sandboxExtensionHandle), allowOverwrite);
633 void NetworkProcess::setCacheModel(uint32_t cm)
635 CacheModel cacheModel = static_cast<CacheModel>(cm);
637 if (m_hasSetCacheModel && (cacheModel == m_cacheModel))
640 m_hasSetCacheModel = true;
641 m_cacheModel = cacheModel;
643 unsigned urlCacheMemoryCapacity = 0;
644 uint64_t urlCacheDiskCapacity = 0;
645 uint64_t diskFreeSize = 0;
646 if (WebCore::FileSystem::getVolumeFreeSpace(m_diskCacheDirectory, diskFreeSize)) {
647 // As a fudge factor, use 1000 instead of 1024, in case the reported byte
648 // count doesn't align exactly to a megabyte boundary.
649 diskFreeSize /= KB * 1000;
650 calculateURLCacheSizes(cacheModel, diskFreeSize, urlCacheMemoryCapacity, urlCacheDiskCapacity);
653 if (m_diskCacheSizeOverride >= 0)
654 urlCacheDiskCapacity = m_diskCacheSizeOverride;
657 m_cache->setCapacity(urlCacheDiskCapacity);
661 platformSetURLCacheSize(urlCacheMemoryCapacity, urlCacheDiskCapacity);
664 void NetworkProcess::setCanHandleHTTPSServerTrustEvaluation(bool value)
666 m_canHandleHTTPSServerTrustEvaluation = value;
669 void NetworkProcess::getNetworkProcessStatistics(uint64_t callbackID)
673 auto& networkProcess = NetworkProcess::singleton();
674 data.statisticsNumbers.set("DownloadsActiveCount", networkProcess.downloadManager().activeDownloadCount());
675 data.statisticsNumbers.set("OutstandingAuthenticationChallengesCount", networkProcess.authenticationManager().outstandingAuthenticationChallengeCount());
677 parentProcessConnection()->send(Messages::WebProcessPool::DidGetStatistics(data, callbackID), 0);
680 void NetworkProcess::setAllowsAnySSLCertificateForWebSocket(bool allows)
682 DeprecatedGlobalSettings::setAllowsAnySSLCertificate(allows);
685 void NetworkProcess::logDiagnosticMessage(uint64_t webPageID, const String& message, const String& description, ShouldSample shouldSample)
687 if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
690 parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessage(webPageID, message, description, ShouldSample::No), 0);
693 void NetworkProcess::logDiagnosticMessageWithResult(uint64_t webPageID, const String& message, const String& description, DiagnosticLoggingResultType result, ShouldSample shouldSample)
695 if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
698 parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessageWithResult(webPageID, message, description, result, ShouldSample::No), 0);
701 void NetworkProcess::logDiagnosticMessageWithValue(uint64_t webPageID, const String& message, const String& description, double value, unsigned significantFigures, ShouldSample shouldSample)
703 if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
706 parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessageWithValue(webPageID, message, description, value, significantFigures, ShouldSample::No), 0);
709 void NetworkProcess::terminate()
711 #if ENABLE(NETWORK_CAPTURE)
712 NetworkCapture::Manager::singleton().terminate();
716 ChildProcess::terminate();
719 // FIXME: We can remove this one by adapting RefCounter.
720 class TaskCounter : public RefCounted<TaskCounter> {
722 explicit TaskCounter(Function<void()>&& callback) : m_callback(WTFMove(callback)) { }
723 ~TaskCounter() { m_callback(); };
726 Function<void()> m_callback;
729 void NetworkProcess::actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend shouldAcknowledgeWhenReadyToSuspend)
731 lowMemoryHandler(Critical::Yes);
733 RefPtr<TaskCounter> delayedTaskCounter;
734 if (shouldAcknowledgeWhenReadyToSuspend == ShouldAcknowledgeWhenReadyToSuspend::Yes) {
735 delayedTaskCounter = adoptRef(new TaskCounter([this] {
736 RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::notifyProcessReadyToSuspend() Sending ProcessReadyToSuspend IPC message", this);
737 if (parentProcessConnection())
738 parentProcessConnection()->send(Messages::NetworkProcessProxy::ProcessReadyToSuspend(), 0);
742 for (auto& connection : m_webProcessConnections)
743 connection->cleanupForSuspension([delayedTaskCounter] { });
746 void NetworkProcess::processWillSuspendImminently(bool& handled)
748 actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend::No);
752 void NetworkProcess::prepareToSuspend()
754 RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::prepareToSuspend()", this);
755 actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend::Yes);
758 void NetworkProcess::cancelPrepareToSuspend()
760 // Although it is tempting to send a NetworkProcessProxy::DidCancelProcessSuspension message from here
761 // we do not because prepareToSuspend() already replied with a NetworkProcessProxy::ProcessReadyToSuspend
762 // message. And NetworkProcessProxy expects to receive either a NetworkProcessProxy::ProcessReadyToSuspend-
763 // or NetworkProcessProxy::DidCancelProcessSuspension- message, but not both.
764 RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::cancelPrepareToSuspend()", this);
765 for (auto& connection : m_webProcessConnections)
766 connection->endSuspension();
769 void NetworkProcess::processDidResume()
771 RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::processDidResume()", this);
772 for (auto& connection : m_webProcessConnections)
773 connection->endSuspension();
776 void NetworkProcess::prefetchDNS(const String& hostname)
778 WebCore::prefetchDNS(hostname);
781 String NetworkProcess::cacheStorageDirectory(PAL::SessionID sessionID) const
783 if (sessionID.isEphemeral())
786 if (sessionID == PAL::SessionID::defaultSessionID())
787 return m_cacheStorageDirectory;
789 auto* session = NetworkStorageSession::storageSession(sessionID);
793 return session->cacheStorageDirectory();
796 void NetworkProcess::preconnectTo(const WebCore::URL& url, WebCore::StoredCredentialsPolicy storedCredentialsPolicy)
798 #if ENABLE(SERVER_PRECONNECT)
799 NetworkLoadParameters parameters;
800 parameters.request = ResourceRequest { url };
801 parameters.sessionID = PAL::SessionID::defaultSessionID();
802 parameters.storedCredentialsPolicy = storedCredentialsPolicy;
803 parameters.shouldPreconnectOnly = PreconnectOnly::Yes;
805 new PreconnectTask(WTFMove(parameters));
808 UNUSED_PARAM(storedCredentialsPolicy);
812 uint64_t NetworkProcess::cacheStoragePerOriginQuota() const
814 return m_cacheStoragePerOriginQuota;
818 void NetworkProcess::initializeProcess(const ChildProcessInitializationParameters&)
822 void NetworkProcess::initializeProcessName(const ChildProcessInitializationParameters&)
826 void NetworkProcess::initializeSandbox(const ChildProcessInitializationParameters&, SandboxInitializationParameters&)
830 void NetworkProcess::syncAllCookies()
836 } // namespace WebKit