Use CompletionHandlers for ResourceHandleClient::didReceiveResponseAsync
[WebKit-https.git] / Source / WebCore / platform / network / curl / ResourceHandleCurlDelegate.cpp
1 /*
2  * Copyright (C) 2004, 2006 Apple Inc.  All rights reserved.
3  * Copyright (C) 2005, 2006 Michael Emmel mike.emmel@gmail.com
4  * Copyright (C) 2018 Sony Interactive Entertainment Inc.
5  * All rights reserved.
6  * Copyright (C) 2017 NAVER Corp. All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
21  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
25  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include "config.h"
31 #include "ResourceHandleCurlDelegate.h"
32
33 #if USE(CURL)
34
35 #include "AuthenticationChallenge.h"
36 #include "CredentialStorage.h"
37 #include "CurlCacheManager.h"
38 #include "CurlRequest.h"
39 #include "HTTPParsers.h"
40 #include "ResourceHandleInternal.h"
41 #include "SharedBuffer.h"
42 #include "TextEncoding.h"
43 #include <wtf/CompletionHandler.h>
44 #include <wtf/text/Base64.h>
45
46 namespace WebCore {
47
48 ResourceHandleCurlDelegate::ResourceHandleCurlDelegate(ResourceHandle* handle)
49     : m_handle(handle)
50     , m_firstRequest(handle->firstRequest().isolatedCopy())
51     , m_currentRequest(handle->firstRequest().isolatedCopy())
52     , m_shouldUseCredentialStorage(handle->shouldUseCredentialStorage())
53     , m_user(handle->getInternal()->m_user.isolatedCopy())
54     , m_pass(handle->getInternal()->m_pass.isolatedCopy())
55     , m_initialCredential(handle->getInternal()->m_initialCredential)
56     , m_defersLoading(handle->getInternal()->m_defersLoading)
57 {
58
59 }
60
61 ResourceHandleCurlDelegate::~ResourceHandleCurlDelegate()
62 {
63     if (m_curlRequest)
64         m_curlRequest->setClient(nullptr);
65 }
66
67 bool ResourceHandleCurlDelegate::hasHandle() const
68 {
69     return !!m_handle;
70 }
71
72 void ResourceHandleCurlDelegate::releaseHandle()
73 {
74     m_handle = nullptr;
75 }
76
77 void ResourceHandleCurlDelegate::start()
78 {
79     ASSERT(isMainThread());
80
81     auto credential = getCredential(m_currentRequest, false);
82
83     m_curlRequest = createCurlRequest(m_currentRequest);
84     m_curlRequest->setUserPass(credential.first, credential.second);
85     m_curlRequest->start();
86 }
87
88 void ResourceHandleCurlDelegate::cancel()
89 {
90     ASSERT(isMainThread());
91
92     releaseHandle();
93
94     if (!m_curlRequest)
95         m_curlRequest->cancel();
96 }
97
98 void ResourceHandleCurlDelegate::setDefersLoading(bool defers)
99 {
100     ASSERT(isMainThread());
101
102     if (defers == m_defersLoading)
103         return;
104
105     m_defersLoading = defers;
106
107     if (!m_curlRequest)
108         return;
109
110     if (m_defersLoading)
111         m_curlRequest->suspend();
112     else
113         m_curlRequest->resume();
114 }
115
116 void ResourceHandleCurlDelegate::setAuthentication(const String& user, const String& password)
117 {
118     ASSERT(isMainThread());
119
120     if (!m_curlRequest)
121         return;
122
123     bool isSyncRequest = m_curlRequest->isSyncRequest();
124     m_curlRequest->cancel();
125     m_curlRequest->setClient(nullptr);
126
127     m_curlRequest = createCurlRequest(m_currentRequest);
128     m_curlRequest->setUserPass(user, password);
129     m_curlRequest->start(isSyncRequest);
130 }
131
132 void ResourceHandleCurlDelegate::dispatchSynchronousJob()
133 {
134     if (m_currentRequest.url().protocolIsData()) {
135         handleDataURL();
136         return;
137     }
138
139     // If defersLoading is true and we call curl_easy_perform
140     // on a paused handle, libcURL would do the transfert anyway
141     // and we would assert so force defersLoading to be false.
142     m_defersLoading = false;
143
144     m_curlRequest = createCurlRequest(m_currentRequest);
145     m_curlRequest->start(true);
146 }
147
148 Ref<CurlRequest> ResourceHandleCurlDelegate::createCurlRequest(ResourceRequest& request)
149 {
150     ASSERT(isMainThread());
151
152     // CurlCache : append additional cache information
153     m_addedCacheValidationHeaders = false;
154
155     bool hasCacheHeaders = request.httpHeaderFields().contains(HTTPHeaderName::IfModifiedSince) || request.httpHeaderFields().contains(HTTPHeaderName::IfNoneMatch);
156     if (!hasCacheHeaders) {
157         auto& cache = CurlCacheManager::singleton();
158         URL cacheUrl = request.url();
159         cacheUrl.removeFragmentIdentifier();
160
161         if (cache.isCached(cacheUrl)) {
162             cache.addCacheEntryClient(cacheUrl, m_handle);
163
164             for (const auto& entry : cache.requestHeaders(cacheUrl))
165                 request.addHTTPHeaderField(entry.key, entry.value);
166
167             m_addedCacheValidationHeaders = true;
168         }
169     }
170
171     CurlRequest::ShouldSuspend shouldSuspend = m_defersLoading ? CurlRequest::ShouldSuspend::Yes : CurlRequest::ShouldSuspend::No;
172     return CurlRequest::create(request, this, shouldSuspend, CurlRequest::EnableMultipart::Yes);
173 }
174
175 bool ResourceHandleCurlDelegate::cancelledOrClientless()
176 {
177     if (!m_handle)
178         return true;
179
180     return !m_handle->client();
181 }
182
183 void ResourceHandleCurlDelegate::curlDidReceiveResponse(const CurlResponse& receivedResponse)
184 {
185     ASSERT(isMainThread());
186     ASSERT(!m_defersLoading);
187
188     if (cancelledOrClientless())
189         return;
190
191     m_handle->getInternal()->m_response = ResourceResponse(receivedResponse);
192
193     if (m_curlRequest)
194         m_handle->getInternal()->m_response.setDeprecatedNetworkLoadMetrics(m_curlRequest->getNetworkLoadMetrics());
195
196     if (response().shouldRedirect()) {
197         willSendRequest();
198         return;
199     }
200
201     if (response().isUnauthorized()) {
202         AuthenticationChallenge challenge(receivedResponse, m_authFailureCount, response(), m_handle);
203         m_handle->didReceiveAuthenticationChallenge(challenge);
204         m_authFailureCount++;
205         return;
206     }
207
208     if (m_handle->client()) {
209         if (response().isNotModified()) {
210             URL cacheUrl = m_currentRequest.url();
211             cacheUrl.removeFragmentIdentifier();
212
213             if (CurlCacheManager::singleton().getCachedResponse(cacheUrl, response())) {
214                 if (m_addedCacheValidationHeaders) {
215                     response().setHTTPStatusCode(200);
216                     response().setHTTPStatusText("OK");
217                 }
218             }
219         }
220
221         CurlCacheManager::singleton().didReceiveResponse(*m_handle, response());
222
223         auto protectedThis = makeRef(*m_handle);
224         m_handle->didReceiveResponse(ResourceResponse(response()), [this, protectedThis = makeRef(*this)] {
225             continueAfterDidReceiveResponse();
226         });
227     }
228 }
229
230 void ResourceHandleCurlDelegate::curlDidReceiveBuffer(Ref<SharedBuffer>&& buffer)
231 {
232     ASSERT(isMainThread());
233
234     if (cancelledOrClientless())
235         return;
236
237     CurlCacheManager::singleton().didReceiveData(*m_handle, buffer->data(), buffer->size());
238     m_handle->client()->didReceiveBuffer(m_handle, WTFMove(buffer), buffer->size());
239 }
240
241 void ResourceHandleCurlDelegate::curlDidComplete()
242 {
243     ASSERT(isMainThread());
244
245     if (cancelledOrClientless())
246         return;
247
248     if (m_curlRequest)
249         m_handle->getInternal()->m_response.setDeprecatedNetworkLoadMetrics(m_curlRequest->getNetworkLoadMetrics());
250
251     if (m_handle->client()) {
252         CurlCacheManager::singleton().didFinishLoading(*m_handle);
253         m_handle->client()->didFinishLoading(m_handle);
254     }
255 }
256
257 void ResourceHandleCurlDelegate::curlDidFailWithError(const ResourceError& resourceError)
258 {
259     ASSERT(isMainThread());
260
261     if (cancelledOrClientless())
262         return;
263
264     CurlCacheManager::singleton().didFail(*m_handle);
265     m_handle->client()->didFail(m_handle, resourceError);
266 }
267
268 void ResourceHandleCurlDelegate::continueDidReceiveResponse()
269 {
270     ASSERT(isMainThread());
271
272     continueAfterDidReceiveResponse();
273 }
274
275 void ResourceHandleCurlDelegate::platformContinueSynchronousDidReceiveResponse()
276 {
277     ASSERT(isMainThread());
278
279     continueAfterDidReceiveResponse();
280 }
281
282 void ResourceHandleCurlDelegate::continueAfterDidReceiveResponse()
283 {
284     ASSERT(isMainThread());
285
286     // continueDidReceiveResponse might cancel the load.
287     if (cancelledOrClientless() || !m_curlRequest)
288         return;
289
290     m_curlRequest->completeDidReceiveResponse();
291 }
292
293 bool ResourceHandleCurlDelegate::shouldRedirectAsGET(const ResourceRequest& request, bool crossOrigin)
294 {
295     if (request.httpMethod() == "GET" || request.httpMethod() == "HEAD")
296         return false;
297
298     if (!request.url().protocolIsInHTTPFamily())
299         return true;
300
301     if (response().isSeeOther())
302         return true;
303
304     if ((response().isMovedPermanently() || response().isFound()) && (request.httpMethod() == "POST"))
305         return true;
306
307     if (crossOrigin && (request.httpMethod() == "DELETE"))
308         return true;
309
310     return false;
311 }
312
313 void ResourceHandleCurlDelegate::willSendRequest()
314 {
315     ASSERT(isMainThread());
316
317     static const int maxRedirects = 20;
318
319     if (m_redirectCount++ > maxRedirects) {
320         m_handle->client()->didFail(m_handle, ResourceError::httpError(CURLE_TOO_MANY_REDIRECTS, response().url()));
321         return;
322     }
323
324     String location = response().httpHeaderField(HTTPHeaderName::Location);
325     URL newURL = URL(m_firstRequest.url(), location);
326     bool crossOrigin = !protocolHostAndPortAreEqual(m_firstRequest.url(), newURL);
327
328     ResourceRequest newRequest = m_firstRequest;
329     newRequest.setURL(newURL);
330
331     if (shouldRedirectAsGET(newRequest, crossOrigin)) {
332         newRequest.setHTTPMethod("GET");
333         newRequest.setHTTPBody(nullptr);
334         newRequest.clearHTTPContentType();
335     }
336
337     // Should not set Referer after a redirect from a secure resource to non-secure one.
338     if (!newURL.protocolIs("https") && protocolIs(newRequest.httpReferrer(), "https") && m_handle->context()->shouldClearReferrerOnHTTPSToHTTPRedirect())
339         newRequest.clearHTTPReferrer();
340
341     m_user = newURL.user();
342     m_pass = newURL.pass();
343     newRequest.removeCredentials();
344
345     if (crossOrigin) {
346         // If the network layer carries over authentication headers from the original request
347         // in a cross-origin redirect, we want to clear those headers here. 
348         newRequest.clearHTTPAuthorization();
349         newRequest.clearHTTPOrigin();
350     }
351
352     ResourceResponse responseCopy = response();
353     m_handle->client()->willSendRequestAsync(m_handle, WTFMove(newRequest), WTFMove(responseCopy), [this, protectedThis = makeRef(*this)] (ResourceRequest&& request) {
354         continueWillSendRequest(WTFMove(request));
355     });
356 }
357
358 void ResourceHandleCurlDelegate::continueWillSendRequest(ResourceRequest&& request)
359 {
360     ASSERT(isMainThread());
361
362     continueAfterWillSendRequest(WTFMove(request));
363 }
364
365 void ResourceHandleCurlDelegate::continueAfterWillSendRequest(ResourceRequest&& request)
366 {
367     ASSERT(isMainThread());
368
369     // willSendRequest might cancel the load.
370     if (cancelledOrClientless() || !m_curlRequest)
371         return;
372
373     m_currentRequest = WTFMove(request);
374
375     bool isSyncRequest = m_curlRequest->isSyncRequest();
376     m_curlRequest->cancel();
377     m_curlRequest->setClient(nullptr);
378
379     m_curlRequest = createCurlRequest(m_currentRequest);
380
381     if (protocolHostAndPortAreEqual(m_currentRequest.url(), response().url())) {
382         auto credential = getCredential(m_currentRequest, true);
383         m_curlRequest->setUserPass(credential.first, credential.second);
384     }
385
386     m_curlRequest->start(isSyncRequest);
387 }
388
389 ResourceResponse& ResourceHandleCurlDelegate::response()
390 {
391     return m_handle->getInternal()->m_response;
392 }
393
394 void ResourceHandleCurlDelegate::handleDataURL()
395 {
396     ASSERT(m_firstRequest.url().protocolIsData());
397     String url = m_firstRequest.url().string();
398
399     ASSERT(m_handle->client());
400
401     auto index = url.find(',');
402     if (index == notFound) {
403         m_handle->client()->cannotShowURL(m_handle);
404         return;
405     }
406
407     String mediaType = url.substring(5, index - 5);
408     String data = url.substring(index + 1);
409     auto originalSize = data.length();
410
411     bool base64 = mediaType.endsWithIgnoringASCIICase(";base64");
412     if (base64)
413         mediaType = mediaType.left(mediaType.length() - 7);
414
415     if (mediaType.isEmpty())
416         mediaType = "text/plain";
417
418     String mimeType = extractMIMETypeFromMediaType(mediaType);
419     String charset = extractCharsetFromMediaType(mediaType);
420
421     if (charset.isEmpty())
422         charset = "US-ASCII";
423
424     ResourceResponse response;
425     response.setMimeType(mimeType);
426     response.setTextEncodingName(charset);
427     response.setURL(m_firstRequest.url());
428
429     if (base64) {
430         data = decodeURLEscapeSequences(data);
431         m_handle->didReceiveResponse(WTFMove(response), [this, protectedThis = makeRef(*this)] {
432             continueAfterDidReceiveResponse();
433         });
434
435         // didReceiveResponse might cause the client to be deleted.
436         if (m_handle->client()) {
437             Vector<char> out;
438             if (base64Decode(data, out, Base64IgnoreSpacesAndNewLines) && out.size() > 0)
439                 m_handle->client()->didReceiveBuffer(m_handle, SharedBuffer::create(out.data(), out.size()), originalSize);
440         }
441     } else {
442         TextEncoding encoding(charset);
443         data = decodeURLEscapeSequences(data, encoding);
444         m_handle->didReceiveResponse(WTFMove(response), [this, protectedThis = makeRef(*this)] {
445             continueAfterDidReceiveResponse();
446         });
447
448         // didReceiveResponse might cause the client to be deleted.
449         if (m_handle->client()) {
450             auto encodedData = encoding.encode(data, UnencodableHandling::URLEncodedEntities);
451             if (encodedData.size())
452                 m_handle->client()->didReceiveBuffer(m_handle, SharedBuffer::create(WTFMove(encodedData)), originalSize);
453         }
454     }
455
456     if (m_handle->client())
457         m_handle->client()->didFinishLoading(m_handle);
458 }
459
460 std::pair<String, String> ResourceHandleCurlDelegate::getCredential(ResourceRequest& request, bool redirect)
461 {
462     // m_user/m_pass are credentials given manually, for instance, by the arguments passed to XMLHttpRequest.open().
463     String partition = request.cachePartition();
464
465     if (m_shouldUseCredentialStorage) {
466         if (m_user.isEmpty() && m_pass.isEmpty()) {
467             // <rdar://problem/7174050> - For URLs that match the paths of those previously challenged for HTTP Basic authentication, 
468             // try and reuse the credential preemptively, as allowed by RFC 2617.
469             m_initialCredential = CredentialStorage::defaultCredentialStorage().get(partition, request.url());
470         } else if (!redirect) {
471             // If there is already a protection space known for the URL, update stored credentials
472             // before sending a request. This makes it possible to implement logout by sending an
473             // XMLHttpRequest with known incorrect credentials, and aborting it immediately (so that
474             // an authentication dialog doesn't pop up).
475             CredentialStorage::defaultCredentialStorage().set(partition, Credential(m_user, m_pass, CredentialPersistenceNone), request.url());
476         }
477     }
478
479     String user = m_user;
480     String password = m_pass;
481
482     if (!m_initialCredential.isEmpty()) {
483         user = m_initialCredential.user();
484         password = m_initialCredential.password();
485     }
486
487     if (user.isEmpty() && password.isEmpty())
488         return std::pair<String, String>("", "");
489
490     return std::pair<String, String>(user, password);
491 }
492
493 } // namespace WebCore
494
495 #endif