Reviewed by Darin Adler.
[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 "FullKeyboardAccessWatcher.h"
30 #import "SandboxExtension.h"
31 #import "WebProcessCreationParameters.h"
32 #import <WebCore/MemoryCache.h>
33 #import <WebCore/PageCache.h>
34 #import <WebKitSystemInterface.h>
35 #import <algorithm>
36 #import <dispatch/dispatch.h>
37 #import <mach/host_info.h>
38 #import <mach/mach.h>
39 #import <mach/mach_error.h>
40
41 #if ENABLE(WEB_PROCESS_SANDBOX)
42 #import <sandbox.h>
43 #import <stdlib.h>
44 #import <sysexits.h>
45 #endif
46
47 using namespace WebCore;
48 using namespace std;
49
50 namespace WebKit {
51
52 static uint64_t memorySize()
53 {
54     static host_basic_info_data_t hostInfo;
55
56     static dispatch_once_t once;
57     dispatch_once(&once, ^() {
58         mach_port_t host = mach_host_self();
59         mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
60         kern_return_t r = host_info(host, HOST_BASIC_INFO, (host_info_t)&hostInfo, &count);
61         mach_port_deallocate(mach_task_self(), host);
62
63         if (r != KERN_SUCCESS)
64             LOG_ERROR("%s : host_info(%d) : %s.\n", __FUNCTION__, r, mach_error_string(r));
65     });
66
67     return hostInfo.max_mem;
68 }
69
70 static uint64_t volumeFreeSize(NSString *path)
71 {
72     NSDictionary *fileSystemAttributesDictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:path error:NULL];
73     return [[fileSystemAttributesDictionary objectForKey:NSFileSystemFreeSize] unsignedLongLongValue];
74 }
75
76 void WebProcess::platformSetCacheModel(CacheModel cacheModel)
77 {
78     RetainPtr<NSString> nsurlCacheDirectory(AdoptNS, (NSString *)WKCopyFoundationCacheDirectory());
79     if (!nsurlCacheDirectory)
80         nsurlCacheDirectory = NSHomeDirectory();
81
82     // As a fudge factor, use 1000 instead of 1024, in case the reported byte 
83     // count doesn't align exactly to a megabyte boundary.
84     uint64_t memSize = memorySize() / 1024 / 1000;
85     uint64_t diskFreeSize = volumeFreeSize(nsurlCacheDirectory.get()) / 1024 / 1000;
86
87     unsigned cacheTotalCapacity = 0;
88     unsigned cacheMinDeadCapacity = 0;
89     unsigned cacheMaxDeadCapacity = 0;
90     double deadDecodedDataDeletionInterval = 0;
91     unsigned pageCacheCapacity = 0;
92     unsigned long urlCacheMemoryCapacity = 0;
93     unsigned long urlCacheDiskCapacity = 0;
94
95     calculateCacheSizes(cacheModel, memSize, diskFreeSize,
96         cacheTotalCapacity, cacheMinDeadCapacity, cacheMaxDeadCapacity, deadDecodedDataDeletionInterval,
97         pageCacheCapacity, urlCacheMemoryCapacity, urlCacheDiskCapacity);
98
99
100     memoryCache()->setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
101     memoryCache()->setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);
102     pageCache()->setCapacity(pageCacheCapacity);
103
104     NSURLCache *nsurlCache = [NSURLCache sharedURLCache];
105     [nsurlCache setMemoryCapacity:urlCacheMemoryCapacity];
106     [nsurlCache setDiskCapacity:max<unsigned long>(urlCacheDiskCapacity, [nsurlCache diskCapacity])]; // Don't shrink a big disk cache, since that would cause churn.
107 }
108
109 void WebProcess::platformClearResourceCaches()
110 {
111     [[NSURLCache sharedURLCache] removeAllCachedResponses];
112 }
113
114 bool WebProcess::fullKeyboardAccessEnabled()
115 {
116     return [FullKeyboardAccessWatcher fullKeyboardAccessEnabled];
117 }
118
119 #if ENABLE(WEB_PROCESS_SANDBOX)
120 static void appendSandboxParameterPath(Vector<const char*>& vector, const char* name, const char* path)
121 {
122     char normalizedPath[PATH_MAX];
123     if (!realpath(path, normalizedPath))
124         normalizedPath[0] = '\0';
125
126     vector.append(name);
127     vector.append(fastStrDup(normalizedPath));
128 }
129
130 static void appendSandboxParameterConfPath(Vector<const char*>& vector, const char* name, int confID)
131 {
132     char path[PATH_MAX];
133     if (confstr(confID, path, PATH_MAX) <= 0)
134         path[0] = '\0';
135
136     appendSandboxParameterPath(vector, name, path);
137 }
138 #endif
139
140 static void initializeSandbox(const WebProcessCreationParameters& parameters)
141 {
142 #if ENABLE(WEB_PROCESS_SANDBOX)
143     if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DisableSandbox"]) {
144         fprintf(stderr, "Bypassing sandbox due to DisableSandbox user default.\n");
145         return;
146     }
147
148     Vector<const char*> sandboxParameters;
149
150     appendSandboxParameterPath(sandboxParameters, "HOME_DIR", [NSHomeDirectory() fileSystemRepresentation]);
151     appendSandboxParameterPath(sandboxParameters, "WEBKIT2_FRAMEWORK_DIR", [[[[NSBundle bundleForClass:NSClassFromString(@"WKView")] bundlePath] stringByDeletingLastPathComponent] fileSystemRepresentation]);
152     appendSandboxParameterConfPath(sandboxParameters, "DARWIN_USER_TEMP_DIR", _CS_DARWIN_USER_TEMP_DIR);
153     appendSandboxParameterConfPath(sandboxParameters, "DARWIN_USER_CACHE_DIR", _CS_DARWIN_USER_CACHE_DIR);
154     appendSandboxParameterPath(sandboxParameters, "WEBKIT_DATABASE_DIR", [(NSString *)parameters.databaseDirectory fileSystemRepresentation]);
155     appendSandboxParameterPath(sandboxParameters, "NSURL_CACHE_DIR", parameters.nsURLCachePath.data());
156     appendSandboxParameterPath(sandboxParameters, "UI_PROCESS_BUNDLE_RESOURCE_DIR", parameters.uiProcessBundleResourcePath.data());
157     sandboxParameters.append(static_cast<const char*>(0));
158
159     const char* profilePath = [[[NSBundle mainBundle] pathForResource:@"com.apple.WebProcess" ofType:@"sb"] fileSystemRepresentation];
160
161     char* errorBuf;
162     if (sandbox_init_with_parameters(profilePath, SANDBOX_NAMED_EXTERNAL, sandboxParameters.data(), &errorBuf)) {
163         fprintf(stderr, "WebProcess: couldn't initialize sandbox profile [%s]\n", profilePath);
164         for (size_t i = 0; sandboxParameters[i]; i += 2)
165             fprintf(stderr, "%s=%s\n", sandboxParameters[i], sandboxParameters[i + 1]);
166         exit(EX_NOPERM);
167     }
168
169     for (size_t i = 0; sandboxParameters[i]; i += 2)
170         fastFree(const_cast<char*>(sandboxParameters[i + 1]));
171 #endif
172 }
173
174 void WebProcess::platformInitializeWebProcess(const WebProcessCreationParameters& parameters, CoreIPC::ArgumentDecoder*)
175 {
176     initializeSandbox(parameters);
177
178     if (!parameters.parentProcessName.isNull()) {
179         // FIXME (WebKit2) <rdar://problem/8728860> WebKit2 needs to be localized
180         NSString *applicationName = [NSString stringWithFormat:@"%@ Web Content", (NSString *)parameters.parentProcessName];
181         WKSetVisibleApplicationName((CFStringRef)applicationName);
182     }
183
184     if (!parameters.nsURLCachePath.isNull()) {
185         NSUInteger cacheMemoryCapacity = parameters.nsURLCacheMemoryCapacity;
186         NSUInteger cacheDiskCapacity = parameters.nsURLCacheDiskCapacity;
187
188         NSString *nsCachePath = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:parameters.nsURLCachePath.data() length:strlen(parameters.nsURLCachePath.data())];
189         RetainPtr<NSURLCache> parentProcessURLCache(AdoptNS, [[NSURLCache alloc] initWithMemoryCapacity:cacheMemoryCapacity diskCapacity:cacheDiskCapacity diskPath:nsCachePath]);
190         [NSURLCache setSharedURLCache:parentProcessURLCache.get()];
191     }
192
193     m_compositingRenderServerPort = parameters.acceleratedCompositingPort.port();
194 }
195
196 void WebProcess::platformTerminate()
197 {
198 }
199
200 } // namespace WebKit