Create a WebResourceLoadStatisticsStore attached to the NetworkSession
[WebKit-https.git] / Source / WebKit / UIProcess / WebsiteData / Cocoa / WebsiteDataStoreCocoa.mm
1 /*
2  * Copyright (C) 2015-2018 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 #import "config.h"
27 #import "WebsiteDataStore.h"
28
29 #import "CookieStorageUtilsCF.h"
30 #import "StorageManager.h"
31 #import "WebResourceLoadStatisticsStore.h"
32 #import "WebsiteDataStoreParameters.h"
33 #import <WebCore/FileSystem.h>
34 #import <WebCore/RuntimeApplicationChecks.h>
35 #import <WebCore/SearchPopupMenuCocoa.h>
36 #import <pal/spi/cf/CFNetworkSPI.h>
37 #import <wtf/NeverDestroyed.h>
38 #import <wtf/ProcessPrivilege.h>
39
40 #if PLATFORM(IOS_FAMILY)
41 #import <UIKit/UIApplication.h>
42 #endif
43
44 namespace WebKit {
45
46 static id terminationObserver;
47
48 static Vector<WebsiteDataStore*>& dataStoresWithStorageManagers()
49 {
50     static NeverDestroyed<Vector<WebsiteDataStore*>> dataStoresWithStorageManagers;
51
52     return dataStoresWithStorageManagers;
53 }
54
55 static NSString * const WebKitNetworkLoadThrottleLatencyMillisecondsDefaultsKey = @"WebKitNetworkLoadThrottleLatencyMilliseconds";
56
57 WebsiteDataStoreParameters WebsiteDataStore::parameters()
58 {
59     ASSERT(hasProcessPrivilege(ProcessPrivilege::CanAccessRawCookies));
60
61     resolveDirectoriesIfNecessary();
62
63     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
64 #if ENABLE(RESOURCE_LOAD_STATISTICS) && !RELEASE_LOG_DISABLED
65     static NSString * const WebKitLogCookieInformationDefaultsKey = @"WebKitLogCookieInformation";
66     bool shouldLogCookieInformation = [defaults boolForKey:WebKitLogCookieInformationDefaultsKey];
67 #else
68     bool shouldLogCookieInformation = false;
69 #endif
70
71     URL httpProxy = m_configuration->httpProxy();
72     URL httpsProxy = m_configuration->httpsProxy();
73     
74     bool isSafari = false;
75 #if PLATFORM(IOS_FAMILY)
76     isSafari = WebCore::IOSApplication::isMobileSafari();
77 #elif PLATFORM(MAC)
78     isSafari = WebCore::MacApplication::isSafari();
79 #endif
80     // FIXME: Remove these once Safari adopts _WKWebsiteDataStoreConfiguration.httpProxy and .httpsProxy.
81     if (!httpProxy.isValid() && isSafari)
82         httpProxy = URL(URL(), [defaults stringForKey:(NSString *)WebKit2HTTPProxyDefaultsKey]);
83     if (!httpsProxy.isValid() && isSafari)
84         httpsProxy = URL(URL(), [defaults stringForKey:(NSString *)WebKit2HTTPSProxyDefaultsKey]);
85
86     auto resourceLoadStatisticsDirectory = m_configuration->resourceLoadStatisticsDirectory();
87     SandboxExtension::Handle resourceLoadStatisticsDirectoryHandle;
88     if (!resourceLoadStatisticsDirectory.isEmpty())
89         SandboxExtension::createHandleForReadWriteDirectory(resourceLoadStatisticsDirectory, resourceLoadStatisticsDirectoryHandle);
90
91     WebsiteDataStoreParameters parameters;
92     parameters.networkSessionParameters = {
93         m_sessionID,
94         m_boundInterfaceIdentifier,
95         m_allowsCellularAccess,
96         m_proxyConfiguration,
97         m_configuration->sourceApplicationBundleIdentifier(),
98         m_configuration->sourceApplicationSecondaryIdentifier(),
99         shouldLogCookieInformation,
100         Seconds { [defaults integerForKey:WebKitNetworkLoadThrottleLatencyMillisecondsDefaultsKey] / 1000. },
101         WTFMove(httpProxy),
102         WTFMove(httpsProxy),
103         WTFMove(resourceLoadStatisticsDirectory),
104         WTFMove(resourceLoadStatisticsDirectoryHandle),
105         false // FIXME(193297): Switch to m_configuration->resourceLoadStatisticsEnabled()
106     };
107
108     auto cookieFile = resolvedCookieStorageFile();
109
110     if (m_uiProcessCookieStorageIdentifier.isEmpty()) {
111         auto utf8File = cookieFile.utf8();
112         auto url = adoptCF(CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (const UInt8 *)utf8File.data(), (CFIndex)utf8File.length(), true));
113         m_cfCookieStorage = adoptCF(CFHTTPCookieStorageCreateFromFile(kCFAllocatorDefault, url.get(), nullptr));
114         m_uiProcessCookieStorageIdentifier = identifyingDataFromCookieStorage(m_cfCookieStorage.get());
115     }
116
117     parameters.uiProcessCookieStorageIdentifier = m_uiProcessCookieStorageIdentifier;
118     parameters.networkSessionParameters.sourceApplicationBundleIdentifier = m_configuration->sourceApplicationBundleIdentifier();
119     parameters.networkSessionParameters.sourceApplicationSecondaryIdentifier = m_configuration->sourceApplicationSecondaryIdentifier();
120
121     parameters.pendingCookies = copyToVector(m_pendingCookies);
122
123     if (!cookieFile.isEmpty())
124         SandboxExtension::createHandleForReadWriteDirectory(WebCore::FileSystem::directoryName(cookieFile), parameters.cookieStoragePathExtensionHandle);
125
126 #if ENABLE(INDEXED_DATABASE)
127     parameters.indexedDatabaseDirectory = resolvedIndexedDatabaseDirectory();
128     if (!parameters.indexedDatabaseDirectory.isEmpty())
129         SandboxExtension::createHandleForReadWriteDirectory(parameters.indexedDatabaseDirectory, parameters.indexedDatabaseDirectoryExtensionHandle);
130 #endif
131
132 #if ENABLE(SERVICE_WORKER)
133     parameters.serviceWorkerRegistrationDirectory = resolvedServiceWorkerRegistrationDirectory();
134     if (!parameters.serviceWorkerRegistrationDirectory.isEmpty())
135         SandboxExtension::createHandleForReadWriteDirectory(parameters.serviceWorkerRegistrationDirectory, parameters.serviceWorkerRegistrationDirectoryExtensionHandle);
136 #endif
137
138     return parameters;
139 }
140
141 void WebsiteDataStore::platformInitialize()
142 {
143     if (!m_storageManager)
144         return;
145
146     if (!terminationObserver) {
147         ASSERT(dataStoresWithStorageManagers().isEmpty());
148
149 #if PLATFORM(MAC)
150         NSString *notificationName = NSApplicationWillTerminateNotification;
151 #else
152         NSString *notificationName = UIApplicationWillTerminateNotification;
153 #endif
154         terminationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:notificationName object:nil queue:nil usingBlock:^(NSNotification *note) {
155             for (auto& dataStore : dataStoresWithStorageManagers()) {
156                 dataStore->m_storageManager->applicationWillTerminate();
157                 if (dataStore->m_resourceLoadStatistics)
158                     dataStore->m_resourceLoadStatistics->applicationWillTerminate();
159             }
160         }];
161     }
162
163     ASSERT(!dataStoresWithStorageManagers().contains(this));
164     dataStoresWithStorageManagers().append(this);
165 }
166
167 void WebsiteDataStore::platformDestroy()
168 {
169     if (m_resourceLoadStatistics)
170         m_resourceLoadStatistics->applicationWillTerminate();
171
172     if (!m_storageManager)
173         return;
174
175     // FIXME: Rename applicationWillTerminate to something that better indicates what StorageManager does (waits for pending writes to finish).
176     m_storageManager->applicationWillTerminate();
177
178     ASSERT(dataStoresWithStorageManagers().contains(this));
179     dataStoresWithStorageManagers().removeFirst(this);
180
181     if (dataStoresWithStorageManagers().isEmpty()) {
182         [[NSNotificationCenter defaultCenter] removeObserver:terminationObserver];
183         terminationObserver = nil;
184     }
185 }
186
187 void WebsiteDataStore::platformRemoveRecentSearches(WallTime oldestTimeToRemove)
188 {
189     WebCore::removeRecentlyModifiedRecentSearches(oldestTimeToRemove);
190 }
191
192 }