b8220f5f0c54544c63e23bd13823dde2ef76b6a6
[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 bool ResourceLoader::init(const ResourceRequest& r)
118 {
119     ASSERT(!m_handle);
120     ASSERT(m_request.isNull());
121     ASSERT(m_deferredRequest.isNull());
122     ASSERT(!m_documentLoader->isSubstituteLoadPending(this));
123     
124     ResourceRequest clientRequest(r);
125
126     m_loadTiming.markStartTimeAndFetchStart();
127
128 #if PLATFORM(IOS)
129     // If the documentLoader was detached while this ResourceLoader was waiting its turn
130     // in ResourceLoadScheduler queue, don't continue.
131     if (!m_documentLoader->frame()) {
132         cancel();
133         return false;
134     }
135 #endif
136     
137     m_defersLoading = m_options.defersLoadingPolicy == DefersLoadingPolicy::AllowDefersLoading && m_frame->page()->defersLoading();
138     m_canAskClientForCredentials = m_options.clientCredentialPolicy == ClientCredentialPolicy::MayAskClientForCredentials && !isMixedContent(r.url());
139
140     if (m_options.securityCheck == DoSecurityCheck && !m_frame->document()->securityOrigin().canDisplay(clientRequest.url())) {
141         FrameLoader::reportLocalLoadFailed(m_frame.get(), clientRequest.url().string());
142         releaseResources();
143         return false;
144     }
145     
146     // https://bugs.webkit.org/show_bug.cgi?id=26391
147     // The various plug-in implementations call directly to ResourceLoader::load() instead of piping requests
148     // through FrameLoader. As a result, they miss the FrameLoader::addExtraFieldsToRequest() step which sets
149     // up the 1st party for cookies URL. Until plug-in implementations can be reigned in to pipe through that
150     // method, we need to make sure there is always a 1st party for cookies set.
151     if (clientRequest.firstPartyForCookies().isNull()) {
152         if (Document* document = m_frame->document())
153             clientRequest.setFirstPartyForCookies(document->firstPartyForCookies());
154     }
155
156     willSendRequestInternal(clientRequest, ResourceResponse());
157
158 #if PLATFORM(IOS)
159     // If this ResourceLoader was stopped as a result of willSendRequest, bail out.
160     if (m_reachedTerminalState)
161         return false;
162 #endif
163
164     if (clientRequest.isNull()) {
165         cancel();
166         return false;
167     }
168
169     m_originalRequest = m_request = clientRequest;
170     return true;
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)
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                 request = { };
369                 didFail(blockedByContentBlockerError());
370                 return;
371             }
372         }
373     }
374 #endif
375
376     if (request.isNull()) {
377         didFail(cannotShowURLError());
378         return;
379     }
380
381     if (m_options.sendLoadCallbacks == SendCallbacks) {
382         if (createdResourceIdentifier)
383             frameLoader()->notifier().assignIdentifierToInitialRequest(m_identifier, documentLoader(), request);
384
385 #if PLATFORM(IOS)
386         // If this ResourceLoader was stopped as a result of assignIdentifierToInitialRequest, bail out
387         if (m_reachedTerminalState)
388             return;
389 #endif
390
391         frameLoader()->notifier().willSendRequest(this, request, redirectResponse);
392     }
393     else
394         InspectorInstrumentation::willSendRequest(m_frame.get(), m_identifier, m_frame->loader().documentLoader(), request, redirectResponse);
395
396 #if USE(QUICK_LOOK)
397     if (auto previewConverter = m_documentLoader->previewConverter())
398         request = previewConverter->safeRequest(request);
399 #endif
400
401     bool isRedirect = !redirectResponse.isNull();
402
403     if (isMixedContent(m_request.url()) || (isRedirect && isMixedContent(request.url())))
404         m_canAskClientForCredentials = false;
405
406     if (isRedirect)
407         platformStrategies()->loaderStrategy()->crossOriginRedirectReceived(this, request.url());
408
409     m_request = request;
410
411     if (isRedirect) {
412         auto& redirectURL = request.url();
413         if (!m_documentLoader->isCommitted())
414             frameLoader()->client().dispatchDidReceiveServerRedirectForProvisionalLoad();
415
416         if (redirectURL.protocolIsData()) {
417             // Handle data URL decoding locally.
418             finishNetworkLoad();
419             loadDataURL();
420         }
421     }
422 }
423
424 void ResourceLoader::willSendRequest(ResourceRequest&& request, const ResourceResponse& redirectResponse, CompletionHandler<void(ResourceRequest&&)>&& callback)
425 {
426     willSendRequestInternal(request, redirectResponse);
427     callback(WTFMove(request));
428 }
429
430 void ResourceLoader::didSendData(unsigned long long, unsigned long long)
431 {
432 }
433
434 static void logResourceResponseSource(Frame* frame, ResourceResponse::Source source)
435 {
436     if (!frame || !frame->page())
437         return;
438
439     String sourceKey;
440     switch (source) {
441     case ResourceResponse::Source::Network:
442         sourceKey = DiagnosticLoggingKeys::networkKey();
443         break;
444     case ResourceResponse::Source::DiskCache:
445         sourceKey = DiagnosticLoggingKeys::diskCacheKey();
446         break;
447     case ResourceResponse::Source::DiskCacheAfterValidation:
448         sourceKey = DiagnosticLoggingKeys::diskCacheAfterValidationKey();
449         break;
450     case ResourceResponse::Source::ServiceWorker:
451         sourceKey = DiagnosticLoggingKeys::serviceWorkerKey();
452         break;
453     case ResourceResponse::Source::MemoryCache:
454     case ResourceResponse::Source::MemoryCacheAfterValidation:
455     case ResourceResponse::Source::Unknown:
456         return;
457     }
458
459     frame->page()->diagnosticLoggingClient().logDiagnosticMessage(DiagnosticLoggingKeys::resourceResponseSourceKey(), sourceKey, ShouldSample::Yes);
460 }
461
462 void ResourceLoader::didReceiveResponse(const ResourceResponse& r)
463 {
464     ASSERT(!m_reachedTerminalState);
465
466     // Protect this in this delegate method since the additional processing can do
467     // anything including possibly derefing this; one example of this is Radar 3266216.
468     Ref<ResourceLoader> protectedThis(*this);
469
470     logResourceResponseSource(m_frame.get(), r.source());
471
472     m_response = r;
473
474     if (FormData* data = m_request.httpBody())
475         data->removeGeneratedFilesIfNeeded();
476
477     if (m_options.sendLoadCallbacks == SendCallbacks)
478         frameLoader()->notifier().didReceiveResponse(this, m_response);
479 }
480
481 void ResourceLoader::didReceiveData(const char* data, unsigned length, long long encodedDataLength, DataPayloadType dataPayloadType)
482 {
483     // The following assertions are not quite valid here, since a subclass
484     // might override didReceiveData in a way that invalidates them. This
485     // happens with the steps listed in 3266216
486     // ASSERT(con == connection);
487     // ASSERT(!m_reachedTerminalState);
488
489     didReceiveDataOrBuffer(data, length, nullptr, encodedDataLength, dataPayloadType);
490 }
491
492 void ResourceLoader::didReceiveBuffer(Ref<SharedBuffer>&& buffer, long long encodedDataLength, DataPayloadType dataPayloadType)
493 {
494     didReceiveDataOrBuffer(nullptr, 0, WTFMove(buffer), encodedDataLength, dataPayloadType);
495 }
496
497 void ResourceLoader::didReceiveDataOrBuffer(const char* data, unsigned length, RefPtr<SharedBuffer>&& buffer, long long encodedDataLength, DataPayloadType dataPayloadType)
498 {
499     // This method should only get data+length *OR* a SharedBuffer.
500     ASSERT(!buffer || (!data && !length));
501
502     // Protect this in this delegate method since the additional processing can do
503     // anything including possibly derefing this; one example of this is Radar 3266216.
504     Ref<ResourceLoader> protectedThis(*this);
505
506     addDataOrBuffer(data, length, buffer.get(), dataPayloadType);
507
508     // FIXME: If we get a resource with more than 2B bytes, this code won't do the right thing.
509     // However, with today's computers and networking speeds, this won't happen in practice.
510     // Could be an issue with a giant local file.
511     if (m_options.sendLoadCallbacks == SendCallbacks && m_frame)
512         frameLoader()->notifier().didReceiveData(this, buffer ? buffer->data() : data, buffer ? buffer->size() : length, static_cast<int>(encodedDataLength));
513 }
514
515 void ResourceLoader::didFinishLoading(const NetworkLoadMetrics& networkLoadMetrics)
516 {
517     didFinishLoadingOnePart(networkLoadMetrics);
518
519     // If the load has been cancelled by a delegate in response to didFinishLoad(), do not release
520     // the resources a second time, they have been released by cancel.
521     if (wasCancelled())
522         return;
523     releaseResources();
524 }
525
526 void ResourceLoader::didFinishLoadingOnePart(const NetworkLoadMetrics& networkLoadMetrics)
527 {
528     // If load has been cancelled after finishing (which could happen with a
529     // JavaScript that changes the window location), do nothing.
530     if (wasCancelled())
531         return;
532     ASSERT(!m_reachedTerminalState);
533
534     if (m_notifiedLoadComplete)
535         return;
536     m_notifiedLoadComplete = true;
537     if (m_options.sendLoadCallbacks == SendCallbacks)
538         frameLoader()->notifier().didFinishLoad(this, networkLoadMetrics);
539 }
540
541 void ResourceLoader::didFail(const ResourceError& error)
542 {
543     if (wasCancelled())
544         return;
545     ASSERT(!m_reachedTerminalState);
546
547     // Protect this in this delegate method since the additional processing can do
548     // anything including possibly derefing this; one example of this is Radar 3266216.
549     Ref<ResourceLoader> protectedThis(*this);
550
551     cleanupForError(error);
552     releaseResources();
553 }
554
555 void ResourceLoader::cleanupForError(const ResourceError& error)
556 {
557     if (FormData* data = m_request.httpBody())
558         data->removeGeneratedFilesIfNeeded();
559
560     if (m_notifiedLoadComplete)
561         return;
562     m_notifiedLoadComplete = true;
563     if (m_options.sendLoadCallbacks == SendCallbacks && m_identifier)
564         frameLoader()->notifier().didFailToLoad(this, error);
565 }
566
567 void ResourceLoader::cancel()
568 {
569     cancel(ResourceError());
570 }
571
572 void ResourceLoader::cancel(const ResourceError& error)
573 {
574     // If the load has already completed - succeeded, failed, or previously cancelled - do nothing.
575     if (m_reachedTerminalState)
576         return;
577        
578     ResourceError nonNullError = error.isNull() ? cancelledError() : error;
579     
580     // willCancel() and didFailToLoad() both call out to clients that might do 
581     // something causing the last reference to this object to go away.
582     Ref<ResourceLoader> protectedThis(*this);
583     
584     // If we re-enter cancel() from inside willCancel(), we want to pick up from where we left 
585     // off without re-running willCancel()
586     if (m_cancellationStatus == NotCancelled) {
587         m_cancellationStatus = CalledWillCancel;
588         
589         willCancel(nonNullError);
590     }
591
592     // If we re-enter cancel() from inside didFailToLoad(), we want to pick up from where we 
593     // left off without redoing any of this work.
594     if (m_cancellationStatus == CalledWillCancel) {
595         m_cancellationStatus = Cancelled;
596
597         if (m_handle)
598             m_handle->clearAuthentication();
599
600         m_documentLoader->cancelPendingSubstituteLoad(this);
601         if (m_handle) {
602             m_handle->cancel();
603             m_handle = nullptr;
604         }
605         cleanupForError(nonNullError);
606     }
607
608     // If cancel() completed from within the call to willCancel() or didFailToLoad(),
609     // we don't want to redo didCancel() or releasesResources().
610     if (m_reachedTerminalState)
611         return;
612
613     didCancel(nonNullError);
614
615     if (m_cancellationStatus == FinishedCancel)
616         return;
617     m_cancellationStatus = FinishedCancel;
618
619     releaseResources();
620 }
621
622 ResourceError ResourceLoader::cancelledError()
623 {
624     return frameLoader()->cancelledError(m_request);
625 }
626
627 ResourceError ResourceLoader::blockedError()
628 {
629     return frameLoader()->client().blockedError(m_request);
630 }
631
632 ResourceError ResourceLoader::blockedByContentBlockerError()
633 {
634     return frameLoader()->client().blockedByContentBlockerError(m_request);
635 }
636
637 ResourceError ResourceLoader::cannotShowURLError()
638 {
639     return frameLoader()->client().cannotShowURLError(m_request);
640 }
641
642 void ResourceLoader::willSendRequestAsync(ResourceHandle* handle, ResourceRequest&& request, ResourceResponse&& redirectResponse, CompletionHandler<void(ResourceRequest&&)>&& completionHandler)
643 {
644     RefPtr<ResourceHandle> protectedHandle(handle);
645     if (documentLoader()->applicationCacheHost().maybeLoadFallbackForRedirect(this, request, redirectResponse)) {
646         completionHandler(WTFMove(request));
647         return;
648     }
649     willSendRequestInternal(request, redirectResponse);
650     completionHandler(WTFMove(request));
651 }
652
653 void ResourceLoader::didSendData(ResourceHandle*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
654 {
655     didSendData(bytesSent, totalBytesToBeSent);
656 }
657
658 void ResourceLoader::didReceiveResponseAsync(ResourceHandle* handle, ResourceResponse&& response)
659 {
660     if (documentLoader()->applicationCacheHost().maybeLoadFallbackForResponse(this, response)) {
661         handle->continueDidReceiveResponse();
662         return;
663     }
664     didReceiveResponse(response);
665     handle->continueDidReceiveResponse();
666 }
667
668 void ResourceLoader::didReceiveData(ResourceHandle*, const char* data, unsigned length, int encodedDataLength)
669 {
670     didReceiveData(data, length, encodedDataLength, DataPayloadBytes);
671 }
672
673 void ResourceLoader::didReceiveBuffer(ResourceHandle*, Ref<SharedBuffer>&& buffer, int encodedDataLength)
674 {
675     didReceiveBuffer(WTFMove(buffer), encodedDataLength, DataPayloadBytes);
676 }
677
678 void ResourceLoader::didFinishLoading(ResourceHandle*)
679 {
680     NetworkLoadMetrics emptyMetrics;
681     didFinishLoading(emptyMetrics);
682 }
683
684 void ResourceLoader::didFail(ResourceHandle*, const ResourceError& error)
685 {
686     if (documentLoader()->applicationCacheHost().maybeLoadFallbackForError(this, error))
687         return;
688     didFail(error);
689 }
690
691 void ResourceLoader::wasBlocked(ResourceHandle*)
692 {
693     didFail(blockedError());
694 }
695
696 void ResourceLoader::cannotShowURL(ResourceHandle*)
697 {
698     didFail(cannotShowURLError());
699 }
700
701 bool ResourceLoader::shouldUseCredentialStorage()
702 {
703     if (m_options.storedCredentialsPolicy == StoredCredentialsPolicy::DoNotUse)
704         return false;
705
706     Ref<ResourceLoader> protectedThis(*this);
707     return frameLoader()->client().shouldUseCredentialStorage(documentLoader(), identifier());
708 }
709
710 bool ResourceLoader::isAllowedToAskUserForCredentials() const
711 {
712     if (!m_canAskClientForCredentials)
713         return false;
714     return m_options.credentials == FetchOptions::Credentials::Include || (m_options.credentials == FetchOptions::Credentials::SameOrigin && m_frame->document()->securityOrigin().canRequest(originalRequest().url()));
715 }
716
717 void ResourceLoader::didReceiveAuthenticationChallenge(const AuthenticationChallenge& challenge)
718 {
719     ASSERT(m_handle->hasAuthenticationChallenge());
720
721     // Protect this in this delegate method since the additional processing can do
722     // anything including possibly derefing this; one example of this is Radar 3266216.
723     Ref<ResourceLoader> protectedThis(*this);
724
725     if (m_options.storedCredentialsPolicy == StoredCredentialsPolicy::Use) {
726         if (isAllowedToAskUserForCredentials()) {
727             frameLoader()->notifier().didReceiveAuthenticationChallenge(this, challenge);
728             return;
729         }
730     }
731     challenge.authenticationClient()->receivedRequestToContinueWithoutCredential(challenge);
732     ASSERT(!m_handle || !m_handle->hasAuthenticationChallenge());
733 }
734
735 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
736 void ResourceLoader::canAuthenticateAgainstProtectionSpaceAsync(ResourceHandle* handle, const ProtectionSpace& protectionSpace)
737 {
738     handle->continueCanAuthenticateAgainstProtectionSpace(canAuthenticateAgainstProtectionSpace(protectionSpace));
739 }
740
741 bool ResourceLoader::canAuthenticateAgainstProtectionSpace(const ProtectionSpace& protectionSpace)
742 {
743     Ref<ResourceLoader> protectedThis(*this);
744     return frameLoader()->client().canAuthenticateAgainstProtectionSpace(documentLoader(), identifier(), protectionSpace);
745 }
746
747 #endif
748     
749 #if PLATFORM(IOS)
750
751 RetainPtr<CFDictionaryRef> ResourceLoader::connectionProperties(ResourceHandle*)
752 {
753     return frameLoader()->connectionProperties(this);
754 }
755
756 #endif
757
758 void ResourceLoader::receivedCancellation(const AuthenticationChallenge&)
759 {
760     cancel();
761 }
762
763 #if PLATFORM(COCOA) && !USE(CFURLCONNECTION)
764
765 void ResourceLoader::schedule(SchedulePair& pair)
766 {
767     if (m_handle)
768         m_handle->schedule(pair);
769 }
770
771 void ResourceLoader::unschedule(SchedulePair& pair)
772 {
773     if (m_handle)
774         m_handle->unschedule(pair);
775 }
776
777 #endif
778
779 #if USE(QUICK_LOOK)
780 bool ResourceLoader::isQuickLookResource() const
781 {
782     return !!m_previewLoader;
783 }
784 #endif
785
786 bool ResourceLoader::isAlwaysOnLoggingAllowed() const
787 {
788     return frameLoader() && frameLoader()->isAlwaysOnLoggingAllowed();
789 }
790
791 void ResourceLoader::didRetrieveDerivedDataFromCache(const String&, SharedBuffer&)
792 {
793 }
794
795 }