[Curl] Unify ResourceHandleManager into CurlJobManager.
[WebKit-https.git] / Source / WebCore / platform / network / curl / ResourceHandleCurl.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  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
17  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
20  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
24  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include "config.h"
30 #include "ResourceHandle.h"
31
32 #if USE(CURL)
33
34 #include "CachedResourceLoader.h"
35 #include "CredentialStorage.h"
36 #include "CurlCacheManager.h"
37 #include "CurlContext.h"
38 #include "CurlJobManager.h"
39 #include "FileSystem.h"
40 #include "Logging.h"
41 #include "MIMETypeRegistry.h"
42 #include "NetworkingContext.h"
43 #include "ResourceHandleInternal.h"
44 #include "SSLHandle.h"
45 #include "SynchronousLoaderClient.h"
46 #include <wtf/text/Base64.h>
47
48 namespace WebCore {
49
50 ResourceHandleInternal::~ResourceHandleInternal()
51 {
52
53 }
54
55 ResourceHandle::~ResourceHandle()
56 {
57 }
58
59 bool ResourceHandle::start()
60 {
61     ASSERT(isMainThread());
62
63     // The frame could be null if the ResourceHandle is not associated to any
64     // Frame, e.g. if we are downloading a file.
65     // If the frame is not null but the page is null this must be an attempted
66     // load from an unload handler, so let's just block it.
67     // If both the frame and the page are not null the context is valid.
68     if (d->m_context && !d->m_context->isValid())
69         return false;
70
71     initialize();
72
73     m_job = CurlJobManager::singleton().add(d->m_curlHandle, [this, protectedThis = makeRef(*this)](CurlJobResult result) {
74         ASSERT(isMainThread());
75
76         switch (result) {
77         case CurlJobResult::Done:
78             didFinish();
79             break;
80
81         case CurlJobResult::Error:
82             didFail();
83             break;
84
85         case CurlJobResult::Cancelled:
86             break;
87         }
88     });
89     ASSERT(m_job);
90
91     return true;
92 }
93
94 void ResourceHandle::cancel()
95 {
96     d->m_cancelled = true;
97     CurlJobManager::singleton().cancel(m_job);
98 }
99
100 void ResourceHandle::initialize()
101 {
102     CurlContext& context = CurlContext::singleton();
103
104     URL url = firstRequest().url();
105
106     // Remove any fragment part, otherwise curl will send it as part of the request.
107     url.removeFragmentIdentifier();
108
109     ResourceHandleInternal* d = getInternal();
110     String urlString = url.string();
111
112     if (url.isLocalFile()) {
113         // Remove any query part sent to a local file.
114         if (!url.query().isEmpty()) {
115             // By setting the query to a null string it'll be removed.
116             url.setQuery(String());
117             urlString = url.string();
118         }
119         // Determine the MIME type based on the path.
120         d->m_response.setMimeType(MIMETypeRegistry::getMIMETypeForPath(url));
121     }
122
123     if (d->m_defersLoading) {
124         CURLcode error = d->m_curlHandle.pause(CURLPAUSE_ALL);
125         // If we did not pause the handle, we would ASSERT in the
126         // header callback. So just assert here.
127         ASSERT_UNUSED(error, error == CURLE_OK);
128     }
129
130 #ifndef NDEBUG
131     d->m_curlHandle.enableVerboseIfUsed();
132     d->m_curlHandle.enableStdErrIfUsed();
133 #endif
134
135     d->m_curlHandle.setSslVerifyPeer(CurlHandle::VerifyPeerEnable);
136     d->m_curlHandle.setSslVerifyHost(CurlHandle::VerifyHostStrictNameCheck);
137     d->m_curlHandle.setPrivateData(this);
138     d->m_curlHandle.setWriteCallbackFunction(writeCallback, this);
139     d->m_curlHandle.setHeaderCallbackFunction(headerCallback, this);
140     d->m_curlHandle.enableAutoReferer();
141     d->m_curlHandle.enableFollowLocation();
142     d->m_curlHandle.enableHttpAuthentication(CURLAUTH_ANY);
143     d->m_curlHandle.enableShareHandle();
144     d->m_curlHandle.enableTimeout();
145     d->m_curlHandle.enableAllowedProtocols();
146     setSSLClientCertificate(this);
147
148     if (CurlContext::singleton().shouldIgnoreSSLErrors())
149         d->m_curlHandle.setSslVerifyPeer(CurlHandle::VerifyPeerDisable);
150     else
151         setSSLVerifyOptions(this);
152
153     d->m_curlHandle.enableCAInfoIfExists();
154
155     d->m_curlHandle.enableAcceptEncoding();
156     d->m_curlHandle.setUrl(urlString);
157     d->m_curlHandle.enableCookieJarIfExists();
158
159     if (firstRequest().httpHeaderFields().size()) {
160         auto customHeaders = firstRequest().httpHeaderFields();
161         auto& cache = CurlCacheManager::getInstance();
162
163         bool hasCacheHeaders = customHeaders.contains(HTTPHeaderName::IfModifiedSince) || customHeaders.contains(HTTPHeaderName::IfNoneMatch);
164         if (!hasCacheHeaders && cache.isCached(url)) {
165             cache.addCacheEntryClient(url, this);
166
167             // append additional cache information
168             for (auto entry : cache.requestHeaders(url))
169                 customHeaders.set(entry.key, entry.value);
170
171             d->m_addedCacheValidationHeaders = true;
172         }
173
174         d->m_curlHandle.appendRequestHeaders(customHeaders);
175     }
176
177     String method = firstRequest().httpMethod();
178     if ("GET" == method)
179         d->m_curlHandle.enableHttpGetRequest();
180     else if ("POST" == method)
181         setupPOST();
182     else if ("PUT" == method)
183         setupPUT();
184     else if ("HEAD" == method)
185         d->m_curlHandle.enableHttpHeadRequest();
186     else {
187         d->m_curlHandle.setHttpCustomRequest(method);
188         setupPUT();
189     }
190
191     d->m_curlHandle.enableRequestHeaders();
192
193     applyAuthentication();
194
195     d->m_curlHandle.enableProxyIfExists();
196 }
197
198 void ResourceHandle::applyAuthentication()
199 {
200     ResourceRequest& request = firstRequest();
201     // m_user/m_pass are credentials given manually, for instance, by the arguments passed to XMLHttpRequest.open().
202     ResourceHandleInternal* d = getInternal();
203
204     String partition = request.cachePartition();
205
206     if (shouldUseCredentialStorage()) {
207         if (d->m_user.isEmpty() && d->m_pass.isEmpty()) {
208             // <rdar://problem/7174050> - For URLs that match the paths of those previously challenged for HTTP Basic authentication, 
209             // try and reuse the credential preemptively, as allowed by RFC 2617.
210             d->m_initialCredential = CredentialStorage::defaultCredentialStorage().get(partition, request.url());
211         } else {
212             // If there is already a protection space known for the URL, update stored credentials
213             // before sending a request. This makes it possible to implement logout by sending an
214             // XMLHttpRequest with known incorrect credentials, and aborting it immediately (so that
215             // an authentication dialog doesn't pop up).
216             CredentialStorage::defaultCredentialStorage().set(partition, Credential(d->m_user, d->m_pass, CredentialPersistenceNone), request.url());
217         }
218     }
219
220     String user = d->m_user;
221     String password = d->m_pass;
222
223     if (!d->m_initialCredential.isEmpty()) {
224         user = d->m_initialCredential.user();
225         password = d->m_initialCredential.password();
226         d->m_curlHandle.enableHttpAuthentication(CURLAUTH_BASIC);
227     }
228
229     // It seems we need to set CURLOPT_USERPWD even if username and password is empty.
230     // Otherwise cURL will not automatically continue with a new request after a 401 response.
231
232     // curl CURLOPT_USERPWD expects username:password
233     d->m_curlHandle.setHttpAuthUserPass(user, password);
234 }
235
236 static inline size_t getFormElementsCount(ResourceHandle* job)
237 {
238     RefPtr<FormData> formData = job->firstRequest().httpBody();
239
240     if (!formData)
241         return 0;
242
243     // Resolve the blob elements so the formData can correctly report it's size.
244     formData = formData->resolveBlobReferences();
245     size_t size = formData->elements().size();
246     job->firstRequest().setHTTPBody(WTFMove(formData));
247
248     return size;
249 }
250
251 void ResourceHandle::setupPUT()
252 {
253     d->m_curlHandle.enableHttpPutRequest();
254
255     // Disable the Expect: 100 continue header
256     d->m_curlHandle.appendRequestHeader("Expect:");
257
258     size_t numElements = getFormElementsCount(this);
259     if (!numElements)
260         return;
261
262     setupFormData(false);
263 }
264
265 void ResourceHandle::setupPOST()
266 {
267     d->m_curlHandle.enableHttpPostRequest();
268
269     size_t numElements = getFormElementsCount(this);
270     if (!numElements)
271         return;
272
273     // Do not stream for simple POST data
274     if (numElements == 1) {
275         firstRequest().httpBody()->flatten(d->m_postBytes);
276         if (d->m_postBytes.size())
277             d->m_curlHandle.setPostFields(d->m_postBytes.data(), d->m_postBytes.size());
278         return;
279     }
280
281     setupFormData(true);
282 }
283
284 void ResourceHandle::setupFormData(bool isPostRequest)
285 {
286     Vector<FormDataElement> elements = firstRequest().httpBody()->elements();
287     size_t numElements = elements.size();
288
289     static const long long maxCurlOffT = d->m_curlHandle.maxCurlOffT();
290
291     // Obtain the total size of the form data
292     curl_off_t size = 0;
293     bool chunkedTransfer = false;
294     for (size_t i = 0; i < numElements; i++) {
295         FormDataElement element = elements[i];
296         if (element.m_type == FormDataElement::Type::EncodedFile) {
297             long long fileSizeResult;
298             if (getFileSize(element.m_filename, fileSizeResult)) {
299                 if (fileSizeResult > maxCurlOffT) {
300                     // File size is too big for specifying it to cURL
301                     chunkedTransfer = true;
302                     break;
303                 }
304                 size += fileSizeResult;
305             } else {
306                 chunkedTransfer = true;
307                 break;
308             }
309         } else
310             size += elements[i].m_data.size();
311     }
312
313     // cURL guesses that we want chunked encoding as long as we specify the header
314     if (chunkedTransfer)
315         d->m_curlHandle.appendRequestHeader("Transfer-Encoding: chunked");
316     else {
317         if (isPostRequest)
318             d->m_curlHandle.setPostFieldLarge(size);
319         else
320             d->m_curlHandle.setInFileSizeLarge(size);
321     }
322
323     d->m_curlHandle.setReadCallbackFunction(readCallback, this);
324 }
325
326 #if OS(WINDOWS)
327
328 void ResourceHandle::setHostAllowsAnyHTTPSCertificate(const String& host)
329 {
330     ASSERT(isMainThread());
331
332     allowsAnyHTTPSCertificateHosts(host);
333 }
334
335 void ResourceHandle::setClientCertificateInfo(const String& host, const String& certificate, const String& key)
336 {
337     ASSERT(isMainThread());
338
339     if (fileExists(certificate))
340         addAllowedClientCertificate(host, certificate, key);
341     else
342         LOG(Network, "Invalid client certificate file: %s!\n", certificate.latin1().data());
343 }
344
345 #endif
346
347 #if OS(WINDOWS) && USE(CF)
348
349 void ResourceHandle::setClientCertificate(const String&, CFDataRef)
350 {
351 }
352
353 #endif
354
355 void ResourceHandle::platformSetDefersLoading(bool defers)
356 {
357     ASSERT(isMainThread());
358
359     auto action = [defers, this, protectedThis = makeRef(*this)]() {
360         if (defers) {
361             CURLcode error = d->m_curlHandle.pause(CURLPAUSE_ALL);
362             // If we could not defer the handle, so don't do it.
363             if (error != CURLE_OK)
364                 return;
365         } else {
366             CURLcode error = d->m_curlHandle.pause(CURLPAUSE_CONT);
367             if (error != CURLE_OK) {
368                 // Restarting the handle has failed so just cancel it.
369                 cancel();
370             }
371         }
372     };
373
374     if (m_job) {
375         CurlJobManager::singleton().callOnJobThread(WTFMove(action));
376     } else {
377         action();
378     }
379 }
380
381 void ResourceHandle::didFinish()
382 {
383 #if ENABLE(WEB_TIMING)
384     calculateWebTimingInformations();
385 #endif
386     if (d->m_cancelled)
387         return;
388
389     if (!d->m_response.responseFired()) {
390         handleLocalReceiveResponse();
391         if (d->m_cancelled)
392             return;
393     }
394
395     if (d->m_multipartHandle)
396         d->m_multipartHandle->contentEnded();
397
398     if (client()) {
399         client()->didFinishLoading(this);
400         CurlCacheManager::getInstance().didFinishLoading(*this);
401     }
402 }
403
404 void ResourceHandle::didFail()
405 {
406     if (d->m_cancelled)
407         return;
408     URL url = d->m_curlHandle.getEffectiveURL();
409     if (client()) {
410         client()->didFail(this, ResourceError(d->m_curlHandle, d->m_sslErrors));
411         CurlCacheManager::getInstance().didFail(*this);
412     }
413 }
414
415 bool ResourceHandle::shouldUseCredentialStorage()
416 {
417     return (!client() || client()->shouldUseCredentialStorage(this)) && firstRequest().url().protocolIsInHTTPFamily();
418 }
419
420 void ResourceHandle::didReceiveAuthenticationChallenge(const AuthenticationChallenge& challenge)
421 {
422     ASSERT(isMainThread());
423
424     String partition = firstRequest().cachePartition();
425
426     if (!d->m_user.isNull() && !d->m_pass.isNull()) {
427         Credential credential(d->m_user, d->m_pass, CredentialPersistenceNone);
428
429         URL urlToStore;
430         if (challenge.failureResponse().httpStatusCode() == 401)
431             urlToStore = challenge.failureResponse().url();
432         CredentialStorage::defaultCredentialStorage().set(partition, credential, challenge.protectionSpace(), urlToStore);
433         
434         d->m_curlHandle.setHttpAuthUserPass(credential.user(), credential.password());
435
436         d->m_user = String();
437         d->m_pass = String();
438         // FIXME: Per the specification, the user shouldn't be asked for credentials if there were incorrect ones provided explicitly.
439         return;
440     }
441
442     if (shouldUseCredentialStorage()) {
443         if (!d->m_initialCredential.isEmpty() || challenge.previousFailureCount()) {
444             // The stored credential wasn't accepted, stop using it.
445             // There is a race condition here, since a different credential might have already been stored by another ResourceHandle,
446             // but the observable effect should be very minor, if any.
447             CredentialStorage::defaultCredentialStorage().remove(partition, challenge.protectionSpace());
448         }
449
450         if (!challenge.previousFailureCount()) {
451             Credential credential = CredentialStorage::defaultCredentialStorage().get(partition, challenge.protectionSpace());
452             if (!credential.isEmpty() && credential != d->m_initialCredential) {
453                 ASSERT(credential.persistence() == CredentialPersistenceNone);
454                 if (challenge.failureResponse().httpStatusCode() == 401) {
455                     // Store the credential back, possibly adding it as a default for this directory.
456                     CredentialStorage::defaultCredentialStorage().set(partition, credential, challenge.protectionSpace(), challenge.failureResponse().url());
457                 }
458
459                 d->m_curlHandle.setHttpAuthUserPass(credential.user(), credential.password());
460                 return;
461             }
462         }
463     }
464
465     d->m_currentWebChallenge = challenge;
466     
467     if (client())
468         client()->didReceiveAuthenticationChallenge(this, d->m_currentWebChallenge);
469 }
470
471 void ResourceHandle::receivedCredential(const AuthenticationChallenge& challenge, const Credential& credential)
472 {
473     ASSERT(isMainThread());
474
475     if (challenge != d->m_currentWebChallenge)
476         return;
477
478     if (credential.isEmpty()) {
479         receivedRequestToContinueWithoutCredential(challenge);
480         return;
481     }
482
483     String partition = firstRequest().cachePartition();
484
485     if (shouldUseCredentialStorage()) {
486         if (challenge.failureResponse().httpStatusCode() == 401) {
487             URL urlToStore = challenge.failureResponse().url();
488             CredentialStorage::defaultCredentialStorage().set(partition, credential, challenge.protectionSpace(), urlToStore);
489         }
490     }
491
492     d->m_curlHandle.setHttpAuthUserPass(credential.user(), credential.password());
493     clearAuthentication();
494 }
495
496 void ResourceHandle::receivedRequestToContinueWithoutCredential(const AuthenticationChallenge& challenge)
497 {
498     ASSERT(isMainThread());
499
500     if (challenge != d->m_currentWebChallenge)
501         return;
502
503     d->m_curlHandle.setHttpAuthUserPass("", "");
504     clearAuthentication();
505 }
506
507 void ResourceHandle::receivedCancellation(const AuthenticationChallenge& challenge)
508 {
509     ASSERT(isMainThread());
510
511     if (challenge != d->m_currentWebChallenge)
512         return;
513
514     if (client())
515         client()->receivedCancellation(this, challenge);
516 }
517
518 void ResourceHandle::receivedRequestToPerformDefaultHandling(const AuthenticationChallenge&)
519 {
520     ASSERT_NOT_REACHED();
521 }
522
523 void ResourceHandle::receivedChallengeRejection(const AuthenticationChallenge&)
524 {
525     ASSERT_NOT_REACHED();
526 }
527
528 #if ENABLE(WEB_TIMING)
529 void ResourceHandle::calculateWebTimingInformations()
530 {
531     double preTransferTime = 0;
532     double dnslookupTime = 0;
533     double connectTime = 0;
534     double appConnectTime = 0;
535
536     d->m_curlHandle.getTimes(preTransferTime, dnslookupTime, connectTime, appConnectTime);
537
538     d->m_response.deprecatedNetworkLoadMetrics().domainLookupStart = Seconds(0);
539     d->m_response.deprecatedNetworkLoadMetrics().domainLookupEnd = Seconds(dnslookupTime);
540
541     d->m_response.deprecatedNetworkLoadMetrics().connectStart = Seconds(dnslookupTime);
542     d->m_response.deprecatedNetworkLoadMetrics().connectEnd = Seconds(connectTime);
543
544     d->m_response.deprecatedNetworkLoadMetrics().requestStart = Seconds(connectTime);
545     d->m_response.deprecatedNetworkLoadMetrics().responseStart = Seconds(preTransferTime);
546
547     if (appConnectTime)
548         d->m_response.deprecatedNetworkLoadMetrics().secureConnectionStart = Seconds(connectTime);
549 }
550 #endif
551
552 void ResourceHandle::handleLocalReceiveResponse()
553 {
554     ASSERT(isMainThread());
555
556     // since the code in headerCallback will not have run for local files
557     // the code to set the URL and fire didReceiveResponse is never run,
558     // which means the ResourceLoader's response does not contain the URL.
559     // Run the code here for local files to resolve the issue.
560     // TODO: See if there is a better approach for handling this.
561     URL url = d->m_curlHandle.getEffectiveURL();
562     ASSERT(url.isValid());
563     d->m_response.setURL(url);
564     if (client())
565         client()->didReceiveResponse(this, ResourceResponse(d->m_response));
566     d->m_response.setResponseFired(true);
567 }
568
569 inline static bool isHttpInfo(int statusCode)
570 {
571     return 100 <= statusCode && statusCode < 200;
572 }
573
574 inline static bool isHttpRedirect(int statusCode)
575 {
576     return 300 <= statusCode && statusCode < 400 && statusCode != 304;
577 }
578
579 inline static bool isHttpAuthentication(int statusCode)
580 {
581     return statusCode == 401;
582 }
583
584 inline static bool isHttpNotModified(int statusCode)
585 {
586     return statusCode == 304;
587 }
588
589 static bool isAppendableHeader(const String &key)
590 {
591     static const char* appendableHeaders[] = {
592         "access-control-allow-headers",
593         "access-control-allow-methods",
594         "access-control-allow-origin",
595         "access-control-expose-headers",
596         "allow",
597         "cache-control",
598         "connection",
599         "content-encoding",
600         "content-language",
601         "if-match",
602         "if-none-match",
603         "keep-alive",
604         "pragma",
605         "proxy-authenticate",
606         "public",
607         "server",
608         "set-cookie",
609         "te",
610         "trailer",
611         "transfer-encoding",
612         "upgrade",
613         "user-agent",
614         "vary",
615         "via",
616         "warning",
617         "www-authenticate"
618     };
619
620     // Custom headers start with 'X-', and need no further checking.
621     if (key.startsWith("x-", /* caseSensitive */ false))
622         return true;
623
624     for (auto& header : appendableHeaders) {
625         if (equalIgnoringASCIICase(key, header))
626             return true;
627     }
628
629     return false;
630 }
631
632 static void removeLeadingAndTrailingQuotes(String& value)
633 {
634     unsigned length = value.length();
635     if (value.startsWith('"') && value.endsWith('"') && length > 1)
636         value = value.substring(1, length - 2);
637 }
638
639 static bool getProtectionSpace(ResourceHandle* job, const ResourceResponse& response, ProtectionSpace& protectionSpace)
640 {
641     ResourceHandleInternal* d = job->getInternal();
642
643     CURLcode err;
644
645     long port = 0;
646     err = d->m_curlHandle.getPrimaryPort(port);
647     if (err != CURLE_OK)
648         return false;
649
650     long availableAuth = CURLAUTH_NONE;
651     err = d->m_curlHandle.getHttpAuthAvail(availableAuth);
652     if (err != CURLE_OK)
653         return false;
654
655     URL url = d->m_curlHandle.getEffectiveURL();
656     if (!url.isValid())
657         return false;
658
659     String host = url.host();
660     StringView protocol = url.protocol();
661
662     String realm;
663
664     const String authHeader = response.httpHeaderField(HTTPHeaderName::Authorization);
665     const String realmString = "realm=";
666     int realmPos = authHeader.find(realmString);
667     if (realmPos > 0) {
668         realm = authHeader.substring(realmPos + realmString.length());
669         realm = realm.left(realm.find(','));
670         removeLeadingAndTrailingQuotes(realm);
671     }
672
673     ProtectionSpaceServerType serverType = ProtectionSpaceServerHTTP;
674     if (protocol == "https")
675         serverType = ProtectionSpaceServerHTTPS;
676
677     ProtectionSpaceAuthenticationScheme authScheme = ProtectionSpaceAuthenticationSchemeUnknown;
678
679     if (availableAuth & CURLAUTH_BASIC)
680         authScheme = ProtectionSpaceAuthenticationSchemeHTTPBasic;
681     if (availableAuth & CURLAUTH_DIGEST)
682         authScheme = ProtectionSpaceAuthenticationSchemeHTTPDigest;
683     if (availableAuth & CURLAUTH_GSSNEGOTIATE)
684         authScheme = ProtectionSpaceAuthenticationSchemeNegotiate;
685     if (availableAuth & CURLAUTH_NTLM)
686         authScheme = ProtectionSpaceAuthenticationSchemeNTLM;
687
688     protectionSpace = ProtectionSpace(host, port, serverType, realm, authScheme);
689
690     return true;
691 }
692
693 size_t ResourceHandle::willPrepareSendData(char* ptr, size_t blockSize, size_t numberOfBlocks)
694 {
695     if (!d->m_formDataStream.hasMoreElements())
696         return 0;
697
698     size_t size = d->m_formDataStream.read(ptr, blockSize, numberOfBlocks);
699
700     // Something went wrong so cancel the job.
701     if (!size) {
702         cancel();
703         return 0;
704     }
705
706     return size;
707
708 }
709
710 void ResourceHandle::didReceiveHeaderLine(const String& header)
711 {
712     int splitPos = header.find(":");
713     if (splitPos != notFound) {
714         String key = header.left(splitPos).stripWhiteSpace();
715         String value = header.substring(splitPos + 1).stripWhiteSpace();
716
717         if (isAppendableHeader(key))
718             d->m_response.addHTTPHeaderField(key, value);
719         else
720             d->m_response.setHTTPHeaderField(key, value);
721     } else if (header.startsWith("HTTP", false)) {
722         // This is the first line of the response.
723         // Extract the http status text from this.
724         //
725         // If the FOLLOWLOCATION option is enabled for the curl handle then
726         // curl will follow the redirections internally. Thus this header callback
727         // will be called more than one time with the line starting "HTTP" for one job.
728         long httpCode = 0;
729         d->m_curlHandle.getResponseCode(httpCode);
730
731         String httpCodeString = String::number(httpCode);
732         int statusCodePos = header.find(httpCodeString);
733
734         if (statusCodePos != notFound) {
735             // The status text is after the status code.
736             String status = header.substring(statusCodePos + httpCodeString.length());
737             d->m_response.setHTTPStatusText(status.stripWhiteSpace());
738         }
739     }
740 }
741
742 void ResourceHandle::didReceiveAllHeaders(long httpCode, long long contentLength)
743 {
744     ASSERT(isMainThread());
745
746     d->m_response.setExpectedContentLength(contentLength);
747
748     d->m_response.setURL(d->m_curlHandle.getEffectiveURL());
749
750     d->m_response.setHTTPStatusCode(httpCode);
751     d->m_response.setMimeType(extractMIMETypeFromMediaType(d->m_response.httpHeaderField(HTTPHeaderName::ContentType)).convertToASCIILowercase());
752     d->m_response.setTextEncodingName(extractCharsetFromMediaType(d->m_response.httpHeaderField(HTTPHeaderName::ContentType)));
753
754     if (d->m_response.isMultipart()) {
755         String boundary;
756         bool parsed = MultipartHandle::extractBoundary(d->m_response.httpHeaderField(HTTPHeaderName::ContentType), boundary);
757         if (parsed)
758             d->m_multipartHandle = std::make_unique<MultipartHandle>(this, boundary);
759     }
760
761     // HTTP redirection
762     if (isHttpRedirect(httpCode)) {
763         String location = d->m_response.httpHeaderField(HTTPHeaderName::Location);
764         if (!location.isEmpty()) {
765             URL newURL = URL(firstRequest().url(), location);
766
767             ResourceRequest redirectedRequest = firstRequest();
768             redirectedRequest.setURL(newURL);
769             ResourceResponse response = d->m_response;
770             if (client())
771                 client()->willSendRequest(this, WTFMove(redirectedRequest), WTFMove(response));
772
773             firstRequest().setURL(newURL);
774
775             return;
776         }
777     } else if (isHttpAuthentication(httpCode)) {
778         ProtectionSpace protectionSpace;
779         if (getProtectionSpace(this, d->m_response, protectionSpace)) {
780             Credential credential;
781             AuthenticationChallenge challenge(protectionSpace, credential, d->m_authFailureCount, d->m_response, ResourceError());
782             challenge.setAuthenticationClient(this);
783             this->didReceiveAuthenticationChallenge(challenge);
784             d->m_authFailureCount++;
785             return;
786         }
787     }
788
789     if (client()) {
790         if (isHttpNotModified(httpCode)) {
791             const String& url = firstRequest().url().string();
792             if (CurlCacheManager::getInstance().getCachedResponse(url, d->m_response)) {
793                 if (d->m_addedCacheValidationHeaders) {
794                     d->m_response.setHTTPStatusCode(200);
795                     d->m_response.setHTTPStatusText("OK");
796                 }
797             }
798         }
799         client()->didReceiveResponse(this, ResourceResponse(d->m_response));
800         CurlCacheManager::getInstance().didReceiveResponse(*this, d->m_response);
801     }
802
803     d->m_response.setResponseFired(true);
804 }
805
806 void ResourceHandle::didReceiveContentData()
807 {
808     ASSERT(isMainThread());
809
810     if (!d->m_response.responseFired())
811         handleLocalReceiveResponse();
812
813     Vector<char> buffer;
814     {
815         LockHolder locker { m_receivedBufferMutex };
816         buffer = WTFMove(m_receivedBuffer);
817     }
818
819     char* ptr = buffer.begin();
820     size_t size = buffer.size();
821
822     if (d->m_multipartHandle)
823         d->m_multipartHandle->contentReceived(static_cast<const char*>(ptr), size);
824     else if (client()) {
825         client()->didReceiveData(this, ptr, size, 0);
826         CurlCacheManager::getInstance().didReceiveData(*this, ptr, size);
827     }
828 }
829
830 /* This is called to obtain HTTP POST or PUT data.
831 Iterate through FormData elements and upload files.
832 Carefully respect the given buffer size and fill the rest of the data at the next calls.
833 */
834 size_t ResourceHandle::readCallback(char* ptr, size_t size, size_t nmemb, void* data)
835 {
836     ASSERT(!isMainThread());
837
838     ResourceHandle* job = static_cast<ResourceHandle*>(data);
839     ResourceHandleInternal* d = job->getInternal();
840
841     if (d->m_cancelled)
842         return 0;
843
844     // We should never be called when deferred loading is activated.
845     ASSERT(!d->m_defersLoading);
846
847     if (!size || !nmemb)
848         return 0;
849
850     return job->willPrepareSendData(ptr, size, nmemb);
851 }
852
853 /*
854 * This is being called for each HTTP header in the response. This includes '\r\n'
855 * for the last line of the header.
856 *
857 * We will add each HTTP Header to the ResourceResponse and on the termination
858 * of the header (\r\n) we will parse Content-Type and Content-Disposition and
859 * update the ResourceResponse and then send it away.
860 *
861 */
862 size_t ResourceHandle::headerCallback(char* ptr, size_t size, size_t nmemb, void* data)
863 {
864     ASSERT(!isMainThread());
865
866     ResourceHandle* job = static_cast<ResourceHandle*>(data);
867     ResourceHandleInternal* d = job->getInternal();
868     if (d->m_cancelled)
869         return 0;
870
871     // We should never be called when deferred loading is activated.
872     ASSERT(!d->m_defersLoading);
873
874     size_t totalSize = size * nmemb;
875
876     String header(static_cast<const char*>(ptr), totalSize);
877
878     /*
879     * a) We can finish and send the ResourceResponse
880     * b) We will add the current header to the HTTPHeaderMap of the ResourceResponse
881     *
882     * The HTTP standard requires to use \r\n but for compatibility it recommends to
883     * accept also \n.
884     */
885     if (header == AtomicString("\r\n") || header == AtomicString("\n")) {
886         long httpCode = 0;
887         d->m_curlHandle.getResponseCode(httpCode);
888
889         if (!httpCode) {
890             // Comes here when receiving 200 Connection Established. Just return.
891             return totalSize;
892         }
893         if (isHttpInfo(httpCode)) {
894             // Just return when receiving http info, e.g. HTTP/1.1 100 Continue.
895             // If not, the request might be cancelled, because the MIME type will be empty for this response.
896             return totalSize;
897         }
898
899         long long contentLength = 0;
900         d->m_curlHandle.getContentLenghtDownload(contentLength);
901
902         callOnMainThread([job = RefPtr<ResourceHandle>(job), httpCode, contentLength] {
903             if (!job->d->m_cancelled)
904                 job->didReceiveAllHeaders(httpCode, contentLength);
905         });
906     } else
907         job->didReceiveHeaderLine(header);
908
909     return totalSize;
910 }
911
912 // called with data after all headers have been processed via headerCallback
913 size_t ResourceHandle::writeCallback(char* ptr, size_t size, size_t nmemb, void* data)
914 {
915     ASSERT(!isMainThread());
916
917     ResourceHandle* job = static_cast<ResourceHandle*>(data);
918     ResourceHandleInternal* d = job->getInternal();
919     if (d->m_cancelled)
920         return 0;
921
922     // We should never be called when deferred loading is activated.
923     ASSERT(!d->m_defersLoading);
924
925     size_t totalSize = size * nmemb;
926
927     // this shouldn't be necessary but apparently is. CURL writes the data
928     // of html page even if it is a redirect that was handled internally
929     // can be observed e.g. on gmail.com
930     long httpCode = 0;
931     CURLcode errCd = d->m_curlHandle.getResponseCode(httpCode);
932     if (CURLE_OK == errCd && httpCode >= 300 && httpCode < 400)
933         return totalSize;
934
935     bool shouldCall { false };
936     {
937         LockHolder locker(job->m_receivedBufferMutex);
938         
939         if (job->m_receivedBuffer.isEmpty())
940             shouldCall = true;
941         
942         job->m_receivedBuffer.append(ptr, totalSize);
943     }
944
945     if (shouldCall) {
946         callOnMainThread([job = RefPtr<ResourceHandle>(job)] {
947             if (!job->d->m_cancelled)
948                 job->didReceiveContentData();
949         });
950     }
951
952     return totalSize;
953 }
954
955 // sync loader
956
957 void ResourceHandle::platformLoadResourceSynchronously(NetworkingContext* context, const ResourceRequest& request, StoredCredentials, ResourceError& error, ResourceResponse& response, Vector<char>& data)
958 {
959     ASSERT(isMainThread());
960
961     SynchronousLoaderClient client;
962     RefPtr<ResourceHandle> handle = adoptRef(new ResourceHandle(context, request, &client, false, false));
963
964     handle.get()->dispatchSynchronousJob();
965
966     error = client.error();
967     data.swap(client.mutableData());
968     response = client.response();
969 }
970
971 void ResourceHandle::dispatchSynchronousJob()
972 {
973     URL kurl = firstRequest().url();
974
975     if (kurl.protocolIsData()) {
976         handleDataURL();
977         return;
978     }
979
980     ResourceHandleInternal* d = getInternal();
981
982     // If defersLoading is true and we call curl_easy_perform
983     // on a paused handle, libcURL would do the transfert anyway
984     // and we would assert so force defersLoading to be false.
985     d->m_defersLoading = false;
986
987     initialize();
988
989     // curl_easy_perform blocks until the transfert is finished.
990     CURLcode ret = d->m_curlHandle.perform();
991
992 #if ENABLE(WEB_TIMING)
993     calculateWebTimingInformations();
994 #endif
995
996     if (client()) {
997         if (ret != CURLE_OK)
998             client()->didFail(this, ResourceError(d->m_curlHandle, d->m_sslErrors));
999         else
1000             client()->didReceiveResponse(this, ResourceResponse(d->m_response));
1001     }
1002 }
1003
1004 void ResourceHandle::handleDataURL()
1005 {
1006     ASSERT(firstRequest().url().protocolIsData());
1007     String url = firstRequest().url().string();
1008
1009     ASSERT(client());
1010
1011     int index = url.find(',');
1012     if (index == -1) {
1013         client()->cannotShowURL(this);
1014         return;
1015     }
1016
1017     String mediaType = url.substring(5, index - 5);
1018     String data = url.substring(index + 1);
1019
1020     bool base64 = mediaType.endsWith(";base64", false);
1021     if (base64)
1022         mediaType = mediaType.left(mediaType.length() - 7);
1023
1024     if (mediaType.isEmpty())
1025         mediaType = "text/plain";
1026
1027     String mimeType = extractMIMETypeFromMediaType(mediaType);
1028     String charset = extractCharsetFromMediaType(mediaType);
1029
1030     if (charset.isEmpty())
1031         charset = "US-ASCII";
1032
1033     ResourceResponse response;
1034     response.setMimeType(mimeType);
1035     response.setTextEncodingName(charset);
1036     response.setURL(firstRequest().url());
1037
1038     if (base64) {
1039         data = decodeURLEscapeSequences(data);
1040         client()->didReceiveResponse(this, WTFMove(response));
1041
1042         // didReceiveResponse might cause the client to be deleted.
1043         if (client()) {
1044             Vector<char> out;
1045             if (base64Decode(data, out, Base64IgnoreSpacesAndNewLines) && out.size() > 0)
1046                 client()->didReceiveData(this, out.data(), out.size(), 0);
1047         }
1048     } else {
1049         TextEncoding encoding(charset);
1050         data = decodeURLEscapeSequences(data, encoding);
1051         client()->didReceiveResponse(this, WTFMove(response));
1052
1053         // didReceiveResponse might cause the client to be deleted.
1054         if (client()) {
1055             CString encodedData = encoding.encode(data, URLEncodedEntitiesForUnencodables);
1056             if (encodedData.length())
1057                 client()->didReceiveData(this, encodedData.data(), encodedData.length(), 0);
1058         }
1059     }
1060
1061     if (client())
1062         client()->didFinishLoading(this);
1063 }
1064
1065 } // namespace WebCore
1066
1067 #endif