1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
|
/*
* Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
* Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "MainResourceLoader.h"
#include "ApplicationCacheHost.h"
#include "BackForwardController.h"
#include "Console.h"
#include "DOMWindow.h"
#include "Document.h"
#include "DocumentLoadTiming.h"
#include "DocumentLoader.h"
#include "FormState.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameLoaderClient.h"
#include "HTMLFormElement.h"
#include "HistoryItem.h"
#include "InspectorInstrumentation.h"
#include "Page.h"
#include "ResourceError.h"
#include "ResourceHandle.h"
#include "ResourceLoadScheduler.h"
#include "SchemeRegistry.h"
#include "SecurityOrigin.h"
#include "Settings.h"
#include <wtf/CurrentTime.h>
#if PLATFORM(QT)
#include "PluginDatabase.h"
#endif
#if PLATFORM(MAC) && !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
#include "WebCoreSystemInterface.h"
#endif
// FIXME: More that is in common with SubresourceLoader should move up into ResourceLoader.
namespace WebCore {
static bool shouldLoadAsEmptyDocument(const KURL& url)
{
return url.isEmpty() || SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(url.protocol());
}
MainResourceLoader::MainResourceLoader(Frame* frame)
: ResourceLoader(frame, ResourceLoaderOptions(SendCallbacks, SniffContent, BufferData, AllowStoredCredentials, AskClientForCrossOriginCredentials, SkipSecurityCheck))
, m_dataLoadTimer(this, &MainResourceLoader::handleSubstituteDataLoadNow)
, m_loadingMultipartContent(false)
, m_waitingForContentPolicy(false)
, m_timeOfLastDataReceived(0.0)
#if PLATFORM(MAC) && !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
, m_filter(0)
#endif
{
}
MainResourceLoader::~MainResourceLoader()
{
#if PLATFORM(MAC) && !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
ASSERT(!m_filter);
#endif
}
PassRefPtr<MainResourceLoader> MainResourceLoader::create(Frame* frame)
{
return adoptRef(new MainResourceLoader(frame));
}
void MainResourceLoader::receivedError(const ResourceError& error)
{
// Calling receivedMainResourceError will likely result in the last reference to this object to go away.
RefPtr<MainResourceLoader> protect(this);
RefPtr<Frame> protectFrame(m_frame);
// It is important that we call DocumentLoader::mainReceivedError before calling
// ResourceLoadNotifier::didFailToLoad because mainReceivedError clears out the relevant
// document loaders. Also, mainReceivedError ends up calling a FrameLoadDelegate method
// and didFailToLoad calls a ResourceLoadDelegate method and they need to be in the correct order.
documentLoader()->mainReceivedError(error);
if (!cancelled()) {
ASSERT(!reachedTerminalState());
frameLoader()->notifier()->didFailToLoad(this, error);
releaseResources();
}
ASSERT(reachedTerminalState());
}
void MainResourceLoader::willCancel(const ResourceError&)
{
m_dataLoadTimer.stop();
if (m_waitingForContentPolicy) {
frameLoader()->policyChecker()->cancelCheck();
ASSERT(m_waitingForContentPolicy);
m_waitingForContentPolicy = false;
deref(); // balances ref in didReceiveResponse
}
}
void MainResourceLoader::didCancel(const ResourceError& error)
{
// We should notify the frame loader after fully canceling the load, because it can do complicated work
// like calling DOMWindow::print(), during which a half-canceled load could try to finish.
documentLoader()->mainReceivedError(error);
#if PLATFORM(MAC) && !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
if (m_filter) {
wkFilterRelease(m_filter);
m_filter = 0;
}
#endif
}
ResourceError MainResourceLoader::interruptedForPolicyChangeError() const
{
return frameLoader()->client()->interruptedForPolicyChangeError(request());
}
void MainResourceLoader::stopLoadingForPolicyChange()
{
ResourceError error = interruptedForPolicyChangeError();
error.setIsCancellation(true);
cancel(error);
}
void MainResourceLoader::callContinueAfterNavigationPolicy(void* argument, const ResourceRequest& request, PassRefPtr<FormState>, bool shouldContinue)
{
static_cast<MainResourceLoader*>(argument)->continueAfterNavigationPolicy(request, shouldContinue);
}
void MainResourceLoader::continueAfterNavigationPolicy(const ResourceRequest& request, bool shouldContinue)
{
if (!shouldContinue)
stopLoadingForPolicyChange();
else if (m_substituteData.isValid()) {
// A redirect resulted in loading substitute data.
ASSERT(documentLoader()->timing()->redirectCount());
handle()->cancel();
handleSubstituteDataLoadSoon(request);
}
deref(); // balances ref in willSendRequest
}
bool MainResourceLoader::isPostOrRedirectAfterPost(const ResourceRequest& newRequest, const ResourceResponse& redirectResponse)
{
if (newRequest.httpMethod() == "POST")
return true;
int status = redirectResponse.httpStatusCode();
if (((status >= 301 && status <= 303) || status == 307)
&& frameLoader()->initialRequest().httpMethod() == "POST")
return true;
return false;
}
void MainResourceLoader::addData(const char* data, int length, bool allAtOnce)
{
ResourceLoader::addData(data, length, allAtOnce);
documentLoader()->receivedData(data, length);
}
void MainResourceLoader::willSendRequest(ResourceRequest& newRequest, const ResourceResponse& redirectResponse)
{
// Note that there are no asserts here as there are for the other callbacks. This is due to the
// fact that this "callback" is sent when starting every load, and the state of callback
// deferrals plays less of a part in this function in preventing the bad behavior deferring
// callbacks is meant to prevent.
ASSERT(!newRequest.isNull());
// The additional processing can do anything including possibly removing the last
// reference to this object; one example of this is 3266216.
RefPtr<MainResourceLoader> protect(this);
ASSERT(documentLoader()->timing()->fetchStart());
if (!redirectResponse.isNull()) {
// If the redirecting url is not allowed to display content from the target origin,
// then block the redirect.
RefPtr<SecurityOrigin> redirectingOrigin = SecurityOrigin::create(redirectResponse.url());
if (!redirectingOrigin->canDisplay(newRequest.url())) {
FrameLoader::reportLocalLoadFailed(m_frame.get(), newRequest.url().string());
cancel();
return;
}
documentLoader()->timing()->addRedirect(redirectResponse.url(), newRequest.url());
}
// Update cookie policy base URL as URL changes, except for subframes, which use the
// URL of the main frame which doesn't change when we redirect.
if (frameLoader()->isLoadingMainFrame())
newRequest.setFirstPartyForCookies(newRequest.url());
// If we're fielding a redirect in response to a POST, force a load from origin, since
// this is a common site technique to return to a page viewing some data that the POST
// just modified.
// Also, POST requests always load from origin, but this does not affect subresources.
if (newRequest.cachePolicy() == UseProtocolCachePolicy && isPostOrRedirectAfterPost(newRequest, redirectResponse))
newRequest.setCachePolicy(ReloadIgnoringCacheData);
Frame* top = m_frame->tree()->top();
if (top != m_frame) {
if (!frameLoader()->checkIfDisplayInsecureContent(top->document()->securityOrigin(), newRequest.url())) {
cancel();
return;
}
}
ResourceLoader::willSendRequest(newRequest, redirectResponse);
// Don't set this on the first request. It is set when the main load was started.
m_documentLoader->setRequest(newRequest);
if (!redirectResponse.isNull()) {
// We checked application cache for initial URL, now we need to check it for redirected one.
ASSERT(!m_substituteData.isValid());
documentLoader()->applicationCacheHost()->maybeLoadMainResourceForRedirect(newRequest, m_substituteData);
}
// FIXME: Ideally we'd stop the I/O until we hear back from the navigation policy delegate
// listener. But there's no way to do that in practice. So instead we cancel later if the
// listener tells us to. In practice that means the navigation policy needs to be decided
// synchronously for these redirect cases.
if (!redirectResponse.isNull()) {
ref(); // balanced by deref in continueAfterNavigationPolicy
frameLoader()->policyChecker()->checkNavigationPolicy(newRequest, callContinueAfterNavigationPolicy, this);
}
}
void MainResourceLoader::continueAfterContentPolicy(PolicyAction contentPolicy, const ResourceResponse& r)
{
KURL url = request().url();
const String& mimeType = r.mimeType();
switch (contentPolicy) {
case PolicyUse: {
// Prevent remote web archives from loading because they can claim to be from any domain and thus avoid cross-domain security checks (4120255).
bool isRemoteWebArchive = (equalIgnoringCase("application/x-webarchive", mimeType)
#if PLATFORM(GTK)
|| equalIgnoringCase("message/rfc822", mimeType)
#endif
|| equalIgnoringCase("multipart/related", mimeType))
&& !m_substituteData.isValid() && !SchemeRegistry::shouldTreatURLSchemeAsLocal(url.protocol());
if (!frameLoader()->client()->canShowMIMEType(mimeType) || isRemoteWebArchive) {
frameLoader()->policyChecker()->cannotShowMIMEType(r);
// Check reachedTerminalState since the load may have already been canceled inside of _handleUnimplementablePolicyWithErrorCode::.
if (!reachedTerminalState())
stopLoadingForPolicyChange();
return;
}
break;
}
case PolicyDownload: {
// m_handle can be null, e.g. when loading a substitute resource from application cache.
if (!m_handle) {
receivedError(cannotShowURLError());
return;
}
InspectorInstrumentation::continueWithPolicyDownload(m_frame.get(), documentLoader(), identifier(), r);
// When starting the request, we didn't know that it would result in download and not navigation. Now we know that main document URL didn't change.
// Download may use this knowledge for purposes unrelated to cookies, notably for setting file quarantine data.
ResourceRequest request = this->request();
frameLoader()->setOriginalURLForDownloadRequest(request);
frameLoader()->client()->download(m_handle.get(), request, r);
// It might have gone missing
if (frameLoader())
receivedError(interruptedForPolicyChangeError());
return;
}
case PolicyIgnore:
InspectorInstrumentation::continueWithPolicyIgnore(m_frame.get(), documentLoader(), identifier(), r);
stopLoadingForPolicyChange();
return;
default:
ASSERT_NOT_REACHED();
}
RefPtr<MainResourceLoader> protect(this);
if (r.isHTTP()) {
int status = r.httpStatusCode();
if (status < 200 || status >= 300) {
bool hostedByObject = frameLoader()->isHostedByObjectElement();
frameLoader()->handleFallbackContent();
// object elements are no longer rendered after we fallback, so don't
// keep trying to process data from their load
if (hostedByObject)
cancel();
}
}
// we may have cancelled this load as part of switching to fallback content
if (!reachedTerminalState())
ResourceLoader::didReceiveResponse(r);
if (frameLoader() && !frameLoader()->activeDocumentLoader()->isStopping()) {
if (m_substituteData.isValid()) {
if (m_substituteData.content()->size())
didReceiveData(m_substituteData.content()->data(), m_substituteData.content()->size(), m_substituteData.content()->size(), true);
if (frameLoader() && !frameLoader()->activeDocumentLoader()->isStopping())
didFinishLoading(0);
} else if (shouldLoadAsEmptyDocument(url) || frameLoader()->client()->representationExistsForURLScheme(url.protocol()))
didFinishLoading(0);
}
}
void MainResourceLoader::callContinueAfterContentPolicy(void* argument, PolicyAction policy)
{
static_cast<MainResourceLoader*>(argument)->continueAfterContentPolicy(policy);
}
void MainResourceLoader::continueAfterContentPolicy(PolicyAction policy)
{
ASSERT(m_waitingForContentPolicy);
m_waitingForContentPolicy = false;
if (frameLoader() && !frameLoader()->activeDocumentLoader()->isStopping())
continueAfterContentPolicy(policy, m_response);
deref(); // balances ref in didReceiveResponse
}
void MainResourceLoader::didReceiveResponse(const ResourceResponse& r)
{
if (documentLoader()->applicationCacheHost()->maybeLoadFallbackForMainResponse(request(), r))
return;
HTTPHeaderMap::const_iterator it = r.httpHeaderFields().find(AtomicString("x-frame-options"));
if (it != r.httpHeaderFields().end()) {
String content = it->second;
if (m_frame->loader()->shouldInterruptLoadForXFrameOptions(content, r.url())) {
InspectorInstrumentation::continueAfterXFrameOptionsDenied(m_frame.get(), documentLoader(), identifier(), r);
DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to display document because display forbidden by X-Frame-Options.\n"));
m_frame->domWindow()->console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, consoleMessage);
cancel();
return;
}
}
// There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
// See <rdar://problem/6304600> for more details.
#if !USE(CF)
ASSERT(shouldLoadAsEmptyDocument(r.url()) || !defersLoading());
#endif
if (m_loadingMultipartContent) {
frameLoader()->activeDocumentLoader()->setupForReplaceByMIMEType(r.mimeType());
clearResourceData();
}
if (r.isMultipart())
m_loadingMultipartContent = true;
// The additional processing can do anything including possibly removing the last
// reference to this object; one example of this is 3266216.
RefPtr<MainResourceLoader> protect(this);
m_documentLoader->setResponse(r);
m_response = r;
ASSERT(!m_waitingForContentPolicy);
m_waitingForContentPolicy = true;
ref(); // balanced by deref in continueAfterContentPolicy and didCancel
ASSERT(frameLoader()->activeDocumentLoader());
// Always show content with valid substitute data.
if (frameLoader()->activeDocumentLoader()->substituteData().isValid()) {
callContinueAfterContentPolicy(this, PolicyUse);
return;
}
#if ENABLE(FTPDIR)
// Respect the hidden FTP Directory Listing pref so it can be tested even if the policy delegate might otherwise disallow it
Settings* settings = m_frame->settings();
if (settings && settings->forceFTPDirectoryListings() && m_response.mimeType() == "application/x-ftp-directory") {
callContinueAfterContentPolicy(this, PolicyUse);
return;
}
#endif
#if PLATFORM(MAC) && !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
if (r.url().protocolIs("https") && wkFilterIsManagedSession())
m_filter = wkFilterCreateInstance(r.nsURLResponse());
#endif
frameLoader()->policyChecker()->checkContentPolicy(m_response, callContinueAfterContentPolicy, this);
}
void MainResourceLoader::didReceiveData(const char* data, int length, long long encodedDataLength, bool allAtOnce)
{
ASSERT(data);
ASSERT(length != 0);
ASSERT(!m_response.isNull());
#if USE(CFNETWORK) || PLATFORM(MAC)
// Workaround for <rdar://problem/6060782>
if (m_response.isNull()) {
m_response = ResourceResponse(KURL(), "text/html", 0, String(), String());
if (DocumentLoader* documentLoader = frameLoader()->activeDocumentLoader())
documentLoader->setResponse(m_response);
}
#endif
// There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
// See <rdar://problem/6304600> for more details.
#if !USE(CF)
ASSERT(!defersLoading());
#endif
#if PLATFORM(MAC) && !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
if (m_filter) {
ASSERT(!wkFilterWasBlocked(m_filter));
const char* blockedData = wkFilterAddData(m_filter, data, &length);
// If we don't have blockedData, that means we're still accumulating data
if (!blockedData) {
// Transition to committed state.
ResourceLoader::didReceiveData("", 0, 0, false);
return;
}
data = blockedData;
encodedDataLength = -1;
}
#endif
documentLoader()->applicationCacheHost()->mainResourceDataReceived(data, length, encodedDataLength, allAtOnce);
// The additional processing can do anything including possibly removing the last
// reference to this object; one example of this is 3266216.
RefPtr<MainResourceLoader> protect(this);
m_timeOfLastDataReceived = monotonicallyIncreasingTime();
ResourceLoader::didReceiveData(data, length, encodedDataLength, allAtOnce);
#if PLATFORM(MAC) && !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
if (WebFilterEvaluator *filter = m_filter) {
// If we got here, it means we know if we were blocked or not. If we were blocked, we're
// done loading the page altogether. Either way, we don't need the filter anymore.
// Remove this->m_filter early so didFinishLoading doesn't see it.
m_filter = 0;
if (wkFilterWasBlocked(filter))
cancel();
wkFilterRelease(filter);
}
#endif
}
void MainResourceLoader::didFinishLoading(double finishTime)
{
// There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
// See <rdar://problem/6304600> for more details.
#if !USE(CF)
ASSERT(shouldLoadAsEmptyDocument(frameLoader()->activeDocumentLoader()->url()) || !defersLoading() || InspectorInstrumentation::isDebuggerPaused(m_frame.get()));
#endif
// The additional processing can do anything including possibly removing the last
// reference to this object.
RefPtr<MainResourceLoader> protect(this);
RefPtr<DocumentLoader> dl = documentLoader();
#if PLATFORM(MAC) && !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
if (m_filter) {
int length;
const char* data = wkFilterDataComplete(m_filter, &length);
WebFilterEvaluator *filter = m_filter;
// Remove this->m_filter early so didReceiveData doesn't see it.
m_filter = 0;
if (data)
didReceiveData(data, length, -1, false);
wkFilterRelease(filter);
}
#endif
if (m_loadingMultipartContent)
dl->maybeFinishLoadingMultipartContent();
documentLoader()->timing()->setResponseEnd(finishTime ? finishTime : (m_timeOfLastDataReceived ? m_timeOfLastDataReceived : monotonicallyIncreasingTime()));
documentLoader()->finishedLoading();
ResourceLoader::didFinishLoading(finishTime);
dl->applicationCacheHost()->finishedLoadingMainResource();
}
void MainResourceLoader::didFail(const ResourceError& error)
{
#if PLATFORM(MAC) && !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
if (m_filter) {
wkFilterRelease(m_filter);
m_filter = 0;
}
#endif
if (documentLoader()->applicationCacheHost()->maybeLoadFallbackForMainError(request(), error))
return;
// There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
// See <rdar://problem/6304600> for more details.
#if !USE(CF)
ASSERT(!defersLoading());
#endif
receivedError(error);
}
void MainResourceLoader::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
{
MemoryClassInfo info(memoryObjectInfo, this, MemoryInstrumentation::Loader);
ResourceLoader::reportMemoryUsage(memoryObjectInfo);
info.addMember(m_initialRequest);
info.addInstrumentedMember(m_substituteData);
info.addMember(m_dataLoadTimer);
}
void MainResourceLoader::handleEmptyLoad(const KURL& url, bool forURLScheme)
{
String mimeType;
if (forURLScheme)
mimeType = frameLoader()->client()->generatedMIMETypeForURLScheme(url.protocol());
else
mimeType = "text/html";
ResourceResponse response(url, mimeType, 0, String(), String());
didReceiveResponse(response);
}
void MainResourceLoader::handleSubstituteDataLoadNow(MainResourceLoaderTimer*)
{
RefPtr<MainResourceLoader> protect(this);
KURL url = m_substituteData.responseURL();
if (url.isEmpty())
url = m_initialRequest.url();
// Clear the initial request here so that subsequent entries into the
// loader will not think there's still a deferred load left to do.
m_initialRequest = ResourceRequest();
ResourceResponse response(url, m_substituteData.mimeType(), m_substituteData.content()->size(), m_substituteData.textEncoding(), "");
didReceiveResponse(response);
}
void MainResourceLoader::startDataLoadTimer()
{
m_dataLoadTimer.startOneShot(0);
#if HAVE(RUNLOOP_TIMER)
if (SchedulePairHashSet* scheduledPairs = m_frame->page()->scheduledRunLoopPairs())
m_dataLoadTimer.schedule(*scheduledPairs);
#endif
}
void MainResourceLoader::handleSubstituteDataLoadSoon(const ResourceRequest& r)
{
m_initialRequest = r;
if (m_documentLoader->deferMainResourceDataLoad())
startDataLoadTimer();
else
handleSubstituteDataLoadNow(0);
}
bool MainResourceLoader::loadNow(ResourceRequest& r)
{
bool shouldLoadEmptyBeforeRedirect = shouldLoadAsEmptyDocument(r.url());
ASSERT(!m_handle);
ASSERT(shouldLoadEmptyBeforeRedirect || !defersLoading());
// Send this synthetic delegate callback since clients expect it, and
// we no longer send the callback from within NSURLConnection for
// initial requests.
willSendRequest(r, ResourceResponse());
ASSERT(!deletionHasBegun());
// <rdar://problem/4801066>
// willSendRequest() is liable to make the call to frameLoader() return NULL, so we need to check that here
if (!frameLoader())
return false;
const KURL& url = r.url();
bool shouldLoadEmpty = shouldLoadAsEmptyDocument(url) && !m_substituteData.isValid();
if (shouldLoadEmptyBeforeRedirect && !shouldLoadEmpty && defersLoading())
return true;
resourceLoadScheduler()->addMainResourceLoad(this);
if (m_substituteData.isValid())
handleSubstituteDataLoadSoon(r);
else if (shouldLoadEmpty || frameLoader()->client()->representationExistsForURLScheme(url.protocol()))
handleEmptyLoad(url, !shouldLoadEmpty);
else
m_handle = ResourceHandle::create(m_frame->loader()->networkingContext(), r, this, false, true);
return false;
}
void MainResourceLoader::load(const ResourceRequest& r, const SubstituteData& substituteData)
{
ASSERT(!m_handle);
// It appears that it is possible for this load to be cancelled and derefenced by the DocumentLoader
// in willSendRequest() if loadNow() is called.
RefPtr<MainResourceLoader> protect(this);
m_substituteData = substituteData;
ASSERT(documentLoader()->timing()->navigationStart());
ASSERT(!documentLoader()->timing()->fetchStart());
documentLoader()->timing()->markFetchStart();
ResourceRequest request(r);
documentLoader()->applicationCacheHost()->maybeLoadMainResource(request, m_substituteData);
bool defer = defersLoading();
if (defer) {
bool shouldLoadEmpty = shouldLoadAsEmptyDocument(request.url());
if (shouldLoadEmpty)
defer = false;
}
if (!defer) {
if (loadNow(request)) {
// Started as an empty document, but was redirected to something non-empty.
ASSERT(defersLoading());
defer = true;
}
}
if (defer)
m_initialRequest = request;
}
void MainResourceLoader::setDefersLoading(bool defers)
{
ResourceLoader::setDefersLoading(defers);
if (defers) {
if (m_dataLoadTimer.isActive())
m_dataLoadTimer.stop();
} else {
if (m_initialRequest.isNull())
return;
ResourceRequest initialRequest(m_initialRequest);
m_initialRequest = ResourceRequest();
loadNow(initialRequest);
}
}
}
|