Remove legacyCustomProtocolManager from NetworkSessionCreationParameters
[WebKit-https.git] / Source / WebKit / NetworkProcess / NetworkProcess.cpp
1 /*
2  * Copyright (C) 2012-2018 Apple Inc. All rights reserved.
3  * Copyright (C) 2018 Sony Interactive Entertainment Inc.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
16  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
18  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
24  * THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28 #include "NetworkProcess.h"
29
30 #include "ArgumentCoders.h"
31 #include "Attachment.h"
32 #include "AuthenticationManager.h"
33 #include "ChildProcessMessages.h"
34 #include "DataReference.h"
35 #include "DownloadProxyMessages.h"
36 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
37 #include "LegacyCustomProtocolManager.h"
38 #endif
39 #include "Logging.h"
40 #include "NetworkBlobRegistry.h"
41 #include "NetworkConnectionToWebProcess.h"
42 #include "NetworkContentRuleListManagerMessages.h"
43 #include "NetworkProcessCreationParameters.h"
44 #include "NetworkProcessPlatformStrategies.h"
45 #include "NetworkProcessProxyMessages.h"
46 #include "NetworkResourceLoader.h"
47 #include "NetworkSession.h"
48 #include "PreconnectTask.h"
49 #include "RemoteNetworkingContext.h"
50 #include "SessionTracker.h"
51 #include "StatisticsData.h"
52 #include "WebCookieManager.h"
53 #include "WebCoreArgumentCoders.h"
54 #include "WebPageProxyMessages.h"
55 #include "WebProcessPoolMessages.h"
56 #include "WebsiteData.h"
57 #include "WebsiteDataFetchOption.h"
58 #include "WebsiteDataStore.h"
59 #include "WebsiteDataStoreParameters.h"
60 #include "WebsiteDataType.h"
61 #include <WebCore/DNS.h>
62 #include <WebCore/DeprecatedGlobalSettings.h>
63 #include <WebCore/DiagnosticLoggingClient.h>
64 #include <WebCore/LogInitialization.h>
65 #include <WebCore/MIMETypeRegistry.h>
66 #include <WebCore/NetworkStateNotifier.h>
67 #include <WebCore/NetworkStorageSession.h>
68 #include <WebCore/PlatformCookieJar.h>
69 #include <WebCore/ResourceRequest.h>
70 #include <WebCore/RuntimeApplicationChecks.h>
71 #include <WebCore/SchemeRegistry.h>
72 #include <WebCore/SecurityOriginData.h>
73 #include <WebCore/SecurityOriginHash.h>
74 #include <WebCore/Settings.h>
75 #include <WebCore/URLParser.h>
76 #include <pal/SessionID.h>
77 #include <wtf/CallbackAggregator.h>
78 #include <wtf/OptionSet.h>
79 #include <wtf/ProcessPrivilege.h>
80 #include <wtf/RunLoop.h>
81 #include <wtf/text/AtomicString.h>
82 #include <wtf/text/CString.h>
83
84 #if ENABLE(SEC_ITEM_SHIM)
85 #include "SecItemShim.h"
86 #endif
87
88 #include "NetworkCache.h"
89 #include "NetworkCacheCoders.h"
90
91 #if ENABLE(NETWORK_CAPTURE)
92 #include "NetworkCaptureManager.h"
93 #endif
94
95 #if PLATFORM(COCOA)
96 #include "NetworkSessionCocoa.h"
97 #endif
98
99 using namespace WebCore;
100
101 namespace WebKit {
102
103 NetworkProcess& NetworkProcess::singleton()
104 {
105     static NeverDestroyed<NetworkProcess> networkProcess;
106     return networkProcess;
107 }
108
109 NetworkProcess::NetworkProcess()
110     : m_hasSetCacheModel(false)
111     , m_cacheModel(CacheModelDocumentViewer)
112     , m_diskCacheIsDisabledForTesting(false)
113     , m_canHandleHTTPSServerTrustEvaluation(true)
114 #if PLATFORM(COCOA)
115     , m_clearCacheDispatchGroup(0)
116 #endif
117 #if PLATFORM(IOS)
118     , m_webSQLiteDatabaseTracker(*this)
119 #endif
120 {
121     NetworkProcessPlatformStrategies::initialize();
122
123     addSupplement<AuthenticationManager>();
124     addSupplement<WebCookieManager>();
125 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
126     addSupplement<LegacyCustomProtocolManager>();
127 #endif
128
129     NetworkStateNotifier::singleton().addListener([this](bool isOnLine) {
130         auto webProcessConnections = m_webProcessConnections;
131         for (auto& webProcessConnection : webProcessConnections)
132             webProcessConnection->setOnLineState(isOnLine);
133     });
134 }
135
136 NetworkProcess::~NetworkProcess()
137 {
138 }
139
140 AuthenticationManager& NetworkProcess::authenticationManager()
141 {
142     return *supplement<AuthenticationManager>();
143 }
144
145 DownloadManager& NetworkProcess::downloadManager()
146 {
147     static NeverDestroyed<DownloadManager> downloadManager(*this);
148     return downloadManager;
149 }
150
151 void NetworkProcess::removeNetworkConnectionToWebProcess(NetworkConnectionToWebProcess* connection)
152 {
153     size_t vectorIndex = m_webProcessConnections.find(connection);
154     ASSERT(vectorIndex != notFound);
155
156     m_webProcessConnections.remove(vectorIndex);
157 }
158
159 bool NetworkProcess::shouldTerminate()
160 {
161     // Network process keeps session cookies and credentials, so it should never terminate (as long as UI process connection is alive).
162     return false;
163 }
164
165 void NetworkProcess::didReceiveMessage(IPC::Connection& connection, IPC::Decoder& decoder)
166 {
167     if (messageReceiverMap().dispatchMessage(connection, decoder))
168         return;
169
170     if (decoder.messageReceiverName() == Messages::ChildProcess::messageReceiverName()) {
171         ChildProcess::didReceiveMessage(connection, decoder);
172         return;
173     }
174
175 #if ENABLE(CONTENT_EXTENSIONS)
176     if (decoder.messageReceiverName() == Messages::NetworkContentRuleListManager::messageReceiverName()) {
177         m_NetworkContentRuleListManager.didReceiveMessage(connection, decoder);
178         return;
179     }
180 #endif
181
182     didReceiveNetworkProcessMessage(connection, decoder);
183 }
184
185 void NetworkProcess::didReceiveSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
186 {
187     if (messageReceiverMap().dispatchSyncMessage(connection, decoder, replyEncoder))
188         return;
189
190     didReceiveSyncNetworkProcessMessage(connection, decoder, replyEncoder);
191 }
192
193 void NetworkProcess::didClose(IPC::Connection&)
194 {
195     // The UIProcess just exited.
196     stopRunLoop();
197 }
198
199 void NetworkProcess::didCreateDownload()
200 {
201     disableTermination();
202 }
203
204 void NetworkProcess::didDestroyDownload()
205 {
206     enableTermination();
207 }
208
209 IPC::Connection* NetworkProcess::downloadProxyConnection()
210 {
211     return parentProcessConnection();
212 }
213
214 AuthenticationManager& NetworkProcess::downloadsAuthenticationManager()
215 {
216     return authenticationManager();
217 }
218
219 void NetworkProcess::lowMemoryHandler(Critical critical)
220 {
221     if (m_suppressMemoryPressureHandler)
222         return;
223
224     WTF::releaseFastMallocFreeMemory();
225 }
226
227 void NetworkProcess::initializeNetworkProcess(NetworkProcessCreationParameters&& parameters)
228 {
229     WTF::setProcessPrivileges({ ProcessPrivilege::CanAccessRawCookies, ProcessPrivilege::CanAccessCredentials });
230     WebCore::NetworkStorageSession::permitProcessToUseCookieAPI(true);
231     WebCore::setPresentingApplicationPID(parameters.presentingApplicationPID);
232     platformInitializeNetworkProcess(parameters);
233
234     WTF::Thread::setCurrentThreadIsUserInitiated();
235     AtomicString::init();
236
237     m_suppressMemoryPressureHandler = parameters.shouldSuppressMemoryPressureHandler;
238     m_loadThrottleLatency = parameters.loadThrottleLatency;
239     if (!m_suppressMemoryPressureHandler) {
240         auto& memoryPressureHandler = MemoryPressureHandler::singleton();
241 #if OS(LINUX)
242         if (parameters.memoryPressureMonitorHandle.fileDescriptor() != -1)
243             memoryPressureHandler.setMemoryPressureMonitorHandle(parameters.memoryPressureMonitorHandle.releaseFileDescriptor());
244 #endif
245         memoryPressureHandler.setLowMemoryHandler([this] (Critical critical, Synchronous) {
246             lowMemoryHandler(critical);
247         });
248         memoryPressureHandler.install();
249     }
250
251 #if ENABLE(NETWORK_CAPTURE)
252     NetworkCapture::Manager::singleton().initialize(
253         parameters.recordReplayMode,
254         parameters.recordReplayCacheLocation);
255 #endif
256
257     m_diskCacheIsDisabledForTesting = parameters.shouldUseTestingNetworkSession;
258
259     m_diskCacheSizeOverride = parameters.diskCacheSizeOverride;
260     setCacheModel(static_cast<uint32_t>(parameters.cacheModel));
261
262     setCanHandleHTTPSServerTrustEvaluation(parameters.canHandleHTTPSServerTrustEvaluation);
263
264     // FIXME: instead of handling this here, a message should be sent later (scales to multiple sessions)
265     if (parameters.privateBrowsingEnabled)
266         RemoteNetworkingContext::ensureWebsiteDataStoreSession(WebsiteDataStoreParameters::legacyPrivateSessionParameters());
267
268     if (parameters.shouldUseTestingNetworkSession)
269         NetworkStorageSession::switchToNewTestingSession();
270
271 #if HAVE(CFNETWORK_STORAGE_PARTITIONING) && !RELEASE_LOG_DISABLED
272     m_logCookieInformation = parameters.logCookieInformation;
273 #endif
274
275     SessionTracker::setSession(PAL::SessionID::defaultSessionID(), NetworkSession::create(WTFMove(parameters.defaultSessionParameters)));
276
277     for (auto& supplement : m_supplements.values())
278         supplement->initialize(parameters);
279
280     for (auto& scheme : parameters.urlSchemesRegisteredAsSecure)
281         registerURLSchemeAsSecure(scheme);
282
283     for (auto& scheme : parameters.urlSchemesRegisteredAsBypassingContentSecurityPolicy)
284         registerURLSchemeAsBypassingContentSecurityPolicy(scheme);
285
286     for (auto& scheme : parameters.urlSchemesRegisteredAsLocal)
287         registerURLSchemeAsLocal(scheme);
288
289     for (auto& scheme : parameters.urlSchemesRegisteredAsNoAccess)
290         registerURLSchemeAsNoAccess(scheme);
291
292     for (auto& scheme : parameters.urlSchemesRegisteredAsDisplayIsolated)
293         registerURLSchemeAsDisplayIsolated(scheme);
294
295     for (auto& scheme : parameters.urlSchemesRegisteredAsCORSEnabled)
296         registerURLSchemeAsCORSEnabled(scheme);
297
298     for (auto& scheme : parameters.urlSchemesRegisteredAsCanDisplayOnlyIfCanRequest)
299         registerURLSchemeAsCanDisplayOnlyIfCanRequest(scheme);
300
301     RELEASE_LOG(Process, "%p - NetworkProcess::initializeNetworkProcess: Presenting process = %d", this, WebCore::presentingApplicationPID());
302 }
303
304 void NetworkProcess::initializeConnection(IPC::Connection* connection)
305 {
306     ChildProcess::initializeConnection(connection);
307
308     for (auto& supplement : m_supplements.values())
309         supplement->initializeConnection(connection);
310 }
311
312 void NetworkProcess::createNetworkConnectionToWebProcess()
313 {
314 #if USE(UNIX_DOMAIN_SOCKETS)
315     IPC::Connection::SocketPair socketPair = IPC::Connection::createPlatformConnection();
316
317     auto connection = NetworkConnectionToWebProcess::create(socketPair.server);
318     m_webProcessConnections.append(WTFMove(connection));
319
320     IPC::Attachment clientSocket(socketPair.client);
321     parentProcessConnection()->send(Messages::NetworkProcessProxy::DidCreateNetworkConnectionToWebProcess(clientSocket), 0);
322 #elif OS(DARWIN)
323     // Create the listening port.
324     mach_port_t listeningPort = MACH_PORT_NULL;
325     auto kr = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &listeningPort);
326     if (kr != KERN_SUCCESS) {
327         LOG_ERROR("Could not allocate mach port, error %x", kr);
328         CRASH();
329     }
330
331     // Create a listening connection.
332     auto connection = NetworkConnectionToWebProcess::create(IPC::Connection::Identifier(listeningPort));
333     m_webProcessConnections.append(WTFMove(connection));
334
335     IPC::Attachment clientPort(listeningPort, MACH_MSG_TYPE_MAKE_SEND);
336     parentProcessConnection()->send(Messages::NetworkProcessProxy::DidCreateNetworkConnectionToWebProcess(clientPort), 0);
337 #elif OS(WINDOWS)
338     IPC::Connection::Identifier serverIdentifier, clientIdentifier;
339     if (!IPC::Connection::createServerAndClientIdentifiers(serverIdentifier, clientIdentifier))
340         return;
341
342     auto connection = NetworkConnectionToWebProcess::create(serverIdentifier);
343     m_webProcessConnections.append(WTFMove(connection));
344
345     IPC::Attachment clientSocket(clientIdentifier);
346     parentProcessConnection()->send(Messages::NetworkProcessProxy::DidCreateNetworkConnectionToWebProcess(clientSocket), 0);
347 #else
348     notImplemented();
349 #endif
350
351     if (!m_webProcessConnections.isEmpty())
352         m_webProcessConnections.last()->setOnLineState(NetworkStateNotifier::singleton().onLine());
353 }
354
355 void NetworkProcess::clearCachedCredentials()
356 {
357     NetworkStorageSession::defaultStorageSession().credentialStorage().clearCredentials();
358     if (auto* networkSession = SessionTracker::networkSession(PAL::SessionID::defaultSessionID()))
359         networkSession->clearCredentials();
360     else
361         ASSERT_NOT_REACHED();
362 }
363
364 void NetworkProcess::addWebsiteDataStore(WebsiteDataStoreParameters&& parameters)
365 {
366     RemoteNetworkingContext::ensureWebsiteDataStoreSession(WTFMove(parameters));
367 }
368
369 void NetworkProcess::destroySession(PAL::SessionID sessionID)
370 {
371     SessionTracker::destroySession(sessionID);
372     m_sessionsControlledByAutomation.remove(sessionID);
373 }
374
375 void NetworkProcess::grantSandboxExtensionsToStorageProcessForBlobs(const Vector<String>& filenames, Function<void ()>&& completionHandler)
376 {
377     static uint64_t lastRequestID;
378
379     uint64_t requestID = ++lastRequestID;
380     m_sandboxExtensionForBlobsCompletionHandlers.set(requestID, WTFMove(completionHandler));
381     parentProcessConnection()->send(Messages::NetworkProcessProxy::GrantSandboxExtensionsToStorageProcessForBlobs(requestID, filenames), 0);
382 }
383
384 void NetworkProcess::didGrantSandboxExtensionsToStorageProcessForBlobs(uint64_t requestID)
385 {
386     if (auto handler = m_sandboxExtensionForBlobsCompletionHandlers.take(requestID))
387         handler();
388 }
389
390 void NetworkProcess::writeBlobToFilePath(const WebCore::URL& url, const String& path, SandboxExtension::Handle&& handleForWriting, uint64_t requestID)
391 {
392     auto extension = SandboxExtension::create(WTFMove(handleForWriting));
393     if (!extension) {
394         parentProcessConnection()->send(Messages::NetworkProcessProxy::DidWriteBlobToFilePath(false, requestID), 0);
395         return;
396     }
397
398     extension->consume();
399     NetworkBlobRegistry::singleton().writeBlobToFilePath(url, path, [this, extension = WTFMove(extension), requestID] (bool success) {
400         extension->revoke();
401         parentProcessConnection()->send(Messages::NetworkProcessProxy::DidWriteBlobToFilePath(success, requestID), 0);
402     });
403 }
404
405 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
406 void NetworkProcess::updatePrevalentDomainsToPartitionOrBlockCookies(PAL::SessionID sessionID, const Vector<String>& domainsToPartition, const Vector<String>& domainsToBlock, const Vector<String>& domainsToNeitherPartitionNorBlock, bool shouldClearFirst)
407 {
408     if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
409         networkStorageSession->setPrevalentDomainsToPartitionOrBlockCookies(domainsToPartition, domainsToBlock, domainsToNeitherPartitionNorBlock, shouldClearFirst);
410 }
411
412 void NetworkProcess::hasStorageAccessForFrame(PAL::SessionID sessionID, const String& resourceDomain, const String& firstPartyDomain, uint64_t frameID, uint64_t pageID, uint64_t contextId)
413 {
414     if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
415         parentProcessConnection()->send(Messages::NetworkProcessProxy::StorageAccessRequestResult(networkStorageSession->hasStorageAccess(resourceDomain, firstPartyDomain, frameID, pageID), contextId), 0);
416     else
417         ASSERT_NOT_REACHED();
418 }
419
420 void NetworkProcess::getAllStorageAccessEntries(PAL::SessionID sessionID, uint64_t contextId)
421 {
422     if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
423         parentProcessConnection()->send(Messages::NetworkProcessProxy::AllStorageAccessEntriesResult(networkStorageSession->getAllStorageAccessEntries(), contextId), 0);
424     else
425         ASSERT_NOT_REACHED();
426 }
427
428 void NetworkProcess::grantStorageAccess(PAL::SessionID sessionID, const String& resourceDomain, const String& firstPartyDomain, std::optional<uint64_t> frameID, uint64_t pageID, uint64_t contextId)
429 {
430     bool isStorageGranted = false;
431     if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID)) {
432         networkStorageSession->grantStorageAccess(resourceDomain, firstPartyDomain, frameID, pageID);
433         ASSERT(networkStorageSession->hasStorageAccess(resourceDomain, firstPartyDomain, frameID, pageID));
434         isStorageGranted = true;
435     } else
436         ASSERT_NOT_REACHED();
437
438     parentProcessConnection()->send(Messages::NetworkProcessProxy::StorageAccessRequestResult(isStorageGranted, contextId), 0);
439 }
440
441 void NetworkProcess::removeAllStorageAccess(PAL::SessionID sessionID)
442 {
443     if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
444         networkStorageSession->removeAllStorageAccess();
445     else
446         ASSERT_NOT_REACHED();
447 }
448
449 void NetworkProcess::removePrevalentDomains(PAL::SessionID sessionID, const Vector<String>& domains)
450 {
451     if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
452         networkStorageSession->removePrevalentDomains(domains);
453 }
454 #endif
455
456 bool NetworkProcess::sessionIsControlledByAutomation(PAL::SessionID sessionID) const
457 {
458     return m_sessionsControlledByAutomation.contains(sessionID);
459 }
460
461 void NetworkProcess::setSessionIsControlledByAutomation(PAL::SessionID sessionID, bool controlled)
462 {
463     if (controlled)
464         m_sessionsControlledByAutomation.add(sessionID);
465     else
466         m_sessionsControlledByAutomation.remove(sessionID);
467 }
468
469 static void fetchDiskCacheEntries(PAL::SessionID sessionID, OptionSet<WebsiteDataFetchOption> fetchOptions, Function<void (Vector<WebsiteData::Entry>)>&& completionHandler)
470 {
471     if (auto* cache = NetworkProcess::singleton().cache()) {
472         HashMap<SecurityOriginData, uint64_t> originsAndSizes;
473         cache->traverse([fetchOptions, completionHandler = WTFMove(completionHandler), originsAndSizes = WTFMove(originsAndSizes)](auto* traversalEntry) mutable {
474             if (!traversalEntry) {
475                 Vector<WebsiteData::Entry> entries;
476
477                 for (auto& originAndSize : originsAndSizes)
478                     entries.append(WebsiteData::Entry { originAndSize.key, WebsiteDataType::DiskCache, originAndSize.value });
479
480                 RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler), entries = WTFMove(entries)] {
481                     completionHandler(entries);
482                 });
483
484                 return;
485             }
486
487             auto url = traversalEntry->entry.response().url();
488             auto result = originsAndSizes.add({url.protocol().toString(), url.host(), url.port()}, 0);
489
490             if (fetchOptions.contains(WebsiteDataFetchOption::ComputeSizes))
491                 result.iterator->value += traversalEntry->entry.sourceStorageRecord().header.size() + traversalEntry->recordInfo.bodySize;
492         });
493
494         return;
495     }
496
497     RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler)] {
498         completionHandler({ });
499     });
500 }
501
502 void NetworkProcess::fetchWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, OptionSet<WebsiteDataFetchOption> fetchOptions, uint64_t callbackID)
503 {
504     struct CallbackAggregator final : public RefCounted<CallbackAggregator> {
505         explicit CallbackAggregator(Function<void (WebsiteData)>&& completionHandler)
506             : m_completionHandler(WTFMove(completionHandler))
507         {
508         }
509
510         ~CallbackAggregator()
511         {
512             ASSERT(RunLoop::isMain());
513
514             RunLoop::main().dispatch([completionHandler = WTFMove(m_completionHandler), websiteData = WTFMove(m_websiteData)] {
515                 completionHandler(websiteData);
516             });
517         }
518
519         Function<void (WebsiteData)> m_completionHandler;
520         WebsiteData m_websiteData;
521     };
522
523     auto callbackAggregator = adoptRef(*new CallbackAggregator([this, callbackID] (WebsiteData websiteData) {
524         parentProcessConnection()->send(Messages::NetworkProcessProxy::DidFetchWebsiteData(callbackID, websiteData), 0);
525     }));
526
527     if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
528         if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
529             getHostnamesWithCookies(*networkStorageSession, callbackAggregator->m_websiteData.hostNamesWithCookies);
530     }
531
532     if (websiteDataTypes.contains(WebsiteDataType::Credentials)) {
533         if (NetworkStorageSession::storageSession(sessionID))
534             callbackAggregator->m_websiteData.originsWithCredentials = NetworkStorageSession::storageSession(sessionID)->credentialStorage().originsWithCredentials();
535     }
536
537     if (websiteDataTypes.contains(WebsiteDataType::DOMCache)) {
538         CacheStorage::Engine::fetchEntries(sessionID, fetchOptions.contains(WebsiteDataFetchOption::ComputeSizes), [callbackAggregator = callbackAggregator.copyRef()](auto entries) mutable {
539             callbackAggregator->m_websiteData.entries.appendVector(entries);
540         });
541     }
542
543     if (websiteDataTypes.contains(WebsiteDataType::DiskCache)) {
544         fetchDiskCacheEntries(sessionID, fetchOptions, [callbackAggregator = WTFMove(callbackAggregator)](auto entries) mutable {
545             callbackAggregator->m_websiteData.entries.appendVector(entries);
546         });
547     }
548 }
549
550 void NetworkProcess::deleteWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, WallTime modifiedSince, uint64_t callbackID)
551 {
552 #if PLATFORM(COCOA)
553     if (websiteDataTypes.contains(WebsiteDataType::HSTSCache)) {
554         if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
555             clearHSTSCache(*networkStorageSession, modifiedSince);
556     }
557 #endif
558
559     if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
560         if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
561             deleteAllCookiesModifiedSince(*networkStorageSession, modifiedSince);
562     }
563
564     if (websiteDataTypes.contains(WebsiteDataType::Credentials)) {
565         if (NetworkStorageSession::storageSession(sessionID))
566             NetworkStorageSession::storageSession(sessionID)->credentialStorage().clearCredentials();
567     }
568
569     auto clearTasksHandler = WTF::CallbackAggregator::create([this, callbackID] {
570         parentProcessConnection()->send(Messages::NetworkProcessProxy::DidDeleteWebsiteData(callbackID), 0);
571     });
572
573     if (websiteDataTypes.contains(WebsiteDataType::DOMCache))
574         CacheStorage::Engine::from(sessionID).clearAllCaches(clearTasksHandler);
575
576     if (websiteDataTypes.contains(WebsiteDataType::DiskCache) && !sessionID.isEphemeral())
577         clearDiskCache(modifiedSince, [clearTasksHandler = WTFMove(clearTasksHandler)] { });
578 }
579
580 static void clearDiskCacheEntries(const Vector<SecurityOriginData>& origins, Function<void ()>&& completionHandler)
581 {
582     if (auto* cache = NetworkProcess::singleton().cache()) {
583         HashSet<RefPtr<SecurityOrigin>> originsToDelete;
584         for (auto& origin : origins)
585             originsToDelete.add(origin.securityOrigin());
586
587         Vector<NetworkCache::Key> cacheKeysToDelete;
588         cache->traverse([cache, completionHandler = WTFMove(completionHandler), originsToDelete = WTFMove(originsToDelete), cacheKeysToDelete = WTFMove(cacheKeysToDelete)](auto* traversalEntry) mutable {
589             if (traversalEntry) {
590                 if (originsToDelete.contains(SecurityOrigin::create(traversalEntry->entry.response().url())))
591                     cacheKeysToDelete.append(traversalEntry->entry.key());
592                 return;
593             }
594
595             cache->remove(cacheKeysToDelete, WTFMove(completionHandler));
596             return;
597         });
598
599         return;
600     }
601
602     RunLoop::main().dispatch(WTFMove(completionHandler));
603 }
604
605 void NetworkProcess::deleteWebsiteDataForOrigins(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, const Vector<SecurityOriginData>& originDatas, const Vector<String>& cookieHostNames, uint64_t callbackID)
606 {
607     if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
608         if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
609             deleteCookiesForHostnames(*networkStorageSession, cookieHostNames);
610     }
611
612     auto clearTasksHandler = WTF::CallbackAggregator::create([this, callbackID] {
613         parentProcessConnection()->send(Messages::NetworkProcessProxy::DidDeleteWebsiteDataForOrigins(callbackID), 0);
614     });
615
616     if (websiteDataTypes.contains(WebsiteDataType::DOMCache)) {
617         for (auto& originData : originDatas)
618             CacheStorage::Engine::from(sessionID).clearCachesForOrigin(originData, clearTasksHandler);
619     }
620
621     if (websiteDataTypes.contains(WebsiteDataType::DiskCache) && !sessionID.isEphemeral())
622         clearDiskCacheEntries(originDatas, [clearTasksHandler = WTFMove(clearTasksHandler)] { });
623 }
624
625 void NetworkProcess::downloadRequest(PAL::SessionID sessionID, DownloadID downloadID, const ResourceRequest& request, const String& suggestedFilename)
626 {
627     downloadManager().startDownload(nullptr, sessionID, downloadID, request, suggestedFilename);
628 }
629
630 void NetworkProcess::resumeDownload(PAL::SessionID sessionID, DownloadID downloadID, const IPC::DataReference& resumeData, const String& path, WebKit::SandboxExtension::Handle&& sandboxExtensionHandle)
631 {
632     downloadManager().resumeDownload(sessionID, downloadID, resumeData, path, WTFMove(sandboxExtensionHandle));
633 }
634
635 void NetworkProcess::cancelDownload(DownloadID downloadID)
636 {
637     downloadManager().cancelDownload(downloadID);
638 }
639     
640 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
641 static uint64_t generateCanAuthenticateIdentifier()
642 {
643     static uint64_t lastLoaderID = 0;
644     return ++lastLoaderID;
645 }
646
647 void NetworkProcess::canAuthenticateAgainstProtectionSpace(NetworkResourceLoader& loader, const WebCore::ProtectionSpace& protectionSpace)
648 {
649     uint64_t loaderID = generateCanAuthenticateIdentifier();
650     m_waitingNetworkResourceLoaders.set(loaderID, loader);
651     parentProcessConnection()->send(Messages::NetworkProcessProxy::CanAuthenticateAgainstProtectionSpace(loaderID, loader.pageID(), loader.frameID(), protectionSpace), 0);
652 }
653
654 #if ENABLE(SERVER_PRECONNECT)
655 void NetworkProcess::canAuthenticateAgainstProtectionSpace(PreconnectTask& preconnectTask, const WebCore::ProtectionSpace& protectionSpace)
656 {
657     uint64_t loaderID = generateCanAuthenticateIdentifier();
658     m_waitingPreconnectTasks.set(loaderID, preconnectTask.createWeakPtr());
659     parentProcessConnection()->send(Messages::NetworkProcessProxy::CanAuthenticateAgainstProtectionSpace(loaderID, preconnectTask.pageID(), preconnectTask.frameID(), protectionSpace), 0);
660 }
661 #endif
662
663 void NetworkProcess::continueCanAuthenticateAgainstProtectionSpace(uint64_t loaderID, bool canAuthenticate)
664 {
665     if (auto resourceLoader = m_waitingNetworkResourceLoaders.take(loaderID)) {
666         resourceLoader.value()->continueCanAuthenticateAgainstProtectionSpace(canAuthenticate);
667         return;
668     }
669 #if ENABLE(SERVER_PRECONNECT)
670     if (auto preconnectTask = m_waitingPreconnectTasks.take(loaderID)) {
671         preconnectTask->continueCanAuthenticateAgainstProtectionSpace(canAuthenticate);
672         return;
673     }
674 #endif
675 }
676
677 #endif
678
679 void NetworkProcess::continueWillSendRequest(DownloadID downloadID, WebCore::ResourceRequest&& request)
680 {
681     downloadManager().continueWillSendRequest(downloadID, WTFMove(request));
682 }
683
684 void NetworkProcess::pendingDownloadCanceled(DownloadID downloadID)
685 {
686     downloadProxyConnection()->send(Messages::DownloadProxy::DidCancel({ }), downloadID.downloadID());
687 }
688
689 void NetworkProcess::findPendingDownloadLocation(NetworkDataTask& networkDataTask, ResponseCompletionHandler&& completionHandler, const ResourceResponse& response)
690 {
691     uint64_t destinationID = networkDataTask.pendingDownloadID().downloadID();
692     downloadProxyConnection()->send(Messages::DownloadProxy::DidReceiveResponse(response), destinationID);
693
694     downloadManager().willDecidePendingDownloadDestination(networkDataTask, WTFMove(completionHandler));
695
696     // As per https://html.spec.whatwg.org/#as-a-download (step 2), the filename from the Content-Disposition header
697     // should override the suggested filename from the download attribute.
698     String suggestedFilename = response.isAttachmentWithFilename() ? response.suggestedFilename() : networkDataTask.suggestedFilename();
699     suggestedFilename = MIMETypeRegistry::appendFileExtensionIfNecessary(suggestedFilename, response.mimeType());
700
701     downloadProxyConnection()->send(Messages::DownloadProxy::DecideDestinationWithSuggestedFilenameAsync(networkDataTask.pendingDownloadID(), suggestedFilename), destinationID);
702 }
703
704 void NetworkProcess::continueDecidePendingDownloadDestination(DownloadID downloadID, String destination, SandboxExtension::Handle&& sandboxExtensionHandle, bool allowOverwrite)
705 {
706     if (destination.isEmpty())
707         downloadManager().cancelDownload(downloadID);
708     else
709         downloadManager().continueDecidePendingDownloadDestination(downloadID, destination, WTFMove(sandboxExtensionHandle), allowOverwrite);
710 }
711
712 void NetworkProcess::setCacheModel(uint32_t cm)
713 {
714     CacheModel cacheModel = static_cast<CacheModel>(cm);
715
716     if (m_hasSetCacheModel && (cacheModel == m_cacheModel))
717         return;
718
719     m_hasSetCacheModel = true;
720     m_cacheModel = cacheModel;
721
722     unsigned urlCacheMemoryCapacity = 0;
723     uint64_t urlCacheDiskCapacity = 0;
724     uint64_t diskFreeSize = 0;
725     if (WebCore::FileSystem::getVolumeFreeSpace(m_diskCacheDirectory, diskFreeSize)) {
726         // As a fudge factor, use 1000 instead of 1024, in case the reported byte
727         // count doesn't align exactly to a megabyte boundary.
728         diskFreeSize /= KB * 1000;
729         calculateURLCacheSizes(cacheModel, diskFreeSize, urlCacheMemoryCapacity, urlCacheDiskCapacity);
730     }
731
732     if (m_diskCacheSizeOverride >= 0)
733         urlCacheDiskCapacity = m_diskCacheSizeOverride;
734
735     if (m_cache) {
736         m_cache->setCapacity(urlCacheDiskCapacity);
737         return;
738     }
739
740     platformSetURLCacheSize(urlCacheMemoryCapacity, urlCacheDiskCapacity);
741 }
742
743 void NetworkProcess::setCanHandleHTTPSServerTrustEvaluation(bool value)
744 {
745     m_canHandleHTTPSServerTrustEvaluation = value;
746 }
747
748 void NetworkProcess::getNetworkProcessStatistics(uint64_t callbackID)
749 {
750     StatisticsData data;
751
752     auto& networkProcess = NetworkProcess::singleton();
753     data.statisticsNumbers.set("DownloadsActiveCount", networkProcess.downloadManager().activeDownloadCount());
754     data.statisticsNumbers.set("OutstandingAuthenticationChallengesCount", networkProcess.authenticationManager().outstandingAuthenticationChallengeCount());
755
756     parentProcessConnection()->send(Messages::WebProcessPool::DidGetStatistics(data, callbackID), 0);
757 }
758
759 void NetworkProcess::setAllowsAnySSLCertificateForWebSocket(bool allows)
760 {
761     DeprecatedGlobalSettings::setAllowsAnySSLCertificate(allows);
762 }
763
764 void NetworkProcess::logDiagnosticMessage(uint64_t webPageID, const String& message, const String& description, ShouldSample shouldSample)
765 {
766     if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
767         return;
768
769     parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessage(webPageID, message, description, ShouldSample::No), 0);
770 }
771
772 void NetworkProcess::logDiagnosticMessageWithResult(uint64_t webPageID, const String& message, const String& description, DiagnosticLoggingResultType result, ShouldSample shouldSample)
773 {
774     if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
775         return;
776
777     parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessageWithResult(webPageID, message, description, result, ShouldSample::No), 0);
778 }
779
780 void NetworkProcess::logDiagnosticMessageWithValue(uint64_t webPageID, const String& message, const String& description, double value, unsigned significantFigures, ShouldSample shouldSample)
781 {
782     if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
783         return;
784
785     parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessageWithValue(webPageID, message, description, value, significantFigures, ShouldSample::No), 0);
786 }
787
788 void NetworkProcess::terminate()
789 {
790 #if ENABLE(NETWORK_CAPTURE)
791     NetworkCapture::Manager::singleton().terminate();
792 #endif
793
794     platformTerminate();
795     ChildProcess::terminate();
796 }
797
798 // FIXME: We can remove this one by adapting RefCounter.
799 class TaskCounter : public RefCounted<TaskCounter> {
800 public:
801     explicit TaskCounter(Function<void()>&& callback) : m_callback(WTFMove(callback)) { }
802     ~TaskCounter() { m_callback(); };
803
804 private:
805     Function<void()> m_callback;
806 };
807
808 void NetworkProcess::actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend shouldAcknowledgeWhenReadyToSuspend)
809 {
810     lowMemoryHandler(Critical::Yes);
811
812     RefPtr<TaskCounter> delayedTaskCounter;
813     if (shouldAcknowledgeWhenReadyToSuspend == ShouldAcknowledgeWhenReadyToSuspend::Yes) {
814         delayedTaskCounter = adoptRef(new TaskCounter([this] {
815             RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::notifyProcessReadyToSuspend() Sending ProcessReadyToSuspend IPC message", this);
816             if (parentProcessConnection())
817                 parentProcessConnection()->send(Messages::NetworkProcessProxy::ProcessReadyToSuspend(), 0);
818         }));
819     }
820
821     for (auto& connection : m_webProcessConnections)
822         connection->cleanupForSuspension([delayedTaskCounter] { });
823 }
824
825 void NetworkProcess::processWillSuspendImminently(bool& handled)
826 {
827     actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend::No);
828     handled = true;
829 }
830
831 void NetworkProcess::prepareToSuspend()
832 {
833     RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::prepareToSuspend()", this);
834     actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend::Yes);
835 }
836
837 void NetworkProcess::cancelPrepareToSuspend()
838 {
839     // Although it is tempting to send a NetworkProcessProxy::DidCancelProcessSuspension message from here
840     // we do not because prepareToSuspend() already replied with a NetworkProcessProxy::ProcessReadyToSuspend
841     // message. And NetworkProcessProxy expects to receive either a NetworkProcessProxy::ProcessReadyToSuspend-
842     // or NetworkProcessProxy::DidCancelProcessSuspension- message, but not both.
843     RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::cancelPrepareToSuspend()", this);
844     for (auto& connection : m_webProcessConnections)
845         connection->endSuspension();
846 }
847
848 void NetworkProcess::processDidResume()
849 {
850     RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::processDidResume()", this);
851     for (auto& connection : m_webProcessConnections)
852         connection->endSuspension();
853 }
854
855 void NetworkProcess::prefetchDNS(const String& hostname)
856 {
857     WebCore::prefetchDNS(hostname);
858 }
859
860 String NetworkProcess::cacheStorageDirectory(PAL::SessionID sessionID) const
861 {
862     if (sessionID.isEphemeral())
863         return { };
864
865     if (sessionID == PAL::SessionID::defaultSessionID())
866         return m_cacheStorageDirectory;
867
868     auto* session = NetworkStorageSession::storageSession(sessionID);
869     if (!session)
870         return { };
871
872     return session->cacheStorageDirectory();
873 }
874
875 void NetworkProcess::preconnectTo(const WebCore::URL& url, WebCore::StoredCredentialsPolicy storedCredentialsPolicy)
876 {
877 #if ENABLE(SERVER_PRECONNECT)
878     NetworkLoadParameters parameters;
879     parameters.request = ResourceRequest { url };
880     parameters.sessionID = PAL::SessionID::defaultSessionID();
881     parameters.storedCredentialsPolicy = storedCredentialsPolicy;
882     parameters.shouldPreconnectOnly = PreconnectOnly::Yes;
883
884     new PreconnectTask(WTFMove(parameters));
885 #else
886     UNUSED_PARAM(url);
887     UNUSED_PARAM(storedCredentialsPolicy);
888 #endif
889 }
890
891 uint64_t NetworkProcess::cacheStoragePerOriginQuota() const
892 {
893     return m_cacheStoragePerOriginQuota;
894 }
895
896 void NetworkProcess::registerURLSchemeAsSecure(const String& scheme) const
897 {
898     SchemeRegistry::registerURLSchemeAsSecure(scheme);
899 }
900
901 void NetworkProcess::registerURLSchemeAsBypassingContentSecurityPolicy(const String& scheme) const
902 {
903     SchemeRegistry::registerURLSchemeAsBypassingContentSecurityPolicy(scheme);
904 }
905
906 void NetworkProcess::registerURLSchemeAsLocal(const String& scheme) const
907 {
908     SchemeRegistry::registerURLSchemeAsLocal(scheme);
909 }
910
911 void NetworkProcess::registerURLSchemeAsNoAccess(const String& scheme) const
912 {
913     SchemeRegistry::registerURLSchemeAsNoAccess(scheme);
914 }
915
916 void NetworkProcess::registerURLSchemeAsDisplayIsolated(const String& scheme) const
917 {
918     SchemeRegistry::registerURLSchemeAsDisplayIsolated(scheme);
919 }
920
921 void NetworkProcess::registerURLSchemeAsCORSEnabled(const String& scheme) const
922 {
923     SchemeRegistry::registerURLSchemeAsCORSEnabled(scheme);
924 }
925
926 void NetworkProcess::registerURLSchemeAsCanDisplayOnlyIfCanRequest(const String& scheme) const
927 {
928     SchemeRegistry::registerAsCanDisplayOnlyIfCanRequest(scheme);
929 }
930
931 #if !PLATFORM(COCOA)
932 void NetworkProcess::initializeProcess(const ChildProcessInitializationParameters&)
933 {
934 }
935
936 void NetworkProcess::initializeProcessName(const ChildProcessInitializationParameters&)
937 {
938 }
939
940 void NetworkProcess::initializeSandbox(const ChildProcessInitializationParameters&, SandboxInitializationParameters&)
941 {
942 }
943
944 void NetworkProcess::syncAllCookies()
945 {
946 }
947
948 #endif
949
950 } // namespace WebKit