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