• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1.  Redistributions of source code must retain the above copyright
9  *     notice, this list of conditions and the following disclaimer.
10  * 2.  Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution.
13  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
14  *     its contributors may be used to endorse or promote products derived
15  *     from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include "config.h"
30 #include "DocumentLoader.h"
31 
32 #include "ApplicationCacheHost.h"
33 #if ENABLE(ARCHIVE) // ANDROID extension: disabled to reduce code size
34 #include "ArchiveFactory.h"
35 #include "ArchiveResourceCollection.h"
36 #else
37 #include "SubstituteResource.h"
38 #endif
39 #include "CachedPage.h"
40 #include "DocLoader.h"
41 #include "Document.h"
42 #include "Event.h"
43 #include "Frame.h"
44 #include "FrameLoader.h"
45 #include "FrameTree.h"
46 #include "HistoryItem.h"
47 #include "Logging.h"
48 #include "MainResourceLoader.h"
49 #include "Page.h"
50 #include "PlatformString.h"
51 #include "Settings.h"
52 #include "SharedBuffer.h"
53 #include "StringBuffer.h"
54 #include "XMLTokenizer.h"
55 
56 #include <wtf/Assertions.h>
57 #include <wtf/unicode/Unicode.h>
58 
59 namespace WebCore {
60 
61 /*
62  * Performs four operations:
63  *  1. Convert backslashes to currency symbols
64  *  2. Convert control characters to spaces
65  *  3. Trim leading and trailing spaces
66  *  4. Collapse internal whitespace.
67  */
canonicalizedTitle(const String & title,Frame * frame)68 static inline String canonicalizedTitle(const String& title, Frame* frame)
69 {
70     ASSERT(!title.isEmpty());
71 
72     const UChar* characters = title.characters();
73     unsigned length = title.length();
74     unsigned i;
75 
76     StringBuffer buffer(length);
77     unsigned builderIndex = 0;
78 
79     // Skip leading spaces and leading characters that would convert to spaces
80     for (i = 0; i < length; ++i) {
81         UChar c = characters[i];
82         if (!(c <= 0x20 || c == 0x7F))
83             break;
84     }
85 
86     if (i == length)
87         return "";
88 
89     // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
90     bool previousCharWasWS = false;
91     for (; i < length; ++i) {
92         UChar c = characters[i];
93         if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
94             if (previousCharWasWS)
95                 continue;
96             buffer[builderIndex++] = ' ';
97             previousCharWasWS = true;
98         } else {
99             buffer[builderIndex++] = c;
100             previousCharWasWS = false;
101         }
102     }
103 
104     // Strip trailing spaces
105     while (builderIndex > 0) {
106         --builderIndex;
107         if (buffer[builderIndex] != ' ')
108             break;
109     }
110 
111     if (!builderIndex && buffer[builderIndex] == ' ')
112         return "";
113 
114     buffer.shrink(builderIndex + 1);
115 
116     // Replace the backslashes with currency symbols if the encoding requires it.
117     frame->document()->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
118 
119     return String::adopt(buffer);
120 }
121 
cancelAll(const ResourceLoaderSet & loaders)122 static void cancelAll(const ResourceLoaderSet& loaders)
123 {
124     const ResourceLoaderSet copy = loaders;
125     ResourceLoaderSet::const_iterator end = copy.end();
126     for (ResourceLoaderSet::const_iterator it = copy.begin(); it != end; ++it)
127         (*it)->cancel();
128 }
129 
setAllDefersLoading(const ResourceLoaderSet & loaders,bool defers)130 static void setAllDefersLoading(const ResourceLoaderSet& loaders, bool defers)
131 {
132     const ResourceLoaderSet copy = loaders;
133     ResourceLoaderSet::const_iterator end = copy.end();
134     for (ResourceLoaderSet::const_iterator it = copy.begin(); it != end; ++it)
135         (*it)->setDefersLoading(defers);
136 }
137 
DocumentLoader(const ResourceRequest & req,const SubstituteData & substituteData)138 DocumentLoader::DocumentLoader(const ResourceRequest& req, const SubstituteData& substituteData)
139     : m_deferMainResourceDataLoad(true)
140     , m_frame(0)
141     , m_originalRequest(req)
142     , m_substituteData(substituteData)
143     , m_originalRequestCopy(req)
144     , m_request(req)
145     , m_committed(false)
146     , m_isStopping(false)
147     , m_loading(false)
148     , m_gotFirstByte(false)
149     , m_primaryLoadComplete(false)
150     , m_isClientRedirect(false)
151     , m_loadingFromCachedPage(false)
152     , m_stopRecordingResponses(false)
153     , m_substituteResourceDeliveryTimer(this, &DocumentLoader::substituteResourceDeliveryTimerFired)
154     , m_didCreateGlobalHistoryEntry(false)
155 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
156     , m_applicationCacheHost(new ApplicationCacheHost(this))
157 #endif
158 {
159 }
160 
frameLoader() const161 FrameLoader* DocumentLoader::frameLoader() const
162 {
163     if (!m_frame)
164         return 0;
165     return m_frame->loader();
166 }
167 
~DocumentLoader()168 DocumentLoader::~DocumentLoader()
169 {
170     ASSERT(!m_frame || frameLoader()->activeDocumentLoader() != this || !frameLoader()->isLoading());
171 }
172 
mainResourceData() const173 PassRefPtr<SharedBuffer> DocumentLoader::mainResourceData() const
174 {
175     if (m_mainResourceData)
176         return m_mainResourceData;
177     if (m_mainResourceLoader)
178         return m_mainResourceLoader->resourceData();
179     return 0;
180 }
181 
originalRequest() const182 const ResourceRequest& DocumentLoader::originalRequest() const
183 {
184     return m_originalRequest;
185 }
186 
originalRequestCopy() const187 const ResourceRequest& DocumentLoader::originalRequestCopy() const
188 {
189     return m_originalRequestCopy;
190 }
191 
request() const192 const ResourceRequest& DocumentLoader::request() const
193 {
194     return m_request;
195 }
196 
request()197 ResourceRequest& DocumentLoader::request()
198 {
199     return m_request;
200 }
201 
url() const202 const KURL& DocumentLoader::url() const
203 {
204     return request().url();
205 }
206 
replaceRequestURLForAnchorScroll(const KURL & url)207 void DocumentLoader::replaceRequestURLForAnchorScroll(const KURL& url)
208 {
209     m_originalRequestCopy.setURL(url);
210     m_request.setURL(url);
211 }
212 
setRequest(const ResourceRequest & req)213 void DocumentLoader::setRequest(const ResourceRequest& req)
214 {
215     // Replacing an unreachable URL with alternate content looks like a server-side
216     // redirect at this point, but we can replace a committed dataSource.
217     bool handlingUnreachableURL = false;
218 
219     handlingUnreachableURL = m_substituteData.isValid() && !m_substituteData.failingURL().isEmpty();
220 
221     if (handlingUnreachableURL)
222         m_committed = false;
223 
224     // We should never be getting a redirect callback after the data
225     // source is committed, except in the unreachable URL case. It
226     // would be a WebFoundation bug if it sent a redirect callback after commit.
227     ASSERT(!m_committed);
228 
229     KURL oldURL = m_request.url();
230     m_request = req;
231 
232     // Only send webView:didReceiveServerRedirectForProvisionalLoadForFrame: if URL changed.
233     // Also, don't send it when replacing unreachable URLs with alternate content.
234     if (!handlingUnreachableURL && oldURL != req.url())
235         frameLoader()->didReceiveServerRedirectForProvisionalLoadForFrame();
236 }
237 
setMainDocumentError(const ResourceError & error)238 void DocumentLoader::setMainDocumentError(const ResourceError& error)
239 {
240     m_mainDocumentError = error;
241     frameLoader()->setMainDocumentError(this, error);
242  }
243 
clearErrors()244 void DocumentLoader::clearErrors()
245 {
246     m_mainDocumentError = ResourceError();
247 }
248 
mainReceivedError(const ResourceError & error,bool isComplete)249 void DocumentLoader::mainReceivedError(const ResourceError& error, bool isComplete)
250 {
251     ASSERT(!error.isNull());
252 
253 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
254     m_applicationCacheHost->failedLoadingMainResource();
255 #endif
256 
257     if (!frameLoader())
258         return;
259     setMainDocumentError(error);
260     if (isComplete)
261         frameLoader()->mainReceivedCompleteError(this, error);
262 }
263 
264 // Cancels the data source's pending loads.  Conceptually, a data source only loads
265 // one document at a time, but one document may have many related resources.
266 // stopLoading will stop all loads initiated by the data source,
267 // but not loads initiated by child frames' data sources -- that's the WebFrame's job.
stopLoading(DatabasePolicy databasePolicy)268 void DocumentLoader::stopLoading(DatabasePolicy databasePolicy)
269 {
270     // In some rare cases, calling FrameLoader::stopLoading could set m_loading to false.
271     // (This can happen when there's a single XMLHttpRequest currently loading and stopLoading causes it
272     // to stop loading. Because of this, we need to save it so we don't return early.
273     bool loading = m_loading;
274 
275     if (m_committed) {
276         // Attempt to stop the frame if the document loader is loading, or if it is done loading but
277         // still  parsing. Failure to do so can cause a world leak.
278         Document* doc = m_frame->document();
279 
280         if (loading || doc->parsing())
281             m_frame->loader()->stopLoading(false, databasePolicy);
282     }
283 
284     // Always cancel multipart loaders
285     cancelAll(m_multipartSubresourceLoaders);
286 
287     if (!loading)
288         return;
289 
290     RefPtr<Frame> protectFrame(m_frame);
291     RefPtr<DocumentLoader> protectLoader(this);
292 
293     m_isStopping = true;
294 
295     FrameLoader* frameLoader = DocumentLoader::frameLoader();
296 
297     if (m_mainResourceLoader)
298         // Stop the main resource loader and let it send the cancelled message.
299         m_mainResourceLoader->cancel();
300     else if (!m_subresourceLoaders.isEmpty())
301         // The main resource loader already finished loading. Set the cancelled error on the
302         // document and let the subresourceLoaders send individual cancelled messages below.
303         setMainDocumentError(frameLoader->cancelledError(m_request));
304     else
305         // If there are no resource loaders, we need to manufacture a cancelled message.
306         // (A back/forward navigation has no resource loaders because its resources are cached.)
307         mainReceivedError(frameLoader->cancelledError(m_request), true);
308 
309     stopLoadingSubresources();
310     stopLoadingPlugIns();
311 
312     m_isStopping = false;
313 }
314 
setupForReplace()315 void DocumentLoader::setupForReplace()
316 {
317     frameLoader()->setupForReplace();
318     m_committed = false;
319 }
320 
commitIfReady()321 void DocumentLoader::commitIfReady()
322 {
323     if (m_gotFirstByte && !m_committed) {
324         m_committed = true;
325         frameLoader()->commitProvisionalLoad(0);
326     }
327 }
328 
finishedLoading()329 void DocumentLoader::finishedLoading()
330 {
331     m_gotFirstByte = true;
332     commitIfReady();
333     if (FrameLoader* loader = frameLoader()) {
334         loader->finishedLoadingDocument(this);
335         loader->end();
336     }
337 }
338 
commitLoad(const char * data,int length)339 void DocumentLoader::commitLoad(const char* data, int length)
340 {
341     // Both unloading the old page and parsing the new page may execute JavaScript which destroys the datasource
342     // by starting a new load, so retain temporarily.
343     RefPtr<DocumentLoader> protect(this);
344 
345     commitIfReady();
346     if (FrameLoader* frameLoader = DocumentLoader::frameLoader())
347         frameLoader->committedLoad(this, data, length);
348 }
349 
doesProgressiveLoad(const String & MIMEType) const350 bool DocumentLoader::doesProgressiveLoad(const String& MIMEType) const
351 {
352     return !frameLoader()->isReplacing() || MIMEType == "text/html";
353 }
354 
receivedData(const char * data,int length)355 void DocumentLoader::receivedData(const char* data, int length)
356 {
357     m_gotFirstByte = true;
358     if (doesProgressiveLoad(m_response.mimeType()))
359         commitLoad(data, length);
360 }
361 
setupForReplaceByMIMEType(const String & newMIMEType)362 void DocumentLoader::setupForReplaceByMIMEType(const String& newMIMEType)
363 {
364     if (!m_gotFirstByte)
365         return;
366 
367     String oldMIMEType = m_response.mimeType();
368 
369     if (!doesProgressiveLoad(oldMIMEType)) {
370         frameLoader()->revertToProvisional(this);
371         setupForReplace();
372         RefPtr<SharedBuffer> resourceData = mainResourceData();
373         commitLoad(resourceData->data(), resourceData->size());
374     }
375 
376     frameLoader()->finishedLoadingDocument(this);
377     m_frame->loader()->end();
378 
379     frameLoader()->setReplacing();
380     m_gotFirstByte = false;
381 
382     if (doesProgressiveLoad(newMIMEType)) {
383         frameLoader()->revertToProvisional(this);
384         setupForReplace();
385     }
386 
387     stopLoadingSubresources();
388     stopLoadingPlugIns();
389 #if ENABLE(ARCHIVE) // ANDROID extension: disabled to reduce code size
390     clearArchiveResources();
391 #endif
392 }
393 
updateLoading()394 void DocumentLoader::updateLoading()
395 {
396     if (!m_frame) {
397         setLoading(false);
398         return;
399     }
400     ASSERT(this == frameLoader()->activeDocumentLoader());
401     setLoading(frameLoader()->isLoading());
402 }
403 
setFrame(Frame * frame)404 void DocumentLoader::setFrame(Frame* frame)
405 {
406     if (m_frame == frame)
407         return;
408     ASSERT(frame && !m_frame);
409     m_frame = frame;
410     attachToFrame();
411 }
412 
attachToFrame()413 void DocumentLoader::attachToFrame()
414 {
415     ASSERT(m_frame);
416 }
417 
detachFromFrame()418 void DocumentLoader::detachFromFrame()
419 {
420     ASSERT(m_frame);
421 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
422     m_applicationCacheHost->setDOMApplicationCache(0);
423 #endif
424     m_frame = 0;
425 }
426 
prepareForLoadStart()427 void DocumentLoader::prepareForLoadStart()
428 {
429     ASSERT(!m_isStopping);
430     setPrimaryLoadComplete(false);
431     ASSERT(frameLoader());
432     clearErrors();
433 
434     setLoading(true);
435 
436     frameLoader()->prepareForLoadStart();
437 }
438 
setPrimaryLoadComplete(bool flag)439 void DocumentLoader::setPrimaryLoadComplete(bool flag)
440 {
441     m_primaryLoadComplete = flag;
442     if (flag) {
443         if (m_mainResourceLoader) {
444             m_mainResourceData = m_mainResourceLoader->resourceData();
445             m_mainResourceLoader = 0;
446         }
447 
448         if (this == frameLoader()->activeDocumentLoader())
449             updateLoading();
450     }
451 }
452 
isLoadingInAPISense() const453 bool DocumentLoader::isLoadingInAPISense() const
454 {
455     // Once a frame has loaded, we no longer need to consider subresources,
456     // but we still need to consider subframes.
457     if (frameLoader()->state() != FrameStateComplete) {
458         if (!m_primaryLoadComplete && isLoading())
459             return true;
460         if (!m_subresourceLoaders.isEmpty())
461             return true;
462         Document* doc = m_frame->document();
463         if (doc->docLoader()->requestCount())
464             return true;
465         if (Tokenizer* tok = doc->tokenizer())
466             if (tok->processingData())
467                 return true;
468     }
469     return frameLoader()->subframeIsLoading();
470 }
471 
472 #if ENABLE(ARCHIVE) // ANDROID extension: disabled to reduce code size
addAllArchiveResources(Archive * archive)473 void DocumentLoader::addAllArchiveResources(Archive* archive)
474 {
475     if (!m_archiveResourceCollection)
476         m_archiveResourceCollection.set(new ArchiveResourceCollection);
477 
478     ASSERT(archive);
479     if (!archive)
480         return;
481 
482     m_archiveResourceCollection->addAllResources(archive);
483 }
484 
485 // FIXME: Adding a resource directly to a DocumentLoader/ArchiveResourceCollection seems like bad design, but is API some apps rely on.
486 // Can we change the design in a manner that will let us deprecate that API without reducing functionality of those apps?
addArchiveResource(PassRefPtr<ArchiveResource> resource)487 void DocumentLoader::addArchiveResource(PassRefPtr<ArchiveResource> resource)
488 {
489     if (!m_archiveResourceCollection)
490         m_archiveResourceCollection.set(new ArchiveResourceCollection);
491 
492     ASSERT(resource);
493     if (!resource)
494         return;
495 
496     m_archiveResourceCollection->addResource(resource);
497 }
498 
archiveResourceForURL(const KURL & url) const499 ArchiveResource* DocumentLoader::archiveResourceForURL(const KURL& url) const
500 {
501     if (!m_archiveResourceCollection)
502         return 0;
503 
504     ArchiveResource* resource = m_archiveResourceCollection->archiveResourceForURL(url);
505 
506     return resource && !resource->shouldIgnoreWhenUnarchiving() ? resource : 0;
507 }
508 
popArchiveForSubframe(const String & frameName)509 PassRefPtr<Archive> DocumentLoader::popArchiveForSubframe(const String& frameName)
510 {
511     return m_archiveResourceCollection ? m_archiveResourceCollection->popSubframeArchive(frameName) : 0;
512 }
513 
clearArchiveResources()514 void DocumentLoader::clearArchiveResources()
515 {
516     m_archiveResourceCollection.clear();
517     m_substituteResourceDeliveryTimer.stop();
518 }
519 
setParsedArchiveData(PassRefPtr<SharedBuffer> data)520 void DocumentLoader::setParsedArchiveData(PassRefPtr<SharedBuffer> data)
521 {
522     m_parsedArchiveData = data;
523 }
524 
parsedArchiveData() const525 SharedBuffer* DocumentLoader::parsedArchiveData() const
526 {
527     return m_parsedArchiveData.get();
528 }
529 
mainResource() const530 PassRefPtr<ArchiveResource> DocumentLoader::mainResource() const
531 {
532     const ResourceResponse& r = response();
533     RefPtr<SharedBuffer> mainResourceBuffer = mainResourceData();
534     if (!mainResourceBuffer)
535         mainResourceBuffer = SharedBuffer::create();
536 
537     return ArchiveResource::create(mainResourceBuffer, r.url(), r.mimeType(), r.textEncodingName(), frame()->tree()->name());
538 }
539 
subresource(const KURL & url) const540 PassRefPtr<ArchiveResource> DocumentLoader::subresource(const KURL& url) const
541 {
542     if (!isCommitted())
543         return 0;
544 
545     CachedResource* resource = m_frame->document()->docLoader()->cachedResource(url);
546     if (!resource || !resource->isLoaded())
547         return archiveResourceForURL(url);
548 
549     // FIXME: This has the side effect of making the resource non-purgeable.
550     // It would be better if it didn't have this permanent effect.
551     if (!resource->makePurgeable(false))
552         return 0;
553 
554     RefPtr<SharedBuffer> data = resource->data();
555     if (!data)
556         return 0;
557 
558     return ArchiveResource::create(data.release(), url, resource->response());
559 }
560 
getSubresources(Vector<PassRefPtr<ArchiveResource>> & subresources) const561 void DocumentLoader::getSubresources(Vector<PassRefPtr<ArchiveResource> >& subresources) const
562 {
563     if (!isCommitted())
564         return;
565 
566     Document* document = m_frame->document();
567 
568     const DocLoader::DocumentResourceMap& allResources = document->docLoader()->allCachedResources();
569     DocLoader::DocumentResourceMap::const_iterator end = allResources.end();
570     for (DocLoader::DocumentResourceMap::const_iterator it = allResources.begin(); it != end; ++it) {
571         RefPtr<ArchiveResource> subresource = this->subresource(KURL(it->second->url()));
572         if (subresource)
573             subresources.append(subresource.release());
574     }
575 
576     return;
577 }
578 #endif
579 
deliverSubstituteResourcesAfterDelay()580 void DocumentLoader::deliverSubstituteResourcesAfterDelay()
581 {
582     if (m_pendingSubstituteResources.isEmpty())
583         return;
584     ASSERT(m_frame && m_frame->page());
585     if (m_frame->page()->defersLoading())
586         return;
587     if (!m_substituteResourceDeliveryTimer.isActive())
588         m_substituteResourceDeliveryTimer.startOneShot(0);
589 }
590 
substituteResourceDeliveryTimerFired(Timer<DocumentLoader> *)591 void DocumentLoader::substituteResourceDeliveryTimerFired(Timer<DocumentLoader>*)
592 {
593     if (m_pendingSubstituteResources.isEmpty())
594         return;
595     ASSERT(m_frame && m_frame->page());
596     if (m_frame->page()->defersLoading())
597         return;
598 
599     SubstituteResourceMap copy;
600     copy.swap(m_pendingSubstituteResources);
601 
602     SubstituteResourceMap::const_iterator end = copy.end();
603     for (SubstituteResourceMap::const_iterator it = copy.begin(); it != end; ++it) {
604         RefPtr<ResourceLoader> loader = it->first;
605         SubstituteResource* resource = it->second.get();
606 
607         if (resource) {
608             SharedBuffer* data = resource->data();
609 
610             loader->didReceiveResponse(resource->response());
611             loader->didReceiveData(data->data(), data->size(), data->size(), true);
612             loader->didFinishLoading();
613         } else {
614             // A null resource means that we should fail the load.
615             // FIXME: Maybe we should use another error here - something like "not in cache".
616             loader->didFail(loader->cannotShowURLError());
617         }
618     }
619 }
620 
621 #ifndef NDEBUG
isSubstituteLoadPending(ResourceLoader * loader) const622 bool DocumentLoader::isSubstituteLoadPending(ResourceLoader* loader) const
623 {
624     return m_pendingSubstituteResources.contains(loader);
625 }
626 #endif
627 
cancelPendingSubstituteLoad(ResourceLoader * loader)628 void DocumentLoader::cancelPendingSubstituteLoad(ResourceLoader* loader)
629 {
630     if (m_pendingSubstituteResources.isEmpty())
631         return;
632     m_pendingSubstituteResources.remove(loader);
633     if (m_pendingSubstituteResources.isEmpty())
634         m_substituteResourceDeliveryTimer.stop();
635 }
636 
637 #if ENABLE(ARCHIVE) // ANDROID extension: disabled to reduce code size
scheduleArchiveLoad(ResourceLoader * loader,const ResourceRequest & request,const KURL & originalURL)638 bool DocumentLoader::scheduleArchiveLoad(ResourceLoader* loader, const ResourceRequest& request, const KURL& originalURL)
639 {
640     ArchiveResource* resource = 0;
641 
642     if (request.url() == originalURL)
643         resource = archiveResourceForURL(originalURL);
644 
645     if (!resource) {
646         // WebArchiveDebugMode means we fail loads instead of trying to fetch them from the network if they're not in the archive.
647         bool shouldFailLoad = m_frame->settings()->webArchiveDebugModeEnabled() && ArchiveFactory::isArchiveMimeType(responseMIMEType());
648 
649         if (!shouldFailLoad)
650             return false;
651     }
652 
653     m_pendingSubstituteResources.set(loader, resource);
654     deliverSubstituteResourcesAfterDelay();
655 
656     return true;
657 }
658 #endif
659 
addResponse(const ResourceResponse & r)660 void DocumentLoader::addResponse(const ResourceResponse& r)
661 {
662     if (!m_stopRecordingResponses)
663         m_responses.append(r);
664 }
665 
stopRecordingResponses()666 void DocumentLoader::stopRecordingResponses()
667 {
668     m_stopRecordingResponses = true;
669 }
670 
setTitle(const String & title)671 void DocumentLoader::setTitle(const String& title)
672 {
673     if (title.isEmpty())
674         return;
675 
676     String trimmed = canonicalizedTitle(title, m_frame);
677     if (!trimmed.isEmpty() && m_pageTitle != trimmed) {
678         frameLoader()->willChangeTitle(this);
679         m_pageTitle = trimmed;
680         frameLoader()->didChangeTitle(this);
681     }
682 }
683 
urlForHistory() const684 KURL DocumentLoader::urlForHistory() const
685 {
686     // Return the URL to be used for history and B/F list.
687     // Returns nil for WebDataProtocol URLs that aren't alternates
688     // for unreachable URLs, because these can't be stored in history.
689     if (m_substituteData.isValid())
690         return unreachableURL();
691 
692     return m_originalRequestCopy.url();
693 }
694 
urlForHistoryReflectsFailure() const695 bool DocumentLoader::urlForHistoryReflectsFailure() const
696 {
697     return m_substituteData.isValid() || m_response.httpStatusCode() >= 400;
698 }
699 
loadFromCachedPage(PassRefPtr<CachedPage> cachedPage)700 void DocumentLoader::loadFromCachedPage(PassRefPtr<CachedPage> cachedPage)
701 {
702     LOG(PageCache, "WebCorePageCache: DocumentLoader %p loading from cached page %p", this, cachedPage.get());
703 
704     prepareForLoadStart();
705     setLoadingFromCachedPage(true);
706     setCommitted(true);
707     frameLoader()->commitProvisionalLoad(cachedPage);
708 }
709 
originalURL() const710 const KURL& DocumentLoader::originalURL() const
711 {
712     return m_originalRequestCopy.url();
713 }
714 
requestURL() const715 const KURL& DocumentLoader::requestURL() const
716 {
717     return request().url();
718 }
719 
responseURL() const720 const KURL& DocumentLoader::responseURL() const
721 {
722     return m_response.url();
723 }
724 
responseMIMEType() const725 const String& DocumentLoader::responseMIMEType() const
726 {
727     return m_response.mimeType();
728 }
729 
unreachableURL() const730 const KURL& DocumentLoader::unreachableURL() const
731 {
732     return m_substituteData.failingURL();
733 }
734 
setDefersLoading(bool defers)735 void DocumentLoader::setDefersLoading(bool defers)
736 {
737     if (m_mainResourceLoader)
738         m_mainResourceLoader->setDefersLoading(defers);
739     setAllDefersLoading(m_subresourceLoaders, defers);
740     setAllDefersLoading(m_plugInStreamLoaders, defers);
741     if (!defers)
742         deliverSubstituteResourcesAfterDelay();
743 }
744 
stopLoadingPlugIns()745 void DocumentLoader::stopLoadingPlugIns()
746 {
747     cancelAll(m_plugInStreamLoaders);
748 }
749 
stopLoadingSubresources()750 void DocumentLoader::stopLoadingSubresources()
751 {
752     cancelAll(m_subresourceLoaders);
753 }
754 
addSubresourceLoader(ResourceLoader * loader)755 void DocumentLoader::addSubresourceLoader(ResourceLoader* loader)
756 {
757     m_subresourceLoaders.add(loader);
758     setLoading(true);
759 }
760 
removeSubresourceLoader(ResourceLoader * loader)761 void DocumentLoader::removeSubresourceLoader(ResourceLoader* loader)
762 {
763     m_subresourceLoaders.remove(loader);
764     updateLoading();
765     if (Frame* frame = m_frame)
766         frame->loader()->checkLoadComplete();
767 }
768 
addPlugInStreamLoader(ResourceLoader * loader)769 void DocumentLoader::addPlugInStreamLoader(ResourceLoader* loader)
770 {
771     m_plugInStreamLoaders.add(loader);
772     setLoading(true);
773 }
774 
removePlugInStreamLoader(ResourceLoader * loader)775 void DocumentLoader::removePlugInStreamLoader(ResourceLoader* loader)
776 {
777     m_plugInStreamLoaders.remove(loader);
778     updateLoading();
779 }
780 
isLoadingMainResource() const781 bool DocumentLoader::isLoadingMainResource() const
782 {
783     return !!m_mainResourceLoader;
784 }
785 
isLoadingSubresources() const786 bool DocumentLoader::isLoadingSubresources() const
787 {
788     return !m_subresourceLoaders.isEmpty();
789 }
790 
isLoadingPlugIns() const791 bool DocumentLoader::isLoadingPlugIns() const
792 {
793     return !m_plugInStreamLoaders.isEmpty();
794 }
795 
isLoadingMultipartContent() const796 bool DocumentLoader::isLoadingMultipartContent() const
797 {
798     return m_mainResourceLoader && m_mainResourceLoader->isLoadingMultipartContent();
799 }
800 
startLoadingMainResource(unsigned long identifier)801 bool DocumentLoader::startLoadingMainResource(unsigned long identifier)
802 {
803     ASSERT(!m_mainResourceLoader);
804     m_mainResourceLoader = MainResourceLoader::create(m_frame);
805     m_mainResourceLoader->setIdentifier(identifier);
806 
807     // FIXME: Is there any way the extra fields could have not been added by now?
808     // If not, it would be great to remove this line of code.
809     frameLoader()->addExtraFieldsToMainResourceRequest(m_request);
810 
811     if (!m_mainResourceLoader->load(m_request, m_substituteData)) {
812         // FIXME: If this should really be caught, we should just ASSERT this doesn't happen;
813         // should it be caught by other parts of WebKit or other parts of the app?
814         LOG_ERROR("could not create WebResourceHandle for URL %s -- should be caught by policy handler level", m_request.url().string().ascii().data());
815         m_mainResourceLoader = 0;
816         return false;
817     }
818 
819     return true;
820 }
821 
cancelMainResourceLoad(const ResourceError & error)822 void DocumentLoader::cancelMainResourceLoad(const ResourceError& error)
823 {
824     m_mainResourceLoader->cancel(error);
825 }
826 
subresourceLoaderFinishedLoadingOnePart(ResourceLoader * loader)827 void DocumentLoader::subresourceLoaderFinishedLoadingOnePart(ResourceLoader* loader)
828 {
829     m_multipartSubresourceLoaders.add(loader);
830     m_subresourceLoaders.remove(loader);
831     updateLoading();
832     if (Frame* frame = m_frame)
833         frame->loader()->checkLoadComplete();
834 }
835 
iconLoadDecisionAvailable()836 void DocumentLoader::iconLoadDecisionAvailable()
837 {
838     if (m_frame)
839         m_frame->loader()->iconLoadDecisionAvailable();
840 }
841 
842 }
843