a6836d9251632b81855316b6dc4ea78ff81cb6b6
[WebKit.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/RegistrableDomain.h>
34 #import <WebCore/RuntimeApplicationChecks.h>
35 #import <WebCore/SearchPopupMenuCocoa.h>
36 #import <pal/spi/cf/CFNetworkSPI.h>
37 #import <wtf/FileSystem.h>
38 #import <wtf/NeverDestroyed.h>
39 #import <wtf/ProcessPrivilege.h>
40 #import <wtf/URL.h>
41 #import <wtf/text/StringBuilder.h>
42
43 #if PLATFORM(IOS_FAMILY)
44 #import <UIKit/UIApplication.h>
45 #endif
46
47 namespace WebKit {
48
49 static id terminationObserver;
50
51 static HashSet<WebsiteDataStore*>& dataStores()
52 {
53     static NeverDestroyed<HashSet<WebsiteDataStore*>> dataStores;
54
55     return dataStores;
56 }
57
58 static NSString * const WebKitNetworkLoadThrottleLatencyMillisecondsDefaultsKey = @"WebKitNetworkLoadThrottleLatencyMilliseconds";
59
60 WebsiteDataStoreParameters WebsiteDataStore::parameters()
61 {
62     ASSERT(hasProcessPrivilege(ProcessPrivilege::CanAccessRawCookies));
63
64     resolveDirectoriesIfNecessary();
65
66     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
67     bool shouldLogCookieInformation = false;
68     bool enableResourceLoadStatisticsDebugMode = false;
69     WebCore::RegistrableDomain resourceLoadStatisticsManualPrevalentResource { };
70 #if ENABLE(RESOURCE_LOAD_STATISTICS)
71     enableResourceLoadStatisticsDebugMode = [defaults boolForKey:@"ITPDebugMode"];
72     auto* manualPrevalentResource = [defaults stringForKey:@"ITPManualPrevalentResource"];
73     if (manualPrevalentResource) {
74         URL url { URL(), manualPrevalentResource };
75         if (!url.isValid()) {
76             StringBuilder builder;
77             builder.appendLiteral("http://");
78             builder.append(manualPrevalentResource);
79             url = { URL(), builder.toString() };
80         }
81         if (url.isValid())
82             resourceLoadStatisticsManualPrevalentResource = WebCore::RegistrableDomain { url };
83     }
84 #if !RELEASE_LOG_DISABLED
85     static NSString * const WebKitLogCookieInformationDefaultsKey = @"WebKitLogCookieInformation";
86     shouldLogCookieInformation = [defaults boolForKey:WebKitLogCookieInformationDefaultsKey];
87 #endif
88 #endif // ENABLE(RESOURCE_LOAD_STATISTICS)
89
90     URL httpProxy = m_configuration->httpProxy();
91     URL httpsProxy = m_configuration->httpsProxy();
92     
93     bool isSafari = false;
94 #if PLATFORM(IOS_FAMILY)
95     isSafari = WebCore::IOSApplication::isMobileSafari();
96 #elif PLATFORM(MAC)
97     isSafari = WebCore::MacApplication::isSafari();
98 #endif
99     // FIXME: Remove these once Safari adopts _WKWebsiteDataStoreConfiguration.httpProxy and .httpsProxy.
100     if (!httpProxy.isValid() && isSafari)
101         httpProxy = URL(URL(), [defaults stringForKey:(NSString *)WebKit2HTTPProxyDefaultsKey]);
102     if (!httpsProxy.isValid() && isSafari)
103         httpsProxy = URL(URL(), [defaults stringForKey:(NSString *)WebKit2HTTPSProxyDefaultsKey]);
104
105     auto resourceLoadStatisticsDirectory = m_configuration->resourceLoadStatisticsDirectory();
106     SandboxExtension::Handle resourceLoadStatisticsDirectoryHandle;
107     if (!resourceLoadStatisticsDirectory.isEmpty())
108         SandboxExtension::createHandleForReadWriteDirectory(resourceLoadStatisticsDirectory, resourceLoadStatisticsDirectoryHandle);
109
110     auto localStorageDirectory = resolvedLocalStorageDirectory();
111     SandboxExtension::Handle localStorageDirectoryExtensionHandle;
112     if (!localStorageDirectory.isEmpty())
113         SandboxExtension::createHandleForReadWriteDirectory(localStorageDirectory, localStorageDirectoryExtensionHandle);
114
115     auto networkCacheDirectory = resolvedNetworkCacheDirectory();
116     SandboxExtension::Handle networkCacheDirectoryExtensionHandle;
117     if (!networkCacheDirectory.isEmpty())
118         SandboxExtension::createHandleForReadWriteDirectory(networkCacheDirectory, networkCacheDirectoryExtensionHandle);
119
120     bool shouldIncludeLocalhostInResourceLoadStatistics = isSafari;
121     WebsiteDataStoreParameters parameters;
122     parameters.networkSessionParameters = {
123         m_sessionID,
124         m_boundInterfaceIdentifier,
125         m_allowsCellularAccess,
126         m_proxyConfiguration,
127         m_sourceApplicationBundleIdentifier,
128         m_sourceApplicationSecondaryIdentifier,
129         m_allowsTLSFallback ? AllowsTLSFallback::Yes : AllowsTLSFallback::No,
130         shouldLogCookieInformation,
131         Seconds { [defaults integerForKey:WebKitNetworkLoadThrottleLatencyMillisecondsDefaultsKey] / 1000. },
132         WTFMove(httpProxy),
133         WTFMove(httpsProxy),
134         WTFMove(resourceLoadStatisticsDirectory),
135         WTFMove(resourceLoadStatisticsDirectoryHandle),
136         false,
137         false,
138         shouldIncludeLocalhostInResourceLoadStatistics,
139         enableResourceLoadStatisticsDebugMode,
140         m_configuration->deviceManagementRestrictionsEnabled(),
141         m_configuration->allLoadsBlockedByDeviceManagementRestrictionsForTesting(),
142         WTFMove(resourceLoadStatisticsManualPrevalentResource),
143         WTFMove(localStorageDirectory),
144         WTFMove(localStorageDirectoryExtensionHandle),
145         WTFMove(networkCacheDirectory),
146         WTFMove(networkCacheDirectoryExtensionHandle),
147     };
148     networkingHasBegun();
149
150     auto cookieFile = resolvedCookieStorageFile();
151
152     if (m_uiProcessCookieStorageIdentifier.isEmpty()) {
153         auto utf8File = cookieFile.utf8();
154         auto url = adoptCF(CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (const UInt8 *)utf8File.data(), (CFIndex)utf8File.length(), true));
155         m_cfCookieStorage = adoptCF(CFHTTPCookieStorageCreateFromFile(kCFAllocatorDefault, url.get(), nullptr));
156         m_uiProcessCookieStorageIdentifier = identifyingDataFromCookieStorage(m_cfCookieStorage.get());
157     }
158
159     parameters.uiProcessCookieStorageIdentifier = m_uiProcessCookieStorageIdentifier;
160     parameters.networkSessionParameters.sourceApplicationBundleIdentifier = m_sourceApplicationBundleIdentifier;
161     parameters.networkSessionParameters.sourceApplicationSecondaryIdentifier = m_sourceApplicationSecondaryIdentifier;
162
163     parameters.pendingCookies = copyToVector(m_pendingCookies);
164
165     if (!cookieFile.isEmpty())
166         SandboxExtension::createHandleForReadWriteDirectory(FileSystem::directoryName(cookieFile), parameters.cookieStoragePathExtensionHandle);
167
168 #if ENABLE(INDEXED_DATABASE)
169     parameters.indexedDatabaseDirectory = resolvedIndexedDatabaseDirectory();
170     if (!parameters.indexedDatabaseDirectory.isEmpty())
171         SandboxExtension::createHandleForReadWriteDirectory(parameters.indexedDatabaseDirectory, parameters.indexedDatabaseDirectoryExtensionHandle);
172 #endif
173
174 #if ENABLE(SERVICE_WORKER)
175     parameters.serviceWorkerRegistrationDirectory = resolvedServiceWorkerRegistrationDirectory();
176     if (!parameters.serviceWorkerRegistrationDirectory.isEmpty())
177         SandboxExtension::createHandleForReadWriteDirectory(parameters.serviceWorkerRegistrationDirectory, parameters.serviceWorkerRegistrationDirectoryExtensionHandle);
178 #endif
179
180     parameters.perOriginStorageQuota = perOriginStorageQuota();
181     parameters.perThirdPartyOriginStorageQuota = perThirdPartyOriginStorageQuota();
182
183     return parameters;
184 }
185
186 void WebsiteDataStore::platformInitialize()
187 {
188     if (!terminationObserver) {
189         ASSERT(dataStores().isEmpty());
190
191 #if PLATFORM(MAC)
192         NSString *notificationName = NSApplicationWillTerminateNotification;
193 #else
194         NSString *notificationName = UIApplicationWillTerminateNotification;
195 #endif
196         terminationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:notificationName object:nil queue:nil usingBlock:^(NSNotification *note) {
197             for (auto& dataStore : dataStores()) {
198 #if ENABLE(RESOURCE_LOAD_STATISTICS)
199                 if (dataStore->m_resourceLoadStatistics)
200                     dataStore->m_resourceLoadStatistics->applicationWillTerminate();
201 #endif
202             }
203         }];
204     }
205
206     ASSERT(!dataStores().contains(this));
207     dataStores().add(this);
208 }
209
210 void WebsiteDataStore::platformDestroy()
211 {
212 #if ENABLE(RESOURCE_LOAD_STATISTICS)
213     if (m_resourceLoadStatistics)
214         m_resourceLoadStatistics->applicationWillTerminate();
215 #endif
216
217     ASSERT(dataStores().contains(this));
218     dataStores().remove(this);
219
220     if (dataStores().isEmpty()) {
221         [[NSNotificationCenter defaultCenter] removeObserver:terminationObserver];
222         terminationObserver = nil;
223     }
224 }
225
226 void WebsiteDataStore::platformRemoveRecentSearches(WallTime oldestTimeToRemove)
227 {
228     WebCore::removeRecentlyModifiedRecentSearches(oldestTimeToRemove);
229 }
230
231 }