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 "CustomProtocolManager.h"
30#import "SandboxExtension.h"
31#import "SandboxInitializationParameters.h"
32#import "WKFullKeyboardAccessWatcher.h"
33#import "WebFrame.h"
34#import "WebInspector.h"
35#import "WebPage.h"
36#import "WebProcessCreationParameters.h"
37#import "WebProcessProxyMessages.h"
38#import <WebCore/AXObjectCache.h>
39#import <WebCore/FileSystem.h>
40#import <WebCore/Font.h>
41#import <WebCore/LocalizedStrings.h>
42#import <WebCore/MemoryCache.h>
43#import <WebCore/PageCache.h>
44#import <WebCore/WebCoreNSURLExtras.h>
45#import <WebKitSystemInterface.h>
46#import <algorithm>
47#import <dispatch/dispatch.h>
48#import <mach/host_info.h>
49#import <mach/mach.h>
50#import <mach/mach_error.h>
51#import <objc/runtime.h>
52#import <stdio.h>
53
54#if USE(SECURITY_FRAMEWORK)
55#import "SecItemShim.h"
56#endif
57
58using namespace WebCore;
59
60const CFStringRef kLSActivePageUserVisibleOriginsKey = CFSTR("LSActivePageUserVisibleOriginsKey");
61
62namespace WebKit {
63
64static uint64_t memorySize()
65{
66    static host_basic_info_data_t hostInfo;
67
68    static dispatch_once_t once;
69    dispatch_once(&once, ^() {
70        mach_port_t host = mach_host_self();
71        mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
72        kern_return_t r = host_info(host, HOST_BASIC_INFO, (host_info_t)&hostInfo, &count);
73        mach_port_deallocate(mach_task_self(), host);
74
75        if (r != KERN_SUCCESS)
76            LOG_ERROR("%s : host_info(%d) : %s.\n", __FUNCTION__, r, mach_error_string(r));
77    });
78
79    return hostInfo.max_mem;
80}
81
82static uint64_t volumeFreeSize(NSString *path)
83{
84    NSDictionary *fileSystemAttributesDictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:path error:NULL];
85    return [[fileSystemAttributesDictionary objectForKey:NSFileSystemFreeSize] unsignedLongLongValue];
86}
87
88void WebProcess::platformSetCacheModel(CacheModel cacheModel)
89{
90    RetainPtr<NSString> nsurlCacheDirectory = adoptNS((NSString *)WKCopyFoundationCacheDirectory());
91    if (!nsurlCacheDirectory)
92        nsurlCacheDirectory = NSHomeDirectory();
93
94    // As a fudge factor, use 1000 instead of 1024, in case the reported byte
95    // count doesn't align exactly to a megabyte boundary.
96    uint64_t memSize = memorySize() / 1024 / 1000;
97    uint64_t diskFreeSize = volumeFreeSize(nsurlCacheDirectory.get()) / 1024 / 1000;
98
99    unsigned cacheTotalCapacity = 0;
100    unsigned cacheMinDeadCapacity = 0;
101    unsigned cacheMaxDeadCapacity = 0;
102    double deadDecodedDataDeletionInterval = 0;
103    unsigned pageCacheCapacity = 0;
104    unsigned long urlCacheMemoryCapacity = 0;
105    unsigned long urlCacheDiskCapacity = 0;
106
107    calculateCacheSizes(cacheModel, memSize, diskFreeSize,
108        cacheTotalCapacity, cacheMinDeadCapacity, cacheMaxDeadCapacity, deadDecodedDataDeletionInterval,
109        pageCacheCapacity, urlCacheMemoryCapacity, urlCacheDiskCapacity);
110
111
112    memoryCache()->setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
113    memoryCache()->setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);
114    pageCache()->setCapacity(pageCacheCapacity);
115
116    NSURLCache *nsurlCache = [NSURLCache sharedURLCache];
117
118#if ENABLE(NETWORK_PROCESS)
119    // FIXME: Once there is no loading being done in the WebProcess, we should remove this,
120    // as calling [NSURLCache sharedURLCache] initializes the cache, which we would rather not do.
121    if (m_usesNetworkProcess) {
122        [nsurlCache setMemoryCapacity:0];
123        [nsurlCache setDiskCapacity:0];
124        return;
125    }
126#endif
127
128    [nsurlCache setMemoryCapacity:urlCacheMemoryCapacity];
129    [nsurlCache setDiskCapacity:max<unsigned long>(urlCacheDiskCapacity, [nsurlCache diskCapacity])]; // Don't shrink a big disk cache, since that would cause churn.
130}
131
132void WebProcess::platformClearResourceCaches(ResourceCachesToClear cachesToClear)
133{
134    if (cachesToClear == InMemoryResourceCachesOnly)
135        return;
136
137    // If we're using the network process then it is the only one that needs to clear the disk cache.
138    if (usesNetworkProcess())
139        return;
140
141    if (!m_clearResourceCachesDispatchGroup)
142        m_clearResourceCachesDispatchGroup = dispatch_group_create();
143
144    dispatch_group_async(m_clearResourceCachesDispatchGroup, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
145        [[NSURLCache sharedURLCache] removeAllCachedResponses];
146    });
147}
148
149static id NSApplicationAccessibilityFocusedUIElement(NSApplication*, SEL)
150{
151    WebPage* page = WebProcess::shared().focusedWebPage();
152    if (!page || !page->accessibilityRemoteObject())
153        return 0;
154
155    return [page->accessibilityRemoteObject() accessibilityFocusedUIElement];
156}
157
158void WebProcess::platformInitializeWebProcess(const WebProcessCreationParameters& parameters, CoreIPC::MessageDecoder&)
159{
160    SandboxExtension::consumePermanently(parameters.uiProcessBundleResourcePathExtensionHandle);
161    SandboxExtension::consumePermanently(parameters.localStorageDirectoryExtensionHandle);
162    SandboxExtension::consumePermanently(parameters.databaseDirectoryExtensionHandle);
163    SandboxExtension::consumePermanently(parameters.applicationCacheDirectoryExtensionHandle);
164    SandboxExtension::consumePermanently(parameters.diskCacheDirectoryExtensionHandle);
165
166    // When the network process is enabled, each web process wants a stand-alone
167    // NSURLCache, which it can disable to save memory.
168#if ENABLE(NETWORK_PROCESS)
169    if (!m_usesNetworkProcess) {
170#endif
171        if (!parameters.diskCacheDirectory.isNull()) {
172            [NSURLCache setSharedURLCache:adoptNS([[NSURLCache alloc]
173                initWithMemoryCapacity:parameters.nsURLCacheMemoryCapacity
174                diskCapacity:parameters.nsURLCacheDiskCapacity
175                diskPath:parameters.diskCacheDirectory]).get()];
176        }
177#if ENABLE(NETWORK_PROCESS)
178    }
179#endif
180
181    m_shouldForceScreenFontSubstitution = parameters.shouldForceScreenFontSubstitution;
182    Font::setDefaultTypesettingFeatures(parameters.shouldEnableKerningAndLigaturesByDefault ? Kerning | Ligatures : 0);
183
184    m_compositingRenderServerPort = parameters.acceleratedCompositingPort.port();
185
186    m_presenterApplicationPid = parameters.presenterApplicationPid;
187
188    setEnhancedAccessibility(parameters.accessibilityEnhancedUserInterfaceEnabled);
189
190    // rdar://9118639 accessibilityFocusedUIElement in NSApplication defaults to use the keyWindow. Since there's
191    // no window in WK2, NSApplication needs to use the focused page's focused element.
192    Method methodToPatch = class_getInstanceMethod([NSApplication class], @selector(accessibilityFocusedUIElement));
193    method_setImplementation(methodToPatch, (IMP)NSApplicationAccessibilityFocusedUIElement);
194}
195
196void WebProcess::initializeProcessName(const ChildProcessInitializationParameters& parameters)
197{
198    NSString *applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content", "Visible name of the web process. The argument is the application name."), (NSString *)parameters.uiProcessName];
199    WKSetVisibleApplicationName((CFStringRef)applicationName);
200}
201
202void WebProcess::platformInitializeProcess(const ChildProcessInitializationParameters&)
203{
204    WKAXRegisterRemoteApp();
205
206#if USE(SECURITY_FRAMEWORK)
207    SecItemShim::shared().initialize(this);
208#endif
209}
210
211void WebProcess::stopRunLoop()
212{
213    ChildProcess::stopNSAppRunLoop();
214}
215
216void WebProcess::platformTerminate()
217{
218    if (m_clearResourceCachesDispatchGroup) {
219        dispatch_group_wait(m_clearResourceCachesDispatchGroup, DISPATCH_TIME_FOREVER);
220        dispatch_release(m_clearResourceCachesDispatchGroup);
221        m_clearResourceCachesDispatchGroup = 0;
222    }
223}
224
225void WebProcess::initializeSandbox(const ChildProcessInitializationParameters& parameters, SandboxInitializationParameters& sandboxParameters)
226{
227    // Need to overide the default, because service has a different bundle ID.
228    NSBundle *webkit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKView")];
229    sandboxParameters.setOverrideSandboxProfilePath([webkit2Bundle pathForResource:@"com.apple.WebProcess" ofType:@"sb"]);
230
231    ChildProcess::initializeSandbox(parameters, sandboxParameters);
232}
233
234void WebProcess::updateActivePages()
235{
236#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
237    RetainPtr<CFMutableArrayRef> activePageURLs = adoptCF(CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks));
238    for (const auto& iter: m_pageMap) {
239        WebPage* page = iter.value.get();
240        WebFrame* mainFrame = page->mainWebFrame();
241        if (!mainFrame)
242            continue;
243        String mainFrameOriginString;
244        RefPtr<SecurityOrigin> mainFrameOrigin = SecurityOrigin::createFromString(mainFrame->url());
245        if (!mainFrameOrigin->isUnique())
246            mainFrameOriginString = mainFrameOrigin->toRawString();
247        else
248            mainFrameOriginString = KURL(KURL(), mainFrame->url()).protocol() + ':'; // toRawString() is not supposed to work with unique origins, and would just return "://".
249
250        NSURL *originAsNSURL = [NSURL URLWithString:mainFrameOriginString];
251        // +[NSURL URLWithString:] returns nil when its argument is malformed. It's unclear how we can possibly have a malformed URL here,
252        // but it happens in practice according to <rdar://problem/14173389>. Leaving an assertion in to catch a reproducible case.
253        ASSERT(originAsNSURL);
254        NSString *userVisibleOriginString = originAsNSURL ? userVisibleString(originAsNSURL) : @"(null)";
255
256        CFArrayAppendValue(activePageURLs.get(), userVisibleOriginString);
257    }
258    WKSetApplicationInformationItem(kLSActivePageUserVisibleOriginsKey, activePageURLs.get());
259#endif
260}
261
262} // namespace WebKit
263