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