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