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