e418396db5da2207c4bdc143a954d43c86c07340
[WebKit-https.git] / Source / WebKit / UIProcess / API / Cocoa / APIWebsiteDataStoreCocoa.mm
1 /*
2  * Copyright (C) 2014, 2016 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 "APIWebsiteDataStore.h"
28
29 #include "SandboxExtension.h"
30 #include "SandboxUtilities.h"
31
32 #include <Foundation/Foundation.h>
33 #include <WebCore/FileSystem.h>
34
35 #if PLATFORM(IOS)
36 #import <WebCore/RuntimeApplicationChecks.h>
37 #endif
38
39 namespace API {
40
41 NSString *WebDatabaseDirectoryDefaultsKey = @"WebDatabaseDirectory";
42 NSString *WebStorageDirectoryDefaultsKey = @"WebKitLocalStorageDatabasePathPreferenceKey";
43 NSString *WebKitMediaCacheDirectoryDefaultsKey = @"WebKitMediaCacheDirectory";
44 NSString *WebKitMediaKeysStorageDirectoryDefaultsKey = @"WebKitMediaKeysStorageDirectory";
45
46 String WebsiteDataStore::defaultApplicationCacheDirectory()
47 {
48 #if PLATFORM(IOS)
49     // This quirk used to make these apps share application cache storage, but doesn't accomplish that any more.
50     // Preserving it avoids the need to migrate data when upgrading.
51     // FIXME: Ideally we should just have Safari, WebApp, and webbookmarksd create a data store with
52     // this application cache path, but that's not supported as of right now.
53     if (WebCore::IOSApplication::isMobileSafari() || WebCore::IOSApplication::isWebApp() || WebCore::IOSApplication::isWebBookmarksD()) {
54         NSString *cachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches/com.apple.WebAppCache"];
55
56         return WebKit::stringByResolvingSymlinksInPath(cachePath.stringByStandardizingPath);
57     }
58 #endif
59
60     return cacheDirectoryFileSystemRepresentation("OfflineWebApplicationCache");
61 }
62
63 String WebsiteDataStore::defaultCacheStorageDirectory()
64 {
65     return cacheDirectoryFileSystemRepresentation("CacheStorage");
66 }
67
68 String WebsiteDataStore::defaultNetworkCacheDirectory()
69 {
70     return cacheDirectoryFileSystemRepresentation("NetworkCache");
71 }
72
73 String WebsiteDataStore::defaultMediaCacheDirectory()
74 {
75     return tempDirectoryFileSystemRepresentation("MediaCache");
76 }
77
78 String WebsiteDataStore::defaultIndexedDBDatabaseDirectory()
79 {
80     return websiteDataDirectoryFileSystemRepresentation("IndexedDB");
81 }
82
83 String WebsiteDataStore::defaultServiceWorkerRegistrationDirectory()
84 {
85     return cacheDirectoryFileSystemRepresentation("ServiceWorkers");
86 }
87
88 String WebsiteDataStore::defaultLocalStorageDirectory()
89 {
90     return websiteDataDirectoryFileSystemRepresentation("LocalStorage");
91 }
92
93 String WebsiteDataStore::defaultMediaKeysStorageDirectory()
94 {
95     return websiteDataDirectoryFileSystemRepresentation("MediaKeys");
96 }
97
98 String WebsiteDataStore::defaultWebSQLDatabaseDirectory()
99 {
100     return websiteDataDirectoryFileSystemRepresentation("WebSQL");
101 }
102
103 String WebsiteDataStore::defaultResourceLoadStatisticsDirectory()
104 {
105     return websiteDataDirectoryFileSystemRepresentation("ResourceLoadStatistics");
106 }
107
108 String WebsiteDataStore::defaultJavaScriptConfigurationDirectory()
109 {
110     return tempDirectoryFileSystemRepresentation("JavaScriptCoreDebug", DontCreateDirectory);
111 }
112
113 String WebsiteDataStore::legacyDefaultApplicationCacheDirectory()
114 {
115     NSString *appName = [[NSBundle mainBundle] bundleIdentifier];
116     if (!appName)
117         appName = [[NSProcessInfo processInfo] processName];
118 #if PLATFORM(IOS)
119     // This quirk used to make these apps share application cache storage, but doesn't accomplish that any more.
120     // Preserving it avoids the need to migrate data when upgrading.
121     if (WebCore::IOSApplication::isMobileSafari() || WebCore::IOSApplication::isWebApp())
122         appName = @"com.apple.WebAppCache";
123 #endif
124     
125     ASSERT(appName);
126     
127 #if PLATFORM(IOS)
128     NSString *cacheDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
129 #else
130     char cacheDirectory[MAXPATHLEN];
131     size_t cacheDirectoryLen = confstr(_CS_DARWIN_USER_CACHE_DIR, cacheDirectory, MAXPATHLEN);
132     if (!cacheDirectoryLen)
133         return String();
134     
135     NSString *cacheDir = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:cacheDirectory length:cacheDirectoryLen - 1];
136 #endif
137     NSString* cachePath = [cacheDir stringByAppendingPathComponent:appName];
138     return WebKit::stringByResolvingSymlinksInPath([cachePath stringByStandardizingPath]);
139 }
140
141 String WebsiteDataStore::legacyDefaultNetworkCacheDirectory()
142 {
143     NSString *cachePath = CFBridgingRelease(_CFURLCacheCopyCacheDirectory([[NSURLCache sharedURLCache] _CFURLCache]));
144     if (!cachePath)
145         cachePath = @"~/Library/Caches/com.apple.WebKit.WebProcess";
146     
147     cachePath = [cachePath stringByAppendingPathComponent:@"WebKitCache"];
148     
149     return WebKit::stringByResolvingSymlinksInPath([cachePath stringByStandardizingPath]);
150 }
151
152 String WebsiteDataStore::legacyDefaultWebSQLDatabaseDirectory()
153 {
154     NSString *databasesDirectory = [[NSUserDefaults standardUserDefaults] objectForKey:WebDatabaseDirectoryDefaultsKey];
155     if (!databasesDirectory || ![databasesDirectory isKindOfClass:[NSString class]])
156         databasesDirectory = @"~/Library/WebKit/Databases";
157     return WebKit::stringByResolvingSymlinksInPath([databasesDirectory stringByStandardizingPath]);
158 }
159
160 String WebsiteDataStore::legacyDefaultIndexedDBDatabaseDirectory()
161 {
162     // Indexed databases exist in a subdirectory of the "database directory path."
163     // Currently, the top level of that directory contains entities related to WebSQL databases.
164     // We should fix this, and move WebSQL into a subdirectory (https://bugs.webkit.org/show_bug.cgi?id=124807)
165     // In the meantime, an entity name prefixed with three underscores will not conflict with any WebSQL entities.
166     return WebCore::FileSystem::pathByAppendingComponent(legacyDefaultWebSQLDatabaseDirectory(), "___IndexedDB");
167 }
168
169 String WebsiteDataStore::legacyDefaultLocalStorageDirectory()
170 {
171     NSString *localStorageDirectory = [[NSUserDefaults standardUserDefaults] objectForKey:WebStorageDirectoryDefaultsKey];
172     if (!localStorageDirectory || ![localStorageDirectory isKindOfClass:[NSString class]])
173         localStorageDirectory = @"~/Library/WebKit/LocalStorage";
174     return WebKit::stringByResolvingSymlinksInPath([localStorageDirectory stringByStandardizingPath]);
175 }
176
177 String WebsiteDataStore::legacyDefaultMediaCacheDirectory()
178 {
179     NSString *mediaKeysCacheDirectory = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitMediaCacheDirectoryDefaultsKey];
180     if (!mediaKeysCacheDirectory || ![mediaKeysCacheDirectory isKindOfClass:[NSString class]]) {
181         mediaKeysCacheDirectory = NSTemporaryDirectory();
182         
183         if (!WebKit::processHasContainer()) {
184             NSString *bundleIdentifier = [NSBundle mainBundle].bundleIdentifier;
185             if (!bundleIdentifier)
186                 bundleIdentifier = [NSProcessInfo processInfo].processName;
187             mediaKeysCacheDirectory = [mediaKeysCacheDirectory stringByAppendingPathComponent:bundleIdentifier];
188         }
189         mediaKeysCacheDirectory = [mediaKeysCacheDirectory stringByAppendingPathComponent:@"WebKit/MediaCache"];
190     }
191     return WebKit::stringByResolvingSymlinksInPath([mediaKeysCacheDirectory stringByStandardizingPath]);
192 }
193
194 String WebsiteDataStore::legacyDefaultMediaKeysStorageDirectory()
195 {
196     NSString *mediaKeysStorageDirectory = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitMediaKeysStorageDirectoryDefaultsKey];
197     if (!mediaKeysStorageDirectory || ![mediaKeysStorageDirectory isKindOfClass:[NSString class]])
198         mediaKeysStorageDirectory = @"~/Library/WebKit/MediaKeys";
199     return WebKit::stringByResolvingSymlinksInPath([mediaKeysStorageDirectory stringByStandardizingPath]);
200 }
201
202 String WebsiteDataStore::legacyDefaultJavaScriptConfigurationDirectory()
203 {
204 #if PLATFORM(IOS)
205     String path = WebKit::pathForProcessContainer();
206     if (path.isEmpty())
207         path = NSHomeDirectory();
208     
209     path = path + "/Library/WebKit/JavaScriptCoreDebug";
210     path = WebKit::stringByResolvingSymlinksInPath(path);
211     
212     return path;
213 #else
214     RetainPtr<NSString> javaScriptConfigPath = @"~/Library/WebKit/JavaScriptCoreDebug";
215     
216     return WebKit::stringByResolvingSymlinksInPath([javaScriptConfigPath stringByStandardizingPath]);
217 #endif
218 }
219
220 String WebsiteDataStore::tempDirectoryFileSystemRepresentation(const String& directoryName, ShouldCreateDirectory shouldCreateDirectory)
221 {
222     static dispatch_once_t onceToken;
223     static NSURL *tempURL;
224     
225     dispatch_once(&onceToken, ^{
226         NSURL *url = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
227         if (!url)
228             RELEASE_ASSERT_NOT_REACHED();
229         
230         if (!WebKit::processHasContainer()) {
231             NSString *bundleIdentifier = [NSBundle mainBundle].bundleIdentifier;
232             if (!bundleIdentifier)
233                 bundleIdentifier = [NSProcessInfo processInfo].processName;
234             url = [url URLByAppendingPathComponent:bundleIdentifier isDirectory:YES];
235         }
236         
237         tempURL = [[url URLByAppendingPathComponent:@"WebKit" isDirectory:YES] retain];
238     });
239     
240     NSURL *url = [tempURL URLByAppendingPathComponent:directoryName isDirectory:YES];
241
242     if (shouldCreateDirectory == CreateDirectory
243         && (![[NSFileManager defaultManager] createDirectoryAtURL:url withIntermediateDirectories:YES attributes:nil error:nullptr]))
244         LOG_ERROR("Failed to create directory %@", url);
245     
246     return url.absoluteURL.path.fileSystemRepresentation;
247 }
248
249 String WebsiteDataStore::cacheDirectoryFileSystemRepresentation(const String& directoryName)
250 {
251     static dispatch_once_t onceToken;
252     static NSURL *cacheURL;
253
254     dispatch_once(&onceToken, ^{
255         NSURL *url = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nullptr create:NO error:nullptr];
256         if (!url)
257             RELEASE_ASSERT_NOT_REACHED();
258
259         if (!WebKit::processHasContainer()) {
260             NSString *bundleIdentifier = [NSBundle mainBundle].bundleIdentifier;
261             if (!bundleIdentifier)
262                 bundleIdentifier = [NSProcessInfo processInfo].processName;
263             url = [url URLByAppendingPathComponent:bundleIdentifier isDirectory:YES];
264         }
265
266         cacheURL = [[url URLByAppendingPathComponent:@"WebKit" isDirectory:YES] retain];
267     });
268
269     NSURL *url = [cacheURL URLByAppendingPathComponent:directoryName isDirectory:YES];
270     if (![[NSFileManager defaultManager] createDirectoryAtURL:url withIntermediateDirectories:YES attributes:nil error:nullptr])
271         LOG_ERROR("Failed to create directory %@", url);
272
273     return url.absoluteURL.path.fileSystemRepresentation;
274 }
275
276 String WebsiteDataStore::websiteDataDirectoryFileSystemRepresentation(const String& directoryName)
277 {
278     static dispatch_once_t onceToken;
279     static NSURL *websiteDataURL;
280
281     dispatch_once(&onceToken, ^{
282         NSURL *url = [[NSFileManager defaultManager] URLForDirectory:NSLibraryDirectory inDomain:NSUserDomainMask appropriateForURL:nullptr create:NO error:nullptr];
283         if (!url)
284             RELEASE_ASSERT_NOT_REACHED();
285
286         url = [url URLByAppendingPathComponent:@"WebKit" isDirectory:YES];
287
288         if (!WebKit::processHasContainer()) {
289             NSString *bundleIdentifier = [NSBundle mainBundle].bundleIdentifier;
290             if (!bundleIdentifier)
291                 bundleIdentifier = [NSProcessInfo processInfo].processName;
292             url = [url URLByAppendingPathComponent:bundleIdentifier isDirectory:YES];
293         }
294
295         websiteDataURL = [[url URLByAppendingPathComponent:@"WebsiteData" isDirectory:YES] retain];
296     });
297
298     NSURL *url = [websiteDataURL URLByAppendingPathComponent:directoryName isDirectory:YES];
299     if (![[NSFileManager defaultManager] createDirectoryAtURL:url withIntermediateDirectories:YES attributes:nil error:nullptr])
300         LOG_ERROR("Failed to create directory %@", url);
301
302     return url.absoluteURL.path.fileSystemRepresentation;
303 }
304
305 WebKit::WebsiteDataStore::Configuration WebsiteDataStore::defaultDataStoreConfiguration()
306 {
307     WebKit::WebsiteDataStore::Configuration configuration;
308
309     configuration.applicationCacheDirectory = defaultApplicationCacheDirectory();
310     configuration.applicationCacheFlatFileSubdirectoryName = "Files";
311     configuration.cacheStorageDirectory = defaultCacheStorageDirectory();
312     configuration.networkCacheDirectory = defaultNetworkCacheDirectory();
313     configuration.mediaCacheDirectory = defaultMediaCacheDirectory();
314
315     configuration.indexedDBDatabaseDirectory = defaultIndexedDBDatabaseDirectory();
316     configuration.serviceWorkerRegistrationDirectory = defaultServiceWorkerRegistrationDirectory();
317     configuration.webSQLDatabaseDirectory = defaultWebSQLDatabaseDirectory();
318     configuration.localStorageDirectory = defaultLocalStorageDirectory();
319     configuration.mediaKeysStorageDirectory = defaultMediaKeysStorageDirectory();
320     configuration.resourceLoadStatisticsDirectory = defaultResourceLoadStatisticsDirectory();
321     
322     configuration.javaScriptConfigurationDirectory = defaultJavaScriptConfigurationDirectory();
323
324     return configuration;
325 }
326
327 } // namespace API