877edd4beaf4ee15c27dd0d24701c5f6bd437c64
[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     WebsiteDataStoreParameters parameters;
87     parameters.networkSessionParameters = {
88         m_sessionID,
89         m_boundInterfaceIdentifier,
90         m_allowsCellularAccess,
91         m_proxyConfiguration,
92         m_configuration->sourceApplicationBundleIdentifier(),
93         m_configuration->sourceApplicationSecondaryIdentifier(),
94         shouldLogCookieInformation,
95         Seconds { [defaults integerForKey:WebKitNetworkLoadThrottleLatencyMillisecondsDefaultsKey] / 1000. },
96         WTFMove(httpProxy),
97         WTFMove(httpsProxy),
98     };
99
100     auto cookieFile = resolvedCookieStorageFile();
101
102     if (m_uiProcessCookieStorageIdentifier.isEmpty()) {
103         auto utf8File = cookieFile.utf8();
104         auto url = adoptCF(CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (const UInt8 *)utf8File.data(), (CFIndex)utf8File.length(), true));
105         m_cfCookieStorage = adoptCF(CFHTTPCookieStorageCreateFromFile(kCFAllocatorDefault, url.get(), nullptr));
106         m_uiProcessCookieStorageIdentifier = identifyingDataFromCookieStorage(m_cfCookieStorage.get());
107     }
108
109     parameters.uiProcessCookieStorageIdentifier = m_uiProcessCookieStorageIdentifier;
110     parameters.networkSessionParameters.sourceApplicationBundleIdentifier = m_configuration->sourceApplicationBundleIdentifier();
111     parameters.networkSessionParameters.sourceApplicationSecondaryIdentifier = m_configuration->sourceApplicationSecondaryIdentifier();
112
113     parameters.pendingCookies = copyToVector(m_pendingCookies);
114
115     if (!cookieFile.isEmpty())
116         SandboxExtension::createHandleForReadWriteDirectory(WebCore::FileSystem::directoryName(cookieFile), parameters.cookieStoragePathExtensionHandle);
117
118 #if ENABLE(INDEXED_DATABASE)
119     parameters.indexedDatabaseDirectory = resolvedIndexedDatabaseDirectory();
120     if (!parameters.indexedDatabaseDirectory.isEmpty())
121         SandboxExtension::createHandleForReadWriteDirectory(parameters.indexedDatabaseDirectory, parameters.indexedDatabaseDirectoryExtensionHandle);
122 #endif
123
124 #if ENABLE(SERVICE_WORKER)
125     parameters.serviceWorkerRegistrationDirectory = resolvedServiceWorkerRegistrationDirectory();
126     if (!parameters.serviceWorkerRegistrationDirectory.isEmpty())
127         SandboxExtension::createHandleForReadWriteDirectory(parameters.serviceWorkerRegistrationDirectory, parameters.serviceWorkerRegistrationDirectoryExtensionHandle);
128 #endif
129
130     return parameters;
131 }
132
133 void WebsiteDataStore::platformInitialize()
134 {
135     if (!m_storageManager)
136         return;
137
138     if (!terminationObserver) {
139         ASSERT(dataStoresWithStorageManagers().isEmpty());
140
141 #if PLATFORM(MAC)
142         NSString *notificationName = NSApplicationWillTerminateNotification;
143 #else
144         NSString *notificationName = UIApplicationWillTerminateNotification;
145 #endif
146         terminationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:notificationName object:nil queue:nil usingBlock:^(NSNotification *note) {
147             for (auto& dataStore : dataStoresWithStorageManagers()) {
148                 dataStore->m_storageManager->applicationWillTerminate();
149                 if (dataStore->m_resourceLoadStatistics)
150                     dataStore->m_resourceLoadStatistics->applicationWillTerminate();
151             }
152         }];
153     }
154
155     ASSERT(!dataStoresWithStorageManagers().contains(this));
156     dataStoresWithStorageManagers().append(this);
157 }
158
159 void WebsiteDataStore::platformDestroy()
160 {
161     if (m_resourceLoadStatistics)
162         m_resourceLoadStatistics->applicationWillTerminate();
163
164     if (!m_storageManager)
165         return;
166
167     // FIXME: Rename applicationWillTerminate to something that better indicates what StorageManager does (waits for pending writes to finish).
168     m_storageManager->applicationWillTerminate();
169
170     ASSERT(dataStoresWithStorageManagers().contains(this));
171     dataStoresWithStorageManagers().removeFirst(this);
172
173     if (dataStoresWithStorageManagers().isEmpty()) {
174         [[NSNotificationCenter defaultCenter] removeObserver:terminationObserver];
175         terminationObserver = nil;
176     }
177 }
178
179 void WebsiteDataStore::platformRemoveRecentSearches(WallTime oldestTimeToRemove)
180 {
181     WebCore::removeRecentlyModifiedRecentSearches(oldestTimeToRemove);
182 }
183
184 }