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 "DOMWindow.h"
35 #include "Document.h"
36 #include "DocumentLoadTiming.h"
37 #include "DocumentLoader.h"
38 #include "FormState.h"
39 #include "Frame.h"
40 #include "FrameLoader.h"
41 #include "FrameLoaderClient.h"
42 #include "HTMLFormElement.h"
43 #include "InspectorInstrumentation.h"
44 #include "Page.h"
45 #include "ResourceError.h"
46 #include "ResourceHandle.h"
47 #include "ResourceLoadScheduler.h"
48 #include "SchemeRegistry.h"
49 #include "SecurityOrigin.h"
50 #include "Settings.h"
51 #include <wtf/CurrentTime.h>
52 
53 #if PLATFORM(QT)
54 #include "PluginDatabase.h"
55 #endif
56 
57 // FIXME: More that is in common with SubresourceLoader should move up into ResourceLoader.
58 
59 namespace WebCore {
60 
MainResourceLoader(Frame * frame)61 MainResourceLoader::MainResourceLoader(Frame* frame)
62     : ResourceLoader(frame, true, true)
63     , m_dataLoadTimer(this, &MainResourceLoader::handleDataLoadNow)
64     , m_loadingMultipartContent(false)
65     , m_waitingForContentPolicy(false)
66     , m_timeOfLastDataReceived(0.0)
67 {
68 }
69 
~MainResourceLoader()70 MainResourceLoader::~MainResourceLoader()
71 {
72 }
73 
create(Frame * frame)74 PassRefPtr<MainResourceLoader> MainResourceLoader::create(Frame* frame)
75 {
76     return adoptRef(new MainResourceLoader(frame));
77 }
78 
receivedError(const ResourceError & error)79 void MainResourceLoader::receivedError(const ResourceError& error)
80 {
81     // Calling receivedMainResourceError will likely result in the last reference to this object to go away.
82     RefPtr<MainResourceLoader> protect(this);
83     RefPtr<Frame> protectFrame(m_frame);
84 
85     // It is important that we call FrameLoader::receivedMainResourceError before calling
86     // FrameLoader::didFailToLoad because receivedMainResourceError clears out the relevant
87     // document loaders. Also, receivedMainResourceError ends up calling a FrameLoadDelegate method
88     // and didFailToLoad calls a ResourceLoadDelegate method and they need to be in the correct order.
89     frameLoader()->receivedMainResourceError(error, true);
90 
91     if (!cancelled()) {
92         ASSERT(!reachedTerminalState());
93         frameLoader()->notifier()->didFailToLoad(this, error);
94 
95         releaseResources();
96     }
97 
98     ASSERT(reachedTerminalState());
99 }
100 
didCancel(const ResourceError & error)101 void MainResourceLoader::didCancel(const ResourceError& error)
102 {
103     m_dataLoadTimer.stop();
104 
105     // FrameLoader won't be reachable after calling ResourceLoader::didCancel().
106     FrameLoader* frameLoader = this->frameLoader();
107 
108     if (m_waitingForContentPolicy) {
109         frameLoader->policyChecker()->cancelCheck();
110         ASSERT(m_waitingForContentPolicy);
111         m_waitingForContentPolicy = false;
112         deref(); // balances ref in didReceiveResponse
113     }
114     ResourceLoader::didCancel(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 
interruptionForPolicyChangeError() const121 ResourceError MainResourceLoader::interruptionForPolicyChangeError() const
122 {
123     return frameLoader()->interruptionForPolicyChangeError(request());
124 }
125 
stopLoadingForPolicyChange()126 void MainResourceLoader::stopLoadingForPolicyChange()
127 {
128     ResourceError error = interruptionForPolicyChangeError();
129     error.setIsCancellation(true);
130     cancel(error);
131 }
132 
callContinueAfterNavigationPolicy(void * argument,const ResourceRequest & request,PassRefPtr<FormState>,bool shouldContinue)133 void MainResourceLoader::callContinueAfterNavigationPolicy(void* argument, const ResourceRequest& request, PassRefPtr<FormState>, bool shouldContinue)
134 {
135     static_cast<MainResourceLoader*>(argument)->continueAfterNavigationPolicy(request, shouldContinue);
136 }
137 
continueAfterNavigationPolicy(const ResourceRequest & request,bool shouldContinue)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 
isPostOrRedirectAfterPost(const ResourceRequest & newRequest,const ResourceResponse & redirectResponse)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 
addData(const char * data,int length,bool allAtOnce)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 
willSendRequest(ResourceRequest & newRequest,const ResourceResponse & redirectResponse)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 
shouldLoadAsEmptyDocument(const KURL & url)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 
continueAfterContentPolicy(PolicyAction contentPolicy,const ResourceResponse & r)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) && !m_substituteData.isValid() && !url.isLocalFile();
260         if (!frameLoader()->canShowMIMEType(mimeType) || isRemoteWebArchive) {
261             frameLoader()->policyChecker()->cannotShowMIMEType(r);
262             // Check reachedTerminalState since the load may have already been cancelled inside of _handleUnimplementablePolicyWithErrorCode::.
263             if (!reachedTerminalState())
264                 stopLoadingForPolicyChange();
265             return;
266         }
267         break;
268     }
269 
270     case PolicyDownload:
271         // m_handle can be null, e.g. when loading a substitute resource from application cache.
272         if (!m_handle) {
273             receivedError(cannotShowURLError());
274             return;
275         }
276         InspectorInstrumentation::continueWithPolicyDownload(m_frame.get(), documentLoader(), identifier(), r);
277         frameLoader()->client()->download(m_handle.get(), request(), m_handle.get()->firstRequest(), r);
278         // It might have gone missing
279         if (frameLoader())
280             receivedError(interruptionForPolicyChangeError());
281         return;
282 
283     case PolicyIgnore:
284         InspectorInstrumentation::continueWithPolicyIgnore(m_frame.get(), documentLoader(), identifier(), r);
285         stopLoadingForPolicyChange();
286         return;
287 
288     default:
289         ASSERT_NOT_REACHED();
290     }
291 
292     RefPtr<MainResourceLoader> protect(this);
293 
294     if (r.isHTTP()) {
295         int status = r.httpStatusCode();
296         if (status < 200 || status >= 300) {
297             bool hostedByObject = frameLoader()->isHostedByObjectElement();
298 
299             frameLoader()->handleFallbackContent();
300             // object elements are no longer rendered after we fallback, so don't
301             // keep trying to process data from their load
302 
303             if (hostedByObject)
304                 cancel();
305         }
306     }
307 
308     // we may have cancelled this load as part of switching to fallback content
309     if (!reachedTerminalState())
310         ResourceLoader::didReceiveResponse(r);
311 
312     if (frameLoader() && !frameLoader()->isStopping()) {
313         if (m_substituteData.isValid()) {
314             if (m_substituteData.content()->size())
315                 didReceiveData(m_substituteData.content()->data(), m_substituteData.content()->size(), m_substituteData.content()->size(), true);
316             if (frameLoader() && !frameLoader()->isStopping())
317                 didFinishLoading(0);
318         } else if (shouldLoadAsEmptyDocument(url) || frameLoader()->representationExistsForURLScheme(url.protocol()))
319             didFinishLoading(0);
320     }
321 }
322 
callContinueAfterContentPolicy(void * argument,PolicyAction policy)323 void MainResourceLoader::callContinueAfterContentPolicy(void* argument, PolicyAction policy)
324 {
325     static_cast<MainResourceLoader*>(argument)->continueAfterContentPolicy(policy);
326 }
327 
continueAfterContentPolicy(PolicyAction policy)328 void MainResourceLoader::continueAfterContentPolicy(PolicyAction policy)
329 {
330     ASSERT(m_waitingForContentPolicy);
331     m_waitingForContentPolicy = false;
332     if (frameLoader() && !frameLoader()->isStopping())
333         continueAfterContentPolicy(policy, m_response);
334     deref(); // balances ref in didReceiveResponse
335 }
336 
337 #if PLATFORM(QT)
substituteMIMETypeFromPluginDatabase(const ResourceResponse & r)338 void MainResourceLoader::substituteMIMETypeFromPluginDatabase(const ResourceResponse& r)
339 {
340     if (!m_frame->loader()->subframeLoader()->allowPlugins(NotAboutToInstantiatePlugin))
341         return;
342 
343     String filename = r.url().lastPathComponent();
344     if (filename.endsWith("/"))
345         return;
346 
347     size_t extensionPos = filename.reverseFind('.');
348     if (extensionPos == notFound)
349         return;
350 
351     String extension = filename.substring(extensionPos + 1);
352     String mimeType = PluginDatabase::installedPlugins()->MIMETypeForExtension(extension);
353     if (!mimeType.isEmpty()) {
354         ResourceResponse* response = const_cast<ResourceResponse*>(&r);
355         response->setMimeType(mimeType);
356     }
357 }
358 #endif
359 
didReceiveResponse(const ResourceResponse & r)360 void MainResourceLoader::didReceiveResponse(const ResourceResponse& r)
361 {
362 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
363     if (documentLoader()->applicationCacheHost()->maybeLoadFallbackForMainResponse(request(), r))
364         return;
365 #endif
366 
367     HTTPHeaderMap::const_iterator it = r.httpHeaderFields().find(AtomicString("x-frame-options"));
368     if (it != r.httpHeaderFields().end()) {
369         String content = it->second;
370         if (m_frame->loader()->shouldInterruptLoadForXFrameOptions(content, r.url())) {
371             InspectorInstrumentation::continueAfterXFrameOptionsDenied(m_frame.get(), documentLoader(), identifier(), r);
372             DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to display document because display forbidden by X-Frame-Options.\n"));
373             m_frame->domWindow()->console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, consoleMessage, 1, String());
374 
375             cancel();
376             return;
377         }
378     }
379 
380     // There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
381     // See <rdar://problem/6304600> for more details.
382 #if !USE(CF)
383     ASSERT(shouldLoadAsEmptyDocument(r.url()) || !defersLoading());
384 #endif
385 
386 #if PLATFORM(QT)
387     if (r.mimeType() == "application/octet-stream")
388         substituteMIMETypeFromPluginDatabase(r);
389 #endif
390 
391     if (m_loadingMultipartContent) {
392         frameLoader()->setupForReplaceByMIMEType(r.mimeType());
393         clearResourceData();
394     }
395 
396     if (r.isMultipart())
397         m_loadingMultipartContent = true;
398 
399     // The additional processing can do anything including possibly removing the last
400     // reference to this object; one example of this is 3266216.
401     RefPtr<MainResourceLoader> protect(this);
402 
403     m_documentLoader->setResponse(r);
404 
405     m_response = r;
406 
407     ASSERT(!m_waitingForContentPolicy);
408     m_waitingForContentPolicy = true;
409     ref(); // balanced by deref in continueAfterContentPolicy and didCancel
410 
411     ASSERT(frameLoader()->activeDocumentLoader());
412 
413     // Always show content with valid substitute data.
414     if (frameLoader()->activeDocumentLoader()->substituteData().isValid()) {
415         callContinueAfterContentPolicy(this, PolicyUse);
416         return;
417     }
418 
419 #if ENABLE(FTPDIR)
420     // Respect the hidden FTP Directory Listing pref so it can be tested even if the policy delegate might otherwise disallow it
421     Settings* settings = m_frame->settings();
422     if (settings && settings->forceFTPDirectoryListings() && m_response.mimeType() == "application/x-ftp-directory") {
423         callContinueAfterContentPolicy(this, PolicyUse);
424         return;
425     }
426 #endif
427 
428     frameLoader()->policyChecker()->checkContentPolicy(m_response, callContinueAfterContentPolicy, this);
429 }
430 
didReceiveData(const char * data,int length,long long encodedDataLength,bool allAtOnce)431 void MainResourceLoader::didReceiveData(const char* data, int length, long long encodedDataLength, bool allAtOnce)
432 {
433     ASSERT(data);
434     ASSERT(length != 0);
435 
436     ASSERT(!m_response.isNull());
437 
438 #if USE(CFNETWORK) || PLATFORM(MAC)
439     // Workaround for <rdar://problem/6060782>
440     if (m_response.isNull()) {
441         m_response = ResourceResponse(KURL(), "text/html", 0, String(), String());
442         if (DocumentLoader* documentLoader = frameLoader()->activeDocumentLoader())
443             documentLoader->setResponse(m_response);
444     }
445 #endif
446 
447     // There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
448     // See <rdar://problem/6304600> for more details.
449 #if !USE(CF)
450     ASSERT(!defersLoading());
451 #endif
452 
453  #if ENABLE(OFFLINE_WEB_APPLICATIONS)
454     documentLoader()->applicationCacheHost()->mainResourceDataReceived(data, length, encodedDataLength, allAtOnce);
455 #endif
456 
457     // The additional processing can do anything including possibly removing the last
458     // reference to this object; one example of this is 3266216.
459     RefPtr<MainResourceLoader> protect(this);
460 
461     m_timeOfLastDataReceived = currentTime();
462 
463     ResourceLoader::didReceiveData(data, length, encodedDataLength, allAtOnce);
464 }
465 
didFinishLoading(double finishTime)466 void MainResourceLoader::didFinishLoading(double finishTime)
467 {
468     // There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
469     // See <rdar://problem/6304600> for more details.
470 #if !USE(CF)
471     ASSERT(shouldLoadAsEmptyDocument(frameLoader()->activeDocumentLoader()->url()) || !defersLoading());
472 #endif
473 
474     // The additional processing can do anything including possibly removing the last
475     // reference to this object.
476     RefPtr<MainResourceLoader> protect(this);
477 
478 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
479     RefPtr<DocumentLoader> dl = documentLoader();
480 #endif
481 
482     ASSERT(!documentLoader()->timing()->responseEnd);
483     documentLoader()->timing()->responseEnd = finishTime ? finishTime : (m_timeOfLastDataReceived ? m_timeOfLastDataReceived : currentTime());
484     frameLoader()->finishedLoading();
485     ResourceLoader::didFinishLoading(finishTime);
486 
487 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
488     dl->applicationCacheHost()->finishedLoadingMainResource();
489 #endif
490 }
491 
didFail(const ResourceError & error)492 void MainResourceLoader::didFail(const ResourceError& error)
493 {
494 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
495     if (documentLoader()->applicationCacheHost()->maybeLoadFallbackForMainError(request(), error))
496         return;
497 #endif
498 
499     // There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
500     // See <rdar://problem/6304600> for more details.
501 #if !USE(CF)
502     ASSERT(!defersLoading());
503 #endif
504 
505     receivedError(error);
506 }
507 
handleEmptyLoad(const KURL & url,bool forURLScheme)508 void MainResourceLoader::handleEmptyLoad(const KURL& url, bool forURLScheme)
509 {
510     String mimeType;
511     if (forURLScheme)
512         mimeType = frameLoader()->generatedMIMETypeForURLScheme(url.protocol());
513     else
514         mimeType = "text/html";
515 
516     ResourceResponse response(url, mimeType, 0, String(), String());
517     didReceiveResponse(response);
518 }
519 
handleDataLoadNow(MainResourceLoaderTimer *)520 void MainResourceLoader::handleDataLoadNow(MainResourceLoaderTimer*)
521 {
522     RefPtr<MainResourceLoader> protect(this);
523 
524     KURL url = m_substituteData.responseURL();
525     if (url.isEmpty())
526         url = m_initialRequest.url();
527 
528     // Clear the initial request here so that subsequent entries into the
529     // loader will not think there's still a deferred load left to do.
530     m_initialRequest = ResourceRequest();
531 
532     ResourceResponse response(url, m_substituteData.mimeType(), m_substituteData.content()->size(), m_substituteData.textEncoding(), "");
533     didReceiveResponse(response);
534 }
535 
startDataLoadTimer()536 void MainResourceLoader::startDataLoadTimer()
537 {
538     m_dataLoadTimer.startOneShot(0);
539 
540 #if HAVE(RUNLOOP_TIMER)
541     if (SchedulePairHashSet* scheduledPairs = m_frame->page()->scheduledRunLoopPairs())
542         m_dataLoadTimer.schedule(*scheduledPairs);
543 #endif
544 }
545 
handleDataLoadSoon(const ResourceRequest & r)546 void MainResourceLoader::handleDataLoadSoon(const ResourceRequest& r)
547 {
548     m_initialRequest = r;
549 
550     if (m_documentLoader->deferMainResourceDataLoad())
551         startDataLoadTimer();
552     else
553         handleDataLoadNow(0);
554 }
555 
loadNow(ResourceRequest & r)556 bool MainResourceLoader::loadNow(ResourceRequest& r)
557 {
558     bool shouldLoadEmptyBeforeRedirect = shouldLoadAsEmptyDocument(r.url());
559 
560     ASSERT(!m_handle);
561     ASSERT(shouldLoadEmptyBeforeRedirect || !defersLoading());
562 
563     // Send this synthetic delegate callback since clients expect it, and
564     // we no longer send the callback from within NSURLConnection for
565     // initial requests.
566     willSendRequest(r, ResourceResponse());
567 
568     // <rdar://problem/4801066>
569     // willSendRequest() is liable to make the call to frameLoader() return NULL, so we need to check that here
570     if (!frameLoader())
571         return false;
572 
573     const KURL& url = r.url();
574     bool shouldLoadEmpty = shouldLoadAsEmptyDocument(url) && !m_substituteData.isValid();
575 
576     if (shouldLoadEmptyBeforeRedirect && !shouldLoadEmpty && defersLoading())
577         return true;
578 
579     resourceLoadScheduler()->addMainResourceLoad(this);
580     if (m_substituteData.isValid())
581         handleDataLoadSoon(r);
582     else if (shouldLoadEmpty || frameLoader()->representationExistsForURLScheme(url.protocol()))
583         handleEmptyLoad(url, !shouldLoadEmpty);
584     else
585         m_handle = ResourceHandle::create(m_frame->loader()->networkingContext(), r, this, false, true);
586 
587     return false;
588 }
589 
load(const ResourceRequest & r,const SubstituteData & substituteData)590 bool MainResourceLoader::load(const ResourceRequest& r, const SubstituteData& substituteData)
591 {
592     ASSERT(!m_handle);
593 
594     m_substituteData = substituteData;
595 
596     ASSERT(documentLoader()->timing()->navigationStart);
597     ASSERT(!documentLoader()->timing()->fetchStart);
598     documentLoader()->timing()->fetchStart = currentTime();
599     ResourceRequest request(r);
600 
601 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
602     documentLoader()->applicationCacheHost()->maybeLoadMainResource(request, m_substituteData);
603 #endif
604 
605     bool defer = defersLoading();
606     if (defer) {
607         bool shouldLoadEmpty = shouldLoadAsEmptyDocument(request.url());
608         if (shouldLoadEmpty)
609             defer = false;
610     }
611     if (!defer) {
612         if (loadNow(request)) {
613             // Started as an empty document, but was redirected to something non-empty.
614             ASSERT(defersLoading());
615             defer = true;
616         }
617     }
618     if (defer)
619         m_initialRequest = request;
620 
621     return true;
622 }
623 
setDefersLoading(bool defers)624 void MainResourceLoader::setDefersLoading(bool defers)
625 {
626     ResourceLoader::setDefersLoading(defers);
627 
628     if (defers) {
629         if (m_dataLoadTimer.isActive())
630             m_dataLoadTimer.stop();
631     } else {
632         if (m_initialRequest.isNull())
633             return;
634 
635         if (m_substituteData.isValid() && m_documentLoader->deferMainResourceDataLoad())
636             startDataLoadTimer();
637         else {
638             ResourceRequest r(m_initialRequest);
639             m_initialRequest = ResourceRequest();
640             loadNow(r);
641         }
642     }
643 }
644 
645 }
646