[CURL] Should handle redirects in WebCore
[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) 2017 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 "MultipartHandle.h"
41 #include "ResourceHandleInternal.h"
42 #include "SharedBuffer.h"
43 #include "TextEncoding.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->setDelegate(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 bool 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     return true;
88 }
89
90 void ResourceHandleCurlDelegate::cancel()
91 {
92     ASSERT(isMainThread());
93
94     releaseHandle();
95
96     if (!m_curlRequest)
97         m_curlRequest->cancel();
98 }
99
100 void ResourceHandleCurlDelegate::setDefersLoading(bool defers)
101 {
102     ASSERT(isMainThread());
103
104     if (defers == m_defersLoading)
105         return;
106
107     m_defersLoading = defers;
108
109     if (!m_curlRequest)
110         return;
111
112     if (m_defersLoading)
113         m_curlRequest->suspend();
114     else
115         m_curlRequest->resume();
116 }
117
118 void ResourceHandleCurlDelegate::setAuthentication(const String& user, const String& password)
119 {
120     ASSERT(isMainThread());
121
122     if (!m_curlRequest)
123         return;
124
125     bool isSyncRequest = m_curlRequest->isSyncRequest();
126     m_curlRequest->cancel();
127     m_curlRequest->setDelegate(nullptr);
128
129     m_curlRequest = createCurlRequest(m_currentRequest);
130     m_curlRequest->setUserPass(user, password);
131     m_curlRequest->start(isSyncRequest);
132 }
133
134 void ResourceHandleCurlDelegate::dispatchSynchronousJob()
135 {
136     if (m_currentRequest.url().protocolIsData()) {
137         handleDataURL();
138         return;
139     }
140
141     // If defersLoading is true and we call curl_easy_perform
142     // on a paused handle, libcURL would do the transfert anyway
143     // and we would assert so force defersLoading to be false.
144     m_defersLoading = false;
145
146     m_curlRequest = createCurlRequest(m_currentRequest);
147     m_curlRequest->start(true);
148 }
149
150 RefPtr<CurlRequest> ResourceHandleCurlDelegate::createCurlRequest(ResourceRequest& request)
151 {
152     ASSERT(isMainThread());
153
154     // CurlCache : append additional cache information
155     m_addedCacheValidationHeaders = false;
156
157     bool hasCacheHeaders = request.httpHeaderFields().contains(HTTPHeaderName::IfModifiedSince) || request.httpHeaderFields().contains(HTTPHeaderName::IfNoneMatch);
158     if (!hasCacheHeaders) {
159         auto& cache = CurlCacheManager::getInstance();
160         URL cacheUrl = request.url();
161         cacheUrl.removeFragmentIdentifier();
162
163         if (cache.isCached(cacheUrl)) {
164             cache.addCacheEntryClient(cacheUrl, m_handle);
165
166             for (auto entry : cache.requestHeaders(cacheUrl))
167                 request.addHTTPHeaderField(entry.key, entry.value);
168
169             m_addedCacheValidationHeaders = true;
170         }
171     }
172
173     return adoptRef(new CurlRequest(request, this, m_defersLoading));
174 }
175
176 bool ResourceHandleCurlDelegate::cancelledOrClientless()
177 {
178     if (!m_handle)
179         return true;
180
181     return !m_handle->client();
182 }
183
184 void ResourceHandleCurlDelegate::curlDidReceiveResponse(const CurlResponse& receivedResponse)
185 {
186     ASSERT(isMainThread());
187     ASSERT(!m_defersLoading);
188
189     if (cancelledOrClientless())
190         return;
191
192     m_handle->getInternal()->m_response = ResourceResponse(receivedResponse);
193
194     if (m_curlRequest)
195         m_handle->getInternal()->m_response.setDeprecatedNetworkLoadMetrics(m_curlRequest->getNetworkLoadMetrics());
196
197     if (response().isMultipart()) {
198         String boundary;
199         bool parsed = MultipartHandle::extractBoundary(response().httpHeaderField(HTTPHeaderName::ContentType), boundary);
200         if (parsed)
201             m_multipartHandle = std::make_unique<MultipartHandle>(m_handle, boundary);
202     }
203
204     if (response().shouldRedirect()) {
205         willSendRequest();
206         return;
207     }
208
209     if (response().isUnauthorized()) {
210         AuthenticationChallenge challenge(receivedResponse, m_authFailureCount, response(), m_handle);
211         m_handle->didReceiveAuthenticationChallenge(challenge);
212         m_authFailureCount++;
213         return;
214     }
215
216     if (m_handle->client()) {
217         if (response().isNotModified()) {
218             URL cacheUrl = m_currentRequest.url();
219             cacheUrl.removeFragmentIdentifier();
220
221             if (CurlCacheManager::getInstance().getCachedResponse(cacheUrl, response())) {
222                 if (m_addedCacheValidationHeaders) {
223                     response().setHTTPStatusCode(200);
224                     response().setHTTPStatusText("OK");
225                 }
226             }
227         }
228
229         CurlCacheManager::getInstance().didReceiveResponse(*m_handle, response());
230         m_handle->client()->didReceiveResponse(m_handle, ResourceResponse(response()));
231     }
232 }
233
234 void ResourceHandleCurlDelegate::curlDidReceiveBuffer(Ref<SharedBuffer>&& buffer)
235 {
236     ASSERT(isMainThread());
237
238     if (cancelledOrClientless())
239         return;
240
241     if (m_multipartHandle)
242         m_multipartHandle->contentReceived(buffer->data(), buffer->size());
243     else if (m_handle->client()) {
244         CurlCacheManager::getInstance().didReceiveData(*m_handle, buffer->data(), buffer->size());
245         m_handle->client()->didReceiveBuffer(m_handle, WTFMove(buffer), buffer->size());
246     }
247 }
248
249 void ResourceHandleCurlDelegate::curlDidComplete()
250 {
251     ASSERT(isMainThread());
252
253     if (cancelledOrClientless())
254         return;
255
256     if (m_curlRequest)
257         m_handle->getInternal()->m_response.setDeprecatedNetworkLoadMetrics(m_curlRequest->getNetworkLoadMetrics());
258
259     if (m_multipartHandle)
260         m_multipartHandle->contentEnded();
261
262     if (m_handle->client()) {
263         CurlCacheManager::getInstance().didFinishLoading(*m_handle);
264         m_handle->client()->didFinishLoading(m_handle);
265     }
266 }
267
268 void ResourceHandleCurlDelegate::curlDidFailWithError(const ResourceError& resourceError)
269 {
270     ASSERT(isMainThread());
271
272     if (cancelledOrClientless())
273         return;
274
275     CurlCacheManager::getInstance().didFail(*m_handle);
276     m_handle->client()->didFail(m_handle, resourceError);
277 }
278
279 bool ResourceHandleCurlDelegate::shouldRedirectAsGET(const ResourceRequest& request, bool crossOrigin)
280 {
281     if ((request.httpMethod() == "GET") || (request.httpMethod() == "HEAD"))
282         return false;
283
284     if (!request.url().protocolIsInHTTPFamily())
285         return true;
286
287     if (response().isSeeOther())
288         return true;
289
290     if ((response().isMovedPermanently() || response().isFound()) && (request.httpMethod() == "POST"))
291         return true;
292
293     if (crossOrigin && (request.httpMethod() == "DELETE"))
294         return true;
295
296     return false;
297 }
298
299 void ResourceHandleCurlDelegate::willSendRequest()
300 {
301     ASSERT(isMainThread());
302
303     static const int maxRedirects = 20;
304
305     if (m_redirectCount++ > maxRedirects) {
306         m_handle->client()->didFail(m_handle, ResourceError::httpError(CURLE_TOO_MANY_REDIRECTS, response().url()));
307         return;
308     }
309
310     String location = response().httpHeaderField(HTTPHeaderName::Location);
311     URL newURL = URL(m_firstRequest.url(), location);
312     bool crossOrigin = !protocolHostAndPortAreEqual(m_firstRequest.url(), newURL);
313
314     ResourceRequest newRequest = m_firstRequest;
315     newRequest.setURL(newURL);
316
317     if (shouldRedirectAsGET(newRequest, crossOrigin)) {
318         newRequest.setHTTPMethod("GET");
319         newRequest.setHTTPBody(nullptr);
320         newRequest.clearHTTPContentType();
321     }
322
323     // Should not set Referer after a redirect from a secure resource to non-secure one.
324     if (!newURL.protocolIs("https") && protocolIs(newRequest.httpReferrer(), "https") && m_handle->context()->shouldClearReferrerOnHTTPSToHTTPRedirect())
325         newRequest.clearHTTPReferrer();
326
327     m_user = newURL.user();
328     m_pass = newURL.pass();
329     newRequest.removeCredentials();
330
331     if (crossOrigin) {
332         // If the network layer carries over authentication headers from the original request
333         // in a cross-origin redirect, we want to clear those headers here. 
334         newRequest.clearHTTPAuthorization();
335         newRequest.clearHTTPOrigin();
336     }
337
338     ResourceResponse responseCopy = response();
339     if (m_handle->client()->usesAsyncCallbacks())
340         m_handle->client()->willSendRequestAsync(m_handle, WTFMove(newRequest), WTFMove(responseCopy));
341     else {
342         auto request = m_handle->client()->willSendRequest(m_handle, WTFMove(newRequest), WTFMove(responseCopy));
343         continueAfterWillSendRequest(WTFMove(request));
344     }
345 }
346
347 void ResourceHandleCurlDelegate::continueWillSendRequest(ResourceRequest&& request)
348 {
349     ASSERT(isMainThread());
350
351     continueAfterWillSendRequest(WTFMove(request));
352 }
353
354 void ResourceHandleCurlDelegate::continueAfterWillSendRequest(ResourceRequest&& request)
355 {
356     ASSERT(isMainThread());
357
358     // willSendRequest might cancel the load.
359     if (cancelledOrClientless() || !m_curlRequest)
360         return;
361
362     m_currentRequest = WTFMove(request);
363
364     bool isSyncRequest = m_curlRequest->isSyncRequest();
365     m_curlRequest->cancel();
366     m_curlRequest->setDelegate(nullptr);
367
368     m_curlRequest = createCurlRequest(m_currentRequest);
369
370     if (protocolHostAndPortAreEqual(m_currentRequest.url(), response().url())) {
371         auto credential = getCredential(m_currentRequest, true);
372         m_curlRequest->setUserPass(credential.first, credential.second);
373     }
374
375     m_curlRequest->start(isSyncRequest);
376 }
377
378 ResourceResponse& ResourceHandleCurlDelegate::response()
379 {
380     return m_handle->getInternal()->m_response;
381 }
382
383 void ResourceHandleCurlDelegate::handleDataURL()
384 {
385     ASSERT(m_firstRequest.url().protocolIsData());
386     String url = m_firstRequest.url().string();
387
388     ASSERT(m_handle->client());
389
390     auto index = url.find(',');
391     if (index == notFound) {
392         m_handle->client()->cannotShowURL(m_handle);
393         return;
394     }
395
396     String mediaType = url.substring(5, index - 5);
397     String data = url.substring(index + 1);
398     auto originalSize = data.length();
399
400     bool base64 = mediaType.endsWith(";base64", false);
401     if (base64)
402         mediaType = mediaType.left(mediaType.length() - 7);
403
404     if (mediaType.isEmpty())
405         mediaType = "text/plain";
406
407     String mimeType = extractMIMETypeFromMediaType(mediaType);
408     String charset = extractCharsetFromMediaType(mediaType);
409
410     if (charset.isEmpty())
411         charset = "US-ASCII";
412
413     ResourceResponse response;
414     response.setMimeType(mimeType);
415     response.setTextEncodingName(charset);
416     response.setURL(m_firstRequest.url());
417
418     if (base64) {
419         data = decodeURLEscapeSequences(data);
420         m_handle->client()->didReceiveResponse(m_handle, WTFMove(response));
421
422         // didReceiveResponse might cause the client to be deleted.
423         if (m_handle->client()) {
424             Vector<char> out;
425             if (base64Decode(data, out, Base64IgnoreSpacesAndNewLines) && out.size() > 0)
426                 m_handle->client()->didReceiveBuffer(m_handle, SharedBuffer::create(out.data(), out.size()), originalSize);
427         }
428     } else {
429         TextEncoding encoding(charset);
430         data = decodeURLEscapeSequences(data, encoding);
431         m_handle->client()->didReceiveResponse(m_handle, WTFMove(response));
432
433         // didReceiveResponse might cause the client to be deleted.
434         if (m_handle->client()) {
435             CString encodedData = encoding.encode(data, URLEncodedEntitiesForUnencodables);
436             if (encodedData.length())
437                 m_handle->client()->didReceiveBuffer(m_handle, SharedBuffer::create(encodedData.data(), encodedData.length()), originalSize);
438         }
439     }
440
441     if (m_handle->client())
442         m_handle->client()->didFinishLoading(m_handle);
443 }
444
445 std::pair<String, String> ResourceHandleCurlDelegate::getCredential(ResourceRequest& request, bool redirect)
446 {
447     // m_user/m_pass are credentials given manually, for instance, by the arguments passed to XMLHttpRequest.open().
448     String partition = request.cachePartition();
449
450     if (m_shouldUseCredentialStorage) {
451         if (m_user.isEmpty() && m_pass.isEmpty()) {
452             // <rdar://problem/7174050> - For URLs that match the paths of those previously challenged for HTTP Basic authentication, 
453             // try and reuse the credential preemptively, as allowed by RFC 2617.
454             m_initialCredential = CredentialStorage::defaultCredentialStorage().get(partition, request.url());
455         } else if (!redirect) {
456             // If there is already a protection space known for the URL, update stored credentials
457             // before sending a request. This makes it possible to implement logout by sending an
458             // XMLHttpRequest with known incorrect credentials, and aborting it immediately (so that
459             // an authentication dialog doesn't pop up).
460             CredentialStorage::defaultCredentialStorage().set(partition, Credential(m_user, m_pass, CredentialPersistenceNone), request.url());
461         }
462     }
463
464     String user = m_user;
465     String password = m_pass;
466
467     if (!m_initialCredential.isEmpty()) {
468         user = m_initialCredential.user();
469         password = m_initialCredential.password();
470     }
471
472     if (user.isEmpty() && password.isEmpty())
473         return std::pair<String, String>("", "");
474
475     return std::pair<String, String>(user, password);
476 }
477
478 } // namespace WebCore
479
480 #endif