[WTF] Add makeUnique<T>, which ensures T is fast-allocated, makeUnique / makeUniqueWi...
[WebKit-https.git] / Source / WebCore / loader / ios / PreviewLoader.mm
1 /*
2  * Copyright (C) 2009-2019 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 "PreviewLoader.h"
28
29 #if USE(QUICK_LOOK)
30
31 #import "DocumentLoader.h"
32 #import "Frame.h"
33 #import "FrameLoader.h"
34 #import "FrameLoaderClient.h"
35 #import "Logging.h"
36 #import "PreviewConverter.h"
37 #import "PreviewLoaderClient.h"
38 #import "QuickLook.h"
39 #import "ResourceLoader.h"
40 #import "Settings.h"
41 #import <pal/spi/ios/QuickLookSPI.h>
42 #import <wtf/NeverDestroyed.h>
43
44 using namespace WebCore;
45
46 @interface WebPreviewLoader : NSObject {
47     WeakPtr<ResourceLoader> _resourceLoader;
48     ResourceResponse _response;
49     RefPtr<PreviewLoaderClient> _client;
50     std::unique_ptr<PreviewConverter> _converter;
51     RetainPtr<NSMutableArray> _bufferedDataArray;
52     BOOL _hasLoadedPreview;
53     BOOL _hasProcessedResponse;
54     RefPtr<SharedBuffer> _bufferedData;
55     long long _lengthReceived;
56     BOOL _needsToCallDidFinishLoading;
57 }
58
59 - (instancetype)initWithResourceLoader:(ResourceLoader&)resourceLoader resourceResponse:(const ResourceResponse&)resourceResponse;
60 - (void)appendDataArray:(NSArray<NSData *> *)dataArray;
61 - (void)finishedAppending;
62 - (void)failed;
63
64 @property (nonatomic, readonly) BOOL shouldDecidePolicyBeforeLoading;
65
66 @end
67
68 @implementation WebPreviewLoader
69
70 static RefPtr<PreviewLoaderClient>& testingClient()
71 {
72     static NeverDestroyed<RefPtr<PreviewLoaderClient>> testingClient;
73     return testingClient.get();
74 }
75
76 static PreviewLoaderClient& emptyClient()
77 {
78     static NeverDestroyed<PreviewLoaderClient> emptyClient;
79     return emptyClient.get();
80 }
81
82 - (instancetype)initWithResourceLoader:(ResourceLoader&)resourceLoader resourceResponse:(const ResourceResponse&)resourceResponse
83 {
84     if (!(self = [super init]))
85         return nil;
86
87     _resourceLoader = makeWeakPtr(resourceLoader);
88     _response = resourceResponse;
89     _converter = makeUnique<PreviewConverter>(self, _response);
90     _bufferedDataArray = adoptNS([[NSMutableArray alloc] init]);
91     _shouldDecidePolicyBeforeLoading = resourceLoader.frame()->settings().shouldDecidePolicyBeforeLoadingQuickLookPreview();
92
93     if (testingClient())
94         _client = testingClient();
95     else if (auto client = resourceLoader.frameLoader()->client().createPreviewLoaderClient(_converter->previewFileName(), _converter->previewUTI()))
96         _client = WTFMove(client);
97     else
98         _client = &emptyClient();
99
100     LOG(Network, "WebPreviewConverter created with preview file name \"%s\".", _converter->previewFileName().utf8().data());
101     return self;
102 }
103
104 - (void)appendDataArray:(NSArray<NSData *> *)dataArray
105 {
106     LOG(Network, "WebPreviewConverter appending data array with count %ld.", dataArray.count);
107     [_converter->platformConverter() appendDataArray:dataArray];
108     [_bufferedDataArray addObjectsFromArray:dataArray];
109     _client->didReceiveDataArray((CFArrayRef)dataArray);
110 }
111
112 - (void)finishedAppending
113 {
114     LOG(Network, "WebPreviewConverter finished appending data.");
115     [_converter->platformConverter() finishedAppendingData];
116     _client->didFinishLoading();
117 }
118
119 - (void)failed
120 {
121     LOG(Network, "WebPreviewConverter failed.");
122     [_converter->platformConverter() finishConverting];
123     _client->didFail();
124 }
125
126 - (void)_loadPreviewIfNeeded
127 {
128     if (!_resourceLoader)
129         return;
130
131     ASSERT(!_resourceLoader->reachedTerminalState());
132     if (_hasLoadedPreview)
133         return;
134
135     _hasLoadedPreview = YES;
136     [_bufferedDataArray removeAllObjects];
137
138     ResourceResponse response { _converter->previewResponse() };
139     response.setIsQuickLook(true);
140     ASSERT(response.mimeType().length());
141
142     _resourceLoader->documentLoader()->setPreviewConverter(WTFMove(_converter));
143
144     if (_shouldDecidePolicyBeforeLoading) {
145         _hasProcessedResponse = YES;
146         _resourceLoader->documentLoader()->setResponse(response);
147         return;
148     }
149
150     _hasProcessedResponse = NO;
151     _resourceLoader->didReceiveResponse(response, [self, retainedSelf = retainPtr(self)] {
152         _hasProcessedResponse = YES;
153
154         if (!_resourceLoader)
155             return;
156
157         if (_resourceLoader->reachedTerminalState())
158             return;
159
160         if (auto bufferedData = WTFMove(_bufferedData)) {
161             _resourceLoader->didReceiveData(bufferedData->data(), bufferedData->size(), _lengthReceived, DataPayloadBytes);
162             _lengthReceived = 0;
163         }
164
165         if (_resourceLoader->reachedTerminalState())
166             return;
167
168         if (_needsToCallDidFinishLoading) {
169             _needsToCallDidFinishLoading = NO;
170             _resourceLoader->didFinishLoading(NetworkLoadMetrics { });
171         }
172     });
173 }
174
175 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data lengthReceived:(long long)lengthReceived
176 {
177     if (!_resourceLoader)
178         return;
179
180     ASSERT_UNUSED(connection, !connection);
181     if (_resourceLoader->reachedTerminalState())
182         return;
183
184     [self _loadPreviewIfNeeded];
185
186     auto dataLength = data.length;
187
188     // QuickLook code sends us a nil data at times. The check below is the same as the one in
189     // ResourceHandleMac.cpp added for a different bug.
190     if (!dataLength)
191         return;
192
193     if (_hasProcessedResponse) {
194         _resourceLoader->didReceiveData(reinterpret_cast<const char*>(data.bytes), dataLength, lengthReceived, DataPayloadBytes);
195         return;
196     }
197
198     if (!_bufferedData)
199         _bufferedData = SharedBuffer::create(data);
200     else
201         _bufferedData->append(data);
202     _lengthReceived += lengthReceived;
203 }
204
205 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
206 {
207     if (!_resourceLoader)
208         return;
209
210     ASSERT_UNUSED(connection, !connection);
211     if (_resourceLoader->reachedTerminalState())
212         return;
213     
214     ASSERT(_hasLoadedPreview);
215
216     if (!_hasProcessedResponse) {
217         _needsToCallDidFinishLoading = YES;
218         return;
219     }
220
221     _resourceLoader->didFinishLoading(NetworkLoadMetrics { });
222 }
223
224 static inline bool isQuickLookPasswordError(NSError *error)
225 {
226     return error.code == kQLReturnPasswordProtected && [error.domain isEqualToString:@"QuickLookErrorDomain"];
227 }
228
229 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
230 {
231     if (!_resourceLoader)
232         return;
233
234     ASSERT_UNUSED(connection, !connection);
235     if (_resourceLoader->reachedTerminalState())
236         return;
237
238     if (!isQuickLookPasswordError(error)) {
239         _resourceLoader->didFail(error);
240         return;
241     }
242
243     if (!_client->supportsPasswordEntry()) {
244         _resourceLoader->didFail(_resourceLoader->cannotShowURLError());
245         return;
246     }
247
248     _client->didRequestPassword([self, retainedSelf = retainPtr(self)] (const String& password) {
249         _converter = makeUnique<PreviewConverter>(self, _response, password);
250         [_converter->platformConverter() appendDataArray:_bufferedDataArray.get()];
251         [_converter->platformConverter() finishedAppendingData];
252     });
253 }
254
255 @end
256
257 namespace WebCore {
258
259 PreviewLoader::PreviewLoader(ResourceLoader& loader, const ResourceResponse& response)
260     : m_previewLoader { adoptNS([[WebPreviewLoader alloc] initWithResourceLoader:loader resourceResponse:response]) }
261 {
262 }
263
264 PreviewLoader::~PreviewLoader()
265 {
266 }
267
268 std::unique_ptr<PreviewLoader> PreviewLoader::create(ResourceLoader& loader, const ResourceResponse& response)
269 {
270     ASSERT(PreviewConverter::supportsMIMEType(response.mimeType()));
271     return makeUnique<PreviewLoader>(loader, response);
272 }
273
274 bool PreviewLoader::didReceiveResponse(const ResourceResponse&)
275 {
276     return ![m_previewLoader shouldDecidePolicyBeforeLoading];
277 }
278
279 bool PreviewLoader::didReceiveData(const char* data, unsigned length)
280 {
281     if (m_finishedLoadingDataIntoConverter)
282         return false;
283
284     [m_previewLoader appendDataArray:@[ [NSData dataWithBytes:data length:length] ]];
285     return true;
286 }
287
288 bool PreviewLoader::didReceiveBuffer(const SharedBuffer& buffer)
289 {
290     if (m_finishedLoadingDataIntoConverter)
291         return false;
292
293     [m_previewLoader appendDataArray:buffer.createNSDataArray().get()];
294     return true;
295 }
296
297 bool PreviewLoader::didFinishLoading()
298 {
299     if (m_finishedLoadingDataIntoConverter)
300         return false;
301
302     m_finishedLoadingDataIntoConverter = true;
303     [m_previewLoader finishedAppending];
304     return true;
305 }
306
307 void PreviewLoader::didFail()
308 {
309     if (m_finishedLoadingDataIntoConverter)
310         return;
311
312     m_finishedLoadingDataIntoConverter = true;
313     [m_previewLoader failed];
314     m_previewLoader = nullptr;
315 }
316
317 void PreviewLoader::setClientForTesting(RefPtr<PreviewLoaderClient>&& client)
318 {
319     testingClient() = WTFMove(client);
320 }
321
322 } // namespace WebCore
323
324 #endif // USE(QUICK_LOOK)