• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "DocumentLoader.h"
35 #include "FormState.h"
36 #include "Frame.h"
37 #include "FrameLoader.h"
38 #include "FrameLoaderClient.h"
39 #include "HTMLFormElement.h"
40 #include "Page.h"
41 #include "ResourceError.h"
42 #include "ResourceHandle.h"
43 #include "Settings.h"
44 
45 // FIXME: More that is in common with SubresourceLoader should move up into ResourceLoader.
46 
47 namespace WebCore {
48 
MainResourceLoader(Frame * frame)49 MainResourceLoader::MainResourceLoader(Frame* frame)
50     : ResourceLoader(frame, true, true)
51     , m_dataLoadTimer(this, &MainResourceLoader::handleDataLoadNow)
52     , m_loadingMultipartContent(false)
53     , m_waitingForContentPolicy(false)
54 {
55 }
56 
~MainResourceLoader()57 MainResourceLoader::~MainResourceLoader()
58 {
59 }
60 
create(Frame * frame)61 PassRefPtr<MainResourceLoader> MainResourceLoader::create(Frame* frame)
62 {
63     return adoptRef(new MainResourceLoader(frame));
64 }
65 
receivedError(const ResourceError & error)66 void MainResourceLoader::receivedError(const ResourceError& error)
67 {
68     // Calling receivedMainResourceError will likely result in the last reference to this object to go away.
69     RefPtr<MainResourceLoader> protect(this);
70     RefPtr<Frame> protectFrame(m_frame);
71 
72     // It is important that we call FrameLoader::receivedMainResourceError before calling
73     // FrameLoader::didFailToLoad because receivedMainResourceError clears out the relevant
74     // document loaders. Also, receivedMainResourceError ends up calling a FrameLoadDelegate method
75     // and didFailToLoad calls a ResourceLoadDelegate method and they need to be in the correct order.
76     frameLoader()->receivedMainResourceError(error, true);
77 
78     if (!cancelled()) {
79         ASSERT(!reachedTerminalState());
80         frameLoader()->didFailToLoad(this, error);
81 
82         releaseResources();
83     }
84 
85     ASSERT(reachedTerminalState());
86 }
87 
didCancel(const ResourceError & error)88 void MainResourceLoader::didCancel(const ResourceError& error)
89 {
90     m_dataLoadTimer.stop();
91 
92     // Calling receivedMainResourceError will likely result in the last reference to this object to go away.
93     RefPtr<MainResourceLoader> protect(this);
94 
95     if (m_waitingForContentPolicy) {
96         frameLoader()->cancelContentPolicyCheck();
97         ASSERT(m_waitingForContentPolicy);
98         m_waitingForContentPolicy = false;
99         deref(); // balances ref in didReceiveResponse
100     }
101     frameLoader()->receivedMainResourceError(error, true);
102     ResourceLoader::didCancel(error);
103 }
104 
interruptionForPolicyChangeError() const105 ResourceError MainResourceLoader::interruptionForPolicyChangeError() const
106 {
107     return frameLoader()->interruptionForPolicyChangeError(request());
108 }
109 
stopLoadingForPolicyChange()110 void MainResourceLoader::stopLoadingForPolicyChange()
111 {
112     cancel(interruptionForPolicyChangeError());
113 }
114 
callContinueAfterNavigationPolicy(void * argument,const ResourceRequest & request,PassRefPtr<FormState>,bool shouldContinue)115 void MainResourceLoader::callContinueAfterNavigationPolicy(void* argument, const ResourceRequest& request, PassRefPtr<FormState>, bool shouldContinue)
116 {
117     static_cast<MainResourceLoader*>(argument)->continueAfterNavigationPolicy(request, shouldContinue);
118 }
119 
continueAfterNavigationPolicy(const ResourceRequest &,bool shouldContinue)120 void MainResourceLoader::continueAfterNavigationPolicy(const ResourceRequest&, bool shouldContinue)
121 {
122     if (!shouldContinue)
123         stopLoadingForPolicyChange();
124     deref(); // balances ref in willSendRequest
125 }
126 
isPostOrRedirectAfterPost(const ResourceRequest & newRequest,const ResourceResponse & redirectResponse)127 bool MainResourceLoader::isPostOrRedirectAfterPost(const ResourceRequest& newRequest, const ResourceResponse& redirectResponse)
128 {
129     if (newRequest.httpMethod() == "POST")
130         return true;
131 
132     int status = redirectResponse.httpStatusCode();
133     if (((status >= 301 && status <= 303) || status == 307)
134         && frameLoader()->initialRequest().httpMethod() == "POST")
135         return true;
136 
137     return false;
138 }
139 
addData(const char * data,int length,bool allAtOnce)140 void MainResourceLoader::addData(const char* data, int length, bool allAtOnce)
141 {
142     ResourceLoader::addData(data, length, allAtOnce);
143     frameLoader()->receivedData(data, length);
144 }
145 
willSendRequest(ResourceRequest & newRequest,const ResourceResponse & redirectResponse)146 void MainResourceLoader::willSendRequest(ResourceRequest& newRequest, const ResourceResponse& redirectResponse)
147 {
148     // Note that there are no asserts here as there are for the other callbacks. This is due to the
149     // fact that this "callback" is sent when starting every load, and the state of callback
150     // deferrals plays less of a part in this function in preventing the bad behavior deferring
151     // callbacks is meant to prevent.
152     ASSERT(!newRequest.isNull());
153 
154     // The additional processing can do anything including possibly removing the last
155     // reference to this object; one example of this is 3266216.
156     RefPtr<MainResourceLoader> protect(this);
157 
158     // Update cookie policy base URL as URL changes, except for subframes, which use the
159     // URL of the main frame which doesn't change when we redirect.
160     if (frameLoader()->isLoadingMainFrame())
161         newRequest.setFirstPartyForCookies(newRequest.url());
162 
163     // If we're fielding a redirect in response to a POST, force a load from origin, since
164     // this is a common site technique to return to a page viewing some data that the POST
165     // just modified.
166     // Also, POST requests always load from origin, but this does not affect subresources.
167     if (newRequest.cachePolicy() == UseProtocolCachePolicy && isPostOrRedirectAfterPost(newRequest, redirectResponse))
168         newRequest.setCachePolicy(ReloadIgnoringCacheData);
169 
170     ResourceLoader::willSendRequest(newRequest, redirectResponse);
171 
172     // Don't set this on the first request. It is set when the main load was started.
173     m_documentLoader->setRequest(newRequest);
174 
175     // FIXME: Ideally we'd stop the I/O until we hear back from the navigation policy delegate
176     // listener. But there's no way to do that in practice. So instead we cancel later if the
177     // listener tells us to. In practice that means the navigation policy needs to be decided
178     // synchronously for these redirect cases.
179     if (!redirectResponse.isNull()) {
180         ref(); // balanced by deref in continueAfterNavigationPolicy
181         frameLoader()->checkNavigationPolicy(newRequest, callContinueAfterNavigationPolicy, this);
182     }
183 }
184 
shouldLoadAsEmptyDocument(const KURL & url)185 static bool shouldLoadAsEmptyDocument(const KURL& url)
186 {
187 #if PLATFORM(TORCHMOBILE)
188     return url.isEmpty() || (url.protocolIs("about") && equalIgnoringRef(url, blankURL()));
189 #else
190     return url.isEmpty() || url.protocolIs("about");
191 #endif
192 }
193 
continueAfterContentPolicy(PolicyAction contentPolicy,const ResourceResponse & r)194 void MainResourceLoader::continueAfterContentPolicy(PolicyAction contentPolicy, const ResourceResponse& r)
195 {
196     KURL url = request().url();
197     const String& mimeType = r.mimeType();
198 
199     switch (contentPolicy) {
200     case PolicyUse: {
201         // Prevent remote web archives from loading because they can claim to be from any domain and thus avoid cross-domain security checks (4120255).
202         bool isRemoteWebArchive = equalIgnoringCase("application/x-webarchive", mimeType) && !m_substituteData.isValid() && !url.isLocalFile();
203         if (!frameLoader()->canShowMIMEType(mimeType) || isRemoteWebArchive) {
204             frameLoader()->cannotShowMIMEType(r);
205             // Check reachedTerminalState since the load may have already been cancelled inside of _handleUnimplementablePolicyWithErrorCode::.
206             if (!reachedTerminalState())
207                 stopLoadingForPolicyChange();
208             return;
209         }
210         break;
211     }
212 
213     case PolicyDownload:
214         // m_handle can be null, e.g. when loading a substitute resource from application cache.
215         if (!m_handle) {
216             receivedError(cannotShowURLError());
217             return;
218         }
219         frameLoader()->client()->download(m_handle.get(), request(), m_handle.get()->request(), r);
220         // It might have gone missing
221         if (frameLoader())
222             receivedError(interruptionForPolicyChangeError());
223         return;
224 
225     case PolicyIgnore:
226         stopLoadingForPolicyChange();
227         return;
228 
229     default:
230         ASSERT_NOT_REACHED();
231     }
232 
233     RefPtr<MainResourceLoader> protect(this);
234 
235     if (r.isHTTP()) {
236         int status = r.httpStatusCode();
237         if (status < 200 || status >= 300) {
238             bool hostedByObject = frameLoader()->isHostedByObjectElement();
239 
240             frameLoader()->handleFallbackContent();
241             // object elements are no longer rendered after we fallback, so don't
242             // keep trying to process data from their load
243 
244             if (hostedByObject)
245                 cancel();
246         }
247     }
248 
249     // we may have cancelled this load as part of switching to fallback content
250     if (!reachedTerminalState())
251         ResourceLoader::didReceiveResponse(r);
252 
253     if (frameLoader() && !frameLoader()->isStopping()) {
254         if (m_substituteData.isValid()) {
255             if (m_substituteData.content()->size())
256                 didReceiveData(m_substituteData.content()->data(), m_substituteData.content()->size(), m_substituteData.content()->size(), true);
257             if (frameLoader() && !frameLoader()->isStopping())
258                 didFinishLoading();
259         } else if (shouldLoadAsEmptyDocument(url) || frameLoader()->representationExistsForURLScheme(url.protocol()))
260             didFinishLoading();
261     }
262 }
263 
callContinueAfterContentPolicy(void * argument,PolicyAction policy)264 void MainResourceLoader::callContinueAfterContentPolicy(void* argument, PolicyAction policy)
265 {
266     static_cast<MainResourceLoader*>(argument)->continueAfterContentPolicy(policy);
267 }
268 
continueAfterContentPolicy(PolicyAction policy)269 void MainResourceLoader::continueAfterContentPolicy(PolicyAction policy)
270 {
271     ASSERT(m_waitingForContentPolicy);
272     m_waitingForContentPolicy = false;
273     if (frameLoader() && !frameLoader()->isStopping())
274         continueAfterContentPolicy(policy, m_response);
275     deref(); // balances ref in didReceiveResponse
276 }
277 
didReceiveResponse(const ResourceResponse & r)278 void MainResourceLoader::didReceiveResponse(const ResourceResponse& r)
279 {
280 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
281     if (documentLoader()->applicationCacheHost()->maybeLoadFallbackForMainResponse(request(), r))
282         return;
283 #endif
284 
285     HTTPHeaderMap::const_iterator it = r.httpHeaderFields().find(AtomicString("x-frame-options"));
286     if (it != r.httpHeaderFields().end()) {
287         String content = it->second;
288         if (m_frame->loader()->shouldInterruptLoadForXFrameOptions(content, r.url())) {
289             cancel();
290             return;
291         }
292     }
293 
294     // There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
295     // See <rdar://problem/6304600> for more details.
296 #if !PLATFORM(CF)
297     ASSERT(shouldLoadAsEmptyDocument(r.url()) || !defersLoading());
298 #endif
299 
300     if (m_loadingMultipartContent) {
301         frameLoader()->setupForReplaceByMIMEType(r.mimeType());
302         clearResourceData();
303     }
304 
305     if (r.isMultipart())
306         m_loadingMultipartContent = true;
307 
308     // The additional processing can do anything including possibly removing the last
309     // reference to this object; one example of this is 3266216.
310     RefPtr<MainResourceLoader> protect(this);
311 
312     m_documentLoader->setResponse(r);
313 
314     m_response = r;
315 
316     ASSERT(!m_waitingForContentPolicy);
317     m_waitingForContentPolicy = true;
318     ref(); // balanced by deref in continueAfterContentPolicy and didCancel
319     frameLoader()->checkContentPolicy(m_response.mimeType(), callContinueAfterContentPolicy, this);
320 }
321 
didReceiveData(const char * data,int length,long long lengthReceived,bool allAtOnce)322 void MainResourceLoader::didReceiveData(const char* data, int length, long long lengthReceived, bool allAtOnce)
323 {
324     ASSERT(data);
325     ASSERT(length != 0);
326 
327     ASSERT(!m_response.isNull());
328 
329 #if USE(CFNETWORK) || (PLATFORM(MAC) && !defined(BUILDING_ON_TIGER))
330     // Workaround for <rdar://problem/6060782>
331     if (m_response.isNull()) {
332         m_response = ResourceResponse(KURL(), "text/html", 0, String(), String());
333         if (DocumentLoader* documentLoader = frameLoader()->activeDocumentLoader())
334             documentLoader->setResponse(m_response);
335     }
336 #endif
337 
338     // There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
339     // See <rdar://problem/6304600> for more details.
340 #if !PLATFORM(CF)
341     ASSERT(!defersLoading());
342 #endif
343 
344  #if ENABLE(OFFLINE_WEB_APPLICATIONS)
345     documentLoader()->applicationCacheHost()->mainResourceDataReceived(data, length, lengthReceived, allAtOnce);
346 #endif
347 
348     // The additional processing can do anything including possibly removing the last
349     // reference to this object; one example of this is 3266216.
350     RefPtr<MainResourceLoader> protect(this);
351 
352     ResourceLoader::didReceiveData(data, length, lengthReceived, allAtOnce);
353 }
354 
didFinishLoading()355 void MainResourceLoader::didFinishLoading()
356 {
357     // There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
358     // See <rdar://problem/6304600> for more details.
359 #if !PLATFORM(CF)
360     ASSERT(shouldLoadAsEmptyDocument(frameLoader()->activeDocumentLoader()->url()) || !defersLoading());
361 #endif
362 
363     // The additional processing can do anything including possibly removing the last
364     // reference to this object.
365     RefPtr<MainResourceLoader> protect(this);
366 
367 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
368     RefPtr<DocumentLoader> dl = documentLoader();
369 #endif
370 
371     frameLoader()->finishedLoading();
372     ResourceLoader::didFinishLoading();
373 
374 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
375     dl->applicationCacheHost()->finishedLoadingMainResource();
376 #endif
377 }
378 
didFail(const ResourceError & error)379 void MainResourceLoader::didFail(const ResourceError& error)
380 {
381 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
382     if (documentLoader()->applicationCacheHost()->maybeLoadFallbackForMainError(request(), error))
383         return;
384 #endif
385 
386     // There is a bug in CFNetwork where callbacks can be dispatched even when loads are deferred.
387     // See <rdar://problem/6304600> for more details.
388 #if !PLATFORM(CF)
389     ASSERT(!defersLoading());
390 #endif
391 
392     receivedError(error);
393 }
394 
handleEmptyLoad(const KURL & url,bool forURLScheme)395 void MainResourceLoader::handleEmptyLoad(const KURL& url, bool forURLScheme)
396 {
397     String mimeType;
398     if (forURLScheme)
399         mimeType = frameLoader()->generatedMIMETypeForURLScheme(url.protocol());
400     else
401         mimeType = "text/html";
402 
403     ResourceResponse response(url, mimeType, 0, String(), String());
404     didReceiveResponse(response);
405 }
406 
handleDataLoadNow(MainResourceLoaderTimer *)407 void MainResourceLoader::handleDataLoadNow(MainResourceLoaderTimer*)
408 {
409     RefPtr<MainResourceLoader> protect(this);
410 
411     KURL url = m_substituteData.responseURL();
412     if (url.isEmpty())
413         url = m_initialRequest.url();
414 
415     ResourceResponse response(url, m_substituteData.mimeType(), m_substituteData.content()->size(), m_substituteData.textEncoding(), "");
416     didReceiveResponse(response);
417 }
418 
startDataLoadTimer()419 void MainResourceLoader::startDataLoadTimer()
420 {
421     m_dataLoadTimer.startOneShot(0);
422 
423 #if HAVE(RUNLOOP_TIMER)
424     if (SchedulePairHashSet* scheduledPairs = m_frame->page()->scheduledRunLoopPairs())
425         m_dataLoadTimer.schedule(*scheduledPairs);
426 #endif
427 }
428 
handleDataLoadSoon(ResourceRequest & r)429 void MainResourceLoader::handleDataLoadSoon(ResourceRequest& r)
430 {
431     m_initialRequest = r;
432 
433     if (m_documentLoader->deferMainResourceDataLoad())
434         startDataLoadTimer();
435     else
436         handleDataLoadNow(0);
437 }
438 
loadNow(ResourceRequest & r)439 bool MainResourceLoader::loadNow(ResourceRequest& r)
440 {
441     bool shouldLoadEmptyBeforeRedirect = shouldLoadAsEmptyDocument(r.url());
442 
443     ASSERT(!m_handle);
444     ASSERT(shouldLoadEmptyBeforeRedirect || !defersLoading());
445 
446     // Send this synthetic delegate callback since clients expect it, and
447     // we no longer send the callback from within NSURLConnection for
448     // initial requests.
449     willSendRequest(r, ResourceResponse());
450 
451     // <rdar://problem/4801066>
452     // willSendRequest() is liable to make the call to frameLoader() return NULL, so we need to check that here
453     if (!frameLoader())
454         return false;
455 
456     const KURL& url = r.url();
457     bool shouldLoadEmpty = shouldLoadAsEmptyDocument(url) && !m_substituteData.isValid();
458 
459     if (shouldLoadEmptyBeforeRedirect && !shouldLoadEmpty && defersLoading())
460         return true;
461 
462     if (m_substituteData.isValid())
463         handleDataLoadSoon(r);
464     else if (shouldLoadEmpty || frameLoader()->representationExistsForURLScheme(url.protocol()))
465         handleEmptyLoad(url, !shouldLoadEmpty);
466     else
467         m_handle = ResourceHandle::create(r, this, m_frame.get(), false, true, true);
468 
469     return false;
470 }
471 
load(const ResourceRequest & r,const SubstituteData & substituteData)472 bool MainResourceLoader::load(const ResourceRequest& r, const SubstituteData& substituteData)
473 {
474     ASSERT(!m_handle);
475 
476     m_substituteData = substituteData;
477 
478     ResourceRequest request(r);
479 
480 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
481     documentLoader()->applicationCacheHost()->maybeLoadMainResource(request, m_substituteData);
482 #endif
483 
484     bool defer = defersLoading();
485     if (defer) {
486         bool shouldLoadEmpty = shouldLoadAsEmptyDocument(request.url());
487         if (shouldLoadEmpty)
488             defer = false;
489     }
490     if (!defer) {
491         if (loadNow(request)) {
492             // Started as an empty document, but was redirected to something non-empty.
493             ASSERT(defersLoading());
494             defer = true;
495         }
496     }
497     if (defer)
498         m_initialRequest = request;
499 
500     return true;
501 }
502 
setDefersLoading(bool defers)503 void MainResourceLoader::setDefersLoading(bool defers)
504 {
505     ResourceLoader::setDefersLoading(defers);
506 
507     if (defers) {
508         if (m_dataLoadTimer.isActive())
509             m_dataLoadTimer.stop();
510     } else {
511         if (m_initialRequest.isNull())
512             return;
513 
514         if (m_substituteData.isValid() && m_documentLoader->deferMainResourceDataLoad())
515             startDataLoadTimer();
516         else {
517             ResourceRequest r(m_initialRequest);
518             m_initialRequest = ResourceRequest();
519             loadNow(r);
520         }
521     }
522 }
523 
524 }
525