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