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 "NetworkConnectionToWebProcess.h"
40 #include "NetworkProcessCreationParameters.h"
41 #include "NetworkProcessPlatformStrategies.h"
42 #include "NetworkProcessProxyMessages.h"
43 #include "NetworkResourceLoader.h"
44 #include "NetworkSession.h"
45 #include "PreconnectTask.h"
46 #include "RemoteNetworkingContext.h"
47 #include "SessionTracker.h"
48 #include "StatisticsData.h"
49 #include "WebCookieManager.h"
50 #include "WebCoreArgumentCoders.h"
51 #include "WebPageProxyMessages.h"
52 #include "WebProcessPoolMessages.h"
53 #include "WebsiteData.h"
54 #include "WebsiteDataFetchOption.h"
55 #include "WebsiteDataStore.h"
56 #include "WebsiteDataStoreParameters.h"
57 #include "WebsiteDataType.h"
58 #include <WebCore/DNS.h>
59 #include <WebCore/DeprecatedGlobalSettings.h>
60 #include <WebCore/DiagnosticLoggingClient.h>
61 #include <WebCore/LogInitialization.h>
62 #include <WebCore/MIMETypeRegistry.h>
63 #include <WebCore/NetworkStorageSession.h>
64 #include <WebCore/PlatformCookieJar.h>
65 #include <WebCore/ResourceRequest.h>
66 #include <WebCore/RuntimeApplicationChecks.h>
67 #include <WebCore/SecurityOriginData.h>
68 #include <WebCore/SecurityOriginHash.h>
69 #include <WebCore/Settings.h>
70 #include <WebCore/URLParser.h>
71 #include <pal/SessionID.h>
72 #include <wtf/CallbackAggregator.h>
73 #include <wtf/OptionSet.h>
74 #include <wtf/RunLoop.h>
75 #include <wtf/text/AtomicString.h>
76 #include <wtf/text/CString.h>
78 #if ENABLE(SEC_ITEM_SHIM)
79 #include "SecItemShim.h"
82 #include "NetworkCache.h"
83 #include "NetworkCacheCoders.h"
85 #if ENABLE(NETWORK_CAPTURE)
86 #include "NetworkCaptureManager.h"
90 #include "NetworkSessionCocoa.h"
93 using namespace WebCore;
97 NetworkProcess& NetworkProcess::singleton()
99 static NeverDestroyed<NetworkProcess> networkProcess;
100 return networkProcess;
103 NetworkProcess::NetworkProcess()
104 : m_hasSetCacheModel(false)
105 , m_cacheModel(CacheModelDocumentViewer)
106 , m_diskCacheIsDisabledForTesting(false)
107 , m_canHandleHTTPSServerTrustEvaluation(true)
109 , m_clearCacheDispatchGroup(0)
112 , m_webSQLiteDatabaseTracker(*this)
115 NetworkProcessPlatformStrategies::initialize();
117 addSupplement<AuthenticationManager>();
118 addSupplement<WebCookieManager>();
119 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
120 addSupplement<LegacyCustomProtocolManager>();
124 NetworkProcess::~NetworkProcess()
128 AuthenticationManager& NetworkProcess::authenticationManager()
130 return *supplement<AuthenticationManager>();
133 DownloadManager& NetworkProcess::downloadManager()
135 static NeverDestroyed<DownloadManager> downloadManager(*this);
136 return downloadManager;
139 void NetworkProcess::removeNetworkConnectionToWebProcess(NetworkConnectionToWebProcess* connection)
141 size_t vectorIndex = m_webProcessConnections.find(connection);
142 ASSERT(vectorIndex != notFound);
144 m_webProcessConnections.remove(vectorIndex);
147 bool NetworkProcess::shouldTerminate()
149 // Network process keeps session cookies and credentials, so it should never terminate (as long as UI process connection is alive).
153 void NetworkProcess::didReceiveMessage(IPC::Connection& connection, IPC::Decoder& decoder)
155 if (messageReceiverMap().dispatchMessage(connection, decoder))
158 if (decoder.messageReceiverName() == Messages::ChildProcess::messageReceiverName()) {
159 ChildProcess::didReceiveMessage(connection, decoder);
163 didReceiveNetworkProcessMessage(connection, decoder);
166 void NetworkProcess::didReceiveSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
168 if (messageReceiverMap().dispatchSyncMessage(connection, decoder, replyEncoder))
171 didReceiveSyncNetworkProcessMessage(connection, decoder, replyEncoder);
174 void NetworkProcess::didClose(IPC::Connection&)
176 // The UIProcess just exited.
180 void NetworkProcess::didCreateDownload()
182 disableTermination();
185 void NetworkProcess::didDestroyDownload()
190 IPC::Connection* NetworkProcess::downloadProxyConnection()
192 return parentProcessConnection();
195 AuthenticationManager& NetworkProcess::downloadsAuthenticationManager()
197 return authenticationManager();
200 void NetworkProcess::lowMemoryHandler(Critical critical)
202 if (m_suppressMemoryPressureHandler)
205 WTF::releaseFastMallocFreeMemory();
208 void NetworkProcess::initializeNetworkProcess(NetworkProcessCreationParameters&& parameters)
210 WebCore::setPresentingApplicationPID(parameters.presentingApplicationPID);
211 platformInitializeNetworkProcess(parameters);
213 WTF::Thread::setCurrentThreadIsUserInitiated();
214 AtomicString::init();
216 m_suppressMemoryPressureHandler = parameters.shouldSuppressMemoryPressureHandler;
217 m_loadThrottleLatency = parameters.loadThrottleLatency;
218 if (!m_suppressMemoryPressureHandler) {
219 auto& memoryPressureHandler = MemoryPressureHandler::singleton();
221 if (parameters.memoryPressureMonitorHandle.fileDescriptor() != -1)
222 memoryPressureHandler.setMemoryPressureMonitorHandle(parameters.memoryPressureMonitorHandle.releaseFileDescriptor());
224 memoryPressureHandler.setLowMemoryHandler([this] (Critical critical, Synchronous) {
225 lowMemoryHandler(critical);
227 memoryPressureHandler.install();
230 #if ENABLE(NETWORK_CAPTURE)
231 NetworkCapture::Manager::singleton().initialize(
232 parameters.recordReplayMode,
233 parameters.recordReplayCacheLocation);
236 m_diskCacheIsDisabledForTesting = parameters.shouldUseTestingNetworkSession;
238 m_diskCacheSizeOverride = parameters.diskCacheSizeOverride;
239 setCacheModel(static_cast<uint32_t>(parameters.cacheModel));
241 setCanHandleHTTPSServerTrustEvaluation(parameters.canHandleHTTPSServerTrustEvaluation);
243 // FIXME: instead of handling this here, a message should be sent later (scales to multiple sessions)
244 if (parameters.privateBrowsingEnabled)
245 RemoteNetworkingContext::ensureWebsiteDataStoreSession(WebsiteDataStoreParameters::legacyPrivateSessionParameters());
247 if (parameters.shouldUseTestingNetworkSession)
248 NetworkStorageSession::switchToNewTestingSession();
250 #if HAVE(CFNETWORK_STORAGE_PARTITIONING) && !RELEASE_LOG_DISABLED
251 m_logCookieInformation = parameters.logCookieInformation;
254 #if USE(NETWORK_SESSION)
255 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
256 parameters.defaultSessionParameters.legacyCustomProtocolManager = supplement<LegacyCustomProtocolManager>();
258 SessionTracker::setSession(PAL::SessionID::defaultSessionID(), NetworkSession::create(WTFMove(parameters.defaultSessionParameters)));
261 for (auto& supplement : m_supplements.values())
262 supplement->initialize(parameters);
265 void NetworkProcess::initializeConnection(IPC::Connection* connection)
267 ChildProcess::initializeConnection(connection);
269 for (auto& supplement : m_supplements.values())
270 supplement->initializeConnection(connection);
273 void NetworkProcess::createNetworkConnectionToWebProcess()
275 #if USE(UNIX_DOMAIN_SOCKETS)
276 IPC::Connection::SocketPair socketPair = IPC::Connection::createPlatformConnection();
278 auto connection = NetworkConnectionToWebProcess::create(socketPair.server);
279 m_webProcessConnections.append(WTFMove(connection));
281 IPC::Attachment clientSocket(socketPair.client);
282 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidCreateNetworkConnectionToWebProcess(clientSocket), 0);
284 // Create the listening port.
285 mach_port_t listeningPort;
286 mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &listeningPort);
288 // Create a listening connection.
289 auto connection = NetworkConnectionToWebProcess::create(IPC::Connection::Identifier(listeningPort));
290 m_webProcessConnections.append(WTFMove(connection));
292 IPC::Attachment clientPort(listeningPort, MACH_MSG_TYPE_MAKE_SEND);
293 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidCreateNetworkConnectionToWebProcess(clientPort), 0);
299 void NetworkProcess::clearCachedCredentials()
301 NetworkStorageSession::defaultStorageSession().credentialStorage().clearCredentials();
302 #if USE(NETWORK_SESSION)
303 if (auto* networkSession = SessionTracker::networkSession(PAL::SessionID::defaultSessionID()))
304 networkSession->clearCredentials();
306 ASSERT_NOT_REACHED();
310 void NetworkProcess::addWebsiteDataStore(WebsiteDataStoreParameters&& parameters)
312 RemoteNetworkingContext::ensureWebsiteDataStoreSession(WTFMove(parameters));
315 void NetworkProcess::destroySession(PAL::SessionID sessionID)
317 SessionTracker::destroySession(sessionID);
320 void NetworkProcess::grantSandboxExtensionsToStorageProcessForBlobs(const Vector<String>& filenames, Function<void ()>&& completionHandler)
322 static uint64_t lastRequestID;
324 uint64_t requestID = ++lastRequestID;
325 m_sandboxExtensionForBlobsCompletionHandlers.set(requestID, WTFMove(completionHandler));
326 parentProcessConnection()->send(Messages::NetworkProcessProxy::GrantSandboxExtensionsToStorageProcessForBlobs(requestID, filenames), 0);
329 void NetworkProcess::didGrantSandboxExtensionsToStorageProcessForBlobs(uint64_t requestID)
331 if (auto handler = m_sandboxExtensionForBlobsCompletionHandlers.take(requestID))
335 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
336 void NetworkProcess::updatePrevalentDomainsToPartitionOrBlockCookies(PAL::SessionID sessionID, const Vector<String>& domainsToPartition, const Vector<String>& domainsToBlock, const Vector<String>& domainsToNeitherPartitionNorBlock, bool shouldClearFirst)
338 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
339 networkStorageSession->setPrevalentDomainsToPartitionOrBlockCookies(domainsToPartition, domainsToBlock, domainsToNeitherPartitionNorBlock, shouldClearFirst);
342 void NetworkProcess::hasStorageAccessForPrevalentDomains(PAL::SessionID sessionID, const String& resourceDomain, const String& firstPartyDomain, uint64_t frameID, uint64_t pageID, uint64_t contextId)
344 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
345 parentProcessConnection()->send(Messages::NetworkProcessProxy::StorageAccessRequestResult(networkStorageSession->isStorageAccessGranted(resourceDomain, firstPartyDomain, frameID, pageID), contextId), 0);
347 ASSERT_NOT_REACHED();
350 void NetworkProcess::updateStorageAccessForPrevalentDomains(PAL::SessionID sessionID, const String& resourceDomain, const String& firstPartyDomain, uint64_t frameID, uint64_t pageID, bool shouldGrantStorage, uint64_t contextId)
352 bool isStorageGranted = false;
353 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID)) {
354 networkStorageSession->setStorageAccessGranted(resourceDomain, firstPartyDomain, frameID, pageID, shouldGrantStorage);
355 ASSERT(networkStorageSession->isStorageAccessGranted(resourceDomain, firstPartyDomain, frameID, pageID) == shouldGrantStorage);
356 isStorageGranted = shouldGrantStorage;
358 ASSERT_NOT_REACHED();
360 parentProcessConnection()->send(Messages::NetworkProcessProxy::StorageAccessRequestResult(isStorageGranted, contextId), 0);
363 void NetworkProcess::removePrevalentDomains(PAL::SessionID sessionID, const Vector<String>& domains)
365 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
366 networkStorageSession->removePrevalentDomains(domains);
370 static void fetchDiskCacheEntries(PAL::SessionID sessionID, OptionSet<WebsiteDataFetchOption> fetchOptions, Function<void (Vector<WebsiteData::Entry>)>&& completionHandler)
372 if (auto* cache = NetworkProcess::singleton().cache()) {
373 HashMap<SecurityOriginData, uint64_t> originsAndSizes;
374 cache->traverse([fetchOptions, completionHandler = WTFMove(completionHandler), originsAndSizes = WTFMove(originsAndSizes)](auto* traversalEntry) mutable {
375 if (!traversalEntry) {
376 Vector<WebsiteData::Entry> entries;
378 for (auto& originAndSize : originsAndSizes)
379 entries.append(WebsiteData::Entry { originAndSize.key, WebsiteDataType::DiskCache, originAndSize.value });
381 RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler), entries = WTFMove(entries)] {
382 completionHandler(entries);
388 auto url = traversalEntry->entry.response().url();
389 auto result = originsAndSizes.add({url.protocol().toString(), url.host(), url.port()}, 0);
391 if (fetchOptions.contains(WebsiteDataFetchOption::ComputeSizes))
392 result.iterator->value += traversalEntry->entry.sourceStorageRecord().header.size() + traversalEntry->recordInfo.bodySize;
398 RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler)] {
399 completionHandler({ });
403 void NetworkProcess::fetchWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, OptionSet<WebsiteDataFetchOption> fetchOptions, uint64_t callbackID)
405 struct CallbackAggregator final : public RefCounted<CallbackAggregator> {
406 explicit CallbackAggregator(Function<void (WebsiteData)>&& completionHandler)
407 : m_completionHandler(WTFMove(completionHandler))
411 ~CallbackAggregator()
413 ASSERT(RunLoop::isMain());
415 RunLoop::main().dispatch([completionHandler = WTFMove(m_completionHandler), websiteData = WTFMove(m_websiteData)] {
416 completionHandler(websiteData);
420 Function<void (WebsiteData)> m_completionHandler;
421 WebsiteData m_websiteData;
424 auto callbackAggregator = adoptRef(*new CallbackAggregator([this, callbackID] (WebsiteData websiteData) {
425 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidFetchWebsiteData(callbackID, websiteData), 0);
428 if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
429 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
430 getHostnamesWithCookies(*networkStorageSession, callbackAggregator->m_websiteData.hostNamesWithCookies);
433 if (websiteDataTypes.contains(WebsiteDataType::Credentials)) {
434 if (NetworkStorageSession::storageSession(sessionID))
435 callbackAggregator->m_websiteData.originsWithCredentials = NetworkStorageSession::storageSession(sessionID)->credentialStorage().originsWithCredentials();
438 if (websiteDataTypes.contains(WebsiteDataType::DOMCache)) {
439 CacheStorage::Engine::fetchEntries(sessionID, fetchOptions.contains(WebsiteDataFetchOption::ComputeSizes), [callbackAggregator = callbackAggregator.copyRef()](auto entries) mutable {
440 callbackAggregator->m_websiteData.entries.appendVector(entries);
444 if (websiteDataTypes.contains(WebsiteDataType::DiskCache)) {
445 fetchDiskCacheEntries(sessionID, fetchOptions, [callbackAggregator = WTFMove(callbackAggregator)](auto entries) mutable {
446 callbackAggregator->m_websiteData.entries.appendVector(entries);
451 void NetworkProcess::deleteWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, std::chrono::system_clock::time_point modifiedSince, uint64_t callbackID)
454 if (websiteDataTypes.contains(WebsiteDataType::HSTSCache)) {
455 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
456 clearHSTSCache(*networkStorageSession, modifiedSince);
460 if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
461 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
462 deleteAllCookiesModifiedSince(*networkStorageSession, modifiedSince);
465 if (websiteDataTypes.contains(WebsiteDataType::Credentials)) {
466 if (NetworkStorageSession::storageSession(sessionID))
467 NetworkStorageSession::storageSession(sessionID)->credentialStorage().clearCredentials();
470 auto clearTasksHandler = WTF::CallbackAggregator::create([this, callbackID] {
471 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidDeleteWebsiteData(callbackID), 0);
474 if (websiteDataTypes.contains(WebsiteDataType::DOMCache))
475 CacheStorage::Engine::from(sessionID).clearAllCaches(clearTasksHandler);
477 if (websiteDataTypes.contains(WebsiteDataType::DiskCache) && !sessionID.isEphemeral())
478 clearDiskCache(modifiedSince, [clearTasksHandler = WTFMove(clearTasksHandler)] { });
481 static void clearDiskCacheEntries(const Vector<SecurityOriginData>& origins, Function<void ()>&& completionHandler)
483 if (auto* cache = NetworkProcess::singleton().cache()) {
484 HashSet<RefPtr<SecurityOrigin>> originsToDelete;
485 for (auto& origin : origins)
486 originsToDelete.add(origin.securityOrigin());
488 Vector<NetworkCache::Key> cacheKeysToDelete;
489 cache->traverse([cache, completionHandler = WTFMove(completionHandler), originsToDelete = WTFMove(originsToDelete), cacheKeysToDelete = WTFMove(cacheKeysToDelete)](auto* traversalEntry) mutable {
490 if (traversalEntry) {
491 if (originsToDelete.contains(SecurityOrigin::create(traversalEntry->entry.response().url())))
492 cacheKeysToDelete.append(traversalEntry->entry.key());
496 cache->remove(cacheKeysToDelete, WTFMove(completionHandler));
503 RunLoop::main().dispatch(WTFMove(completionHandler));
506 void NetworkProcess::deleteWebsiteDataForOrigins(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, const Vector<SecurityOriginData>& originDatas, const Vector<String>& cookieHostNames, uint64_t callbackID)
508 if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
509 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
510 deleteCookiesForHostnames(*networkStorageSession, cookieHostNames);
513 auto clearTasksHandler = WTF::CallbackAggregator::create([this, callbackID] {
514 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidDeleteWebsiteDataForOrigins(callbackID), 0);
517 if (websiteDataTypes.contains(WebsiteDataType::DOMCache)) {
518 for (auto& originData : originDatas) {
519 auto origin = originData.securityOrigin()->toString();
520 CacheStorage::Engine::from(sessionID).clearCachesForOrigin(origin, clearTasksHandler);
524 if (websiteDataTypes.contains(WebsiteDataType::DiskCache) && !sessionID.isEphemeral())
525 clearDiskCacheEntries(originDatas, [clearTasksHandler = WTFMove(clearTasksHandler)] { });
528 void NetworkProcess::downloadRequest(PAL::SessionID sessionID, DownloadID downloadID, const ResourceRequest& request, const String& suggestedFilename)
530 downloadManager().startDownload(nullptr, sessionID, downloadID, request, suggestedFilename);
533 void NetworkProcess::resumeDownload(PAL::SessionID sessionID, DownloadID downloadID, const IPC::DataReference& resumeData, const String& path, WebKit::SandboxExtension::Handle&& sandboxExtensionHandle)
535 downloadManager().resumeDownload(sessionID, downloadID, resumeData, path, WTFMove(sandboxExtensionHandle));
538 void NetworkProcess::cancelDownload(DownloadID downloadID)
540 downloadManager().cancelDownload(downloadID);
543 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
544 static uint64_t generateCanAuthenticateIdentifier()
546 static uint64_t lastLoaderID = 0;
547 return ++lastLoaderID;
550 void NetworkProcess::canAuthenticateAgainstProtectionSpace(NetworkResourceLoader& loader, const WebCore::ProtectionSpace& protectionSpace)
552 uint64_t loaderID = generateCanAuthenticateIdentifier();
553 m_waitingNetworkResourceLoaders.set(loaderID, loader);
554 parentProcessConnection()->send(Messages::NetworkProcessProxy::CanAuthenticateAgainstProtectionSpace(loaderID, loader.pageID(), loader.frameID(), protectionSpace), 0);
557 #if ENABLE(SERVER_PRECONNECT)
558 void NetworkProcess::canAuthenticateAgainstProtectionSpace(PreconnectTask& preconnectTask, const WebCore::ProtectionSpace& protectionSpace)
560 uint64_t loaderID = generateCanAuthenticateIdentifier();
561 m_waitingPreconnectTasks.set(loaderID, preconnectTask.createWeakPtr());
562 parentProcessConnection()->send(Messages::NetworkProcessProxy::CanAuthenticateAgainstProtectionSpace(loaderID, preconnectTask.pageID(), preconnectTask.frameID(), protectionSpace), 0);
566 void NetworkProcess::continueCanAuthenticateAgainstProtectionSpace(uint64_t loaderID, bool canAuthenticate)
568 if (auto resourceLoader = m_waitingNetworkResourceLoaders.take(loaderID)) {
569 resourceLoader.value()->continueCanAuthenticateAgainstProtectionSpace(canAuthenticate);
572 #if ENABLE(SERVER_PRECONNECT)
573 if (auto preconnectTask = m_waitingPreconnectTasks.take(loaderID)) {
574 preconnectTask->continueCanAuthenticateAgainstProtectionSpace(canAuthenticate);
582 #if USE(NETWORK_SESSION)
583 void NetworkProcess::continueWillSendRequest(DownloadID downloadID, WebCore::ResourceRequest&& request)
585 downloadManager().continueWillSendRequest(downloadID, WTFMove(request));
588 void NetworkProcess::pendingDownloadCanceled(DownloadID downloadID)
590 downloadProxyConnection()->send(Messages::DownloadProxy::DidCancel({ }), downloadID.downloadID());
593 void NetworkProcess::findPendingDownloadLocation(NetworkDataTask& networkDataTask, ResponseCompletionHandler&& completionHandler, const ResourceResponse& response)
595 uint64_t destinationID = networkDataTask.pendingDownloadID().downloadID();
596 downloadProxyConnection()->send(Messages::DownloadProxy::DidReceiveResponse(response), destinationID);
598 downloadManager().willDecidePendingDownloadDestination(networkDataTask, WTFMove(completionHandler));
600 // As per https://html.spec.whatwg.org/#as-a-download (step 2), the filename from the Content-Disposition header
601 // should override the suggested filename from the download attribute.
602 String suggestedFilename = response.isAttachmentWithFilename() ? response.suggestedFilename() : networkDataTask.suggestedFilename();
603 suggestedFilename = MIMETypeRegistry::appendFileExtensionIfNecessary(suggestedFilename, response.mimeType());
605 downloadProxyConnection()->send(Messages::DownloadProxy::DecideDestinationWithSuggestedFilenameAsync(networkDataTask.pendingDownloadID(), suggestedFilename), destinationID);
609 void NetworkProcess::continueDecidePendingDownloadDestination(DownloadID downloadID, String destination, SandboxExtension::Handle&& sandboxExtensionHandle, bool allowOverwrite)
611 if (destination.isEmpty())
612 downloadManager().cancelDownload(downloadID);
614 downloadManager().continueDecidePendingDownloadDestination(downloadID, destination, WTFMove(sandboxExtensionHandle), allowOverwrite);
617 void NetworkProcess::setCacheModel(uint32_t cm)
619 CacheModel cacheModel = static_cast<CacheModel>(cm);
621 if (m_hasSetCacheModel && (cacheModel == m_cacheModel))
624 m_hasSetCacheModel = true;
625 m_cacheModel = cacheModel;
627 unsigned urlCacheMemoryCapacity = 0;
628 uint64_t urlCacheDiskCapacity = 0;
629 uint64_t diskFreeSize = 0;
630 if (WebCore::FileSystem::getVolumeFreeSpace(m_diskCacheDirectory, diskFreeSize)) {
631 // As a fudge factor, use 1000 instead of 1024, in case the reported byte
632 // count doesn't align exactly to a megabyte boundary.
633 diskFreeSize /= KB * 1000;
634 calculateURLCacheSizes(cacheModel, diskFreeSize, urlCacheMemoryCapacity, urlCacheDiskCapacity);
637 if (m_diskCacheSizeOverride >= 0)
638 urlCacheDiskCapacity = m_diskCacheSizeOverride;
641 m_cache->setCapacity(urlCacheDiskCapacity);
645 platformSetURLCacheSize(urlCacheMemoryCapacity, urlCacheDiskCapacity);
648 void NetworkProcess::setCanHandleHTTPSServerTrustEvaluation(bool value)
650 m_canHandleHTTPSServerTrustEvaluation = value;
653 void NetworkProcess::getNetworkProcessStatistics(uint64_t callbackID)
657 auto& networkProcess = NetworkProcess::singleton();
658 data.statisticsNumbers.set("DownloadsActiveCount", networkProcess.downloadManager().activeDownloadCount());
659 data.statisticsNumbers.set("OutstandingAuthenticationChallengesCount", networkProcess.authenticationManager().outstandingAuthenticationChallengeCount());
661 parentProcessConnection()->send(Messages::WebProcessPool::DidGetStatistics(data, callbackID), 0);
664 void NetworkProcess::setAllowsAnySSLCertificateForWebSocket(bool allows)
666 DeprecatedGlobalSettings::setAllowsAnySSLCertificate(allows);
669 void NetworkProcess::logDiagnosticMessage(uint64_t webPageID, const String& message, const String& description, ShouldSample shouldSample)
671 if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
674 parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessage(webPageID, message, description, ShouldSample::No), 0);
677 void NetworkProcess::logDiagnosticMessageWithResult(uint64_t webPageID, const String& message, const String& description, DiagnosticLoggingResultType result, ShouldSample shouldSample)
679 if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
682 parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessageWithResult(webPageID, message, description, result, ShouldSample::No), 0);
685 void NetworkProcess::logDiagnosticMessageWithValue(uint64_t webPageID, const String& message, const String& description, double value, unsigned significantFigures, ShouldSample shouldSample)
687 if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
690 parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessageWithValue(webPageID, message, description, value, significantFigures, ShouldSample::No), 0);
693 void NetworkProcess::terminate()
695 #if ENABLE(NETWORK_CAPTURE)
696 NetworkCapture::Manager::singleton().terminate();
700 ChildProcess::terminate();
703 // FIXME: We can remove this one by adapting RefCounter.
704 class TaskCounter : public RefCounted<TaskCounter> {
706 explicit TaskCounter(Function<void()>&& callback) : m_callback(WTFMove(callback)) { }
707 ~TaskCounter() { m_callback(); };
710 Function<void()> m_callback;
713 void NetworkProcess::actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend shouldAcknowledgeWhenReadyToSuspend)
715 lowMemoryHandler(Critical::Yes);
717 RefPtr<TaskCounter> delayedTaskCounter;
718 if (shouldAcknowledgeWhenReadyToSuspend == ShouldAcknowledgeWhenReadyToSuspend::Yes) {
719 delayedTaskCounter = adoptRef(new TaskCounter([this] {
720 RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::notifyProcessReadyToSuspend() Sending ProcessReadyToSuspend IPC message", this);
721 if (parentProcessConnection())
722 parentProcessConnection()->send(Messages::NetworkProcessProxy::ProcessReadyToSuspend(), 0);
726 for (auto& connection : m_webProcessConnections)
727 connection->cleanupForSuspension([delayedTaskCounter] { });
730 void NetworkProcess::processWillSuspendImminently(bool& handled)
732 actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend::No);
736 void NetworkProcess::prepareToSuspend()
738 RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::prepareToSuspend()", this);
739 actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend::Yes);
742 void NetworkProcess::cancelPrepareToSuspend()
744 // Although it is tempting to send a NetworkProcessProxy::DidCancelProcessSuspension message from here
745 // we do not because prepareToSuspend() already replied with a NetworkProcessProxy::ProcessReadyToSuspend
746 // message. And NetworkProcessProxy expects to receive either a NetworkProcessProxy::ProcessReadyToSuspend-
747 // or NetworkProcessProxy::DidCancelProcessSuspension- message, but not both.
748 RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::cancelPrepareToSuspend()", this);
749 for (auto& connection : m_webProcessConnections)
750 connection->endSuspension();
753 void NetworkProcess::processDidResume()
755 RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::processDidResume()", this);
756 for (auto& connection : m_webProcessConnections)
757 connection->endSuspension();
760 void NetworkProcess::prefetchDNS(const String& hostname)
762 WebCore::prefetchDNS(hostname);
765 String NetworkProcess::cacheStorageDirectory(PAL::SessionID sessionID) const
767 if (sessionID.isEphemeral())
770 if (sessionID == PAL::SessionID::defaultSessionID())
771 return m_cacheStorageDirectory;
773 auto* session = NetworkStorageSession::storageSession(sessionID);
777 return session->cacheStorageDirectory();
780 void NetworkProcess::preconnectTo(const WebCore::URL& url, WebCore::StoredCredentialsPolicy storedCredentialsPolicy)
782 #if ENABLE(SERVER_PRECONNECT)
783 NetworkLoadParameters parameters;
784 parameters.request = ResourceRequest { url };
785 parameters.sessionID = PAL::SessionID::defaultSessionID();
786 parameters.storedCredentialsPolicy = storedCredentialsPolicy;
787 parameters.shouldPreconnectOnly = PreconnectOnly::Yes;
789 new PreconnectTask(WTFMove(parameters));
792 UNUSED_PARAM(storedCredentialsPolicy);
796 uint64_t NetworkProcess::cacheStoragePerOriginQuota() const
798 return m_cacheStoragePerOriginQuota;
802 void NetworkProcess::initializeProcess(const ChildProcessInitializationParameters&)
806 void NetworkProcess::initializeProcessName(const ChildProcessInitializationParameters&)
810 void NetworkProcess::initializeSandbox(const ChildProcessInitializationParameters&, SandboxInitializationParameters&)
814 void NetworkProcess::syncAllCookies()
820 } // namespace WebKit