5ae4eb8b1cd4fd90b9b41e64c5e210ee128f5138
[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::updateCookiePartitioningForTopPrivatelyOwnedDomains(PAL::SessionID sessionID, const Vector<String>& domainsToRemove, const Vector<String>& domainsToAdd,  bool shouldClearFirst)
323 {
324     if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
325         networkStorageSession->setShouldPartitionCookiesForHosts(domainsToRemove, domainsToAdd, shouldClearFirst);
326 }
327 #endif
328
329 static void fetchDiskCacheEntries(PAL::SessionID sessionID, OptionSet<WebsiteDataFetchOption> fetchOptions, Function<void (Vector<WebsiteData::Entry>)>&& completionHandler)
330 {
331 #if ENABLE(NETWORK_CACHE)
332     if (auto* cache = NetworkProcess::singleton().cache()) {
333         HashMap<SecurityOriginData, uint64_t> originsAndSizes;
334         cache->traverse([fetchOptions, completionHandler = WTFMove(completionHandler), originsAndSizes = WTFMove(originsAndSizes)](auto* traversalEntry) mutable {
335             if (!traversalEntry) {
336                 Vector<WebsiteData::Entry> entries;
337
338                 for (auto& originAndSize : originsAndSizes)
339                     entries.append(WebsiteData::Entry { originAndSize.key, WebsiteDataType::DiskCache, originAndSize.value });
340
341                 RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler), entries = WTFMove(entries)] {
342                     completionHandler(entries);
343                 });
344
345                 return;
346             }
347
348             auto url = traversalEntry->entry.response().url();
349             auto result = originsAndSizes.add({url.protocol().toString(), url.host(), url.port()}, 0);
350
351             if (fetchOptions.contains(WebsiteDataFetchOption::ComputeSizes))
352                 result.iterator->value += traversalEntry->entry.sourceStorageRecord().header.size() + traversalEntry->recordInfo.bodySize;
353         });
354
355         return;
356     }
357 #endif
358
359     RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler)] {
360         completionHandler({ });
361     });
362 }
363
364 void NetworkProcess::fetchWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, OptionSet<WebsiteDataFetchOption> fetchOptions, uint64_t callbackID)
365 {
366     struct CallbackAggregator final : public RefCounted<CallbackAggregator> {
367         explicit CallbackAggregator(Function<void (WebsiteData)>&& completionHandler)
368             : m_completionHandler(WTFMove(completionHandler))
369         {
370         }
371
372         ~CallbackAggregator()
373         {
374             ASSERT(RunLoop::isMain());
375
376             RunLoop::main().dispatch([completionHandler = WTFMove(m_completionHandler), websiteData = WTFMove(m_websiteData)] {
377                 completionHandler(websiteData);
378             });
379         }
380
381         Function<void (WebsiteData)> m_completionHandler;
382         WebsiteData m_websiteData;
383     };
384
385     auto callbackAggregator = adoptRef(*new CallbackAggregator([this, callbackID] (WebsiteData websiteData) {
386         parentProcessConnection()->send(Messages::NetworkProcessProxy::DidFetchWebsiteData(callbackID, websiteData), 0);
387     }));
388
389     if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
390         if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
391             getHostnamesWithCookies(*networkStorageSession, callbackAggregator->m_websiteData.hostNamesWithCookies);
392     }
393
394     if (websiteDataTypes.contains(WebsiteDataType::Credentials)) {
395         if (NetworkStorageSession::storageSession(sessionID))
396             callbackAggregator->m_websiteData.originsWithCredentials = NetworkStorageSession::storageSession(sessionID)->credentialStorage().originsWithCredentials();
397     }
398
399     if (websiteDataTypes.contains(WebsiteDataType::DiskCache)) {
400         fetchDiskCacheEntries(sessionID, fetchOptions, [callbackAggregator = WTFMove(callbackAggregator)](auto entries) mutable {
401             callbackAggregator->m_websiteData.entries.appendVector(entries);
402         });
403     }
404 }
405
406 void NetworkProcess::deleteWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, std::chrono::system_clock::time_point modifiedSince, uint64_t callbackID)
407 {
408 #if PLATFORM(COCOA)
409     if (websiteDataTypes.contains(WebsiteDataType::HSTSCache)) {
410         if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
411             clearHSTSCache(*networkStorageSession, modifiedSince);
412     }
413 #endif
414
415     if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
416         if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
417             deleteAllCookiesModifiedSince(*networkStorageSession, modifiedSince);
418     }
419
420     if (websiteDataTypes.contains(WebsiteDataType::Credentials)) {
421         if (NetworkStorageSession::storageSession(sessionID))
422             NetworkStorageSession::storageSession(sessionID)->credentialStorage().clearCredentials();
423     }
424     
425     auto completionHandler = [this, callbackID] {
426         parentProcessConnection()->send(Messages::NetworkProcessProxy::DidDeleteWebsiteData(callbackID), 0);
427     };
428
429     if (websiteDataTypes.contains(WebsiteDataType::DiskCache) && !sessionID.isEphemeral()) {
430         clearDiskCache(modifiedSince, WTFMove(completionHandler));
431         return;
432     }
433
434     completionHandler();
435 }
436
437 static void clearDiskCacheEntries(const Vector<SecurityOriginData>& origins, Function<void ()>&& completionHandler)
438 {
439 #if ENABLE(NETWORK_CACHE)
440     if (auto* cache = NetworkProcess::singleton().cache()) {
441         HashSet<RefPtr<SecurityOrigin>> originsToDelete;
442         for (auto& origin : origins)
443             originsToDelete.add(origin.securityOrigin());
444
445         Vector<NetworkCache::Key> cacheKeysToDelete;
446         cache->traverse([cache, completionHandler = WTFMove(completionHandler), originsToDelete = WTFMove(originsToDelete), cacheKeysToDelete = WTFMove(cacheKeysToDelete)](auto* traversalEntry) mutable {
447             if (traversalEntry) {
448                 if (originsToDelete.contains(SecurityOrigin::create(traversalEntry->entry.response().url())))
449                     cacheKeysToDelete.append(traversalEntry->entry.key());
450                 return;
451             }
452
453             cache->remove(cacheKeysToDelete, WTFMove(completionHandler));
454             return;
455         });
456
457         return;
458     }
459 #endif
460
461     RunLoop::main().dispatch(WTFMove(completionHandler));
462 }
463
464 void NetworkProcess::deleteWebsiteDataForOrigins(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, const Vector<SecurityOriginData>& origins, const Vector<String>& cookieHostNames, uint64_t callbackID)
465 {
466     if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
467         if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
468             deleteCookiesForHostnames(*networkStorageSession, cookieHostNames);
469     }
470
471     auto completionHandler = [this, callbackID] {
472         parentProcessConnection()->send(Messages::NetworkProcessProxy::DidDeleteWebsiteDataForOrigins(callbackID), 0);
473     };
474
475     if (websiteDataTypes.contains(WebsiteDataType::DiskCache) && !sessionID.isEphemeral()) {
476         clearDiskCacheEntries(origins, WTFMove(completionHandler));
477         return;
478     }
479
480     completionHandler();
481 }
482
483 void NetworkProcess::downloadRequest(PAL::SessionID sessionID, DownloadID downloadID, const ResourceRequest& request, const String& suggestedFilename)
484 {
485     downloadManager().startDownload(nullptr, sessionID, downloadID, request, suggestedFilename);
486 }
487
488 void NetworkProcess::resumeDownload(PAL::SessionID sessionID, DownloadID downloadID, const IPC::DataReference& resumeData, const String& path, const WebKit::SandboxExtension::Handle& sandboxExtensionHandle)
489 {
490     downloadManager().resumeDownload(sessionID, downloadID, resumeData, path, sandboxExtensionHandle);
491 }
492
493 void NetworkProcess::cancelDownload(DownloadID downloadID)
494 {
495     downloadManager().cancelDownload(downloadID);
496 }
497     
498 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
499 void NetworkProcess::canAuthenticateAgainstProtectionSpace(NetworkResourceLoader& loader, const WebCore::ProtectionSpace& protectionSpace)
500 {
501     static uint64_t lastLoaderID = 0;
502     uint64_t loaderID = ++lastLoaderID;
503     m_waitingNetworkResourceLoaders.set(lastLoaderID, loader);
504     parentProcessConnection()->send(Messages::NetworkProcessProxy::CanAuthenticateAgainstProtectionSpace(loaderID, loader.pageID(), loader.frameID(), protectionSpace), 0);
505 }
506
507 void NetworkProcess::continueCanAuthenticateAgainstProtectionSpace(uint64_t loaderID, bool canAuthenticate)
508 {
509     m_waitingNetworkResourceLoaders.take(loaderID).value()->continueCanAuthenticateAgainstProtectionSpace(canAuthenticate);
510 }
511 #endif
512
513 #if USE(NETWORK_SESSION)
514 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
515 void NetworkProcess::continueCanAuthenticateAgainstProtectionSpaceDownload(DownloadID downloadID, bool canAuthenticate)
516 {
517     downloadManager().continueCanAuthenticateAgainstProtectionSpace(downloadID, canAuthenticate);
518 }
519 #endif
520
521 void NetworkProcess::continueWillSendRequest(DownloadID downloadID, WebCore::ResourceRequest&& request)
522 {
523     downloadManager().continueWillSendRequest(downloadID, WTFMove(request));
524 }
525
526 void NetworkProcess::pendingDownloadCanceled(DownloadID downloadID)
527 {
528     downloadProxyConnection()->send(Messages::DownloadProxy::DidCancel({ }), downloadID.downloadID());
529 }
530
531 void NetworkProcess::findPendingDownloadLocation(NetworkDataTask& networkDataTask, ResponseCompletionHandler&& completionHandler, const ResourceResponse& response)
532 {
533     uint64_t destinationID = networkDataTask.pendingDownloadID().downloadID();
534     downloadProxyConnection()->send(Messages::DownloadProxy::DidReceiveResponse(response), destinationID);
535
536     downloadManager().willDecidePendingDownloadDestination(networkDataTask, WTFMove(completionHandler));
537
538     // As per https://html.spec.whatwg.org/#as-a-download (step 2), the filename from the Content-Disposition header
539     // should override the suggested filename from the download attribute.
540     String suggestedFilename = response.isAttachmentWithFilename() ? response.suggestedFilename() : networkDataTask.suggestedFilename();
541     suggestedFilename = MIMETypeRegistry::appendFileExtensionIfNecessary(suggestedFilename, response.mimeType());
542
543     downloadProxyConnection()->send(Messages::DownloadProxy::DecideDestinationWithSuggestedFilenameAsync(networkDataTask.pendingDownloadID(), suggestedFilename), destinationID);
544 }
545 #endif
546
547 void NetworkProcess::continueDecidePendingDownloadDestination(DownloadID downloadID, String destination, const SandboxExtension::Handle& sandboxExtensionHandle, bool allowOverwrite)
548 {
549     if (destination.isEmpty())
550         downloadManager().cancelDownload(downloadID);
551     else
552         downloadManager().continueDecidePendingDownloadDestination(downloadID, destination, sandboxExtensionHandle, allowOverwrite);
553 }
554
555 void NetworkProcess::setCacheModel(uint32_t cm)
556 {
557     CacheModel cacheModel = static_cast<CacheModel>(cm);
558
559     if (m_hasSetCacheModel && (cacheModel == m_cacheModel))
560         return;
561
562     m_hasSetCacheModel = true;
563     m_cacheModel = cacheModel;
564
565     unsigned urlCacheMemoryCapacity = 0;
566     uint64_t urlCacheDiskCapacity = 0;
567     uint64_t diskFreeSize = 0;
568     if (WebCore::getVolumeFreeSpace(m_diskCacheDirectory, diskFreeSize)) {
569         // As a fudge factor, use 1000 instead of 1024, in case the reported byte
570         // count doesn't align exactly to a megabyte boundary.
571         diskFreeSize /= KB * 1000;
572         calculateURLCacheSizes(cacheModel, diskFreeSize, urlCacheMemoryCapacity, urlCacheDiskCapacity);
573     }
574
575     if (m_diskCacheSizeOverride >= 0)
576         urlCacheDiskCapacity = m_diskCacheSizeOverride;
577
578 #if ENABLE(NETWORK_CACHE)
579     if (m_cache) {
580         m_cache->setCapacity(urlCacheDiskCapacity);
581         return;
582     }
583 #endif
584
585     platformSetURLCacheSize(urlCacheMemoryCapacity, urlCacheDiskCapacity);
586 }
587
588 void NetworkProcess::setCanHandleHTTPSServerTrustEvaluation(bool value)
589 {
590     m_canHandleHTTPSServerTrustEvaluation = value;
591 }
592
593 void NetworkProcess::getNetworkProcessStatistics(uint64_t callbackID)
594 {
595     StatisticsData data;
596
597     auto& networkProcess = NetworkProcess::singleton();
598     data.statisticsNumbers.set("DownloadsActiveCount", networkProcess.downloadManager().activeDownloadCount());
599     data.statisticsNumbers.set("OutstandingAuthenticationChallengesCount", networkProcess.authenticationManager().outstandingAuthenticationChallengeCount());
600
601     parentProcessConnection()->send(Messages::WebProcessPool::DidGetStatistics(data, callbackID), 0);
602 }
603
604 void NetworkProcess::setAllowsAnySSLCertificateForWebSocket(bool allows)
605 {
606     Settings::setAllowsAnySSLCertificate(allows);
607 }
608
609 void NetworkProcess::logDiagnosticMessage(uint64_t webPageID, const String& message, const String& description, ShouldSample shouldSample)
610 {
611     if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
612         return;
613
614     parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessage(webPageID, message, description, ShouldSample::No), 0);
615 }
616
617 void NetworkProcess::logDiagnosticMessageWithResult(uint64_t webPageID, const String& message, const String& description, DiagnosticLoggingResultType result, ShouldSample shouldSample)
618 {
619     if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
620         return;
621
622     parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessageWithResult(webPageID, message, description, result, ShouldSample::No), 0);
623 }
624
625 void NetworkProcess::logDiagnosticMessageWithValue(uint64_t webPageID, const String& message, const String& description, double value, unsigned significantFigures, ShouldSample shouldSample)
626 {
627     if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
628         return;
629
630     parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessageWithValue(webPageID, message, description, value, significantFigures, ShouldSample::No), 0);
631 }
632
633 void NetworkProcess::terminate()
634 {
635 #if ENABLE(NETWORK_CAPTURE)
636     NetworkCapture::Manager::singleton().terminate();
637 #endif
638
639     platformTerminate();
640     ChildProcess::terminate();
641 }
642
643 // FIXME: We can remove this one by adapting RefCounter.
644 class TaskCounter : public RefCounted<TaskCounter> {
645 public:
646     explicit TaskCounter(Function<void()>&& callback) : m_callback(WTFMove(callback)) { }
647     ~TaskCounter() { m_callback(); };
648
649 private:
650     Function<void()> m_callback;
651 };
652
653 void NetworkProcess::actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend shouldAcknowledgeWhenReadyToSuspend)
654 {
655     lowMemoryHandler(Critical::Yes);
656
657     RefPtr<TaskCounter> delayedTaskCounter;
658     if (shouldAcknowledgeWhenReadyToSuspend == ShouldAcknowledgeWhenReadyToSuspend::Yes) {
659         delayedTaskCounter = adoptRef(new TaskCounter([this] {
660             RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::notifyProcessReadyToSuspend() Sending ProcessReadyToSuspend IPC message", this);
661             if (parentProcessConnection())
662                 parentProcessConnection()->send(Messages::NetworkProcessProxy::ProcessReadyToSuspend(), 0);
663         }));
664     }
665
666     for (auto& connection : m_webProcessConnections)
667         connection->cleanupForSuspension([delayedTaskCounter] { });
668 }
669
670 void NetworkProcess::processWillSuspendImminently(bool& handled)
671 {
672     actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend::No);
673     handled = true;
674 }
675
676 void NetworkProcess::prepareToSuspend()
677 {
678     RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::prepareToSuspend()", this);
679     actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend::Yes);
680 }
681
682 void NetworkProcess::cancelPrepareToSuspend()
683 {
684     // Although it is tempting to send a NetworkProcessProxy::DidCancelProcessSuspension message from here
685     // we do not because prepareToSuspend() already replied with a NetworkProcessProxy::ProcessReadyToSuspend
686     // message. And NetworkProcessProxy expects to receive either a NetworkProcessProxy::ProcessReadyToSuspend-
687     // or NetworkProcessProxy::DidCancelProcessSuspension- message, but not both.
688     RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::cancelPrepareToSuspend()", this);
689     for (auto& connection : m_webProcessConnections)
690         connection->endSuspension();
691 }
692
693 void NetworkProcess::processDidResume()
694 {
695     RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::processDidResume()", this);
696     for (auto& connection : m_webProcessConnections)
697         connection->endSuspension();
698 }
699
700 void NetworkProcess::prefetchDNS(const String& hostname)
701 {
702     WebCore::prefetchDNS(hostname);
703 }
704
705 String NetworkProcess::cacheStorageDirectory(PAL::SessionID sessionID) const
706 {
707     if (sessionID.isEphemeral())
708         return { };
709
710     if (sessionID == PAL::SessionID::defaultSessionID())
711         return m_cacheStorageDirectory;
712
713     auto* session = NetworkStorageSession::storageSession(sessionID);
714     if (!session)
715         return { };
716
717     return session->cacheStorageDirectory();
718 }
719
720 #if !PLATFORM(COCOA)
721 void NetworkProcess::initializeProcess(const ChildProcessInitializationParameters&)
722 {
723 }
724
725 void NetworkProcess::initializeProcessName(const ChildProcessInitializationParameters&)
726 {
727 }
728
729 void NetworkProcess::initializeSandbox(const ChildProcessInitializationParameters&, SandboxInitializationParameters&)
730 {
731 }
732
733 void NetworkProcess::syncAllCookies()
734 {
735 }
736
737 #endif
738
739 } // namespace WebKit