84e1fda28d941d45342de71f2b9985913280cfd9
[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()));
225     }
226 }
227
228 void ResourceHandleCurlDelegate::curlDidReceiveBuffer(Ref<SharedBuffer>&& buffer)
229 {
230     ASSERT(isMainThread());
231
232     if (cancelledOrClientless())
233         return;
234
235     CurlCacheManager::singleton().didReceiveData(*m_handle, buffer->data(), buffer->size());
236     m_handle->client()->didReceiveBuffer(m_handle, WTFMove(buffer), buffer->size());
237 }
238
239 void ResourceHandleCurlDelegate::curlDidComplete()
240 {
241     ASSERT(isMainThread());
242
243     if (cancelledOrClientless())
244         return;
245
246     if (m_curlRequest)
247         m_handle->getInternal()->m_response.setDeprecatedNetworkLoadMetrics(m_curlRequest->getNetworkLoadMetrics());
248
249     if (m_handle->client()) {
250         CurlCacheManager::singleton().didFinishLoading(*m_handle);
251         m_handle->client()->didFinishLoading(m_handle);
252     }
253 }
254
255 void ResourceHandleCurlDelegate::curlDidFailWithError(const ResourceError& resourceError)
256 {
257     ASSERT(isMainThread());
258
259     if (cancelledOrClientless())
260         return;
261
262     CurlCacheManager::singleton().didFail(*m_handle);
263     m_handle->client()->didFail(m_handle, resourceError);
264 }
265
266 void ResourceHandleCurlDelegate::continueDidReceiveResponse()
267 {
268     ASSERT(isMainThread());
269
270     continueAfterDidReceiveResponse();
271 }
272
273 void ResourceHandleCurlDelegate::platformContinueSynchronousDidReceiveResponse()
274 {
275     ASSERT(isMainThread());
276
277     continueAfterDidReceiveResponse();
278 }
279
280 void ResourceHandleCurlDelegate::continueAfterDidReceiveResponse()
281 {
282     ASSERT(isMainThread());
283
284     // continueDidReceiveResponse might cancel the load.
285     if (cancelledOrClientless() || !m_curlRequest)
286         return;
287
288     m_curlRequest->completeDidReceiveResponse();
289 }
290
291 bool ResourceHandleCurlDelegate::shouldRedirectAsGET(const ResourceRequest& request, bool crossOrigin)
292 {
293     if (request.httpMethod() == "GET" || request.httpMethod() == "HEAD")
294         return false;
295
296     if (!request.url().protocolIsInHTTPFamily())
297         return true;
298
299     if (response().isSeeOther())
300         return true;
301
302     if ((response().isMovedPermanently() || response().isFound()) && (request.httpMethod() == "POST"))
303         return true;
304
305     if (crossOrigin && (request.httpMethod() == "DELETE"))
306         return true;
307
308     return false;
309 }
310
311 void ResourceHandleCurlDelegate::willSendRequest()
312 {
313     ASSERT(isMainThread());
314
315     static const int maxRedirects = 20;
316
317     if (m_redirectCount++ > maxRedirects) {
318         m_handle->client()->didFail(m_handle, ResourceError::httpError(CURLE_TOO_MANY_REDIRECTS, response().url()));
319         return;
320     }
321
322     String location = response().httpHeaderField(HTTPHeaderName::Location);
323     URL newURL = URL(m_firstRequest.url(), location);
324     bool crossOrigin = !protocolHostAndPortAreEqual(m_firstRequest.url(), newURL);
325
326     ResourceRequest newRequest = m_firstRequest;
327     newRequest.setURL(newURL);
328
329     if (shouldRedirectAsGET(newRequest, crossOrigin)) {
330         newRequest.setHTTPMethod("GET");
331         newRequest.setHTTPBody(nullptr);
332         newRequest.clearHTTPContentType();
333     }
334
335     // Should not set Referer after a redirect from a secure resource to non-secure one.
336     if (!newURL.protocolIs("https") && protocolIs(newRequest.httpReferrer(), "https") && m_handle->context()->shouldClearReferrerOnHTTPSToHTTPRedirect())
337         newRequest.clearHTTPReferrer();
338
339     m_user = newURL.user();
340     m_pass = newURL.pass();
341     newRequest.removeCredentials();
342
343     if (crossOrigin) {
344         // If the network layer carries over authentication headers from the original request
345         // in a cross-origin redirect, we want to clear those headers here. 
346         newRequest.clearHTTPAuthorization();
347         newRequest.clearHTTPOrigin();
348     }
349
350     ResourceResponse responseCopy = response();
351     m_handle->client()->willSendRequestAsync(m_handle, WTFMove(newRequest), WTFMove(responseCopy), [this, protectedThis = makeRef(*this)] (ResourceRequest&& request) {
352         continueWillSendRequest(WTFMove(request));
353     });
354 }
355
356 void ResourceHandleCurlDelegate::continueWillSendRequest(ResourceRequest&& request)
357 {
358     ASSERT(isMainThread());
359
360     continueAfterWillSendRequest(WTFMove(request));
361 }
362
363 void ResourceHandleCurlDelegate::continueAfterWillSendRequest(ResourceRequest&& request)
364 {
365     ASSERT(isMainThread());
366
367     // willSendRequest might cancel the load.
368     if (cancelledOrClientless() || !m_curlRequest)
369         return;
370
371     m_currentRequest = WTFMove(request);
372
373     bool isSyncRequest = m_curlRequest->isSyncRequest();
374     m_curlRequest->cancel();
375     m_curlRequest->setClient(nullptr);
376
377     m_curlRequest = createCurlRequest(m_currentRequest);
378
379     if (protocolHostAndPortAreEqual(m_currentRequest.url(), response().url())) {
380         auto credential = getCredential(m_currentRequest, true);
381         m_curlRequest->setUserPass(credential.first, credential.second);
382     }
383
384     m_curlRequest->start(isSyncRequest);
385 }
386
387 ResourceResponse& ResourceHandleCurlDelegate::response()
388 {
389     return m_handle->getInternal()->m_response;
390 }
391
392 void ResourceHandleCurlDelegate::handleDataURL()
393 {
394     ASSERT(m_firstRequest.url().protocolIsData());
395     String url = m_firstRequest.url().string();
396
397     ASSERT(m_handle->client());
398
399     auto index = url.find(',');
400     if (index == notFound) {
401         m_handle->client()->cannotShowURL(m_handle);
402         return;
403     }
404
405     String mediaType = url.substring(5, index - 5);
406     String data = url.substring(index + 1);
407     auto originalSize = data.length();
408
409     bool base64 = mediaType.endsWithIgnoringASCIICase(";base64");
410     if (base64)
411         mediaType = mediaType.left(mediaType.length() - 7);
412
413     if (mediaType.isEmpty())
414         mediaType = "text/plain";
415
416     String mimeType = extractMIMETypeFromMediaType(mediaType);
417     String charset = extractCharsetFromMediaType(mediaType);
418
419     if (charset.isEmpty())
420         charset = "US-ASCII";
421
422     ResourceResponse response;
423     response.setMimeType(mimeType);
424     response.setTextEncodingName(charset);
425     response.setURL(m_firstRequest.url());
426
427     if (base64) {
428         data = decodeURLEscapeSequences(data);
429         m_handle->didReceiveResponse(WTFMove(response));
430
431         // didReceiveResponse might cause the client to be deleted.
432         if (m_handle->client()) {
433             Vector<char> out;
434             if (base64Decode(data, out, Base64IgnoreSpacesAndNewLines) && out.size() > 0)
435                 m_handle->client()->didReceiveBuffer(m_handle, SharedBuffer::create(out.data(), out.size()), originalSize);
436         }
437     } else {
438         TextEncoding encoding(charset);
439         data = decodeURLEscapeSequences(data, encoding);
440         m_handle->didReceiveResponse(WTFMove(response));
441
442         // didReceiveResponse might cause the client to be deleted.
443         if (m_handle->client()) {
444             auto encodedData = encoding.encode(data, UnencodableHandling::URLEncodedEntities);
445             if (encodedData.size())
446                 m_handle->client()->didReceiveBuffer(m_handle, SharedBuffer::create(WTFMove(encodedData)), originalSize);
447         }
448     }
449
450     if (m_handle->client())
451         m_handle->client()->didFinishLoading(m_handle);
452 }
453
454 std::pair<String, String> ResourceHandleCurlDelegate::getCredential(ResourceRequest& request, bool redirect)
455 {
456     // m_user/m_pass are credentials given manually, for instance, by the arguments passed to XMLHttpRequest.open().
457     String partition = request.cachePartition();
458
459     if (m_shouldUseCredentialStorage) {
460         if (m_user.isEmpty() && m_pass.isEmpty()) {
461             // <rdar://problem/7174050> - For URLs that match the paths of those previously challenged for HTTP Basic authentication, 
462             // try and reuse the credential preemptively, as allowed by RFC 2617.
463             m_initialCredential = CredentialStorage::defaultCredentialStorage().get(partition, request.url());
464         } else if (!redirect) {
465             // If there is already a protection space known for the URL, update stored credentials
466             // before sending a request. This makes it possible to implement logout by sending an
467             // XMLHttpRequest with known incorrect credentials, and aborting it immediately (so that
468             // an authentication dialog doesn't pop up).
469             CredentialStorage::defaultCredentialStorage().set(partition, Credential(m_user, m_pass, CredentialPersistenceNone), request.url());
470         }
471     }
472
473     String user = m_user;
474     String password = m_pass;
475
476     if (!m_initialCredential.isEmpty()) {
477         user = m_initialCredential.user();
478         password = m_initialCredential.password();
479     }
480
481     if (user.isEmpty() && password.isEmpty())
482         return std::pair<String, String>("", "");
483
484     return std::pair<String, String>(user, password);
485 }
486
487 } // namespace WebCore
488
489 #endif