initial import
[vuplus_webkit] / Source / WebCore / loader / MainResourceLoader.cpp
1 /*
2  * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.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 Computer, 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 "MainResourceLoader.h"
32
33 #include "ApplicationCacheHost.h"
34 #include "Console.h"
35 #include "DOMWindow.h"
36 #include "Document.h"
37 #include "DocumentLoadTiming.h"
38 #include "DocumentLoader.h"
39 #include "FormState.h"
40 #include "Frame.h"
41 #include "FrameLoader.h"
42 #include "FrameLoaderClient.h"
43 #include "HTMLFormElement.h"
44 #include "InspectorInstrumentation.h"
45 #include "Page.h"
46 #include "ResourceError.h"
47 #include "ResourceHandle.h"
48 #include "ResourceLoadScheduler.h"
49 #include "SchemeRegistry.h"
50 #include "SecurityOrigin.h"
51 #include "Settings.h"
52 #include <wtf/CurrentTime.h>
53
54 #if PLATFORM(QT)
55 #include "PluginDatabase.h"
56 #endif
57
58 // FIXME: More that is in common with SubresourceLoader should move up into ResourceLoader.
59
60 namespace WebCore {
61
62 MainResourceLoader::MainResourceLoader(Frame* frame)
63     : ResourceLoader(frame, ResourceLoaderOptions(SendCallbacks, SniffContent, BufferData, AllowStoredCredentials))
64     , m_dataLoadTimer(this, &MainResourceLoader::handleDataLoadNow)
65     , m_loadingMultipartContent(false)
66     , m_waitingForContentPolicy(false)
67     , m_timeOfLastDataReceived(0.0)
68 {
69 }
70
71 MainResourceLoader::~MainResourceLoader()
72 {
73 }
74
75 PassRefPtr<MainResourceLoader> MainResourceLoader::create(Frame* frame)
76 {
77     return adoptRef(new MainResourceLoader(frame));
78 }
79
80 void MainResourceLoader::receivedError(const ResourceError& error)
81 {
82     // Calling receivedMainResourceError will likely result in the last reference to this object to go away.
83     RefPtr<MainResourceLoader> protect(this);
84     RefPtr<Frame> protectFrame(m_frame);
85
86     // It is important that we call FrameLoader::receivedMainResourceError before calling 
87     // FrameLoader::didFailToLoad because receivedMainResourceError clears out the relevant
88     // document loaders. Also, receivedMainResourceError ends up calling a FrameLoadDelegate method
89     // and didFailToLoad calls a ResourceLoadDelegate method and they need to be in the correct order.
90     frameLoader()->receivedMainResourceError(error, true);
91
92     if (!cancelled()) {
93         ASSERT(!reachedTerminalState());
94         frameLoader()->notifier()->didFailToLoad(this, error);
95         
96         releaseResources();
97     }
98
99     ASSERT(reachedTerminalState());
100 }
101
102 void MainResourceLoader::willCancel(const ResourceError&)
103 {
104     m_dataLoadTimer.stop();
105
106     if (m_waitingForContentPolicy) {
107         frameLoader()->policyChecker()->cancelCheck();
108         ASSERT(m_waitingForContentPolicy);
109         m_waitingForContentPolicy = false;
110         deref(); // balances ref in didReceiveResponse
111     }
112 }
113
114 void MainResourceLoader::didCancel(const ResourceError& error)
115 {
116     // We should notify the frame loader after fully canceling the load, because it can do complicated work
117     // like calling DOMWindow::print(), during which a half-canceled load could try to finish.
118     frameLoader()->receivedMainResourceError(error, true);
119 }
120
121 ResourceError MainResourceLoader::interruptedForPolicyChangeError() const
122 {
123     return frameLoader()->client()->interruptedForPolicyChangeError(request());
124 }
125
126 void MainResourceLoader::stopLoadingForPolicyChange()
127 {
128     ResourceError error = interruptedForPolicyChangeError();
129     error.setIsCancellation(true);
130     cancel(error);
131 }
132
133 void MainResourceLoader::callContinueAfterNavigationPolicy(void* argument, const ResourceRequest& request, PassRefPtr<FormState>, bool shouldContinue)
134 {
135     static_cast<MainResourceLoader*>(argument)->continueAfterNavigationPolicy(request, shouldContinue);
136 }
137
138 void MainResourceLoader::continueAfterNavigationPolicy(const ResourceRequest& request, bool shouldContinue)
139 {
140     if (!shouldContinue)
141         stopLoadingForPolicyChange();
142     else if (m_substituteData.isValid()) {
143         // A redirect resulted in loading substitute data.
144         ASSERT(documentLoader()->timing()->redirectCount);
145         handle()->cancel();
146         handleDataLoadSoon(request);
147     }
148
149     deref(); // balances ref in willSendRequest
150 }
151
152 bool MainResourceLoader::isPostOrRedirectAfterPost(const ResourceRequest& newRequest, const ResourceResponse& redirectResponse)
153 {
154     if (newRequest.httpMethod() == "POST")
155         return true;
156
157     int status = redirectResponse.httpStatusCode();
158     if (((status >= 301 && status <= 303) || status == 307)
159         && frameLoader()->initialRequest().httpMethod() == "POST")
160         return true;
161     
162     return false;
163 }
164
165 void MainResourceLoader::addData(const char* data, int length, bool allAtOnce)
166 {
167     ResourceLoader::addData(data, length, allAtOnce);
168     documentLoader()->receivedData(data, length);
169 }
170
171 void MainResourceLoader::willSendRequest(ResourceRequest& newRequest, const ResourceResponse& redirectResponse)
172 {
173     // Note that there are no asserts here as there are for the other callbacks. This is due to the
174     // fact that this "callback" is sent when starting every load, and the state of callback
175     // deferrals plays less of a part in this function in preventing the bad behavior deferring 
176     // callbacks is meant to prevent.
177     ASSERT(!newRequest.isNull());
178
179     // The additional processing can do anything including possibly removing the last
180     // reference to this object; one example of this is 3266216.
181     RefPtr<MainResourceLoader> protect(this);
182
183     ASSERT(documentLoader()->timing()->fetchStart);
184     if (!redirectResponse.isNull()) {
185         DocumentLoadTiming* documentLoadTiming = documentLoader()->timing();
186
187         // Check if the redirected url is allowed to access the redirecting url's timing information.
188         RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::create(newRequest.url());
189         if (!securityOrigin->canRequest(redirectResponse.url()))
190             documentLoadTiming->hasCrossOriginRedirect = true;
191
192         documentLoadTiming->redirectCount++;
193         if (!documentLoadTiming->redirectStart)
194             documentLoadTiming->redirectStart = documentLoadTiming->fetchStart;
195         documentLoadTiming->redirectEnd = currentTime();
196         documentLoadTiming->fetchStart = documentLoadTiming->redirectEnd;
197     }
198
199     // Update cookie policy base URL as URL changes, except for subframes, which use the
200     // URL of the main frame which doesn't change when we redirect.
201     if (frameLoader()->isLoadingMainFrame())
202         newRequest.setFirstPartyForCookies(newRequest.url());
203
204     // If we're fielding a redirect in response to a POST, force a load from origin, since
205     // this is a common site technique to return to a page viewing some data that the POST
206     // just modified.
207     // Also, POST requests always load from origin, but this does not affect subresources.
208     if (newRequest.cachePolicy() == UseProtocolCachePolicy && isPostOrRedirectAfterPost(newRequest, redirectResponse))
209         newRequest.setCachePolicy(ReloadIgnoringCacheData);
210
211     Frame* top = m_frame->tree()->top();
212     if (top != m_frame) {
213         if (!frameLoader()->checkIfDisplayInsecureContent(top->document()->securityOrigin(), newRequest.url())) {
214             cancel();
215             return;
216         }
217     }
218
219     ResourceLoader::willSendRequest(newRequest, redirectResponse);
220
221     // Don't set this on the first request. It is set when the main load was started.
222     m_documentLoader->setRequest(newRequest);
223
224 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
225     if (!redirectResponse.isNull()) {
226         // We checked application cache for initial URL, now we need to check it for redirected one.
227         ASSERT(!m_substituteData.isValid());
228         documentLoader()->applicationCacheHost()->maybeLoadMainResourceForRedirect(newRequest, m_substituteData);
229     }
230 #endif
231
232     // FIXME: Ideally we'd stop the I/O until we hear back from the navigation policy delegate
233     // listener. But there's no way to do that in practice. So instead we cancel later if the
234     // listener tells us to. In practice that means the navigation policy needs to be decided
235     // synchronously for these redirect cases.
236     if (!redirectResponse.isNull()) {
237         ref(); // balanced by deref in continueAfterNavigationPolicy
238         frameLoader()->policyChecker()->checkNavigationPolicy(newRequest, callContinueAfterNavigationPolicy, this);
239     }
240 }
241
242 static bool shouldLoadAsEmptyDocument(const KURL& url)
243 {
244 #if PLATFORM(TORCHMOBILE)
245     return url.isEmpty() || (url.protocolIs("about") && equalIgnoringRef(url, blankURL()));
246 #else 
247     return url.isEmpty() || SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(url.protocol());
248 #endif
249 }
250
251 void MainResourceLoader::continueAfterContentPolicy(PolicyAction contentPolicy, const ResourceResponse& r)
252 {
253     KURL url = request().url();
254     const String& mimeType = r.mimeType();
255     
256     switch (contentPolicy) {
257     case PolicyUse: {
258         // Prevent remote web archives from loading because they can claim to be from any domain and thus avoid cross-domain security checks (4120255).
259         bool isRemoteWebArchive = (equalIgnoringCase("application/x-webarchive", mimeType) || equalIgnoringCase("multipart/related", mimeType))
260             && !m_substituteData.isValid() && !url.isLocalFile();
261         if (!frameLoader()->client()->canShowMIMEType(mimeType) || isRemoteWebArchive) {
262             frameLoader()->policyChecker()->cannotShowMIMEType(r);
263             // Check reachedTerminalState since the load may have already been cancelled inside of _handleUnimplementablePolicyWithErrorCode::.
264             if (!reachedTerminalState())
265                 stopLoadingForPolicyChange();
266             return;
267         }
268         break;
269     }
270
271     case PolicyDownload:
272         // m_handle can be null, e.g. when loading a substitute resource from application cache.
273         if (!m_handle) {
274             receivedError(cannotShowURLError());
275             return;
276         }
277         InspectorInstrumentation::continueWithPolicyDownload(m_frame.get(), documentLoader(), identifier(), r);
278         frameLoader()->client()->download(m_handle.get(), request(), m_handle.get()->firstRequest(), r);
279         // It might have gone missing
280         if (frameLoader())
281             receivedError(interruptedForPolicyChangeError());
282         return;
283
284     case PolicyIgnore:
285         InspectorInstrumentation::continueWithPolicyIgnore(m_frame.get(), documentLoader(), identifier(), r);
286         stopLoadingForPolicyChange();
287         return;
288     
289     default:
290         ASSERT_NOT_REACHED();
291     }
292
293     RefPtr<MainResourceLoader> protect(this);
294
295     if (r.isHTTP()) {
296         int status = r.httpStatusCode();
297         if (status < 200 || status >= 300) {
298             bool hostedByObject = frameLoader()->isHostedByObjectElement();
299
300             frameLoader()->handleFallbackContent();
301             // object elements are no longer rendered after we fallback, so don't
302             // keep trying to process data from their load
303
304             if (hostedByObject)
305                 cancel();
306         }
307     }
308
309     // we may have cancelled this load as part of switching to fallback content
310     if (!reachedTerminalState())
311         ResourceLoader::didReceiveResponse(r);
312
313     if (frameLoader() && !frameLoader()->activeDocumentLoader()->isStopping()) {
314         if (m_substituteData.isValid()) {
315             if (m_substituteData.content()->size())
316                 didReceiveData(m_substituteData.content()->data(), m_substituteData.content()->size(), m_substituteData.content()->size(), true);
317             if (frameLoader() && !frameLoader()->activeDocumentLoader()->isStopping()) 
318                 didFinishLoading(0);
319         } else if (shouldLoadAsEmptyDocument(url) || frameLoader()->client()->representationExistsForURLScheme(url.protocol()))
320             didFinishLoading(0);
321     }
322 }
323
324 void MainResourceLoader::callContinueAfterContentPolicy(void* argument, PolicyAction policy)
325 {
326     static_cast<MainResourceLoader*>(argument)->continueAfterContentPolicy(policy);
327 }
328
329 void MainResourceLoader::continueAfterContentPolicy(PolicyAction policy)
330 {
331     ASSERT(m_waitingForContentPolicy);
332     m_waitingForContentPolicy = false;
333     if (frameLoader() && !frameLoader()->activeDocumentLoader()->isStopping())
334         continueAfterContentPolicy(policy, m_response);
335     deref(); // balances ref in didReceiveResponse
336 }
337
338 #if PLATFORM(QT)
339 void MainResourceLoader::substituteMIMETypeFromPluginDatabase(const ResourceResponse& r)
340 {
341     if (!m_frame->loader()->subframeLoader()->allowPlugins(NotAboutToInstantiatePlugin))
342         return;
343
344     String filename = r.url().lastPathComponent();
345     if (filename.endsWith("/"))
346         return;
347
348     size_t extensionPos = filename.reverseFind('.');
349     if (extensionPos == notFound)
350         return;
351
352     String extension = filename.substring(extensionPos + 1);
353     String mimeType = PluginDatabase::installedPlugins()->MIMETypeForExtension(extension);
354     if (!mimeType.isEmpty()) {
355         ResourceResponse* response = const_cast<ResourceResponse*>(&r);
356         response->setMimeType(mimeType);
357     }
358 }
359 #endif
360
361 void MainResourceLoader::didReceiveResponse(const ResourceResponse& r)
362 {
363 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
364     if (documentLoader()->applicationCacheHost()->maybeLoadFallbackForMainResponse(request(), r))
365         return;
366 #endif
367
368     HTTPHeaderMap::const_iterator it = r.httpHeaderFields().find(AtomicString("x-frame-options"));
369     if (it != r.httpHeaderFields().end()) {
370         String content = it->second;
371         if (m_frame->loader()->shouldInterruptLoadForXFrameOptions(content, r.url())) {
372             InspectorInstrumentation::continueAfterXFrameOptionsDenied(m_frame.get(), documentLoader(), identifier(), r);
373             DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to display document because display forbidden by X-Frame-Options.\n"));
374             m_frame->domWindow()->console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, consoleMessage, 1, String());
375
376             cancel();
377             return;
378         }
379     }
380
381     // There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
382     // See <rdar://problem/6304600> for more details.
383 #if !USE(CF)
384     ASSERT(shouldLoadAsEmptyDocument(r.url()) || !defersLoading());
385 #endif
386
387 #if PLATFORM(QT)
388     if (r.mimeType() == "application/octet-stream")
389         substituteMIMETypeFromPluginDatabase(r);
390 #endif
391
392     if (m_loadingMultipartContent) {
393         frameLoader()->activeDocumentLoader()->setupForReplaceByMIMEType(r.mimeType());
394         clearResourceData();
395     }
396     
397     if (r.isMultipart())
398         m_loadingMultipartContent = true;
399         
400     // The additional processing can do anything including possibly removing the last
401     // reference to this object; one example of this is 3266216.
402     RefPtr<MainResourceLoader> protect(this);
403
404     m_documentLoader->setResponse(r);
405
406     m_response = r;
407
408     ASSERT(!m_waitingForContentPolicy);
409     m_waitingForContentPolicy = true;
410     ref(); // balanced by deref in continueAfterContentPolicy and didCancel
411
412     ASSERT(frameLoader()->activeDocumentLoader());
413
414     // Always show content with valid substitute data.
415     if (frameLoader()->activeDocumentLoader()->substituteData().isValid()) {
416         callContinueAfterContentPolicy(this, PolicyUse);
417         return;
418     }
419
420 #if ENABLE(FTPDIR)
421     // Respect the hidden FTP Directory Listing pref so it can be tested even if the policy delegate might otherwise disallow it
422     Settings* settings = m_frame->settings();
423     if (settings && settings->forceFTPDirectoryListings() && m_response.mimeType() == "application/x-ftp-directory") {
424         callContinueAfterContentPolicy(this, PolicyUse);
425         return;
426     }
427 #endif
428
429     frameLoader()->policyChecker()->checkContentPolicy(m_response, callContinueAfterContentPolicy, this);
430 }
431
432 void MainResourceLoader::didReceiveData(const char* data, int length, long long encodedDataLength, bool allAtOnce)
433 {
434     ASSERT(data);
435     ASSERT(length != 0);
436
437     ASSERT(!m_response.isNull());
438
439 #if USE(CFNETWORK) || PLATFORM(MAC)
440     // Workaround for <rdar://problem/6060782>
441     if (m_response.isNull()) {
442         m_response = ResourceResponse(KURL(), "text/html", 0, String(), String());
443         if (DocumentLoader* documentLoader = frameLoader()->activeDocumentLoader())
444             documentLoader->setResponse(m_response);
445     }
446 #endif
447
448     // There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
449     // See <rdar://problem/6304600> for more details.
450 #if !USE(CF)
451     ASSERT(!defersLoading());
452 #endif
453  
454  #if ENABLE(OFFLINE_WEB_APPLICATIONS)
455     documentLoader()->applicationCacheHost()->mainResourceDataReceived(data, length, encodedDataLength, allAtOnce);
456 #endif
457
458     // The additional processing can do anything including possibly removing the last
459     // reference to this object; one example of this is 3266216.
460     RefPtr<MainResourceLoader> protect(this);
461
462     m_timeOfLastDataReceived = currentTime();
463
464     ResourceLoader::didReceiveData(data, length, encodedDataLength, allAtOnce);
465 }
466
467 void MainResourceLoader::didFinishLoading(double finishTime)
468 {
469     // There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
470     // See <rdar://problem/6304600> for more details.
471 #if !USE(CF)
472     ASSERT(shouldLoadAsEmptyDocument(frameLoader()->activeDocumentLoader()->url()) || !defersLoading());
473 #endif
474     
475     // The additional processing can do anything including possibly removing the last
476     // reference to this object.
477     RefPtr<MainResourceLoader> protect(this);
478
479 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
480     RefPtr<DocumentLoader> dl = documentLoader();
481 #endif
482
483     ASSERT(!documentLoader()->timing()->responseEnd);
484     documentLoader()->timing()->responseEnd = finishTime ? finishTime : (m_timeOfLastDataReceived ? m_timeOfLastDataReceived : currentTime());
485     frameLoader()->finishedLoading();
486     ResourceLoader::didFinishLoading(finishTime);
487     
488 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
489     dl->applicationCacheHost()->finishedLoadingMainResource();
490 #endif
491 }
492
493 void MainResourceLoader::didFail(const ResourceError& error)
494 {
495 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
496     if (documentLoader()->applicationCacheHost()->maybeLoadFallbackForMainError(request(), error))
497         return;
498 #endif
499
500     // There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
501     // See <rdar://problem/6304600> for more details.
502 #if !USE(CF)
503     ASSERT(!defersLoading());
504 #endif
505     
506     receivedError(error);
507 }
508
509 void MainResourceLoader::handleEmptyLoad(const KURL& url, bool forURLScheme)
510 {
511     String mimeType;
512     if (forURLScheme)
513         mimeType = frameLoader()->client()->generatedMIMETypeForURLScheme(url.protocol());
514     else
515         mimeType = "text/html";
516     
517     ResourceResponse response(url, mimeType, 0, String(), String());
518     didReceiveResponse(response);
519 }
520
521 void MainResourceLoader::handleDataLoadNow(MainResourceLoaderTimer*)
522 {
523     RefPtr<MainResourceLoader> protect(this);
524
525     KURL url = m_substituteData.responseURL();
526     if (url.isEmpty())
527         url = m_initialRequest.url();
528
529     // Clear the initial request here so that subsequent entries into the
530     // loader will not think there's still a deferred load left to do.
531     m_initialRequest = ResourceRequest();
532         
533     ResourceResponse response(url, m_substituteData.mimeType(), m_substituteData.content()->size(), m_substituteData.textEncoding(), "");
534     didReceiveResponse(response);
535 }
536
537 void MainResourceLoader::startDataLoadTimer()
538 {
539     m_dataLoadTimer.startOneShot(0);
540
541 #if HAVE(RUNLOOP_TIMER)
542     if (SchedulePairHashSet* scheduledPairs = m_frame->page()->scheduledRunLoopPairs())
543         m_dataLoadTimer.schedule(*scheduledPairs);
544 #endif
545 }
546
547 void MainResourceLoader::handleDataLoadSoon(const ResourceRequest& r)
548 {
549     m_initialRequest = r;
550     
551     if (m_documentLoader->deferMainResourceDataLoad())
552         startDataLoadTimer();
553     else
554         handleDataLoadNow(0);
555 }
556
557 bool MainResourceLoader::loadNow(ResourceRequest& r)
558 {
559     bool shouldLoadEmptyBeforeRedirect = shouldLoadAsEmptyDocument(r.url());
560
561     ASSERT(!m_handle);
562     ASSERT(shouldLoadEmptyBeforeRedirect || !defersLoading());
563
564     // Send this synthetic delegate callback since clients expect it, and
565     // we no longer send the callback from within NSURLConnection for
566     // initial requests.
567     willSendRequest(r, ResourceResponse());
568
569     // <rdar://problem/4801066>
570     // willSendRequest() is liable to make the call to frameLoader() return NULL, so we need to check that here
571     if (!frameLoader())
572         return false;
573     
574     const KURL& url = r.url();
575     bool shouldLoadEmpty = shouldLoadAsEmptyDocument(url) && !m_substituteData.isValid();
576
577     if (shouldLoadEmptyBeforeRedirect && !shouldLoadEmpty && defersLoading())
578         return true;
579
580     resourceLoadScheduler()->addMainResourceLoad(this);
581     if (m_substituteData.isValid()) 
582         handleDataLoadSoon(r);
583     else if (shouldLoadEmpty || frameLoader()->client()->representationExistsForURLScheme(url.protocol()))
584         handleEmptyLoad(url, !shouldLoadEmpty);
585     else
586         m_handle = ResourceHandle::create(m_frame->loader()->networkingContext(), r, this, false, true);
587
588     return false;
589 }
590
591 bool MainResourceLoader::load(const ResourceRequest& r, const SubstituteData& substituteData)
592 {
593     ASSERT(!m_handle);
594
595     m_substituteData = substituteData;
596
597     ASSERT(documentLoader()->timing()->navigationStart);
598     ASSERT(!documentLoader()->timing()->fetchStart);
599     documentLoader()->timing()->fetchStart = currentTime();
600     ResourceRequest request(r);
601
602 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
603     documentLoader()->applicationCacheHost()->maybeLoadMainResource(request, m_substituteData);
604 #endif
605
606     bool defer = defersLoading();
607     if (defer) {
608         bool shouldLoadEmpty = shouldLoadAsEmptyDocument(request.url());
609         if (shouldLoadEmpty)
610             defer = false;
611     }
612     if (!defer) {
613         if (loadNow(request)) {
614             // Started as an empty document, but was redirected to something non-empty.
615             ASSERT(defersLoading());
616             defer = true;
617         }
618     }
619     if (defer)
620         m_initialRequest = request;
621
622     return true;
623 }
624
625 void MainResourceLoader::setDefersLoading(bool defers)
626 {
627     ResourceLoader::setDefersLoading(defers);
628
629     if (defers) {
630         if (m_dataLoadTimer.isActive())
631             m_dataLoadTimer.stop();
632     } else {
633         if (m_initialRequest.isNull())
634             return;
635
636         if (m_substituteData.isValid() && m_documentLoader->deferMainResourceDataLoad())
637             startDataLoadTimer();
638         else {
639             ResourceRequest r(m_initialRequest);
640             m_initialRequest = ResourceRequest();
641             loadNow(r);
642         }
643     }
644 }
645
646 }