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 #include "LegacyCustomProtocolManager.h"
37 #include "NetworkConnectionToWebProcess.h"
38 #include "NetworkProcessCreationParameters.h"
39 #include "NetworkProcessPlatformStrategies.h"
40 #include "NetworkProcessProxyMessages.h"
41 #include "NetworkResourceLoader.h"
42 #include "NetworkSession.h"
43 #include "RemoteNetworkingContext.h"
44 #include "SessionTracker.h"
45 #include "StatisticsData.h"
46 #include "WebCookieManager.h"
47 #include "WebCoreArgumentCoders.h"
48 #include "WebPageProxyMessages.h"
49 #include "WebProcessPoolMessages.h"
50 #include "WebsiteData.h"
51 #include "WebsiteDataFetchOption.h"
52 #include "WebsiteDataStoreParameters.h"
53 #include "WebsiteDataType.h"
54 #include <WebCore/DNS.h>
55 #include <WebCore/DiagnosticLoggingClient.h>
56 #include <WebCore/LogInitialization.h>
57 #include <WebCore/MIMETypeRegistry.h>
58 #include <WebCore/NetworkStorageSession.h>
59 #include <WebCore/PlatformCookieJar.h>
60 #include <WebCore/ResourceRequest.h>
61 #include <WebCore/RuntimeApplicationChecks.h>
62 #include <WebCore/SecurityOriginData.h>
63 #include <WebCore/SecurityOriginHash.h>
64 #include <WebCore/Settings.h>
65 #include <WebCore/URLParser.h>
66 #include <pal/SessionID.h>
67 #include <wtf/OptionSet.h>
68 #include <wtf/RunLoop.h>
69 #include <wtf/text/CString.h>
71 #if ENABLE(SEC_ITEM_SHIM)
72 #include "SecItemShim.h"
75 #if ENABLE(NETWORK_CACHE)
76 #include "NetworkCache.h"
77 #include "NetworkCacheCoders.h"
80 #if ENABLE(NETWORK_CAPTURE)
81 #include "NetworkCaptureManager.h"
85 #include "NetworkSessionCocoa.h"
88 using namespace WebCore;
92 NetworkProcess& NetworkProcess::singleton()
94 static NeverDestroyed<NetworkProcess> networkProcess;
95 return networkProcess;
98 NetworkProcess::NetworkProcess()
99 : m_hasSetCacheModel(false)
100 , m_cacheModel(CacheModelDocumentViewer)
101 , m_diskCacheIsDisabledForTesting(false)
102 , m_canHandleHTTPSServerTrustEvaluation(true)
104 , m_clearCacheDispatchGroup(0)
107 , m_webSQLiteDatabaseTracker(*this)
110 NetworkProcessPlatformStrategies::initialize();
112 addSupplement<AuthenticationManager>();
113 addSupplement<WebCookieManager>();
114 addSupplement<LegacyCustomProtocolManager>();
115 #if USE(NETWORK_SESSION) && PLATFORM(COCOA)
116 NetworkSessionCocoa::setLegacyCustomProtocolManager(supplement<LegacyCustomProtocolManager>());
120 NetworkProcess::~NetworkProcess()
124 AuthenticationManager& NetworkProcess::authenticationManager()
126 return *supplement<AuthenticationManager>();
129 DownloadManager& NetworkProcess::downloadManager()
131 static NeverDestroyed<DownloadManager> downloadManager(*this);
132 return downloadManager;
135 void NetworkProcess::removeNetworkConnectionToWebProcess(NetworkConnectionToWebProcess* connection)
137 size_t vectorIndex = m_webProcessConnections.find(connection);
138 ASSERT(vectorIndex != notFound);
140 m_webProcessConnections.remove(vectorIndex);
143 bool NetworkProcess::shouldTerminate()
145 // Network process keeps session cookies and credentials, so it should never terminate (as long as UI process connection is alive).
149 void NetworkProcess::didReceiveMessage(IPC::Connection& connection, IPC::Decoder& decoder)
151 if (messageReceiverMap().dispatchMessage(connection, decoder))
154 if (decoder.messageReceiverName() == Messages::ChildProcess::messageReceiverName()) {
155 ChildProcess::didReceiveMessage(connection, decoder);
159 didReceiveNetworkProcessMessage(connection, decoder);
162 void NetworkProcess::didReceiveSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
164 if (messageReceiverMap().dispatchSyncMessage(connection, decoder, replyEncoder))
167 didReceiveSyncNetworkProcessMessage(connection, decoder, replyEncoder);
170 void NetworkProcess::didClose(IPC::Connection&)
172 // The UIProcess just exited.
176 void NetworkProcess::didCreateDownload()
178 disableTermination();
181 void NetworkProcess::didDestroyDownload()
186 IPC::Connection* NetworkProcess::downloadProxyConnection()
188 return parentProcessConnection();
191 AuthenticationManager& NetworkProcess::downloadsAuthenticationManager()
193 return authenticationManager();
196 void NetworkProcess::lowMemoryHandler(Critical critical)
198 if (m_suppressMemoryPressureHandler)
201 WTF::releaseFastMallocFreeMemory();
204 void NetworkProcess::initializeNetworkProcess(NetworkProcessCreationParameters&& parameters)
206 WebCore::setPresentingApplicationPID(parameters.presentingApplicationPID);
207 platformInitializeNetworkProcess(parameters);
209 WTF::Thread::setCurrentThreadIsUserInitiated();
211 m_suppressMemoryPressureHandler = parameters.shouldSuppressMemoryPressureHandler;
212 m_loadThrottleLatency = parameters.loadThrottleLatency;
213 if (!m_suppressMemoryPressureHandler) {
214 auto& memoryPressureHandler = MemoryPressureHandler::singleton();
216 if (parameters.memoryPressureMonitorHandle.fileDescriptor() != -1)
217 memoryPressureHandler.setMemoryPressureMonitorHandle(parameters.memoryPressureMonitorHandle.releaseFileDescriptor());
219 memoryPressureHandler.setLowMemoryHandler([this] (Critical critical, Synchronous) {
220 lowMemoryHandler(critical);
222 memoryPressureHandler.install();
225 #if ENABLE(NETWORK_CAPTURE)
226 NetworkCapture::Manager::singleton().initialize(
227 parameters.recordReplayMode,
228 parameters.recordReplayCacheLocation);
231 m_diskCacheIsDisabledForTesting = parameters.shouldUseTestingNetworkSession;
233 m_diskCacheSizeOverride = parameters.diskCacheSizeOverride;
234 setCacheModel(static_cast<uint32_t>(parameters.cacheModel));
236 setCanHandleHTTPSServerTrustEvaluation(parameters.canHandleHTTPSServerTrustEvaluation);
238 // FIXME: instead of handling this here, a message should be sent later (scales to multiple sessions)
239 if (parameters.privateBrowsingEnabled)
240 RemoteNetworkingContext::ensurePrivateBrowsingSession({PAL::SessionID::legacyPrivateSessionID(), { }, { }, { }, { }, { }});
242 if (parameters.shouldUseTestingNetworkSession)
243 NetworkStorageSession::switchToNewTestingSession();
245 for (auto& supplement : m_supplements.values())
246 supplement->initialize(parameters);
249 void NetworkProcess::initializeConnection(IPC::Connection* connection)
251 ChildProcess::initializeConnection(connection);
253 for (auto& supplement : m_supplements.values())
254 supplement->initializeConnection(connection);
257 void NetworkProcess::createNetworkConnectionToWebProcess()
259 #if USE(UNIX_DOMAIN_SOCKETS)
260 IPC::Connection::SocketPair socketPair = IPC::Connection::createPlatformConnection();
262 auto connection = NetworkConnectionToWebProcess::create(socketPair.server);
263 m_webProcessConnections.append(WTFMove(connection));
265 IPC::Attachment clientSocket(socketPair.client);
266 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidCreateNetworkConnectionToWebProcess(clientSocket), 0);
268 // Create the listening port.
269 mach_port_t listeningPort;
270 mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &listeningPort);
272 // Create a listening connection.
273 auto connection = NetworkConnectionToWebProcess::create(IPC::Connection::Identifier(listeningPort));
274 m_webProcessConnections.append(WTFMove(connection));
276 IPC::Attachment clientPort(listeningPort, MACH_MSG_TYPE_MAKE_SEND);
277 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidCreateNetworkConnectionToWebProcess(clientPort), 0);
283 void NetworkProcess::clearCachedCredentials()
285 NetworkStorageSession::defaultStorageSession().credentialStorage().clearCredentials();
286 #if USE(NETWORK_SESSION)
287 NetworkSession::defaultSession().clearCredentials();
291 void NetworkProcess::ensurePrivateBrowsingSession(WebsiteDataStoreParameters&& parameters)
293 RemoteNetworkingContext::ensurePrivateBrowsingSession(WTFMove(parameters));
296 void NetworkProcess::addWebsiteDataStore(WebsiteDataStoreParameters&& parameters)
298 RemoteNetworkingContext::ensureWebsiteDataStoreSession(WTFMove(parameters));
301 void NetworkProcess::destroySession(PAL::SessionID sessionID)
303 SessionTracker::destroySession(sessionID);
306 void NetworkProcess::grantSandboxExtensionsToStorageProcessForBlobs(const Vector<String>& filenames, Function<void ()>&& completionHandler)
308 static uint64_t lastRequestID;
310 uint64_t requestID = ++lastRequestID;
311 m_sandboxExtensionForBlobsCompletionHandlers.set(requestID, WTFMove(completionHandler));
312 parentProcessConnection()->send(Messages::NetworkProcessProxy::GrantSandboxExtensionsToStorageProcessForBlobs(requestID, filenames), 0);
315 void NetworkProcess::didGrantSandboxExtensionsToStorageProcessForBlobs(uint64_t requestID)
317 if (auto handler = m_sandboxExtensionForBlobsCompletionHandlers.take(requestID))
321 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
322 void NetworkProcess::updatePrevalentDomainsWithAndWithoutInteraction(PAL::SessionID sessionID, const Vector<String>& domainsWithInteraction, const Vector<String>& domainsWithoutInteraction, bool shouldClearFirst)
324 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
325 networkStorageSession->setPrevalentDomainsWithAndWithoutInteraction(domainsWithInteraction, domainsWithoutInteraction, shouldClearFirst);
328 void NetworkProcess::removePrevalentDomains(PAL::SessionID sessionID, const Vector<String>& domains)
330 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
331 networkStorageSession->removePrevalentDomains(domains);
335 static void fetchDiskCacheEntries(PAL::SessionID sessionID, OptionSet<WebsiteDataFetchOption> fetchOptions, Function<void (Vector<WebsiteData::Entry>)>&& completionHandler)
337 #if ENABLE(NETWORK_CACHE)
338 if (auto* cache = NetworkProcess::singleton().cache()) {
339 HashMap<SecurityOriginData, uint64_t> originsAndSizes;
340 cache->traverse([fetchOptions, completionHandler = WTFMove(completionHandler), originsAndSizes = WTFMove(originsAndSizes)](auto* traversalEntry) mutable {
341 if (!traversalEntry) {
342 Vector<WebsiteData::Entry> entries;
344 for (auto& originAndSize : originsAndSizes)
345 entries.append(WebsiteData::Entry { originAndSize.key, WebsiteDataType::DiskCache, originAndSize.value });
347 RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler), entries = WTFMove(entries)] {
348 completionHandler(entries);
354 auto url = traversalEntry->entry.response().url();
355 auto result = originsAndSizes.add({url.protocol().toString(), url.host(), url.port()}, 0);
357 if (fetchOptions.contains(WebsiteDataFetchOption::ComputeSizes))
358 result.iterator->value += traversalEntry->entry.sourceStorageRecord().header.size() + traversalEntry->recordInfo.bodySize;
365 RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler)] {
366 completionHandler({ });
370 void NetworkProcess::fetchWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, OptionSet<WebsiteDataFetchOption> fetchOptions, uint64_t callbackID)
372 struct CallbackAggregator final : public RefCounted<CallbackAggregator> {
373 explicit CallbackAggregator(Function<void (WebsiteData)>&& completionHandler)
374 : m_completionHandler(WTFMove(completionHandler))
378 ~CallbackAggregator()
380 ASSERT(RunLoop::isMain());
382 RunLoop::main().dispatch([completionHandler = WTFMove(m_completionHandler), websiteData = WTFMove(m_websiteData)] {
383 completionHandler(websiteData);
387 Function<void (WebsiteData)> m_completionHandler;
388 WebsiteData m_websiteData;
391 auto callbackAggregator = adoptRef(*new CallbackAggregator([this, callbackID] (WebsiteData websiteData) {
392 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidFetchWebsiteData(callbackID, websiteData), 0);
395 if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
396 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
397 getHostnamesWithCookies(*networkStorageSession, callbackAggregator->m_websiteData.hostNamesWithCookies);
400 if (websiteDataTypes.contains(WebsiteDataType::Credentials)) {
401 if (NetworkStorageSession::storageSession(sessionID))
402 callbackAggregator->m_websiteData.originsWithCredentials = NetworkStorageSession::storageSession(sessionID)->credentialStorage().originsWithCredentials();
405 if (websiteDataTypes.contains(WebsiteDataType::DiskCache)) {
406 fetchDiskCacheEntries(sessionID, fetchOptions, [callbackAggregator = WTFMove(callbackAggregator)](auto entries) mutable {
407 callbackAggregator->m_websiteData.entries.appendVector(entries);
412 void NetworkProcess::deleteWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, std::chrono::system_clock::time_point modifiedSince, uint64_t callbackID)
415 if (websiteDataTypes.contains(WebsiteDataType::HSTSCache)) {
416 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
417 clearHSTSCache(*networkStorageSession, modifiedSince);
421 if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
422 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
423 deleteAllCookiesModifiedSince(*networkStorageSession, modifiedSince);
426 if (websiteDataTypes.contains(WebsiteDataType::Credentials)) {
427 if (NetworkStorageSession::storageSession(sessionID))
428 NetworkStorageSession::storageSession(sessionID)->credentialStorage().clearCredentials();
431 auto completionHandler = [this, callbackID] {
432 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidDeleteWebsiteData(callbackID), 0);
435 if (websiteDataTypes.contains(WebsiteDataType::DiskCache) && !sessionID.isEphemeral()) {
436 clearDiskCache(modifiedSince, WTFMove(completionHandler));
443 static void clearDiskCacheEntries(const Vector<SecurityOriginData>& origins, Function<void ()>&& completionHandler)
445 #if ENABLE(NETWORK_CACHE)
446 if (auto* cache = NetworkProcess::singleton().cache()) {
447 HashSet<RefPtr<SecurityOrigin>> originsToDelete;
448 for (auto& origin : origins)
449 originsToDelete.add(origin.securityOrigin());
451 Vector<NetworkCache::Key> cacheKeysToDelete;
452 cache->traverse([cache, completionHandler = WTFMove(completionHandler), originsToDelete = WTFMove(originsToDelete), cacheKeysToDelete = WTFMove(cacheKeysToDelete)](auto* traversalEntry) mutable {
453 if (traversalEntry) {
454 if (originsToDelete.contains(SecurityOrigin::create(traversalEntry->entry.response().url())))
455 cacheKeysToDelete.append(traversalEntry->entry.key());
459 cache->remove(cacheKeysToDelete, WTFMove(completionHandler));
467 RunLoop::main().dispatch(WTFMove(completionHandler));
470 void NetworkProcess::deleteWebsiteDataForOrigins(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, const Vector<SecurityOriginData>& origins, const Vector<String>& cookieHostNames, uint64_t callbackID)
472 if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
473 if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
474 deleteCookiesForHostnames(*networkStorageSession, cookieHostNames);
477 auto completionHandler = [this, callbackID] {
478 parentProcessConnection()->send(Messages::NetworkProcessProxy::DidDeleteWebsiteDataForOrigins(callbackID), 0);
481 if (websiteDataTypes.contains(WebsiteDataType::DiskCache) && !sessionID.isEphemeral()) {
482 clearDiskCacheEntries(origins, WTFMove(completionHandler));
489 void NetworkProcess::downloadRequest(PAL::SessionID sessionID, DownloadID downloadID, const ResourceRequest& request, const String& suggestedFilename)
491 downloadManager().startDownload(nullptr, sessionID, downloadID, request, suggestedFilename);
494 void NetworkProcess::resumeDownload(PAL::SessionID sessionID, DownloadID downloadID, const IPC::DataReference& resumeData, const String& path, const WebKit::SandboxExtension::Handle& sandboxExtensionHandle)
496 downloadManager().resumeDownload(sessionID, downloadID, resumeData, path, sandboxExtensionHandle);
499 void NetworkProcess::cancelDownload(DownloadID downloadID)
501 downloadManager().cancelDownload(downloadID);
504 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
505 void NetworkProcess::canAuthenticateAgainstProtectionSpace(NetworkResourceLoader& loader, const WebCore::ProtectionSpace& protectionSpace)
507 static uint64_t lastLoaderID = 0;
508 uint64_t loaderID = ++lastLoaderID;
509 m_waitingNetworkResourceLoaders.set(lastLoaderID, loader);
510 parentProcessConnection()->send(Messages::NetworkProcessProxy::CanAuthenticateAgainstProtectionSpace(loaderID, loader.pageID(), loader.frameID(), protectionSpace), 0);
513 void NetworkProcess::continueCanAuthenticateAgainstProtectionSpace(uint64_t loaderID, bool canAuthenticate)
515 m_waitingNetworkResourceLoaders.take(loaderID).value()->continueCanAuthenticateAgainstProtectionSpace(canAuthenticate);
519 #if USE(NETWORK_SESSION)
520 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
521 void NetworkProcess::continueCanAuthenticateAgainstProtectionSpaceDownload(DownloadID downloadID, bool canAuthenticate)
523 downloadManager().continueCanAuthenticateAgainstProtectionSpace(downloadID, canAuthenticate);
527 void NetworkProcess::continueWillSendRequest(DownloadID downloadID, WebCore::ResourceRequest&& request)
529 downloadManager().continueWillSendRequest(downloadID, WTFMove(request));
532 void NetworkProcess::pendingDownloadCanceled(DownloadID downloadID)
534 downloadProxyConnection()->send(Messages::DownloadProxy::DidCancel({ }), downloadID.downloadID());
537 void NetworkProcess::findPendingDownloadLocation(NetworkDataTask& networkDataTask, ResponseCompletionHandler&& completionHandler, const ResourceResponse& response)
539 uint64_t destinationID = networkDataTask.pendingDownloadID().downloadID();
540 downloadProxyConnection()->send(Messages::DownloadProxy::DidReceiveResponse(response), destinationID);
542 downloadManager().willDecidePendingDownloadDestination(networkDataTask, WTFMove(completionHandler));
544 // As per https://html.spec.whatwg.org/#as-a-download (step 2), the filename from the Content-Disposition header
545 // should override the suggested filename from the download attribute.
546 String suggestedFilename = response.isAttachmentWithFilename() ? response.suggestedFilename() : networkDataTask.suggestedFilename();
547 suggestedFilename = MIMETypeRegistry::appendFileExtensionIfNecessary(suggestedFilename, response.mimeType());
549 downloadProxyConnection()->send(Messages::DownloadProxy::DecideDestinationWithSuggestedFilenameAsync(networkDataTask.pendingDownloadID(), suggestedFilename), destinationID);
553 void NetworkProcess::continueDecidePendingDownloadDestination(DownloadID downloadID, String destination, const SandboxExtension::Handle& sandboxExtensionHandle, bool allowOverwrite)
555 if (destination.isEmpty())
556 downloadManager().cancelDownload(downloadID);
558 downloadManager().continueDecidePendingDownloadDestination(downloadID, destination, sandboxExtensionHandle, allowOverwrite);
561 void NetworkProcess::setCacheModel(uint32_t cm)
563 CacheModel cacheModel = static_cast<CacheModel>(cm);
565 if (m_hasSetCacheModel && (cacheModel == m_cacheModel))
568 m_hasSetCacheModel = true;
569 m_cacheModel = cacheModel;
571 unsigned urlCacheMemoryCapacity = 0;
572 uint64_t urlCacheDiskCapacity = 0;
573 uint64_t diskFreeSize = 0;
574 if (WebCore::getVolumeFreeSpace(m_diskCacheDirectory, diskFreeSize)) {
575 // As a fudge factor, use 1000 instead of 1024, in case the reported byte
576 // count doesn't align exactly to a megabyte boundary.
577 diskFreeSize /= KB * 1000;
578 calculateURLCacheSizes(cacheModel, diskFreeSize, urlCacheMemoryCapacity, urlCacheDiskCapacity);
581 if (m_diskCacheSizeOverride >= 0)
582 urlCacheDiskCapacity = m_diskCacheSizeOverride;
584 #if ENABLE(NETWORK_CACHE)
586 m_cache->setCapacity(urlCacheDiskCapacity);
591 platformSetURLCacheSize(urlCacheMemoryCapacity, urlCacheDiskCapacity);
594 void NetworkProcess::setCanHandleHTTPSServerTrustEvaluation(bool value)
596 m_canHandleHTTPSServerTrustEvaluation = value;
599 void NetworkProcess::getNetworkProcessStatistics(uint64_t callbackID)
603 auto& networkProcess = NetworkProcess::singleton();
604 data.statisticsNumbers.set("DownloadsActiveCount", networkProcess.downloadManager().activeDownloadCount());
605 data.statisticsNumbers.set("OutstandingAuthenticationChallengesCount", networkProcess.authenticationManager().outstandingAuthenticationChallengeCount());
607 parentProcessConnection()->send(Messages::WebProcessPool::DidGetStatistics(data, callbackID), 0);
610 void NetworkProcess::setAllowsAnySSLCertificateForWebSocket(bool allows)
612 Settings::setAllowsAnySSLCertificate(allows);
615 void NetworkProcess::logDiagnosticMessage(uint64_t webPageID, const String& message, const String& description, ShouldSample shouldSample)
617 if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
620 parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessage(webPageID, message, description, ShouldSample::No), 0);
623 void NetworkProcess::logDiagnosticMessageWithResult(uint64_t webPageID, const String& message, const String& description, DiagnosticLoggingResultType result, ShouldSample shouldSample)
625 if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
628 parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessageWithResult(webPageID, message, description, result, ShouldSample::No), 0);
631 void NetworkProcess::logDiagnosticMessageWithValue(uint64_t webPageID, const String& message, const String& description, double value, unsigned significantFigures, ShouldSample shouldSample)
633 if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
636 parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessageWithValue(webPageID, message, description, value, significantFigures, ShouldSample::No), 0);
639 void NetworkProcess::terminate()
641 #if ENABLE(NETWORK_CAPTURE)
642 NetworkCapture::Manager::singleton().terminate();
646 ChildProcess::terminate();
649 // FIXME: We can remove this one by adapting RefCounter.
650 class TaskCounter : public RefCounted<TaskCounter> {
652 explicit TaskCounter(Function<void()>&& callback) : m_callback(WTFMove(callback)) { }
653 ~TaskCounter() { m_callback(); };
656 Function<void()> m_callback;
659 void NetworkProcess::actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend shouldAcknowledgeWhenReadyToSuspend)
661 lowMemoryHandler(Critical::Yes);
663 RefPtr<TaskCounter> delayedTaskCounter;
664 if (shouldAcknowledgeWhenReadyToSuspend == ShouldAcknowledgeWhenReadyToSuspend::Yes) {
665 delayedTaskCounter = adoptRef(new TaskCounter([this] {
666 RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::notifyProcessReadyToSuspend() Sending ProcessReadyToSuspend IPC message", this);
667 if (parentProcessConnection())
668 parentProcessConnection()->send(Messages::NetworkProcessProxy::ProcessReadyToSuspend(), 0);
672 for (auto& connection : m_webProcessConnections)
673 connection->cleanupForSuspension([delayedTaskCounter] { });
676 void NetworkProcess::processWillSuspendImminently(bool& handled)
678 actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend::No);
682 void NetworkProcess::prepareToSuspend()
684 RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::prepareToSuspend()", this);
685 actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend::Yes);
688 void NetworkProcess::cancelPrepareToSuspend()
690 // Although it is tempting to send a NetworkProcessProxy::DidCancelProcessSuspension message from here
691 // we do not because prepareToSuspend() already replied with a NetworkProcessProxy::ProcessReadyToSuspend
692 // message. And NetworkProcessProxy expects to receive either a NetworkProcessProxy::ProcessReadyToSuspend-
693 // or NetworkProcessProxy::DidCancelProcessSuspension- message, but not both.
694 RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::cancelPrepareToSuspend()", this);
695 for (auto& connection : m_webProcessConnections)
696 connection->endSuspension();
699 void NetworkProcess::processDidResume()
701 RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::processDidResume()", this);
702 for (auto& connection : m_webProcessConnections)
703 connection->endSuspension();
706 void NetworkProcess::prefetchDNS(const String& hostname)
708 WebCore::prefetchDNS(hostname);
711 String NetworkProcess::cacheStorageDirectory(PAL::SessionID sessionID) const
713 if (sessionID.isEphemeral())
716 if (sessionID == PAL::SessionID::defaultSessionID())
717 return m_cacheStorageDirectory;
719 auto* session = NetworkStorageSession::storageSession(sessionID);
723 return session->cacheStorageDirectory();
727 void NetworkProcess::initializeProcess(const ChildProcessInitializationParameters&)
731 void NetworkProcess::initializeProcessName(const ChildProcessInitializationParameters&)
735 void NetworkProcess::initializeSandbox(const ChildProcessInitializationParameters&, SandboxInitializationParameters&)
739 void NetworkProcess::syncAllCookies()
745 } // namespace WebKit