a65fbf9db42b527ff6c43846ae8e30355a6a4cb9
[WebKit-https.git] / Source / WebKit2 / WebProcess / cocoa / WebProcessCocoa.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 "CustomProtocolManager.h"
30 #import "ObjCObjectGraph.h"
31 #import "SandboxExtension.h"
32 #import "SandboxInitializationParameters.h"
33 #import "SecItemShim.h"
34 #import "WKBrowsingContextHandleInternal.h"
35 #import "WKFullKeyboardAccessWatcher.h"
36 #import "WKTypeRefWrapper.h"
37 #import "WKWebProcessPlugInBrowserContextControllerInternal.h"
38 #import "WebFrame.h"
39 #import "WebInspector.h"
40 #import "WebPage.h"
41 #import "WebProcessCreationParameters.h"
42 #import "WebProcessProxyMessages.h"
43 #import <JavaScriptCore/Options.h>
44 #import <WebCore/AXObjectCache.h>
45 #import <WebCore/CFNetworkSPI.h>
46 #import <WebCore/FileSystem.h>
47 #import <WebCore/FontCascade.h>
48 #import <WebCore/LocalizedStrings.h>
49 #import <WebCore/MemoryCache.h>
50 #import <WebCore/MemoryPressureHandler.h>
51 #import <WebCore/PageCache.h>
52 #import <WebCore/WebCoreNSURLExtras.h>
53 #import <WebKitSystemInterface.h>
54 #import <algorithm>
55 #import <dispatch/dispatch.h>
56 #import <mach/host_info.h>
57 #import <mach/mach.h>
58 #import <mach/mach_error.h>
59 #import <objc/runtime.h>
60 #import <stdio.h>
61
62 #define ENABLE_MANUAL_WEBPROCESS_SANDBOXING !PLATFORM(IOS)
63
64 using namespace WebCore;
65
66 namespace WebKit {
67
68 static uint64_t memorySize()
69 {
70     static host_basic_info_data_t hostInfo;
71
72     static dispatch_once_t once;
73     dispatch_once(&once, ^() {
74         mach_port_t host = mach_host_self();
75         mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
76         kern_return_t r = host_info(host, HOST_BASIC_INFO, (host_info_t)&hostInfo, &count);
77         mach_port_deallocate(mach_task_self(), host);
78
79         if (r != KERN_SUCCESS)
80             LOG_ERROR("%s : host_info(%d) : %s.\n", __FUNCTION__, r, mach_error_string(r));
81     });
82
83     return hostInfo.max_mem;
84 }
85
86 static uint64_t volumeFreeSize(NSString *path)
87 {
88     NSDictionary *fileSystemAttributesDictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:path error:NULL];
89     return [[fileSystemAttributesDictionary objectForKey:NSFileSystemFreeSize] unsignedLongLongValue];
90 }
91
92 void WebProcess::platformSetCacheModel(CacheModel cacheModel)
93 {
94     RetainPtr<NSString> nsurlCacheDirectory = adoptNS((NSString *)WKCopyFoundationCacheDirectory());
95     if (!nsurlCacheDirectory)
96         nsurlCacheDirectory = NSHomeDirectory();
97
98     // As a fudge factor, use 1000 instead of 1024, in case the reported byte 
99     // count doesn't align exactly to a megabyte boundary.
100     uint64_t memSize = memorySize() / 1024 / 1000;
101     uint64_t diskFreeSize = volumeFreeSize(nsurlCacheDirectory.get()) / 1024 / 1000;
102
103     unsigned cacheTotalCapacity = 0;
104     unsigned cacheMinDeadCapacity = 0;
105     unsigned cacheMaxDeadCapacity = 0;
106     auto deadDecodedDataDeletionInterval = std::chrono::seconds { 0 };
107     unsigned pageCacheSize = 0;
108     unsigned long urlCacheMemoryCapacity = 0;
109     unsigned long urlCacheDiskCapacity = 0;
110
111     calculateCacheSizes(cacheModel, memSize, diskFreeSize,
112         cacheTotalCapacity, cacheMinDeadCapacity, cacheMaxDeadCapacity, deadDecodedDataDeletionInterval,
113         pageCacheSize, urlCacheMemoryCapacity, urlCacheDiskCapacity);
114
115     auto& memoryCache = MemoryCache::singleton();
116     memoryCache.setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
117     memoryCache.setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);
118     PageCache::singleton().setMaxSize(pageCacheSize);
119
120     NSURLCache *nsurlCache = [NSURLCache sharedURLCache];
121
122     [nsurlCache setMemoryCapacity:urlCacheMemoryCapacity];
123     if (!m_diskCacheIsDisabledForTesting)
124         [nsurlCache setDiskCapacity:std::max<unsigned long>(urlCacheDiskCapacity, [nsurlCache diskCapacity])]; // Don't shrink a big disk cache, since that would cause churn.
125 }
126
127 void WebProcess::platformClearResourceCaches(ResourceCachesToClear cachesToClear)
128 {
129     if (cachesToClear == InMemoryResourceCachesOnly)
130         return;
131
132     // If we're using the network process then it is the only one that needs to clear the disk cache.
133     if (usesNetworkProcess())
134         return;
135
136     if (!m_clearResourceCachesDispatchGroup)
137         m_clearResourceCachesDispatchGroup = dispatch_group_create();
138
139     dispatch_group_async(m_clearResourceCachesDispatchGroup, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
140         [[NSURLCache sharedURLCache] removeAllCachedResponses];
141     });
142 }
143
144 #if USE(APPKIT)
145 static id NSApplicationAccessibilityFocusedUIElement(NSApplication*, SEL)
146 {
147     WebPage* page = WebProcess::singleton().focusedWebPage();
148     if (!page || !page->accessibilityRemoteObject())
149         return 0;
150
151     return [page->accessibilityRemoteObject() accessibilityFocusedUIElement];
152 }
153 #endif
154
155 void WebProcess::platformInitializeWebProcess(WebProcessCreationParameters&& parameters)
156 {
157 #if ENABLE(SANDBOX_EXTENSIONS)
158     SandboxExtension::consumePermanently(parameters.uiProcessBundleResourcePathExtensionHandle);
159     SandboxExtension::consumePermanently(parameters.webSQLDatabaseDirectoryExtensionHandle);
160     SandboxExtension::consumePermanently(parameters.applicationCacheDirectoryExtensionHandle);
161     SandboxExtension::consumePermanently(parameters.diskCacheDirectoryExtensionHandle);
162     SandboxExtension::consumePermanently(parameters.mediaKeyStorageDirectoryExtensionHandle);
163 #if PLATFORM(IOS)
164     SandboxExtension::consumePermanently(parameters.cookieStorageDirectoryExtensionHandle);
165     SandboxExtension::consumePermanently(parameters.containerCachesDirectoryExtensionHandle);
166     SandboxExtension::consumePermanently(parameters.containerTemporaryDirectoryExtensionHandle);
167 #endif
168 #endif
169
170     // FIXME: Most of what this function does for cache size gets immediately overridden by setCacheModel().
171     // - memory cache size passed from UI process is always ignored;
172     // - disk cache size passed from UI process is effectively a minimum size.
173     // One non-obvious constraint is that we need to use -setSharedURLCache: even in testing mode, to prevent creating a default one on disk later, when some other code touches the cache.
174
175     ASSERT(!m_diskCacheIsDisabledForTesting || !parameters.nsURLCacheDiskCapacity);
176
177 #if PLATFORM(IOS)
178     if (!parameters.uiProcessBundleIdentifier.isNull()) {
179         [NSURLCache setSharedURLCache:adoptNS([[NSURLCache alloc]
180             _initWithMemoryCapacity:parameters.nsURLCacheMemoryCapacity
181             diskCapacity:parameters.nsURLCacheDiskCapacity
182             relativePath:parameters.uiProcessBundleIdentifier]).get()];
183     }
184 #else
185     if (!parameters.diskCacheDirectory.isNull()) {
186         [NSURLCache setSharedURLCache:adoptNS([[NSURLCache alloc]
187             initWithMemoryCapacity:parameters.nsURLCacheMemoryCapacity
188             diskCapacity:parameters.nsURLCacheDiskCapacity
189             diskPath:parameters.diskCacheDirectory]).get()];
190     }
191 #endif
192
193     m_compositingRenderServerPort = WTF::move(parameters.acceleratedCompositingPort);
194     m_presenterApplicationPid = parameters.presenterApplicationPid;
195     FontCascade::setDefaultTypesettingFeatures(parameters.shouldEnableKerningAndLigaturesByDefault ? Kerning | Ligatures : 0);
196
197     MemoryPressureHandler::ReliefLogger::setLoggingEnabled(parameters.shouldEnableMemoryPressureReliefLogging);
198
199     setEnhancedAccessibility(parameters.accessibilityEnhancedUserInterfaceEnabled);
200
201 #if USE(APPKIT)
202     [[NSUserDefaults standardUserDefaults] registerDefaults:@{ @"NSApplicationCrashOnExceptions" : @YES }];
203
204     // rdar://9118639 accessibilityFocusedUIElement in NSApplication defaults to use the keyWindow. Since there's
205     // no window in WK2, NSApplication needs to use the focused page's focused element.
206     Method methodToPatch = class_getInstanceMethod([NSApplication class], @selector(accessibilityFocusedUIElement));
207     method_setImplementation(methodToPatch, (IMP)NSApplicationAccessibilityFocusedUIElement);
208 #endif
209 #if (TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100)
210     _CFNetworkSetATSContext(parameters.networkATSContext.get());
211 #endif
212 }
213
214 void WebProcess::initializeProcessName(const ChildProcessInitializationParameters& parameters)
215 {
216 #if !PLATFORM(IOS)
217     NSString *applicationName;
218     if (parameters.extraInitializationData.get(ASCIILiteral("inspector-process")) == "1")
219         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Inspector", "Visible name of Web Inspector's web process. The argument is the application name."), (NSString *)parameters.uiProcessName];
220     else
221         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content", "Visible name of the web process. The argument is the application name."), (NSString *)parameters.uiProcessName];
222     WKSetVisibleApplicationName((CFStringRef)applicationName);
223 #endif
224 }
225
226 void WebProcess::platformInitializeProcess(const ChildProcessInitializationParameters&)
227 {
228     WKAXRegisterRemoteApp();
229
230 #if ENABLE(SEC_ITEM_SHIM)
231     SecItemShim::singleton().initialize(this);
232 #endif
233 }
234
235 #if USE(APPKIT)
236 void WebProcess::stopRunLoop()
237 {
238     ChildProcess::stopNSAppRunLoop();
239 }
240 #endif
241
242 void WebProcess::platformTerminate()
243 {
244     if (m_clearResourceCachesDispatchGroup) {
245         dispatch_group_wait(m_clearResourceCachesDispatchGroup, DISPATCH_TIME_FOREVER);
246         dispatch_release(m_clearResourceCachesDispatchGroup);
247         m_clearResourceCachesDispatchGroup = 0;
248     }
249 }
250
251 void WebProcess::initializeSandbox(const ChildProcessInitializationParameters& parameters, SandboxInitializationParameters& sandboxParameters)
252 {
253 #if ENABLE(WEB_PROCESS_SANDBOX)
254 #if ENABLE_MANUAL_WEBPROCESS_SANDBOXING
255     // Need to override the default, because service has a different bundle ID.
256     NSBundle *webkit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKView")];
257 #if PLATFORM(IOS)
258     sandboxParameters.setOverrideSandboxProfilePath([webkit2Bundle pathForResource:@"com.apple.WebKit.WebContent" ofType:@"sb"]);
259 #else
260     sandboxParameters.setOverrideSandboxProfilePath([webkit2Bundle pathForResource:@"com.apple.WebProcess" ofType:@"sb"]);
261 #endif
262     ChildProcess::initializeSandbox(parameters, sandboxParameters);
263 #endif
264 #else
265     UNUSED_PARAM(parameters);
266     UNUSED_PARAM(sandboxParameters);
267 #endif
268 }
269
270 #if PLATFORM(MAC)
271
272 static NSURL *origin(WebPage& page)
273 {
274     WebFrame* mainFrame = page.mainWebFrame();
275     if (!mainFrame)
276         return nil;
277
278     URL mainFrameURL(URL(), mainFrame->url());
279     RefPtr<SecurityOrigin> mainFrameOrigin = SecurityOrigin::create(mainFrameURL);
280     String mainFrameOriginString;
281     if (!mainFrameOrigin->isUnique())
282         mainFrameOriginString = mainFrameOrigin->toRawString();
283     else
284         mainFrameOriginString = mainFrameURL.protocol() + ':'; // toRawString() is not supposed to work with unique origins, and would just return "://".
285
286     // +[NSURL URLWithString:] returns nil when its argument is malformed. It's unclear when we would have a malformed URL here,
287     // but it happens in practice according to <rdar://problem/14173389>. Leaving an assertion in to catch a reproducible case.
288     ASSERT([NSURL URLWithString:mainFrameOriginString]);
289
290     return [NSURL URLWithString:mainFrameOriginString];
291 }
292
293 #endif
294
295 void WebProcess::updateActivePages()
296 {
297 #if PLATFORM(MAC)
298     RetainPtr<CFMutableArrayRef> activePageURLs = adoptCF(CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks));
299     for (auto& page : m_pageMap.values()) {
300         if (NSURL *originAsURL = origin(*page))
301             CFArrayAppendValue(activePageURLs.get(), userVisibleString(originAsURL));
302     }
303     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), [activePageURLs] {
304         WKSetApplicationInformationItem(CFSTR("LSActivePageUserVisibleOriginsKey"), activePageURLs.get());
305     });
306 #endif
307 }
308
309 RefPtr<ObjCObjectGraph> WebProcess::transformHandlesToObjects(ObjCObjectGraph& objectGraph)
310 {
311     struct Transformer final : ObjCObjectGraph::Transformer {
312         Transformer(WebProcess& webProcess)
313             : m_webProcess(webProcess)
314         {
315         }
316
317         virtual bool shouldTransformObject(id object) const override
318         {
319 #if WK_API_ENABLED
320             if (dynamic_objc_cast<WKBrowsingContextHandle>(object))
321                 return true;
322
323             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
324                 return true;
325 #endif
326             return false;
327         }
328
329         virtual RetainPtr<id> transformObject(id object) const override
330         {
331 #if WK_API_ENABLED
332             if (auto* handle = dynamic_objc_cast<WKBrowsingContextHandle>(object)) {
333                 if (auto* webPage = m_webProcess.webPage(handle._pageID))
334                     return wrapper(*webPage);
335
336                 return [NSNull null];
337             }
338
339             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
340                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(m_webProcess.transformHandlesToObjects(toImpl(wrapper.object)).get())]);
341 #endif
342             return object;
343         }
344
345         WebProcess& m_webProcess;
346     };
347
348     return ObjCObjectGraph::create(ObjCObjectGraph::transform(objectGraph.rootObject(), Transformer(*this)).get());
349 }
350
351 RefPtr<ObjCObjectGraph> WebProcess::transformObjectsToHandles(ObjCObjectGraph& objectGraph)
352 {
353     struct Transformer final : ObjCObjectGraph::Transformer {
354         virtual bool shouldTransformObject(id object) const override
355         {
356 #if WK_API_ENABLED
357             if (dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
358                 return true;
359
360             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
361                 return true;
362 #endif
363
364             return false;
365         }
366
367         virtual RetainPtr<id> transformObject(id object) const override
368         {
369 #if WK_API_ENABLED
370             if (auto* controller = dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
371                 return controller.handle;
372
373             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
374                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(transformObjectsToHandles(toImpl(wrapper.object)).get())]);
375 #endif
376             return object;
377         }
378     };
379
380     return ObjCObjectGraph::create(ObjCObjectGraph::transform(objectGraph.rootObject(), Transformer()).get());
381 }
382
383 } // namespace WebKit