Versioning.
[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 bundleIdentifierIfNotInContainer:(NSString *)bundleIdentifier
109 {
110     NSURL *url = [containerURL URLByAppendingPathComponent:@"Library" isDirectory:YES];
111     url = [url URLByAppendingPathComponent:@"WebKit" isDirectory:YES];
112
113     if (!WebKit::processHasContainer() && bundleIdentifier)
114         url = [url URLByAppendingPathComponent:bundleIdentifier isDirectory:YES];
115
116     return [url URLByAppendingPathComponent:@"WebsiteData" isDirectory:YES];
117 }
118
119 static NSURL *websiteDataDirectoryURL(NSString *directoryName)
120 {
121     static dispatch_once_t onceToken;
122     static NSURL *websiteDataURL;
123
124     dispatch_once(&onceToken, ^{
125         NSURL *url = [[NSFileManager defaultManager] URLForDirectory:NSLibraryDirectory inDomain:NSUserDomainMask appropriateForURL:nullptr create:NO error:nullptr];
126         if (!url)
127             RELEASE_ASSERT_NOT_REACHED();
128
129         url = [url URLByAppendingPathComponent:@"WebKit" isDirectory:YES];
130
131         if (!WebKit::processHasContainer()) {
132             NSString *bundleIdentifier = [NSBundle mainBundle].bundleIdentifier;
133             if (!bundleIdentifier)
134                 bundleIdentifier = [NSProcessInfo processInfo].processName;
135             url = [url URLByAppendingPathComponent:bundleIdentifier isDirectory:YES];
136         }
137
138         websiteDataURL = [[url URLByAppendingPathComponent:@"WebsiteData" isDirectory:YES] retain];
139     });
140
141     NSURL *url = [websiteDataURL URLByAppendingPathComponent:directoryName isDirectory:YES];
142     if (![[NSFileManager defaultManager] createDirectoryAtURL:url withIntermediateDirectories:YES attributes:nil error:nullptr])
143         LOG_ERROR("Failed to create directory %@", url);
144
145     return url;
146 }
147
148 - (instancetype)_initWithConfiguration:(_WKProcessPoolConfiguration *)configuration
149 {
150     if (!(self = [super init]))
151         return nil;
152
153     _configuration = adoptNS([configuration copy]);
154
155 #if PLATFORM(IOS)
156     // FIXME: Remove once <rdar://problem/15256572> is fixed.
157     InitWebCoreThreadSystemInterface();
158 #endif
159
160     WebKit::WebContextConfiguration webContextConfiguration;
161
162     if (NSURL *bundleURL = [_configuration injectedBundleURL]) {
163         if (!bundleURL.isFileURL)
164             [NSException raise:NSInvalidArgumentException format:@"Injected Bundle URL must be a file URL"];
165
166         webContextConfiguration.injectedBundlePath = bundleURL.path;
167     }
168
169     webContextConfiguration.localStorageDirectory = websiteDataDirectoryURL(@"LocalStorage").absoluteURL.path.fileSystemRepresentation;
170     webContextConfiguration.webSQLDatabaseDirectory = websiteDataDirectoryURL(@"WebSQL").absoluteURL.path.fileSystemRepresentation;
171     webContextConfiguration.indexedDBDatabaseDirectory = websiteDataDirectoryURL(@"IndexedDB").absoluteURL.path.fileSystemRepresentation;
172
173     API::Object::constructInWrapper<WebKit::WebContext>(self, WTF::move(webContextConfiguration));
174     _context->setHistoryClient(std::make_unique<WebKit::HistoryClient>());
175     _context->setUsesNetworkProcess(true);
176     _context->setProcessModel(WebKit::ProcessModelMultipleSecondaryProcesses);
177     _context->setMaximumNumberOfProcesses([_configuration maximumProcessCount]);
178
179 #if ENABLE(CACHE_PARTITIONING)
180     for (NSString *urlScheme in [_configuration cachePartitionedURLSchemes])
181         _context->registerURLSchemeAsCachePartitioned(urlScheme);
182 #endif
183
184     // FIXME: Add a way to configure the cache model, see <rdar://problem/16206857>.
185     _context->setCacheModel(WebKit::CacheModelPrimaryWebBrowser);
186
187     return self;
188 }
189
190 - (void)_setAllowsSpecificHTTPSCertificate:(NSArray *)certificateChain forHost:(NSString *)host
191 {
192     _context->allowSpecificHTTPSCertificateForHost(WebKit::WebCertificateInfo::create(WebCore::CertificateInfo((CFArrayRef)certificateChain)).get(), host);
193 }
194
195 static WebKit::HTTPCookieAcceptPolicy toHTTPCookieAcceptPolicy(NSHTTPCookieAcceptPolicy policy)
196 {
197     switch (static_cast<NSUInteger>(policy)) {
198     case NSHTTPCookieAcceptPolicyAlways:
199         return WebKit::HTTPCookieAcceptPolicyAlways;
200     case NSHTTPCookieAcceptPolicyNever:
201         return WebKit::HTTPCookieAcceptPolicyNever;
202     case NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain:
203         return WebKit::HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain;
204     case NSHTTPCookieAcceptPolicyExclusivelyFromMainDocumentDomain:
205         return WebKit::HTTPCookieAcceptPolicyExclusivelyFromMainDocumentDomain;
206     }
207
208     ASSERT_NOT_REACHED();
209     return WebKit::HTTPCookieAcceptPolicyAlways;
210 }
211
212 - (void)_setCookieAcceptPolicy:(NSHTTPCookieAcceptPolicy)policy
213 {
214     _context->supplement<WebKit::WebCookieManagerProxy>()->setHTTPCookieAcceptPolicy(toHTTPCookieAcceptPolicy(policy));
215 }
216
217 - (id)_objectForBundleParameter:(NSString *)parameter
218 {
219     return [_context->bundleParameters() objectForKey:parameter];
220 }
221
222 - (void)_setObject:(id <NSCopying, NSSecureCoding>)object forBundleParameter:(NSString *)parameter
223 {
224     auto copy = adoptNS([(NSObject *)object copy]);
225
226     auto data = adoptNS([[NSMutableData alloc] init]);
227     auto keyedArchiver = adoptNS([[NSKeyedArchiver alloc] initForWritingWithMutableData:data.get()]);
228     [keyedArchiver setRequiresSecureCoding:YES];
229
230     @try {
231         [keyedArchiver encodeObject:copy.get() forKey:@"parameter"];
232         [keyedArchiver finishEncoding];
233     } @catch (NSException *exception) {
234         LOG_ERROR("Failed to encode bundle parameter: %@", exception);
235     }
236
237     if (copy)
238         [_context->ensureBundleParameters() setObject:copy.get() forKey:parameter];
239     else
240         [_context->ensureBundleParameters() removeObjectForKey:parameter];
241
242     _context->sendToAllProcesses(Messages::WebProcess::SetInjectedBundleParameter(parameter, IPC::DataReference(static_cast<const uint8_t*>([data bytes]), [data length])));
243 }
244
245 - (id <_WKDownloadDelegate>)_downloadDelegate
246 {
247     return _downloadDelegate.getAutoreleased();
248 }
249
250 - (void)_setDownloadDelegate:(id <_WKDownloadDelegate>)downloadDelegate
251 {
252     _downloadDelegate = downloadDelegate;
253     _context->setDownloadClient(std::make_unique<WebKit::DownloadClient>(downloadDelegate));
254 }
255
256 @end
257
258 #endif // WK_API_ENABLED