Remove Cocoa CFURLConnection loading code
[WebKit-https.git] / Source / WebCore / loader / ResourceLoader.cpp
1 /*
2  * Copyright (C) 2006-2007, 2010-2011, 2016 Apple Inc. All rights reserved.
3  *           (C) 2007 Graham Dennis (graham.dennis@gmail.com)
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer. 
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution. 
14  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission. 
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include "config.h"
31 #include "ResourceLoader.h"
32
33 #include "ApplicationCacheHost.h"
34 #include "AuthenticationChallenge.h"
35 #include "DataURLDecoder.h"
36 #include "DiagnosticLoggingClient.h"
37 #include "DiagnosticLoggingKeys.h"
38 #include "DocumentLoader.h"
39 #include "Frame.h"
40 #include "FrameLoader.h"
41 #include "FrameLoaderClient.h"
42 #include "InspectorInstrumentation.h"
43 #include "LoaderStrategy.h"
44 #include "MainFrame.h"
45 #include "MixedContentChecker.h"
46 #include "Page.h"
47 #include "PlatformStrategies.h"
48 #include "ProgressTracker.h"
49 #include "ResourceError.h"
50 #include "ResourceHandle.h"
51 #include "SecurityOrigin.h"
52 #include "SharedBuffer.h"
53 #include <wtf/CompletionHandler.h>
54 #include <wtf/Ref.h>
55
56 #if ENABLE(CONTENT_EXTENSIONS)
57 #include "UserContentController.h"
58 #endif
59
60 #if USE(QUICK_LOOK)
61 #include "PreviewConverter.h"
62 #include "PreviewLoader.h"
63 #endif
64
65 namespace WebCore {
66
67 ResourceLoader::ResourceLoader(Frame& frame, ResourceLoaderOptions options)
68     : m_frame { &frame }
69     , m_documentLoader { frame.loader().activeDocumentLoader() }
70     , m_defersLoading { options.defersLoadingPolicy == DefersLoadingPolicy::AllowDefersLoading && frame.page()->defersLoading() }
71     , m_canAskClientForCredentials { options.clientCredentialPolicy == ClientCredentialPolicy::MayAskClientForCredentials }
72     , m_options { options }
73 {
74 }
75
76 ResourceLoader::~ResourceLoader()
77 {
78     ASSERT(m_reachedTerminalState);
79 }
80
81 void ResourceLoader::finishNetworkLoad()
82 {
83     platformStrategies()->loaderStrategy()->remove(this);
84
85     if (m_handle) {
86         ASSERT(m_handle->client() == this);
87         m_handle->clearClient();
88         m_handle = nullptr;
89     }
90 }
91
92 void ResourceLoader::releaseResources()
93 {
94     ASSERT(!m_reachedTerminalState);
95     
96     // It's possible that when we release the handle, it will be
97     // deallocated and release the last reference to this object.
98     // We need to retain to avoid accessing the object after it
99     // has been deallocated and also to avoid reentering this method.
100     Ref<ResourceLoader> protectedThis(*this);
101
102     m_frame = nullptr;
103     m_documentLoader = nullptr;
104     
105     // We need to set reachedTerminalState to true before we release
106     // the resources to prevent a double dealloc of WebView <rdar://problem/4372628>
107     m_reachedTerminalState = true;
108
109     finishNetworkLoad();
110
111     m_identifier = 0;
112
113     m_resourceData = nullptr;
114     m_deferredRequest = ResourceRequest();
115 }
116
117 void ResourceLoader::init(ResourceRequest&& clientRequest, CompletionHandler<void(bool)>&& completionHandler)
118 {
119     ASSERT(!m_handle);
120     ASSERT(m_request.isNull());
121     ASSERT(m_deferredRequest.isNull());
122     ASSERT(!m_documentLoader->isSubstituteLoadPending(this));
123     
124     m_loadTiming.markStartTimeAndFetchStart();
125
126 #if PLATFORM(IOS)
127     // If the documentLoader was detached while this ResourceLoader was waiting its turn
128     // in ResourceLoadScheduler queue, don't continue.
129     if (!m_documentLoader->frame()) {
130         cancel();
131         return completionHandler(false);
132     }
133 #endif
134     
135     m_defersLoading = m_options.defersLoadingPolicy == DefersLoadingPolicy::AllowDefersLoading && m_frame->page()->defersLoading();
136     m_canAskClientForCredentials = m_options.clientCredentialPolicy == ClientCredentialPolicy::MayAskClientForCredentials && !isMixedContent(clientRequest.url());
137
138     if (m_options.securityCheck == DoSecurityCheck && !m_frame->document()->securityOrigin().canDisplay(clientRequest.url())) {
139         FrameLoader::reportLocalLoadFailed(m_frame.get(), clientRequest.url().string());
140         releaseResources();
141         return completionHandler(false);
142     }
143     
144     // https://bugs.webkit.org/show_bug.cgi?id=26391
145     // The various plug-in implementations call directly to ResourceLoader::load() instead of piping requests
146     // through FrameLoader. As a result, they miss the FrameLoader::addExtraFieldsToRequest() step which sets
147     // up the 1st party for cookies URL. Until plug-in implementations can be reigned in to pipe through that
148     // method, we need to make sure there is always a 1st party for cookies set.
149     if (clientRequest.firstPartyForCookies().isNull()) {
150         if (Document* document = m_frame->document())
151             clientRequest.setFirstPartyForCookies(document->firstPartyForCookies());
152     }
153
154     willSendRequestInternal(WTFMove(clientRequest), ResourceResponse(), [this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)](ResourceRequest&& request) mutable {
155
156 #if PLATFORM(IOS)
157         // If this ResourceLoader was stopped as a result of willSendRequest, bail out.
158         if (m_reachedTerminalState)
159             return completionHandler(false);
160 #endif
161
162         if (request.isNull()) {
163             cancel();
164             return completionHandler(false);
165         }
166
167         m_request = WTFMove(request);
168         m_originalRequest = m_request;
169         completionHandler(true);
170     });
171 }
172
173 void ResourceLoader::deliverResponseAndData(const ResourceResponse& response, RefPtr<SharedBuffer>&& buffer)
174 {
175     Ref<ResourceLoader> protectedThis(*this);
176
177     didReceiveResponse(response);
178     if (reachedTerminalState())
179         return;
180
181     if (buffer) {
182         unsigned size = buffer->size();
183         didReceiveBuffer(buffer.releaseNonNull(), size, DataPayloadWholeResource);
184         if (reachedTerminalState())
185             return;
186     }
187
188     NetworkLoadMetrics emptyMetrics;
189     didFinishLoading(emptyMetrics);
190 }
191
192 void ResourceLoader::start()
193 {
194     ASSERT(!m_handle);
195     ASSERT(!m_request.isNull());
196     ASSERT(m_deferredRequest.isNull());
197     ASSERT(frameLoader());
198
199 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
200     if (m_documentLoader->scheduleArchiveLoad(*this, m_request))
201         return;
202 #endif
203
204     if (m_documentLoader->applicationCacheHost().maybeLoadResource(*this, m_request, m_request.url()))
205         return;
206
207     if (m_defersLoading) {
208         m_deferredRequest = m_request;
209         return;
210     }
211
212     if (m_reachedTerminalState)
213         return;
214
215     if (m_request.url().protocolIsData()) {
216         loadDataURL();
217         return;
218     }
219
220     m_handle = ResourceHandle::create(frameLoader()->networkingContext(), m_request, this, m_defersLoading, m_options.sniffContent == SniffContent, m_options.sniffContentEncoding == ContentEncodingSniffingPolicy::Sniff);
221 }
222
223 void ResourceLoader::setDefersLoading(bool defers)
224 {
225     if (m_options.defersLoadingPolicy == DefersLoadingPolicy::DisallowDefersLoading)
226         return;
227
228     m_defersLoading = defers;
229     if (m_handle)
230         m_handle->setDefersLoading(defers);
231     if (!defers && !m_deferredRequest.isNull()) {
232         m_request = m_deferredRequest;
233         m_deferredRequest = ResourceRequest();
234         start();
235     }
236
237     platformStrategies()->loaderStrategy()->setDefersLoading(this, defers);
238 }
239
240 FrameLoader* ResourceLoader::frameLoader() const
241 {
242     if (!m_frame)
243         return nullptr;
244     return &m_frame->loader();
245 }
246
247 void ResourceLoader::loadDataURL()
248 {
249     auto url = m_request.url();
250     ASSERT(url.protocolIsData());
251
252     DataURLDecoder::ScheduleContext scheduleContext;
253 #if HAVE(RUNLOOP_TIMER)
254     if (auto* scheduledPairs = m_frame->page()->scheduledRunLoopPairs())
255         scheduleContext.scheduledPairs = *scheduledPairs;
256 #endif
257     DataURLDecoder::decode(url, scheduleContext, [protectedThis = makeRef(*this), url](auto decodeResult) {
258         if (protectedThis->reachedTerminalState())
259             return;
260         if (!decodeResult) {
261             protectedThis->didFail(ResourceError(errorDomainWebKitInternal, 0, url, "Data URL decoding failed"));
262             return;
263         }
264         if (protectedThis->wasCancelled())
265             return;
266         auto& result = decodeResult.value();
267         auto dataSize = result.data ? result.data->size() : 0;
268
269         ResourceResponse dataResponse { url, result.mimeType, static_cast<long long>(dataSize), result.charset };
270         dataResponse.setHTTPStatusCode(200);
271         dataResponse.setHTTPStatusText(ASCIILiteral("OK"));
272         dataResponse.setHTTPHeaderField(HTTPHeaderName::ContentType, result.contentType);
273         dataResponse.setSource(ResourceResponse::Source::Network);
274         protectedThis->didReceiveResponse(dataResponse);
275
276         if (!protectedThis->reachedTerminalState() && dataSize)
277             protectedThis->didReceiveBuffer(result.data.releaseNonNull(), dataSize, DataPayloadWholeResource);
278
279         if (!protectedThis->reachedTerminalState()) {
280             NetworkLoadMetrics emptyMetrics;
281             protectedThis->didFinishLoading(emptyMetrics);
282         }
283     });
284 }
285
286 void ResourceLoader::setDataBufferingPolicy(DataBufferingPolicy dataBufferingPolicy)
287 {
288     m_options.dataBufferingPolicy = dataBufferingPolicy;
289
290     // Reset any already buffered data
291     if (dataBufferingPolicy == DoNotBufferData)
292         m_resourceData = nullptr;
293 }
294
295 void ResourceLoader::willSwitchToSubstituteResource()
296 {
297     ASSERT(!m_documentLoader->isSubstituteLoadPending(this));
298     platformStrategies()->loaderStrategy()->remove(this);
299     if (m_handle)
300         m_handle->cancel();
301 }
302
303 void ResourceLoader::addDataOrBuffer(const char* data, unsigned length, SharedBuffer* buffer, DataPayloadType dataPayloadType)
304 {
305     if (m_options.dataBufferingPolicy == DoNotBufferData)
306         return;
307
308     if (!m_resourceData || dataPayloadType == DataPayloadWholeResource) {
309         if (buffer)
310             m_resourceData = buffer;
311         else
312             m_resourceData = SharedBuffer::create(data, length);
313         return;
314     }
315     
316     if (buffer)
317         m_resourceData->append(*buffer);
318     else
319         m_resourceData->append(data, length);
320 }
321
322 void ResourceLoader::clearResourceData()
323 {
324     if (m_resourceData)
325         m_resourceData->clear();
326 }
327
328 bool ResourceLoader::isSubresourceLoader()
329 {
330     return false;
331 }
332
333 bool ResourceLoader::isMixedContent(const URL& url) const
334 {
335     if (MixedContentChecker::isMixedContent(m_frame->document()->securityOrigin(), url))
336         return true;
337     Frame& topFrame = m_frame->tree().top();
338     if (&topFrame != m_frame && MixedContentChecker::isMixedContent(topFrame.document()->securityOrigin(), url))
339         return true;
340     return false;
341 }
342
343 void ResourceLoader::willSendRequestInternal(ResourceRequest&& request, const ResourceResponse& redirectResponse, CompletionHandler<void(ResourceRequest&&)>&& completionHandler)
344 {
345     // Protect this in this delegate method since the additional processing can do
346     // anything including possibly derefing this; one example of this is Radar 3266216.
347     Ref<ResourceLoader> protectedThis(*this);
348
349     ASSERT(!m_reachedTerminalState);
350 #if ENABLE(CONTENT_EXTENSIONS)
351     ASSERT(m_resourceType != ResourceType::Invalid);
352 #endif
353
354     // We need a resource identifier for all requests, even if FrameLoader is never going to see it (such as with CORS preflight requests).
355     bool createdResourceIdentifier = false;
356     if (!m_identifier) {
357         m_identifier = m_frame->page()->progress().createUniqueIdentifier();
358         createdResourceIdentifier = true;
359     }
360
361 #if ENABLE(CONTENT_EXTENSIONS)
362     if (!redirectResponse.isNull() && frameLoader()) {
363         Page* page = frameLoader()->frame().page();
364         if (page && m_documentLoader) {
365             auto blockedStatus = page->userContentProvider().processContentExtensionRulesForLoad(request.url(), m_resourceType, *m_documentLoader);
366             applyBlockedStatusToRequest(blockedStatus, page, request);
367             if (blockedStatus.blockedLoad) {
368                 didFail(blockedByContentBlockerError());
369                 completionHandler({ });
370                 return;
371             }
372         }
373     }
374 #endif
375
376     if (request.isNull()) {
377         didFail(cannotShowURLError());
378         completionHandler({ });
379         return;
380     }
381
382     if (m_options.sendLoadCallbacks == SendCallbacks) {
383         if (createdResourceIdentifier)
384             frameLoader()->notifier().assignIdentifierToInitialRequest(m_identifier, documentLoader(), request);
385
386 #if PLATFORM(IOS)
387         // If this ResourceLoader was stopped as a result of assignIdentifierToInitialRequest, bail out
388         if (m_reachedTerminalState) {
389             completionHandler(WTFMove(request));
390             return;
391         }
392 #endif
393
394         frameLoader()->notifier().willSendRequest(this, request, redirectResponse);
395     }
396     else
397         InspectorInstrumentation::willSendRequest(m_frame.get(), m_identifier, m_frame->loader().documentLoader(), request, redirectResponse);
398
399 #if USE(QUICK_LOOK)
400     if (auto previewConverter = m_documentLoader->previewConverter())
401         request = previewConverter->safeRequest(request);
402 #endif
403
404     bool isRedirect = !redirectResponse.isNull();
405
406     if (isMixedContent(m_request.url()) || (isRedirect && isMixedContent(request.url())))
407         m_canAskClientForCredentials = false;
408
409     if (isRedirect)
410         platformStrategies()->loaderStrategy()->crossOriginRedirectReceived(this, request.url());
411
412     m_request = request;
413
414     if (isRedirect) {
415         auto& redirectURL = request.url();
416         if (!m_documentLoader->isCommitted())
417             frameLoader()->client().dispatchDidReceiveServerRedirectForProvisionalLoad();
418
419         if (redirectURL.protocolIsData()) {
420             // Handle data URL decoding locally.
421             finishNetworkLoad();
422             loadDataURL();
423         }
424     }
425     completionHandler(WTFMove(request));
426 }
427
428 void ResourceLoader::willSendRequest(ResourceRequest&& request, const ResourceResponse& redirectResponse, CompletionHandler<void(ResourceRequest&&)>&& completionHandler)
429 {
430     willSendRequestInternal(WTFMove(request), redirectResponse, WTFMove(completionHandler));
431 }
432
433 void ResourceLoader::didSendData(unsigned long long, unsigned long long)
434 {
435 }
436
437 static void logResourceResponseSource(Frame* frame, ResourceResponse::Source source)
438 {
439     if (!frame || !frame->page())
440         return;
441
442     String sourceKey;
443     switch (source) {
444     case ResourceResponse::Source::Network:
445         sourceKey = DiagnosticLoggingKeys::networkKey();
446         break;
447     case ResourceResponse::Source::DiskCache:
448         sourceKey = DiagnosticLoggingKeys::diskCacheKey();
449         break;
450     case ResourceResponse::Source::DiskCacheAfterValidation:
451         sourceKey = DiagnosticLoggingKeys::diskCacheAfterValidationKey();
452         break;
453     case ResourceResponse::Source::ServiceWorker:
454         sourceKey = DiagnosticLoggingKeys::serviceWorkerKey();
455         break;
456     case ResourceResponse::Source::MemoryCache:
457     case ResourceResponse::Source::MemoryCacheAfterValidation:
458     case ResourceResponse::Source::Unknown:
459         return;
460     }
461
462     frame->page()->diagnosticLoggingClient().logDiagnosticMessage(DiagnosticLoggingKeys::resourceResponseSourceKey(), sourceKey, ShouldSample::Yes);
463 }
464
465 void ResourceLoader::didReceiveResponse(const ResourceResponse& r)
466 {
467     ASSERT(!m_reachedTerminalState);
468
469     // Protect this in this delegate method since the additional processing can do
470     // anything including possibly derefing this; one example of this is Radar 3266216.
471     Ref<ResourceLoader> protectedThis(*this);
472
473     logResourceResponseSource(m_frame.get(), r.source());
474
475     m_response = r;
476
477     if (FormData* data = m_request.httpBody())
478         data->removeGeneratedFilesIfNeeded();
479
480     if (m_options.sendLoadCallbacks == SendCallbacks)
481         frameLoader()->notifier().didReceiveResponse(this, m_response);
482 }
483
484 void ResourceLoader::didReceiveData(const char* data, unsigned length, long long encodedDataLength, DataPayloadType dataPayloadType)
485 {
486     // The following assertions are not quite valid here, since a subclass
487     // might override didReceiveData in a way that invalidates them. This
488     // happens with the steps listed in 3266216
489     // ASSERT(con == connection);
490     // ASSERT(!m_reachedTerminalState);
491
492     didReceiveDataOrBuffer(data, length, nullptr, encodedDataLength, dataPayloadType);
493 }
494
495 void ResourceLoader::didReceiveBuffer(Ref<SharedBuffer>&& buffer, long long encodedDataLength, DataPayloadType dataPayloadType)
496 {
497     didReceiveDataOrBuffer(nullptr, 0, WTFMove(buffer), encodedDataLength, dataPayloadType);
498 }
499
500 void ResourceLoader::didReceiveDataOrBuffer(const char* data, unsigned length, RefPtr<SharedBuffer>&& buffer, long long encodedDataLength, DataPayloadType dataPayloadType)
501 {
502     // This method should only get data+length *OR* a SharedBuffer.
503     ASSERT(!buffer || (!data && !length));
504
505     // Protect this in this delegate method since the additional processing can do
506     // anything including possibly derefing this; one example of this is Radar 3266216.
507     Ref<ResourceLoader> protectedThis(*this);
508
509     addDataOrBuffer(data, length, buffer.get(), dataPayloadType);
510
511     // FIXME: If we get a resource with more than 2B bytes, this code won't do the right thing.
512     // However, with today's computers and networking speeds, this won't happen in practice.
513     // Could be an issue with a giant local file.
514     if (m_options.sendLoadCallbacks == SendCallbacks && m_frame)
515         frameLoader()->notifier().didReceiveData(this, buffer ? buffer->data() : data, buffer ? buffer->size() : length, static_cast<int>(encodedDataLength));
516 }
517
518 void ResourceLoader::didFinishLoading(const NetworkLoadMetrics& networkLoadMetrics)
519 {
520     didFinishLoadingOnePart(networkLoadMetrics);
521
522     // If the load has been cancelled by a delegate in response to didFinishLoad(), do not release
523     // the resources a second time, they have been released by cancel.
524     if (wasCancelled())
525         return;
526     releaseResources();
527 }
528
529 void ResourceLoader::didFinishLoadingOnePart(const NetworkLoadMetrics& networkLoadMetrics)
530 {
531     // If load has been cancelled after finishing (which could happen with a
532     // JavaScript that changes the window location), do nothing.
533     if (wasCancelled())
534         return;
535     ASSERT(!m_reachedTerminalState);
536
537     if (m_notifiedLoadComplete)
538         return;
539     m_notifiedLoadComplete = true;
540     if (m_options.sendLoadCallbacks == SendCallbacks)
541         frameLoader()->notifier().didFinishLoad(this, networkLoadMetrics);
542 }
543
544 void ResourceLoader::didFail(const ResourceError& error)
545 {
546     if (wasCancelled())
547         return;
548     ASSERT(!m_reachedTerminalState);
549
550     // Protect this in this delegate method since the additional processing can do
551     // anything including possibly derefing this; one example of this is Radar 3266216.
552     Ref<ResourceLoader> protectedThis(*this);
553
554     cleanupForError(error);
555     releaseResources();
556 }
557
558 void ResourceLoader::cleanupForError(const ResourceError& error)
559 {
560     if (FormData* data = m_request.httpBody())
561         data->removeGeneratedFilesIfNeeded();
562
563     if (m_notifiedLoadComplete)
564         return;
565     m_notifiedLoadComplete = true;
566     if (m_options.sendLoadCallbacks == SendCallbacks && m_identifier)
567         frameLoader()->notifier().didFailToLoad(this, error);
568 }
569
570 void ResourceLoader::cancel()
571 {
572     cancel(ResourceError());
573 }
574
575 void ResourceLoader::cancel(const ResourceError& error)
576 {
577     // If the load has already completed - succeeded, failed, or previously cancelled - do nothing.
578     if (m_reachedTerminalState)
579         return;
580        
581     ResourceError nonNullError = error.isNull() ? cancelledError() : error;
582     
583     // willCancel() and didFailToLoad() both call out to clients that might do 
584     // something causing the last reference to this object to go away.
585     Ref<ResourceLoader> protectedThis(*this);
586     
587     // If we re-enter cancel() from inside willCancel(), we want to pick up from where we left 
588     // off without re-running willCancel()
589     if (m_cancellationStatus == NotCancelled) {
590         m_cancellationStatus = CalledWillCancel;
591         
592         willCancel(nonNullError);
593     }
594
595     // If we re-enter cancel() from inside didFailToLoad(), we want to pick up from where we 
596     // left off without redoing any of this work.
597     if (m_cancellationStatus == CalledWillCancel) {
598         m_cancellationStatus = Cancelled;
599
600         if (m_handle)
601             m_handle->clearAuthentication();
602
603         m_documentLoader->cancelPendingSubstituteLoad(this);
604         if (m_handle) {
605             m_handle->cancel();
606             m_handle = nullptr;
607         }
608         cleanupForError(nonNullError);
609     }
610
611     // If cancel() completed from within the call to willCancel() or didFailToLoad(),
612     // we don't want to redo didCancel() or releasesResources().
613     if (m_reachedTerminalState)
614         return;
615
616     didCancel(nonNullError);
617
618     if (m_cancellationStatus == FinishedCancel)
619         return;
620     m_cancellationStatus = FinishedCancel;
621
622     releaseResources();
623 }
624
625 ResourceError ResourceLoader::cancelledError()
626 {
627     return frameLoader()->cancelledError(m_request);
628 }
629
630 ResourceError ResourceLoader::blockedError()
631 {
632     return frameLoader()->client().blockedError(m_request);
633 }
634
635 ResourceError ResourceLoader::blockedByContentBlockerError()
636 {
637     return frameLoader()->client().blockedByContentBlockerError(m_request);
638 }
639
640 ResourceError ResourceLoader::cannotShowURLError()
641 {
642     return frameLoader()->client().cannotShowURLError(m_request);
643 }
644
645 void ResourceLoader::willSendRequestAsync(ResourceHandle* handle, ResourceRequest&& request, ResourceResponse&& redirectResponse, CompletionHandler<void(ResourceRequest&&)>&& completionHandler)
646 {
647     RefPtr<ResourceHandle> protectedHandle(handle);
648     if (documentLoader()->applicationCacheHost().maybeLoadFallbackForRedirect(this, request, redirectResponse)) {
649         completionHandler(WTFMove(request));
650         return;
651     }
652     willSendRequestInternal(WTFMove(request), redirectResponse, WTFMove(completionHandler));
653 }
654
655 void ResourceLoader::didSendData(ResourceHandle*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
656 {
657     didSendData(bytesSent, totalBytesToBeSent);
658 }
659
660 void ResourceLoader::didReceiveResponseAsync(ResourceHandle* handle, ResourceResponse&& response)
661 {
662     if (documentLoader()->applicationCacheHost().maybeLoadFallbackForResponse(this, response)) {
663         handle->continueDidReceiveResponse();
664         return;
665     }
666     didReceiveResponse(response);
667     handle->continueDidReceiveResponse();
668 }
669
670 void ResourceLoader::didReceiveData(ResourceHandle*, const char* data, unsigned length, int encodedDataLength)
671 {
672     didReceiveData(data, length, encodedDataLength, DataPayloadBytes);
673 }
674
675 void ResourceLoader::didReceiveBuffer(ResourceHandle*, Ref<SharedBuffer>&& buffer, int encodedDataLength)
676 {
677     didReceiveBuffer(WTFMove(buffer), encodedDataLength, DataPayloadBytes);
678 }
679
680 void ResourceLoader::didFinishLoading(ResourceHandle*)
681 {
682     NetworkLoadMetrics emptyMetrics;
683     didFinishLoading(emptyMetrics);
684 }
685
686 void ResourceLoader::didFail(ResourceHandle*, const ResourceError& error)
687 {
688     if (documentLoader()->applicationCacheHost().maybeLoadFallbackForError(this, error))
689         return;
690     didFail(error);
691 }
692
693 void ResourceLoader::wasBlocked(ResourceHandle*)
694 {
695     didFail(blockedError());
696 }
697
698 void ResourceLoader::cannotShowURL(ResourceHandle*)
699 {
700     didFail(cannotShowURLError());
701 }
702
703 bool ResourceLoader::shouldUseCredentialStorage()
704 {
705     if (m_options.storedCredentialsPolicy == StoredCredentialsPolicy::DoNotUse)
706         return false;
707
708     Ref<ResourceLoader> protectedThis(*this);
709     return frameLoader()->client().shouldUseCredentialStorage(documentLoader(), identifier());
710 }
711
712 bool ResourceLoader::isAllowedToAskUserForCredentials() const
713 {
714     if (!m_canAskClientForCredentials)
715         return false;
716     return m_options.credentials == FetchOptions::Credentials::Include || (m_options.credentials == FetchOptions::Credentials::SameOrigin && m_frame->document()->securityOrigin().canRequest(originalRequest().url()));
717 }
718
719 void ResourceLoader::didReceiveAuthenticationChallenge(const AuthenticationChallenge& challenge)
720 {
721     ASSERT(m_handle->hasAuthenticationChallenge());
722
723     // Protect this in this delegate method since the additional processing can do
724     // anything including possibly derefing this; one example of this is Radar 3266216.
725     Ref<ResourceLoader> protectedThis(*this);
726
727     if (m_options.storedCredentialsPolicy == StoredCredentialsPolicy::Use) {
728         if (isAllowedToAskUserForCredentials()) {
729             frameLoader()->notifier().didReceiveAuthenticationChallenge(this, challenge);
730             return;
731         }
732     }
733     challenge.authenticationClient()->receivedRequestToContinueWithoutCredential(challenge);
734     ASSERT(!m_handle || !m_handle->hasAuthenticationChallenge());
735 }
736
737 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
738 void ResourceLoader::canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle* handle, const ProtectionSpace& protectionSpace)
739 {
740     handle->continueCanAuthenticateAgainstProtectionSpace(canAuthenticateAgainstProtectionSpace(protectionSpace));
741 }
742
743 bool ResourceLoader::canAuthenticateAgainstProtectionSpace(const ProtectionSpace& protectionSpace)
744 {
745     Ref<ResourceLoader> protectedThis(*this);
746     return frameLoader()->client().canAuthenticateAgainstProtectionSpace(documentLoader(), identifier(), protectionSpace);
747 }
748
749 #endif
750     
751 #if PLATFORM(IOS)
752
753 RetainPtr<CFDictionaryRef> ResourceLoader::connectionProperties(ResourceHandle*)
754 {
755     return frameLoader()->connectionProperties(this);
756 }
757
758 #endif
759
760 void ResourceLoader::receivedCancellation(const AuthenticationChallenge&)
761 {
762     cancel();
763 }
764
765 #if PLATFORM(COCOA)
766
767 void ResourceLoader::schedule(SchedulePair& pair)
768 {
769     if (m_handle)
770         m_handle->schedule(pair);
771 }
772
773 void ResourceLoader::unschedule(SchedulePair& pair)
774 {
775     if (m_handle)
776         m_handle->unschedule(pair);
777 }
778
779 #endif
780
781 #if USE(QUICK_LOOK)
782 bool ResourceLoader::isQuickLookResource() const
783 {
784     return !!m_previewLoader;
785 }
786 #endif
787
788 bool ResourceLoader::isAlwaysOnLoggingAllowed() const
789 {
790     return frameLoader() && frameLoader()->isAlwaysOnLoggingAllowed();
791 }
792
793 void ResourceLoader::didRetrieveDerivedDataFromCache(const String&, SharedBuffer&)
794 {
795 }
796
797 }