<http://webkit.org/b/91015> Remove BUILDING_ON / TARGETING macros in favor of system...
[WebKit-https.git] / Source / WebKit2 / WebProcess / mac / WebProcessMac.mm
1 /*
2  * Copyright (C) 2010 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 "WebProcess.h"
28
29 #import "SandboxExtension.h"
30 #import "WKFullKeyboardAccessWatcher.h"
31 #import "WebInspector.h"
32 #import "WebPage.h"
33 #import "WebProcessCreationParameters.h"
34 #import "WebProcessProxyMessages.h"
35 #import <WebCore/FileSystem.h>
36 #import <WebCore/LocalizedStrings.h>
37 #import <WebCore/MemoryCache.h>
38 #import <WebCore/PageCache.h>
39 #import <WebKitSystemInterface.h>
40 #import <algorithm>
41 #import <dispatch/dispatch.h>
42 #import <mach/host_info.h>
43 #import <mach/mach.h>
44 #import <mach/mach_error.h>
45 #import <objc/runtime.h>
46 #import <stdio.h>
47
48 #if __MAC_OS_X_VERSION_MIN_REQUIRED == 1060
49 #import "KeychainItemShimMethods.h"
50 #else
51 #import "SecItemShimMethods.h"
52 #endif
53
54 #if ENABLE(WEB_PROCESS_SANDBOX)
55 #import <stdlib.h>
56 #import <sysexits.h>
57
58 // We have to #undef __APPLE_API_PRIVATE to prevent sandbox.h from looking for a header file that does not exist (<rdar://problem/9679211>). 
59 #undef __APPLE_API_PRIVATE
60 #import <sandbox.h>
61
62 #define SANDBOX_NAMED_EXTERNAL 0x0003
63 extern "C" int sandbox_init_with_parameters(const char *profile, uint64_t flags, const char *const parameters[], char **errorbuf);
64
65 #endif
66
67 using namespace WebCore;
68 using namespace std;
69
70 namespace WebKit {
71
72 static uint64_t memorySize()
73 {
74     static host_basic_info_data_t hostInfo;
75
76     static dispatch_once_t once;
77     dispatch_once(&once, ^() {
78         mach_port_t host = mach_host_self();
79         mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
80         kern_return_t r = host_info(host, HOST_BASIC_INFO, (host_info_t)&hostInfo, &count);
81         mach_port_deallocate(mach_task_self(), host);
82
83         if (r != KERN_SUCCESS)
84             LOG_ERROR("%s : host_info(%d) : %s.\n", __FUNCTION__, r, mach_error_string(r));
85     });
86
87     return hostInfo.max_mem;
88 }
89
90 static uint64_t volumeFreeSize(NSString *path)
91 {
92     NSDictionary *fileSystemAttributesDictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:path error:NULL];
93     return [[fileSystemAttributesDictionary objectForKey:NSFileSystemFreeSize] unsignedLongLongValue];
94 }
95
96 void WebProcess::platformSetCacheModel(CacheModel cacheModel)
97 {
98     RetainPtr<NSString> nsurlCacheDirectory(AdoptNS, (NSString *)WKCopyFoundationCacheDirectory());
99     if (!nsurlCacheDirectory)
100         nsurlCacheDirectory = NSHomeDirectory();
101
102     // As a fudge factor, use 1000 instead of 1024, in case the reported byte 
103     // count doesn't align exactly to a megabyte boundary.
104     uint64_t memSize = memorySize() / 1024 / 1000;
105     uint64_t diskFreeSize = volumeFreeSize(nsurlCacheDirectory.get()) / 1024 / 1000;
106
107     unsigned cacheTotalCapacity = 0;
108     unsigned cacheMinDeadCapacity = 0;
109     unsigned cacheMaxDeadCapacity = 0;
110     double deadDecodedDataDeletionInterval = 0;
111     unsigned pageCacheCapacity = 0;
112     unsigned long urlCacheMemoryCapacity = 0;
113     unsigned long urlCacheDiskCapacity = 0;
114
115     calculateCacheSizes(cacheModel, memSize, diskFreeSize,
116         cacheTotalCapacity, cacheMinDeadCapacity, cacheMaxDeadCapacity, deadDecodedDataDeletionInterval,
117         pageCacheCapacity, urlCacheMemoryCapacity, urlCacheDiskCapacity);
118
119
120     memoryCache()->setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
121     memoryCache()->setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);
122     pageCache()->setCapacity(pageCacheCapacity);
123
124     NSURLCache *nsurlCache = [NSURLCache sharedURLCache];
125     [nsurlCache setMemoryCapacity:urlCacheMemoryCapacity];
126     [nsurlCache setDiskCapacity:max<unsigned long>(urlCacheDiskCapacity, [nsurlCache diskCapacity])]; // Don't shrink a big disk cache, since that would cause churn.
127 }
128
129 void WebProcess::platformClearResourceCaches(ResourceCachesToClear cachesToClear)
130 {
131     if (cachesToClear == InMemoryResourceCachesOnly)
132         return;
133
134     if (!m_clearResourceCachesDispatchGroup)
135         m_clearResourceCachesDispatchGroup = dispatch_group_create();
136
137     dispatch_group_async(m_clearResourceCachesDispatchGroup, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
138         [[NSURLCache sharedURLCache] removeAllCachedResponses];
139     });
140 }
141
142 #if ENABLE(WEB_PROCESS_SANDBOX)
143 static void appendSandboxParameterPathInternal(Vector<const char*>& vector, const char* name, const char* path)
144 {
145     char normalizedPath[PATH_MAX];
146     if (!realpath(path, normalizedPath))
147         normalizedPath[0] = '\0';
148
149     vector.append(name);
150     vector.append(fastStrDup(normalizedPath));
151 }
152
153 static void appendReadwriteConfDirectory(Vector<const char*>& vector, const char* name, int confID)
154 {
155     char path[PATH_MAX];
156     if (confstr(confID, path, PATH_MAX) <= 0)
157         path[0] = '\0';
158
159     appendSandboxParameterPathInternal(vector, name, path);
160 }
161
162 static void appendReadonlySandboxDirectory(Vector<const char*>& vector, const char* name, NSString *path)
163 {
164     appendSandboxParameterPathInternal(vector, name, [path length] ? [(NSString *)path fileSystemRepresentation] : "");
165 }
166
167 static void appendReadwriteSandboxDirectory(Vector<const char*>& vector, const char* name, NSString *path)
168 {
169     NSError *error = nil;
170
171     // This is very unlikely to fail, but in case it actually happens, we'd like some sort of output in the console.
172     if (![[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error])
173         NSLog(@"could not create \"%@\", error %@", path, error);
174
175     appendSandboxParameterPathInternal(vector, name, [(NSString *)path fileSystemRepresentation]);
176 }
177
178 #endif
179
180 static void initializeSandbox(const WebProcessCreationParameters& parameters)
181 {
182 #if ENABLE(WEB_PROCESS_SANDBOX)
183     if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DisableSandbox"]) {
184         WTFLogAlways("Bypassing sandbox due to DisableSandbox user default.\n");
185         return;
186     }
187
188 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
189     // Use private temporary and cache directories.
190     String systemDirectorySuffix = "com.apple.WebProcess+" + parameters.uiProcessBundleIdentifier;
191     setenv("DIRHELPER_USER_DIR_SUFFIX", fileSystemRepresentation(systemDirectorySuffix).data(), 0);
192     char temporaryDirectory[PATH_MAX];
193     if (!confstr(_CS_DARWIN_USER_TEMP_DIR, temporaryDirectory, sizeof(temporaryDirectory))) {
194         WTFLogAlways("WebProcess: couldn't retrieve private temporary directory path: %d\n", errno);
195         exit(EX_NOPERM);
196     }
197     setenv("TMPDIR", temporaryDirectory, 1);
198 #endif
199
200     Vector<const char*> sandboxParameters;
201
202     // These are read-only.
203     appendReadonlySandboxDirectory(sandboxParameters, "WEBKIT2_FRAMEWORK_DIR", [[[NSBundle bundleForClass:NSClassFromString(@"WKView")] bundlePath] stringByDeletingLastPathComponent]);
204     appendReadonlySandboxDirectory(sandboxParameters, "UI_PROCESS_BUNDLE_RESOURCE_DIR", parameters.uiProcessBundleResourcePath);
205     appendReadonlySandboxDirectory(sandboxParameters, "WEBKIT_WEB_INSPECTOR_DIR", parameters.webInspectorBaseDirectory);
206
207     // These are read-write getconf paths.
208     appendReadwriteConfDirectory(sandboxParameters, "DARWIN_USER_TEMP_DIR", _CS_DARWIN_USER_TEMP_DIR);
209     appendReadwriteConfDirectory(sandboxParameters, "DARWIN_USER_CACHE_DIR", _CS_DARWIN_USER_CACHE_DIR);
210
211     // These are read-write paths.
212     appendReadwriteSandboxDirectory(sandboxParameters, "HOME_DIR", NSHomeDirectory());
213     appendReadwriteSandboxDirectory(sandboxParameters, "WEBKIT_DATABASE_DIR", parameters.databaseDirectory);
214     appendReadwriteSandboxDirectory(sandboxParameters, "WEBKIT_LOCALSTORAGE_DIR", parameters.localStorageDirectory);
215     appendReadwriteSandboxDirectory(sandboxParameters, "WEBKIT_APPLICATION_CACHE_DIR", parameters.applicationCacheDirectory);
216     appendReadwriteSandboxDirectory(sandboxParameters, "NSURL_CACHE_DIR", parameters.nsURLCachePath);
217
218     sandboxParameters.append(static_cast<const char*>(0));
219
220     const char* profilePath = [[[NSBundle mainBundle] pathForResource:@"com.apple.WebProcess" ofType:@"sb"] fileSystemRepresentation];
221
222     char* errorBuf;
223     if (sandbox_init_with_parameters(profilePath, SANDBOX_NAMED_EXTERNAL, sandboxParameters.data(), &errorBuf)) {
224         WTFLogAlways("WebProcess: couldn't initialize sandbox profile [%s] error '%s'\n", profilePath, errorBuf);
225         for (size_t i = 0; sandboxParameters[i]; i += 2)
226             WTFLogAlways("%s=%s\n", sandboxParameters[i], sandboxParameters[i + 1]);
227         exit(EX_NOPERM);
228     }
229
230     for (size_t i = 0; sandboxParameters[i]; i += 2)
231         fastFree(const_cast<char*>(sandboxParameters[i + 1]));
232
233     // This will override LSFileQuarantineEnabled from Info.plist unless sandbox quarantine is globally disabled.
234     OSStatus error = WKEnableSandboxStyleFileQuarantine();
235     if (error) {
236         WTFLogAlways("WebProcess: couldn't enable sandbox style file quarantine: %ld\n", (long)error);
237         exit(EX_NOPERM);
238     }
239 #endif
240 }
241
242 static id NSApplicationAccessibilityFocusedUIElement(NSApplication*, SEL)
243 {
244     WebPage* page = WebProcess::shared().focusedWebPage();
245     if (!page || !page->accessibilityRemoteObject())
246         return 0;
247
248     return [page->accessibilityRemoteObject() accessibilityFocusedUIElement];
249 }
250     
251 void WebProcess::platformInitializeWebProcess(const WebProcessCreationParameters& parameters, CoreIPC::ArgumentDecoder*)
252 {
253     [[NSFileManager defaultManager] changeCurrentDirectoryPath:[[NSBundle mainBundle] bundlePath]];
254
255     initializeSandbox(parameters);
256
257     if (!parameters.parentProcessName.isNull()) {
258         NSString *applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content", "Visible name of the web process. The argument is the application name."), (NSString *)parameters.parentProcessName];
259         WKSetVisibleApplicationName((CFStringRef)applicationName);
260     }
261
262     if (!parameters.nsURLCachePath.isNull()) {
263         NSUInteger cacheMemoryCapacity = parameters.nsURLCacheMemoryCapacity;
264         NSUInteger cacheDiskCapacity = parameters.nsURLCacheDiskCapacity;
265
266         RetainPtr<NSURLCache> parentProcessURLCache(AdoptNS, [[NSURLCache alloc] initWithMemoryCapacity:cacheMemoryCapacity diskCapacity:cacheDiskCapacity diskPath:parameters.nsURLCachePath]);
267         [NSURLCache setSharedURLCache:parentProcessURLCache.get()];
268     }
269
270     m_compositingRenderServerPort = parameters.acceleratedCompositingPort.port();
271
272 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
273     m_notificationManager.initialize(parameters.notificationPermissions);
274 #endif
275
276     // rdar://9118639 accessibilityFocusedUIElement in NSApplication defaults to use the keyWindow. Since there's
277     // no window in WK2, NSApplication needs to use the focused page's focused element.
278     Method methodToPatch = class_getInstanceMethod([NSApplication class], @selector(accessibilityFocusedUIElement));
279     method_setImplementation(methodToPatch, (IMP)NSApplicationAccessibilityFocusedUIElement);
280 }
281
282 void WebProcess::initializeShim()
283 {
284 #if __MAC_OS_X_VERSION_MIN_REQUIRED == 1060
285     initializeKeychainItemShim();
286 #else
287     initializeSecItemShim();
288 #endif
289 }
290
291 void WebProcess::platformTerminate()
292 {
293     if (m_clearResourceCachesDispatchGroup) {
294         dispatch_group_wait(m_clearResourceCachesDispatchGroup, DISPATCH_TIME_FOREVER);
295         dispatch_release(m_clearResourceCachesDispatchGroup);
296         m_clearResourceCachesDispatchGroup = 0;
297     }
298 }
299
300 void WebProcess::secItemResponse(CoreIPC::Connection*, uint64_t requestID, const SecItemResponseData& response)
301 {
302 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
303     didReceiveSecItemResponse(requestID, response);
304 #endif
305 }
306
307 void WebProcess::secKeychainItemResponse(CoreIPC::Connection*, uint64_t requestID, const SecKeychainItemResponseData& response)
308 {
309 #if __MAC_OS_X_VERSION_MIN_REQUIRED == 1060
310     didReceiveSecKeychainItemResponse(requestID, response);
311 #endif
312 }
313
314 } // namespace WebKit