Deny third-party cookie creation for prevalent resources without interaction
[WebKit-https.git] / Source / WebKit / NetworkProcess / NetworkProcess.cpp
1 /*
2  * Copyright (C) 2012-2017 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
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.
12  *
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.
24  */
25
26 #include "config.h"
27 #include "NetworkProcess.h"
28
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"
36 #include "Logging.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>
70
71 #if ENABLE(SEC_ITEM_SHIM)
72 #include "SecItemShim.h"
73 #endif
74
75 #if ENABLE(NETWORK_CACHE)
76 #include "NetworkCache.h"
77 #include "NetworkCacheCoders.h"
78 #endif
79
80 #if ENABLE(NETWORK_CAPTURE)
81 #include "NetworkCaptureManager.h"
82 #endif
83
84 #if PLATFORM(COCOA)
85 #include "NetworkSessionCocoa.h"
86 #endif
87
88 using namespace WebCore;
89
90 namespace WebKit {
91
92 NetworkProcess& NetworkProcess::singleton()
93 {
94     static NeverDestroyed<NetworkProcess> networkProcess;
95     return networkProcess;
96 }
97
98 NetworkProcess::NetworkProcess()
99     : m_hasSetCacheModel(false)
100     , m_cacheModel(CacheModelDocumentViewer)
101     , m_diskCacheIsDisabledForTesting(false)
102     , m_canHandleHTTPSServerTrustEvaluation(true)
103 #if PLATFORM(COCOA)
104     , m_clearCacheDispatchGroup(0)
105 #endif
106 #if PLATFORM(IOS)
107     , m_webSQLiteDatabaseTracker(*this)
108 #endif
109 {
110     NetworkProcessPlatformStrategies::initialize();
111
112     addSupplement<AuthenticationManager>();
113     addSupplement<WebCookieManager>();
114     addSupplement<LegacyCustomProtocolManager>();
115 #if USE(NETWORK_SESSION) && PLATFORM(COCOA)
116     NetworkSessionCocoa::setLegacyCustomProtocolManager(supplement<LegacyCustomProtocolManager>());
117 #endif
118 }
119
120 NetworkProcess::~NetworkProcess()
121 {
122 }
123
124 AuthenticationManager& NetworkProcess::authenticationManager()
125 {
126     return *supplement<AuthenticationManager>();
127 }
128
129 DownloadManager& NetworkProcess::downloadManager()
130 {
131     static NeverDestroyed<DownloadManager> downloadManager(*this);
132     return downloadManager;
133 }
134
135 void NetworkProcess::removeNetworkConnectionToWebProcess(NetworkConnectionToWebProcess* connection)
136 {
137     size_t vectorIndex = m_webProcessConnections.find(connection);
138     ASSERT(vectorIndex != notFound);
139
140     m_webProcessConnections.remove(vectorIndex);
141 }
142
143 bool NetworkProcess::shouldTerminate()
144 {
145     // Network process keeps session cookies and credentials, so it should never terminate (as long as UI process connection is alive).
146     return false;
147 }
148
149 void NetworkProcess::didReceiveMessage(IPC::Connection& connection, IPC::Decoder& decoder)
150 {
151     if (messageReceiverMap().dispatchMessage(connection, decoder))
152         return;
153
154     if (decoder.messageReceiverName() == Messages::ChildProcess::messageReceiverName()) {
155         ChildProcess::didReceiveMessage(connection, decoder);
156         return;
157     }
158
159     didReceiveNetworkProcessMessage(connection, decoder);
160 }
161
162 void NetworkProcess::didReceiveSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
163 {
164     if (messageReceiverMap().dispatchSyncMessage(connection, decoder, replyEncoder))
165         return;
166
167     didReceiveSyncNetworkProcessMessage(connection, decoder, replyEncoder);
168 }
169
170 void NetworkProcess::didClose(IPC::Connection&)
171 {
172     // The UIProcess just exited.
173     stopRunLoop();
174 }
175
176 void NetworkProcess::didCreateDownload()
177 {
178     disableTermination();
179 }
180
181 void NetworkProcess::didDestroyDownload()
182 {
183     enableTermination();
184 }
185
186 IPC::Connection* NetworkProcess::downloadProxyConnection()
187 {
188     return parentProcessConnection();
189 }
190
191 AuthenticationManager& NetworkProcess::downloadsAuthenticationManager()
192 {
193     return authenticationManager();
194 }
195
196 void NetworkProcess::lowMemoryHandler(Critical critical)
197 {
198     if (m_suppressMemoryPressureHandler)
199         return;
200
201     WTF::releaseFastMallocFreeMemory();
202 }
203
204 void NetworkProcess::initializeNetworkProcess(NetworkProcessCreationParameters&& parameters)
205 {
206     WebCore::setPresentingApplicationPID(parameters.presentingApplicationPID);
207     platformInitializeNetworkProcess(parameters);
208
209     WTF::Thread::setCurrentThreadIsUserInitiated();
210
211     m_suppressMemoryPressureHandler = parameters.shouldSuppressMemoryPressureHandler;
212     m_loadThrottleLatency = parameters.loadThrottleLatency;
213     if (!m_suppressMemoryPressureHandler) {
214         auto& memoryPressureHandler = MemoryPressureHandler::singleton();
215 #if OS(LINUX)
216         if (parameters.memoryPressureMonitorHandle.fileDescriptor() != -1)
217             memoryPressureHandler.setMemoryPressureMonitorHandle(parameters.memoryPressureMonitorHandle.releaseFileDescriptor());
218 #endif
219         memoryPressureHandler.setLowMemoryHandler([this] (Critical critical, Synchronous) {
220             lowMemoryHandler(critical);
221         });
222         memoryPressureHandler.install();
223     }
224
225 #if ENABLE(NETWORK_CAPTURE)
226     NetworkCapture::Manager::singleton().initialize(
227         parameters.recordReplayMode,
228         parameters.recordReplayCacheLocation);
229 #endif
230
231     m_diskCacheIsDisabledForTesting = parameters.shouldUseTestingNetworkSession;
232
233     m_diskCacheSizeOverride = parameters.diskCacheSizeOverride;
234     setCacheModel(static_cast<uint32_t>(parameters.cacheModel));
235
236     setCanHandleHTTPSServerTrustEvaluation(parameters.canHandleHTTPSServerTrustEvaluation);
237
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(), { }, { }, { }, { }, { }});
241
242     if (parameters.shouldUseTestingNetworkSession)
243         NetworkStorageSession::switchToNewTestingSession();
244
245     for (auto& supplement : m_supplements.values())
246         supplement->initialize(parameters);
247 }
248
249 void NetworkProcess::initializeConnection(IPC::Connection* connection)
250 {
251     ChildProcess::initializeConnection(connection);
252
253     for (auto& supplement : m_supplements.values())
254         supplement->initializeConnection(connection);
255 }
256
257 void NetworkProcess::createNetworkConnectionToWebProcess()
258 {
259 #if USE(UNIX_DOMAIN_SOCKETS)
260     IPC::Connection::SocketPair socketPair = IPC::Connection::createPlatformConnection();
261
262     auto connection = NetworkConnectionToWebProcess::create(socketPair.server);
263     m_webProcessConnections.append(WTFMove(connection));
264
265     IPC::Attachment clientSocket(socketPair.client);
266     parentProcessConnection()->send(Messages::NetworkProcessProxy::DidCreateNetworkConnectionToWebProcess(clientSocket), 0);
267 #elif OS(DARWIN)
268     // Create the listening port.
269     mach_port_t listeningPort;
270     mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &listeningPort);
271
272     // Create a listening connection.
273     auto connection = NetworkConnectionToWebProcess::create(IPC::Connection::Identifier(listeningPort));
274     m_webProcessConnections.append(WTFMove(connection));
275
276     IPC::Attachment clientPort(listeningPort, MACH_MSG_TYPE_MAKE_SEND);
277     parentProcessConnection()->send(Messages::NetworkProcessProxy::DidCreateNetworkConnectionToWebProcess(clientPort), 0);
278 #else
279     notImplemented();
280 #endif
281 }
282
283 void NetworkProcess::clearCachedCredentials()
284 {
285     NetworkStorageSession::defaultStorageSession().credentialStorage().clearCredentials();
286 #if USE(NETWORK_SESSION)
287     NetworkSession::defaultSession().clearCredentials();
288 #endif
289 }
290
291 void NetworkProcess::ensurePrivateBrowsingSession(WebsiteDataStoreParameters&& parameters)
292 {
293     RemoteNetworkingContext::ensurePrivateBrowsingSession(WTFMove(parameters));
294 }
295
296 void NetworkProcess::addWebsiteDataStore(WebsiteDataStoreParameters&& parameters)
297 {
298     RemoteNetworkingContext::ensureWebsiteDataStoreSession(WTFMove(parameters));
299 }
300
301 void NetworkProcess::destroySession(PAL::SessionID sessionID)
302 {
303     SessionTracker::destroySession(sessionID);
304 }
305
306 void NetworkProcess::grantSandboxExtensionsToStorageProcessForBlobs(const Vector<String>& filenames, Function<void ()>&& completionHandler)
307 {
308     static uint64_t lastRequestID;
309
310     uint64_t requestID = ++lastRequestID;
311     m_sandboxExtensionForBlobsCompletionHandlers.set(requestID, WTFMove(completionHandler));
312     parentProcessConnection()->send(Messages::NetworkProcessProxy::GrantSandboxExtensionsToStorageProcessForBlobs(requestID, filenames), 0);
313 }
314
315 void NetworkProcess::didGrantSandboxExtensionsToStorageProcessForBlobs(uint64_t requestID)
316 {
317     if (auto handler = m_sandboxExtensionForBlobsCompletionHandlers.take(requestID))
318         handler();
319 }
320
321 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
322 void NetworkProcess::updatePrevalentDomainsWithAndWithoutInteraction(PAL::SessionID sessionID, const Vector<String>& domainsWithInteraction, const Vector<String>& domainsWithoutInteraction, bool shouldClearFirst)
323 {
324     if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
325         networkStorageSession->setPrevalentDomainsWithAndWithoutInteraction(domainsWithInteraction, domainsWithoutInteraction, shouldClearFirst);
326 }
327
328 void NetworkProcess::removePrevalentDomains(PAL::SessionID sessionID, const Vector<String>& domains)
329 {
330     if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
331         networkStorageSession->removePrevalentDomains(domains);
332 }
333 #endif
334
335 static void fetchDiskCacheEntries(PAL::SessionID sessionID, OptionSet<WebsiteDataFetchOption> fetchOptions, Function<void (Vector<WebsiteData::Entry>)>&& completionHandler)
336 {
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;
343
344                 for (auto& originAndSize : originsAndSizes)
345                     entries.append(WebsiteData::Entry { originAndSize.key, WebsiteDataType::DiskCache, originAndSize.value });
346
347                 RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler), entries = WTFMove(entries)] {
348                     completionHandler(entries);
349                 });
350
351                 return;
352             }
353
354             auto url = traversalEntry->entry.response().url();
355             auto result = originsAndSizes.add({url.protocol().toString(), url.host(), url.port()}, 0);
356
357             if (fetchOptions.contains(WebsiteDataFetchOption::ComputeSizes))
358                 result.iterator->value += traversalEntry->entry.sourceStorageRecord().header.size() + traversalEntry->recordInfo.bodySize;
359         });
360
361         return;
362     }
363 #endif
364
365     RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler)] {
366         completionHandler({ });
367     });
368 }
369
370 void NetworkProcess::fetchWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, OptionSet<WebsiteDataFetchOption> fetchOptions, uint64_t callbackID)
371 {
372     struct CallbackAggregator final : public RefCounted<CallbackAggregator> {
373         explicit CallbackAggregator(Function<void (WebsiteData)>&& completionHandler)
374             : m_completionHandler(WTFMove(completionHandler))
375         {
376         }
377
378         ~CallbackAggregator()
379         {
380             ASSERT(RunLoop::isMain());
381
382             RunLoop::main().dispatch([completionHandler = WTFMove(m_completionHandler), websiteData = WTFMove(m_websiteData)] {
383                 completionHandler(websiteData);
384             });
385         }
386
387         Function<void (WebsiteData)> m_completionHandler;
388         WebsiteData m_websiteData;
389     };
390
391     auto callbackAggregator = adoptRef(*new CallbackAggregator([this, callbackID] (WebsiteData websiteData) {
392         parentProcessConnection()->send(Messages::NetworkProcessProxy::DidFetchWebsiteData(callbackID, websiteData), 0);
393     }));
394
395     if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
396         if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
397             getHostnamesWithCookies(*networkStorageSession, callbackAggregator->m_websiteData.hostNamesWithCookies);
398     }
399
400     if (websiteDataTypes.contains(WebsiteDataType::Credentials)) {
401         if (NetworkStorageSession::storageSession(sessionID))
402             callbackAggregator->m_websiteData.originsWithCredentials = NetworkStorageSession::storageSession(sessionID)->credentialStorage().originsWithCredentials();
403     }
404
405     if (websiteDataTypes.contains(WebsiteDataType::DiskCache)) {
406         fetchDiskCacheEntries(sessionID, fetchOptions, [callbackAggregator = WTFMove(callbackAggregator)](auto entries) mutable {
407             callbackAggregator->m_websiteData.entries.appendVector(entries);
408         });
409     }
410 }
411
412 void NetworkProcess::deleteWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, std::chrono::system_clock::time_point modifiedSince, uint64_t callbackID)
413 {
414 #if PLATFORM(COCOA)
415     if (websiteDataTypes.contains(WebsiteDataType::HSTSCache)) {
416         if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
417             clearHSTSCache(*networkStorageSession, modifiedSince);
418     }
419 #endif
420
421     if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
422         if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
423             deleteAllCookiesModifiedSince(*networkStorageSession, modifiedSince);
424     }
425
426     if (websiteDataTypes.contains(WebsiteDataType::Credentials)) {
427         if (NetworkStorageSession::storageSession(sessionID))
428             NetworkStorageSession::storageSession(sessionID)->credentialStorage().clearCredentials();
429     }
430     
431     auto completionHandler = [this, callbackID] {
432         parentProcessConnection()->send(Messages::NetworkProcessProxy::DidDeleteWebsiteData(callbackID), 0);
433     };
434
435     if (websiteDataTypes.contains(WebsiteDataType::DiskCache) && !sessionID.isEphemeral()) {
436         clearDiskCache(modifiedSince, WTFMove(completionHandler));
437         return;
438     }
439
440     completionHandler();
441 }
442
443 static void clearDiskCacheEntries(const Vector<SecurityOriginData>& origins, Function<void ()>&& completionHandler)
444 {
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());
450
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());
456                 return;
457             }
458
459             cache->remove(cacheKeysToDelete, WTFMove(completionHandler));
460             return;
461         });
462
463         return;
464     }
465 #endif
466
467     RunLoop::main().dispatch(WTFMove(completionHandler));
468 }
469
470 void NetworkProcess::deleteWebsiteDataForOrigins(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, const Vector<SecurityOriginData>& origins, const Vector<String>& cookieHostNames, uint64_t callbackID)
471 {
472     if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
473         if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
474             deleteCookiesForHostnames(*networkStorageSession, cookieHostNames);
475     }
476
477     auto completionHandler = [this, callbackID] {
478         parentProcessConnection()->send(Messages::NetworkProcessProxy::DidDeleteWebsiteDataForOrigins(callbackID), 0);
479     };
480
481     if (websiteDataTypes.contains(WebsiteDataType::DiskCache) && !sessionID.isEphemeral()) {
482         clearDiskCacheEntries(origins, WTFMove(completionHandler));
483         return;
484     }
485
486     completionHandler();
487 }
488
489 void NetworkProcess::downloadRequest(PAL::SessionID sessionID, DownloadID downloadID, const ResourceRequest& request, const String& suggestedFilename)
490 {
491     downloadManager().startDownload(nullptr, sessionID, downloadID, request, suggestedFilename);
492 }
493
494 void NetworkProcess::resumeDownload(PAL::SessionID sessionID, DownloadID downloadID, const IPC::DataReference& resumeData, const String& path, const WebKit::SandboxExtension::Handle& sandboxExtensionHandle)
495 {
496     downloadManager().resumeDownload(sessionID, downloadID, resumeData, path, sandboxExtensionHandle);
497 }
498
499 void NetworkProcess::cancelDownload(DownloadID downloadID)
500 {
501     downloadManager().cancelDownload(downloadID);
502 }
503     
504 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
505 void NetworkProcess::canAuthenticateAgainstProtectionSpace(NetworkResourceLoader& loader, const WebCore::ProtectionSpace& protectionSpace)
506 {
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);
511 }
512
513 void NetworkProcess::continueCanAuthenticateAgainstProtectionSpace(uint64_t loaderID, bool canAuthenticate)
514 {
515     m_waitingNetworkResourceLoaders.take(loaderID).value()->continueCanAuthenticateAgainstProtectionSpace(canAuthenticate);
516 }
517 #endif
518
519 #if USE(NETWORK_SESSION)
520 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
521 void NetworkProcess::continueCanAuthenticateAgainstProtectionSpaceDownload(DownloadID downloadID, bool canAuthenticate)
522 {
523     downloadManager().continueCanAuthenticateAgainstProtectionSpace(downloadID, canAuthenticate);
524 }
525 #endif
526
527 void NetworkProcess::continueWillSendRequest(DownloadID downloadID, WebCore::ResourceRequest&& request)
528 {
529     downloadManager().continueWillSendRequest(downloadID, WTFMove(request));
530 }
531
532 void NetworkProcess::pendingDownloadCanceled(DownloadID downloadID)
533 {
534     downloadProxyConnection()->send(Messages::DownloadProxy::DidCancel({ }), downloadID.downloadID());
535 }
536
537 void NetworkProcess::findPendingDownloadLocation(NetworkDataTask& networkDataTask, ResponseCompletionHandler&& completionHandler, const ResourceResponse& response)
538 {
539     uint64_t destinationID = networkDataTask.pendingDownloadID().downloadID();
540     downloadProxyConnection()->send(Messages::DownloadProxy::DidReceiveResponse(response), destinationID);
541
542     downloadManager().willDecidePendingDownloadDestination(networkDataTask, WTFMove(completionHandler));
543
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());
548
549     downloadProxyConnection()->send(Messages::DownloadProxy::DecideDestinationWithSuggestedFilenameAsync(networkDataTask.pendingDownloadID(), suggestedFilename), destinationID);
550 }
551 #endif
552
553 void NetworkProcess::continueDecidePendingDownloadDestination(DownloadID downloadID, String destination, const SandboxExtension::Handle& sandboxExtensionHandle, bool allowOverwrite)
554 {
555     if (destination.isEmpty())
556         downloadManager().cancelDownload(downloadID);
557     else
558         downloadManager().continueDecidePendingDownloadDestination(downloadID, destination, sandboxExtensionHandle, allowOverwrite);
559 }
560
561 void NetworkProcess::setCacheModel(uint32_t cm)
562 {
563     CacheModel cacheModel = static_cast<CacheModel>(cm);
564
565     if (m_hasSetCacheModel && (cacheModel == m_cacheModel))
566         return;
567
568     m_hasSetCacheModel = true;
569     m_cacheModel = cacheModel;
570
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);
579     }
580
581     if (m_diskCacheSizeOverride >= 0)
582         urlCacheDiskCapacity = m_diskCacheSizeOverride;
583
584 #if ENABLE(NETWORK_CACHE)
585     if (m_cache) {
586         m_cache->setCapacity(urlCacheDiskCapacity);
587         return;
588     }
589 #endif
590
591     platformSetURLCacheSize(urlCacheMemoryCapacity, urlCacheDiskCapacity);
592 }
593
594 void NetworkProcess::setCanHandleHTTPSServerTrustEvaluation(bool value)
595 {
596     m_canHandleHTTPSServerTrustEvaluation = value;
597 }
598
599 void NetworkProcess::getNetworkProcessStatistics(uint64_t callbackID)
600 {
601     StatisticsData data;
602
603     auto& networkProcess = NetworkProcess::singleton();
604     data.statisticsNumbers.set("DownloadsActiveCount", networkProcess.downloadManager().activeDownloadCount());
605     data.statisticsNumbers.set("OutstandingAuthenticationChallengesCount", networkProcess.authenticationManager().outstandingAuthenticationChallengeCount());
606
607     parentProcessConnection()->send(Messages::WebProcessPool::DidGetStatistics(data, callbackID), 0);
608 }
609
610 void NetworkProcess::setAllowsAnySSLCertificateForWebSocket(bool allows)
611 {
612     Settings::setAllowsAnySSLCertificate(allows);
613 }
614
615 void NetworkProcess::logDiagnosticMessage(uint64_t webPageID, const String& message, const String& description, ShouldSample shouldSample)
616 {
617     if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
618         return;
619
620     parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessage(webPageID, message, description, ShouldSample::No), 0);
621 }
622
623 void NetworkProcess::logDiagnosticMessageWithResult(uint64_t webPageID, const String& message, const String& description, DiagnosticLoggingResultType result, ShouldSample shouldSample)
624 {
625     if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
626         return;
627
628     parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessageWithResult(webPageID, message, description, result, ShouldSample::No), 0);
629 }
630
631 void NetworkProcess::logDiagnosticMessageWithValue(uint64_t webPageID, const String& message, const String& description, double value, unsigned significantFigures, ShouldSample shouldSample)
632 {
633     if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
634         return;
635
636     parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessageWithValue(webPageID, message, description, value, significantFigures, ShouldSample::No), 0);
637 }
638
639 void NetworkProcess::terminate()
640 {
641 #if ENABLE(NETWORK_CAPTURE)
642     NetworkCapture::Manager::singleton().terminate();
643 #endif
644
645     platformTerminate();
646     ChildProcess::terminate();
647 }
648
649 // FIXME: We can remove this one by adapting RefCounter.
650 class TaskCounter : public RefCounted<TaskCounter> {
651 public:
652     explicit TaskCounter(Function<void()>&& callback) : m_callback(WTFMove(callback)) { }
653     ~TaskCounter() { m_callback(); };
654
655 private:
656     Function<void()> m_callback;
657 };
658
659 void NetworkProcess::actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend shouldAcknowledgeWhenReadyToSuspend)
660 {
661     lowMemoryHandler(Critical::Yes);
662
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);
669         }));
670     }
671
672     for (auto& connection : m_webProcessConnections)
673         connection->cleanupForSuspension([delayedTaskCounter] { });
674 }
675
676 void NetworkProcess::processWillSuspendImminently(bool& handled)
677 {
678     actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend::No);
679     handled = true;
680 }
681
682 void NetworkProcess::prepareToSuspend()
683 {
684     RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::prepareToSuspend()", this);
685     actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend::Yes);
686 }
687
688 void NetworkProcess::cancelPrepareToSuspend()
689 {
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();
697 }
698
699 void NetworkProcess::processDidResume()
700 {
701     RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::processDidResume()", this);
702     for (auto& connection : m_webProcessConnections)
703         connection->endSuspension();
704 }
705
706 void NetworkProcess::prefetchDNS(const String& hostname)
707 {
708     WebCore::prefetchDNS(hostname);
709 }
710
711 String NetworkProcess::cacheStorageDirectory(PAL::SessionID sessionID) const
712 {
713     if (sessionID.isEphemeral())
714         return { };
715
716     if (sessionID == PAL::SessionID::defaultSessionID())
717         return m_cacheStorageDirectory;
718
719     auto* session = NetworkStorageSession::storageSession(sessionID);
720     if (!session)
721         return { };
722
723     return session->cacheStorageDirectory();
724 }
725
726 #if !PLATFORM(COCOA)
727 void NetworkProcess::initializeProcess(const ChildProcessInitializationParameters&)
728 {
729 }
730
731 void NetworkProcess::initializeProcessName(const ChildProcessInitializationParameters&)
732 {
733 }
734
735 void NetworkProcess::initializeSandbox(const ChildProcessInitializationParameters&, SandboxInitializationParameters&)
736 {
737 }
738
739 void NetworkProcess::syncAllCookies()
740 {
741 }
742
743 #endif
744
745 } // namespace WebKit