Add WTF::move()
[WebKit-https.git] / Source / WebKit2 / UIProcess / API / Cocoa / WKProcessPool.mm
1 /*
2  * Copyright (C) 2014 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 "WKProcessPoolInternal.h"
28
29 #if WK_API_ENABLED
30
31 #import "CacheModel.h"
32 #import "DownloadClient.h"
33 #import "HistoryClient.h"
34 #import "ProcessModel.h"
35 #import "SandboxUtilities.h"
36 #import "WKObject.h"
37 #import "WeakObjCPtr.h"
38 #import "WebCertificateInfo.h"
39 #import "WebContext.h"
40 #import "WebCookieManagerProxy.h"
41 #import "WebProcessMessages.h"
42 #import "_WKDownloadDelegate.h"
43 #import "_WKProcessPoolConfiguration.h"
44 #import <WebCore/CertificateInfo.h>
45 #import <wtf/RetainPtr.h>
46
47 #if PLATFORM(IOS)
48 #import <WebCore/WebCoreThreadSystemInterface.h>
49 #import "WKGeolocationProviderIOS.h"
50 #endif
51
52 #if __has_include(<CFNetwork/CFNSURLConnection.h>)
53 #import <CFNetwork/CFNSURLConnection.h>
54 #else
55 enum : NSUInteger {
56     NSHTTPCookieAcceptPolicyExclusivelyFromMainDocumentDomain = 3,
57 };
58 #endif
59
60 @implementation WKProcessPool {
61     WebKit::WeakObjCPtr<id <_WKDownloadDelegate>> _downloadDelegate;
62
63 #if PLATFORM(IOS)
64     RetainPtr<WKGeolocationProviderIOS> _geolocationProvider;
65 #endif // PLATFORM(IOS)
66 }
67
68 - (instancetype)init
69 {
70     return [self _initWithConfiguration:adoptNS([[_WKProcessPoolConfiguration alloc] init]).get()];
71 }
72
73 - (void)dealloc
74 {
75     _context->~WebContext();
76
77     [super dealloc];
78 }
79
80 - (NSString *)description
81 {
82     return [NSString stringWithFormat:@"<%@: %p; configuration = %@>", NSStringFromClass(self.class), self, _configuration.get()];
83 }
84
85 - (_WKProcessPoolConfiguration *)_configuration
86 {
87     return [[_configuration copy] autorelease];
88 }
89
90 - (API::Object&)_apiObject
91 {
92     return *_context;
93 }
94
95 #if PLATFORM(IOS)
96 - (WKGeolocationProviderIOS *)_geolocationProvider
97 {
98     if (!_geolocationProvider)
99         _geolocationProvider = adoptNS([[WKGeolocationProviderIOS alloc] initWithContext:_context.get()]);
100     return _geolocationProvider.get();
101 }
102 #endif // PLATFORM(IOS)
103
104 @end
105
106 @implementation WKProcessPool (WKPrivate)
107
108 + (NSURL *)_websiteDataURLForContainerWithURL:(NSURL *)containerURL
109 {
110     NSURL *url = [containerURL URLByAppendingPathComponent:@"Library" isDirectory:YES];
111     url = [url URLByAppendingPathComponent:@"WebKit" isDirectory:YES];
112     return [url URLByAppendingPathComponent:@"WebsiteData" isDirectory:YES];
113 }
114
115 static NSURL *websiteDataDirectoryURL(NSString *directoryName)
116 {
117     static dispatch_once_t onceToken;
118     static NSURL *websiteDataURL;
119
120     dispatch_once(&onceToken, ^{
121         NSURL *url = [[NSFileManager defaultManager] URLForDirectory:NSLibraryDirectory inDomain:NSUserDomainMask appropriateForURL:nullptr create:NO error:nullptr];
122         if (!url)
123             RELEASE_ASSERT_NOT_REACHED();
124
125         url = [url URLByAppendingPathComponent:@"WebKit" isDirectory:YES];
126
127         if (!WebKit::processHasContainer()) {
128             NSString *bundleIdentifier = [NSBundle mainBundle].bundleIdentifier;
129             if (!bundleIdentifier)
130                 bundleIdentifier = [NSProcessInfo processInfo].processName;
131             url = [url URLByAppendingPathComponent:bundleIdentifier isDirectory:YES];
132         }
133
134         websiteDataURL = [[url URLByAppendingPathComponent:@"WebsiteData" isDirectory:YES] retain];
135     });
136
137     NSURL *url = [websiteDataURL URLByAppendingPathComponent:directoryName isDirectory:YES];
138     if (![[NSFileManager defaultManager] createDirectoryAtURL:url withIntermediateDirectories:YES attributes:nil error:nullptr])
139         LOG_ERROR("Failed to create directory %@", url);
140
141     return url;
142 }
143
144 - (instancetype)_initWithConfiguration:(_WKProcessPoolConfiguration *)configuration
145 {
146     if (!(self = [super init]))
147         return nil;
148
149     _configuration = adoptNS([configuration copy]);
150
151 #if PLATFORM(IOS)
152     // FIXME: Remove once <rdar://problem/15256572> is fixed.
153     InitWebCoreThreadSystemInterface();
154 #endif
155
156     WebKit::WebContextConfiguration webContextConfiguration;
157
158     if (NSURL *bundleURL = [_configuration injectedBundleURL]) {
159         if (!bundleURL.isFileURL)
160             [NSException raise:NSInvalidArgumentException format:@"Injected Bundle URL must be a file URL"];
161
162         webContextConfiguration.injectedBundlePath = bundleURL.path;
163     }
164
165     webContextConfiguration.localStorageDirectory = websiteDataDirectoryURL(@"LocalStorage").absoluteURL.path.fileSystemRepresentation;
166     webContextConfiguration.webSQLDatabaseDirectory = websiteDataDirectoryURL(@"WebSQL").absoluteURL.path.fileSystemRepresentation;
167     webContextConfiguration.indexedDBDatabaseDirectory = websiteDataDirectoryURL(@"IndexedDB").absoluteURL.path.fileSystemRepresentation;
168
169     API::Object::constructInWrapper<WebKit::WebContext>(self, WTF::move(webContextConfiguration));
170     _context->setHistoryClient(std::make_unique<WebKit::HistoryClient>());
171     _context->setUsesNetworkProcess(true);
172     _context->setProcessModel(WebKit::ProcessModelMultipleSecondaryProcesses);
173
174 #if ENABLE(CACHE_PARTITIONING)
175     for (NSString *urlScheme in [_configuration cachePartitionedURLSchemes])
176         _context->registerURLSchemeAsCachePartitioned(urlScheme);
177 #endif
178
179     // FIXME: Add a way to configure the cache model, see <rdar://problem/16206857>.
180     _context->setCacheModel(WebKit::CacheModelPrimaryWebBrowser);
181
182     return self;
183 }
184
185 - (void)_setAllowsSpecificHTTPSCertificate:(NSArray *)certificateChain forHost:(NSString *)host
186 {
187     _context->allowSpecificHTTPSCertificateForHost(WebKit::WebCertificateInfo::create(WebCore::CertificateInfo((CFArrayRef)certificateChain)).get(), host);
188 }
189
190 static WebKit::HTTPCookieAcceptPolicy toHTTPCookieAcceptPolicy(NSHTTPCookieAcceptPolicy policy)
191 {
192     switch (static_cast<NSUInteger>(policy)) {
193     case NSHTTPCookieAcceptPolicyAlways:
194         return WebKit::HTTPCookieAcceptPolicyAlways;
195     case NSHTTPCookieAcceptPolicyNever:
196         return WebKit::HTTPCookieAcceptPolicyNever;
197     case NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain:
198         return WebKit::HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain;
199     case NSHTTPCookieAcceptPolicyExclusivelyFromMainDocumentDomain:
200         return WebKit::HTTPCookieAcceptPolicyExclusivelyFromMainDocumentDomain;
201     }
202
203     ASSERT_NOT_REACHED();
204     return WebKit::HTTPCookieAcceptPolicyAlways;
205 }
206
207 - (void)_setCookieAcceptPolicy:(NSHTTPCookieAcceptPolicy)policy
208 {
209     _context->supplement<WebKit::WebCookieManagerProxy>()->setHTTPCookieAcceptPolicy(toHTTPCookieAcceptPolicy(policy));
210 }
211
212 - (id)_objectForBundleParameter:(NSString *)parameter
213 {
214     return [_context->bundleParameters() objectForKey:parameter];
215 }
216
217 - (void)_setObject:(id <NSCopying, NSSecureCoding>)object forBundleParameter:(NSString *)parameter
218 {
219     auto copy = adoptNS([(NSObject *)object copy]);
220
221     auto data = adoptNS([[NSMutableData alloc] init]);
222     auto keyedArchiver = adoptNS([[NSKeyedArchiver alloc] initForWritingWithMutableData:data.get()]);
223     [keyedArchiver setRequiresSecureCoding:YES];
224
225     @try {
226         [keyedArchiver encodeObject:copy.get() forKey:@"parameter"];
227         [keyedArchiver finishEncoding];
228     } @catch (NSException *exception) {
229         LOG_ERROR("Failed to encode bundle parameter: %@", exception);
230     }
231
232     if (copy)
233         [_context->ensureBundleParameters() setObject:copy.get() forKey:parameter];
234     else
235         [_context->ensureBundleParameters() removeObjectForKey:parameter];
236
237     _context->sendToAllProcesses(Messages::WebProcess::SetInjectedBundleParameter(parameter, IPC::DataReference(static_cast<const uint8_t*>([data bytes]), [data length])));
238 }
239
240 - (id <_WKDownloadDelegate>)_downloadDelegate
241 {
242     return _downloadDelegate.getAutoreleased();
243 }
244
245 - (void)_setDownloadDelegate:(id <_WKDownloadDelegate>)downloadDelegate
246 {
247     _downloadDelegate = downloadDelegate;
248     _context->setDownloadClient(std::make_unique<WebKit::DownloadClient>(downloadDelegate));
249 }
250
251 @end
252
253 #endif // WK_API_ENABLED