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 USE(NETWORK_SESSION)
251 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
252 parameters.defaultSessionParameters.legacyCustomProtocolManager = supplement<LegacyCustomProtocolManager>();
254 SessionTracker::setSession(PAL::SessionID::defaultSessionID(), NetworkSession::create(WTFMove(parameters.defaultSessionParameters)));
257 for (auto& supplement : m_supplements.values())
258 supplement->initialize(parameters);
261 void NetworkProcess::initializeConnection(IPC::Connection* connection)
263 ChildProcess::initializeConnection(connection);
265 for (auto& supplement : m_supplements.values())
266 supplement->initializeConnection(connection);
269 void NetworkProcess::createNetworkConnectionToWebProcess()
271 #if USE(UNIX_DOMAIN_SOCKETS)
272 IPC::Connection::SocketPair socketPair = IPC::Connection::createPlatformConnection();
274 auto connection = NetworkConnectionToWebProcess::create(socketPair.server);
275 m_webProcessConnections.append(WTFMove(connection));
277 IPC::Attachment clientSocket(socketPair.client);
278 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidCreateNetworkConnectionToWebProcess(clientSocket), 0);
280 // Create the listening port.
281 mach_port_t listeningPort;
282 mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &listeningPort);
284 // Create a listening connection.
285 auto connection = NetworkConnectionToWebProcess::create(IPC::Connection::Identifier(listeningPort));
286 m_webProcessConnections.append(WTFMove(connection));
288 IPC::Attachment clientPort(listeningPort, MACH_MSG_TYPE_MAKE_SEND);
289 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidCreateNetworkConnectionToWebProcess(clientPort), 0);
295 void NetworkProcess::clearCachedCredentials()
297 NetworkStorageSession::defaultStorageSession().credentialStorage().clearCredentials();
298 #if USE(NETWORK_SESSION)
299 if (auto* networkSession = SessionTracker::networkSession(PAL::SessionID::defaultSessionID()))
300 networkSession->clearCredentials();
302 ASSERT_NOT_REACHED();
306 void NetworkProcess::addWebsiteDataStore(WebsiteDataStoreParameters&& parameters)
308 RemoteNetworkingContext::ensureWebsiteDataStoreSession(WTFMove(parameters));
311 void NetworkProcess::destroySession(PAL::SessionID sessionID)
313 SessionTracker::destroySession(sessionID);
316 void NetworkProcess::grantSandboxExtensionsToStorageProcessForBlobs(const Vector<String>& filenames, Function<void ()>&& completionHandler)
318 static uint64_t lastRequestID;
320 uint64_t requestID = ++lastRequestID;
321 m_sandboxExtensionForBlobsCompletionHandlers.set(requestID, WTFMove(completionHandler));
322 parentProcessConnection()->send(Messages::NetworkProcessProxy::GrantSandboxExtensionsToStorageProcessForBlobs(requestID, filenames), 0);
325 void NetworkProcess::didGrantSandboxExtensionsToStorageProcessForBlobs(uint64_t requestID)
327 if (auto handler = m_sandboxExtensionForBlobsCompletionHandlers.take(requestID))
331 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
332 void NetworkProcess::updatePrevalentDomainsToPartitionOrBlockCookies(PAL::SessionID sessionID, const Vector<String>& domainsToPartition, const Vector<String>& domainsToBlock, const Vector<String>& domainsToNeitherPartitionNorBlock, bool shouldClearFirst)
334 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
335 networkStorageSession->setPrevalentDomainsToPartitionOrBlockCookies(domainsToPartition, domainsToBlock, domainsToNeitherPartitionNorBlock, shouldClearFirst);
338 void NetworkProcess::hasStorageAccessForPrevalentDomains(PAL::SessionID sessionID, const String& resourceDomain, const String& firstPartyDomain, uint64_t frameID, uint64_t pageID, uint64_t contextId)
340 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
341 parentProcessConnection()->send(Messages::NetworkProcessProxy::StorageAccessRequestResult(networkStorageSession->isStorageAccessGranted(resourceDomain, firstPartyDomain, frameID, pageID), contextId), 0);
343 ASSERT_NOT_REACHED();
346 void NetworkProcess::updateStorageAccessForPrevalentDomains(PAL::SessionID sessionID, const String& resourceDomain, const String& firstPartyDomain, uint64_t frameID, uint64_t pageID, bool shouldGrantStorage, uint64_t contextId)
348 bool isStorageGranted = false;
349 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID)) {
350 networkStorageSession->setStorageAccessGranted(resourceDomain, firstPartyDomain, frameID, pageID, shouldGrantStorage);
351 ASSERT(networkStorageSession->isStorageAccessGranted(resourceDomain, firstPartyDomain, frameID, pageID) == shouldGrantStorage);
352 isStorageGranted = shouldGrantStorage;
354 ASSERT_NOT_REACHED();
356 parentProcessConnection()->send(Messages::NetworkProcessProxy::StorageAccessRequestResult(isStorageGranted, contextId), 0);
359 void NetworkProcess::removePrevalentDomains(PAL::SessionID sessionID, const Vector<String>& domains)
361 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
362 networkStorageSession->removePrevalentDomains(domains);
366 static void fetchDiskCacheEntries(PAL::SessionID sessionID, OptionSet<WebsiteDataFetchOption> fetchOptions, Function<void (Vector<WebsiteData::Entry>)>&& completionHandler)
368 if (auto* cache = NetworkProcess::singleton().cache()) {
369 HashMap<SecurityOriginData, uint64_t> originsAndSizes;
370 cache->traverse([fetchOptions, completionHandler = WTFMove(completionHandler), originsAndSizes = WTFMove(originsAndSizes)](auto* traversalEntry) mutable {
371 if (!traversalEntry) {
372 Vector<WebsiteData::Entry> entries;
374 for (auto& originAndSize : originsAndSizes)
375 entries.append(WebsiteData::Entry { originAndSize.key, WebsiteDataType::DiskCache, originAndSize.value });
377 RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler), entries = WTFMove(entries)] {
378 completionHandler(entries);
384 auto url = traversalEntry->entry.response().url();
385 auto result = originsAndSizes.add({url.protocol().toString(), url.host(), url.port()}, 0);
387 if (fetchOptions.contains(WebsiteDataFetchOption::ComputeSizes))
388 result.iterator->value += traversalEntry->entry.sourceStorageRecord().header.size() + traversalEntry->recordInfo.bodySize;
394 RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler)] {
395 completionHandler({ });
399 void NetworkProcess::fetchWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, OptionSet<WebsiteDataFetchOption> fetchOptions, uint64_t callbackID)
401 struct CallbackAggregator final : public RefCounted<CallbackAggregator> {
402 explicit CallbackAggregator(Function<void (WebsiteData)>&& completionHandler)
403 : m_completionHandler(WTFMove(completionHandler))
407 ~CallbackAggregator()
409 ASSERT(RunLoop::isMain());
411 RunLoop::main().dispatch([completionHandler = WTFMove(m_completionHandler), websiteData = WTFMove(m_websiteData)] {
412 completionHandler(websiteData);
416 Function<void (WebsiteData)> m_completionHandler;
417 WebsiteData m_websiteData;
420 auto callbackAggregator = adoptRef(*new CallbackAggregator([this, callbackID] (WebsiteData websiteData) {
421 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidFetchWebsiteData(callbackID, websiteData), 0);
424 if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
425 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
426 getHostnamesWithCookies(*networkStorageSession, callbackAggregator->m_websiteData.hostNamesWithCookies);
429 if (websiteDataTypes.contains(WebsiteDataType::Credentials)) {
430 if (NetworkStorageSession::storageSession(sessionID))
431 callbackAggregator->m_websiteData.originsWithCredentials = NetworkStorageSession::storageSession(sessionID)->credentialStorage().originsWithCredentials();
434 if (websiteDataTypes.contains(WebsiteDataType::DOMCache)) {
435 CacheStorage::Engine::fetchEntries(sessionID, fetchOptions.contains(WebsiteDataFetchOption::ComputeSizes), [callbackAggregator = callbackAggregator.copyRef()](auto entries) mutable {
436 callbackAggregator->m_websiteData.entries.appendVector(entries);
440 if (websiteDataTypes.contains(WebsiteDataType::DiskCache)) {
441 fetchDiskCacheEntries(sessionID, fetchOptions, [callbackAggregator = WTFMove(callbackAggregator)](auto entries) mutable {
442 callbackAggregator->m_websiteData.entries.appendVector(entries);
447 void NetworkProcess::deleteWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, std::chrono::system_clock::time_point modifiedSince, uint64_t callbackID)
450 if (websiteDataTypes.contains(WebsiteDataType::HSTSCache)) {
451 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
452 clearHSTSCache(*networkStorageSession, modifiedSince);
456 if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
457 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
458 deleteAllCookiesModifiedSince(*networkStorageSession, modifiedSince);
461 if (websiteDataTypes.contains(WebsiteDataType::Credentials)) {
462 if (NetworkStorageSession::storageSession(sessionID))
463 NetworkStorageSession::storageSession(sessionID)->credentialStorage().clearCredentials();
466 auto clearTasksHandler = WTF::CallbackAggregator::create([this, callbackID] {
467 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidDeleteWebsiteData(callbackID), 0);
470 if (websiteDataTypes.contains(WebsiteDataType::DOMCache))
471 CacheStorage::Engine::from(sessionID).clearAllCaches(clearTasksHandler);
473 if (websiteDataTypes.contains(WebsiteDataType::DiskCache) && !sessionID.isEphemeral())
474 clearDiskCache(modifiedSince, [clearTasksHandler = WTFMove(clearTasksHandler)] { });
477 static void clearDiskCacheEntries(const Vector<SecurityOriginData>& origins, Function<void ()>&& completionHandler)
479 if (auto* cache = NetworkProcess::singleton().cache()) {
480 HashSet<RefPtr<SecurityOrigin>> originsToDelete;
481 for (auto& origin : origins)
482 originsToDelete.add(origin.securityOrigin());
484 Vector<NetworkCache::Key> cacheKeysToDelete;
485 cache->traverse([cache, completionHandler = WTFMove(completionHandler), originsToDelete = WTFMove(originsToDelete), cacheKeysToDelete = WTFMove(cacheKeysToDelete)](auto* traversalEntry) mutable {
486 if (traversalEntry) {
487 if (originsToDelete.contains(SecurityOrigin::create(traversalEntry->entry.response().url())))
488 cacheKeysToDelete.append(traversalEntry->entry.key());
492 cache->remove(cacheKeysToDelete, WTFMove(completionHandler));
499 RunLoop::main().dispatch(WTFMove(completionHandler));
502 void NetworkProcess::deleteWebsiteDataForOrigins(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, const Vector<SecurityOriginData>& originDatas, const Vector<String>& cookieHostNames, uint64_t callbackID)
504 if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
505 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
506 deleteCookiesForHostnames(*networkStorageSession, cookieHostNames);
509 auto clearTasksHandler = WTF::CallbackAggregator::create([this, callbackID] {
510 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidDeleteWebsiteDataForOrigins(callbackID), 0);
513 if (websiteDataTypes.contains(WebsiteDataType::DOMCache)) {
514 for (auto& originData : originDatas) {
515 auto origin = originData.securityOrigin()->toString();
516 CacheStorage::Engine::from(sessionID).clearCachesForOrigin(origin, clearTasksHandler);
520 if (websiteDataTypes.contains(WebsiteDataType::DiskCache) && !sessionID.isEphemeral())
521 clearDiskCacheEntries(originDatas, [clearTasksHandler = WTFMove(clearTasksHandler)] { });
524 void NetworkProcess::downloadRequest(PAL::SessionID sessionID, DownloadID downloadID, const ResourceRequest& request, const String& suggestedFilename)
526 downloadManager().startDownload(nullptr, sessionID, downloadID, request, suggestedFilename);
529 void NetworkProcess::resumeDownload(PAL::SessionID sessionID, DownloadID downloadID, const IPC::DataReference& resumeData, const String& path, WebKit::SandboxExtension::Handle&& sandboxExtensionHandle)
531 downloadManager().resumeDownload(sessionID, downloadID, resumeData, path, WTFMove(sandboxExtensionHandle));
534 void NetworkProcess::cancelDownload(DownloadID downloadID)
536 downloadManager().cancelDownload(downloadID);
539 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
540 static uint64_t generateCanAuthenticateIdentifier()
542 static uint64_t lastLoaderID = 0;
543 return ++lastLoaderID;
546 void NetworkProcess::canAuthenticateAgainstProtectionSpace(NetworkResourceLoader& loader, const WebCore::ProtectionSpace& protectionSpace)
548 uint64_t loaderID = generateCanAuthenticateIdentifier();
549 m_waitingNetworkResourceLoaders.set(loaderID, loader);
550 parentProcessConnection()->send(Messages::NetworkProcessProxy::CanAuthenticateAgainstProtectionSpace(loaderID, loader.pageID(), loader.frameID(), protectionSpace), 0);
553 #if ENABLE(SERVER_PRECONNECT)
554 void NetworkProcess::canAuthenticateAgainstProtectionSpace(PreconnectTask& preconnectTask, const WebCore::ProtectionSpace& protectionSpace)
556 uint64_t loaderID = generateCanAuthenticateIdentifier();
557 m_waitingPreconnectTasks.set(loaderID, preconnectTask.createWeakPtr());
558 parentProcessConnection()->send(Messages::NetworkProcessProxy::CanAuthenticateAgainstProtectionSpace(loaderID, preconnectTask.pageID(), preconnectTask.frameID(), protectionSpace), 0);
562 void NetworkProcess::continueCanAuthenticateAgainstProtectionSpace(uint64_t loaderID, bool canAuthenticate)
564 if (auto resourceLoader = m_waitingNetworkResourceLoaders.take(loaderID)) {
565 resourceLoader.value()->continueCanAuthenticateAgainstProtectionSpace(canAuthenticate);
568 #if ENABLE(SERVER_PRECONNECT)
569 if (auto preconnectTask = m_waitingPreconnectTasks.take(loaderID)) {
570 preconnectTask->continueCanAuthenticateAgainstProtectionSpace(canAuthenticate);
578 #if USE(NETWORK_SESSION)
579 void NetworkProcess::continueWillSendRequest(DownloadID downloadID, WebCore::ResourceRequest&& request)
581 downloadManager().continueWillSendRequest(downloadID, WTFMove(request));
584 void NetworkProcess::pendingDownloadCanceled(DownloadID downloadID)
586 downloadProxyConnection()->send(Messages::DownloadProxy::DidCancel({ }), downloadID.downloadID());
589 void NetworkProcess::findPendingDownloadLocation(NetworkDataTask& networkDataTask, ResponseCompletionHandler&& completionHandler, const ResourceResponse& response)
591 uint64_t destinationID = networkDataTask.pendingDownloadID().downloadID();
592 downloadProxyConnection()->send(Messages::DownloadProxy::DidReceiveResponse(response), destinationID);
594 downloadManager().willDecidePendingDownloadDestination(networkDataTask, WTFMove(completionHandler));
596 // As per https://html.spec.whatwg.org/#as-a-download (step 2), the filename from the Content-Disposition header
597 // should override the suggested filename from the download attribute.
598 String suggestedFilename = response.isAttachmentWithFilename() ? response.suggestedFilename() : networkDataTask.suggestedFilename();
599 suggestedFilename = MIMETypeRegistry::appendFileExtensionIfNecessary(suggestedFilename, response.mimeType());
601 downloadProxyConnection()->send(Messages::DownloadProxy::DecideDestinationWithSuggestedFilenameAsync(networkDataTask.pendingDownloadID(), suggestedFilename), destinationID);
605 void NetworkProcess::continueDecidePendingDownloadDestination(DownloadID downloadID, String destination, SandboxExtension::Handle&& sandboxExtensionHandle, bool allowOverwrite)
607 if (destination.isEmpty())
608 downloadManager().cancelDownload(downloadID);
610 downloadManager().continueDecidePendingDownloadDestination(downloadID, destination, WTFMove(sandboxExtensionHandle), allowOverwrite);
613 void NetworkProcess::setCacheModel(uint32_t cm)
615 CacheModel cacheModel = static_cast<CacheModel>(cm);
617 if (m_hasSetCacheModel && (cacheModel == m_cacheModel))
620 m_hasSetCacheModel = true;
621 m_cacheModel = cacheModel;
623 unsigned urlCacheMemoryCapacity = 0;
624 uint64_t urlCacheDiskCapacity = 0;
625 uint64_t diskFreeSize = 0;
626 if (WebCore::FileSystem::getVolumeFreeSpace(m_diskCacheDirectory, diskFreeSize)) {
627 // As a fudge factor, use 1000 instead of 1024, in case the reported byte
628 // count doesn't align exactly to a megabyte boundary.
629 diskFreeSize /= KB * 1000;
630 calculateURLCacheSizes(cacheModel, diskFreeSize, urlCacheMemoryCapacity, urlCacheDiskCapacity);
633 if (m_diskCacheSizeOverride >= 0)
634 urlCacheDiskCapacity = m_diskCacheSizeOverride;
637 m_cache->setCapacity(urlCacheDiskCapacity);
641 platformSetURLCacheSize(urlCacheMemoryCapacity, urlCacheDiskCapacity);
644 void NetworkProcess::setCanHandleHTTPSServerTrustEvaluation(bool value)
646 m_canHandleHTTPSServerTrustEvaluation = value;
649 void NetworkProcess::getNetworkProcessStatistics(uint64_t callbackID)
653 auto& networkProcess = NetworkProcess::singleton();
654 data.statisticsNumbers.set("DownloadsActiveCount", networkProcess.downloadManager().activeDownloadCount());
655 data.statisticsNumbers.set("OutstandingAuthenticationChallengesCount", networkProcess.authenticationManager().outstandingAuthenticationChallengeCount());
657 parentProcessConnection()->send(Messages::WebProcessPool::DidGetStatistics(data, callbackID), 0);
660 void NetworkProcess::setAllowsAnySSLCertificateForWebSocket(bool allows)
662 DeprecatedGlobalSettings::setAllowsAnySSLCertificate(allows);
665 void NetworkProcess::logDiagnosticMessage(uint64_t webPageID, const String& message, const String& description, ShouldSample shouldSample)
667 if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
670 parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessage(webPageID, message, description, ShouldSample::No), 0);
673 void NetworkProcess::logDiagnosticMessageWithResult(uint64_t webPageID, const String& message, const String& description, DiagnosticLoggingResultType result, ShouldSample shouldSample)
675 if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
678 parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessageWithResult(webPageID, message, description, result, ShouldSample::No), 0);
681 void NetworkProcess::logDiagnosticMessageWithValue(uint64_t webPageID, const String& message, const String& description, double value, unsigned significantFigures, ShouldSample shouldSample)
683 if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
686 parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessageWithValue(webPageID, message, description, value, significantFigures, ShouldSample::No), 0);
689 void NetworkProcess::terminate()
691 #if ENABLE(NETWORK_CAPTURE)
692 NetworkCapture::Manager::singleton().terminate();
696 ChildProcess::terminate();
699 // FIXME: We can remove this one by adapting RefCounter.
700 class TaskCounter : public RefCounted<TaskCounter> {
702 explicit TaskCounter(Function<void()>&& callback) : m_callback(WTFMove(callback)) { }
703 ~TaskCounter() { m_callback(); };
706 Function<void()> m_callback;
709 void NetworkProcess::actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend shouldAcknowledgeWhenReadyToSuspend)
711 lowMemoryHandler(Critical::Yes);
713 RefPtr<TaskCounter> delayedTaskCounter;
714 if (shouldAcknowledgeWhenReadyToSuspend == ShouldAcknowledgeWhenReadyToSuspend::Yes) {
715 delayedTaskCounter = adoptRef(new TaskCounter([this] {
716 RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::notifyProcessReadyToSuspend() Sending ProcessReadyToSuspend IPC message", this);
717 if (parentProcessConnection())
718 parentProcessConnection()->send(Messages::NetworkProcessProxy::ProcessReadyToSuspend(), 0);
722 for (auto& connection : m_webProcessConnections)
723 connection->cleanupForSuspension([delayedTaskCounter] { });
726 void NetworkProcess::processWillSuspendImminently(bool& handled)
728 actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend::No);
732 void NetworkProcess::prepareToSuspend()
734 RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::prepareToSuspend()", this);
735 actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend::Yes);
738 void NetworkProcess::cancelPrepareToSuspend()
740 // Although it is tempting to send a NetworkProcessProxy::DidCancelProcessSuspension message from here
741 // we do not because prepareToSuspend() already replied with a NetworkProcessProxy::ProcessReadyToSuspend
742 // message. And NetworkProcessProxy expects to receive either a NetworkProcessProxy::ProcessReadyToSuspend-
743 // or NetworkProcessProxy::DidCancelProcessSuspension- message, but not both.
744 RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::cancelPrepareToSuspend()", this);
745 for (auto& connection : m_webProcessConnections)
746 connection->endSuspension();
749 void NetworkProcess::processDidResume()
751 RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::processDidResume()", this);
752 for (auto& connection : m_webProcessConnections)
753 connection->endSuspension();
756 void NetworkProcess::prefetchDNS(const String& hostname)
758 WebCore::prefetchDNS(hostname);
761 String NetworkProcess::cacheStorageDirectory(PAL::SessionID sessionID) const
763 if (sessionID.isEphemeral())
766 if (sessionID == PAL::SessionID::defaultSessionID())
767 return m_cacheStorageDirectory;
769 auto* session = NetworkStorageSession::storageSession(sessionID);
773 return session->cacheStorageDirectory();
776 void NetworkProcess::preconnectTo(const WebCore::URL& url, WebCore::StoredCredentialsPolicy storedCredentialsPolicy)
778 #if ENABLE(SERVER_PRECONNECT)
779 NetworkLoadParameters parameters;
780 parameters.request = ResourceRequest { url };
781 parameters.sessionID = PAL::SessionID::defaultSessionID();
782 parameters.storedCredentialsPolicy = storedCredentialsPolicy;
783 parameters.shouldPreconnectOnly = PreconnectOnly::Yes;
785 new PreconnectTask(WTFMove(parameters));
788 UNUSED_PARAM(storedCredentialsPolicy);
792 uint64_t NetworkProcess::cacheStoragePerOriginQuota() const
794 return m_cacheStoragePerOriginQuota;
798 void NetworkProcess::initializeProcess(const ChildProcessInitializationParameters&)
802 void NetworkProcess::initializeProcessName(const ChildProcessInitializationParameters&)
806 void NetworkProcess::initializeSandbox(const ChildProcessInitializationParameters&, SandboxInitializationParameters&)
810 void NetworkProcess::syncAllCookies()
816 } // namespace WebKit