initial import
[vuplus_webkit] / Source / WebCore / loader / ResourceLoader.cpp
1 /*
2  * Copyright (C) 2006, 2007, 2010, 2011 Apple Inc. All rights reserved.
3  *           (C) 2007 Graham Dennis (graham.dennis@gmail.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 "ResourceLoader.h"
32
33 #include "ApplicationCacheHost.h"
34 #include "DocumentLoader.h"
35 #include "FileStreamProxy.h"
36 #include "Frame.h"
37 #include "FrameLoader.h"
38 #include "FrameLoaderClient.h"
39 #include "InspectorInstrumentation.h"
40 #include "Page.h"
41 #include "ProgressTracker.h"
42 #include "ResourceError.h"
43 #include "ResourceHandle.h"
44 #include "ResourceLoadScheduler.h"
45 #include "Settings.h"
46 #include "SharedBuffer.h"
47
48 namespace WebCore {
49
50 PassRefPtr<SharedBuffer> ResourceLoader::resourceData()
51 {
52     return m_resourceData;
53 }
54
55 ResourceLoader::ResourceLoader(Frame* frame, ResourceLoaderOptions options)
56     : m_frame(frame)
57     , m_documentLoader(frame->loader()->activeDocumentLoader())
58     , m_identifier(0)
59     , m_reachedTerminalState(false)
60     , m_calledWillCancel(false)
61     , m_cancelled(false)
62     , m_calledDidFinishLoad(false)
63     , m_defersLoading(frame->page()->defersLoading())
64     , m_options(options)
65 {
66 }
67
68 ResourceLoader::~ResourceLoader()
69 {
70     ASSERT(m_reachedTerminalState);
71 }
72
73 void ResourceLoader::releaseResources()
74 {
75     ASSERT(!m_reachedTerminalState);
76     
77     // It's possible that when we release the handle, it will be
78     // deallocated and release the last reference to this object.
79     // We need to retain to avoid accessing the object after it
80     // has been deallocated and also to avoid reentering this method.
81     RefPtr<ResourceLoader> protector(this);
82
83     m_frame = 0;
84     m_documentLoader = 0;
85     
86     // We need to set reachedTerminalState to true before we release
87     // the resources to prevent a double dealloc of WebView <rdar://problem/4372628>
88     m_reachedTerminalState = true;
89
90     m_identifier = 0;
91
92     resourceLoadScheduler()->remove(this);
93
94     if (m_handle) {
95         // Clear out the ResourceHandle's client so that it doesn't try to call
96         // us back after we release it, unless it has been replaced by someone else.
97         if (m_handle->client() == this)
98             m_handle->setClient(0);
99         m_handle = 0;
100     }
101
102     m_resourceData = 0;
103     m_deferredRequest = ResourceRequest();
104 }
105
106 bool ResourceLoader::init(const ResourceRequest& r)
107 {
108     ASSERT(!m_handle);
109     ASSERT(m_request.isNull());
110     ASSERT(m_deferredRequest.isNull());
111     ASSERT(!m_documentLoader->isSubstituteLoadPending(this));
112     
113     ResourceRequest clientRequest(r);
114     
115     // https://bugs.webkit.org/show_bug.cgi?id=26391
116     // The various plug-in implementations call directly to ResourceLoader::load() instead of piping requests
117     // through FrameLoader. As a result, they miss the FrameLoader::addExtraFieldsToRequest() step which sets
118     // up the 1st party for cookies URL. Until plug-in implementations can be reigned in to pipe through that
119     // method, we need to make sure there is always a 1st party for cookies set.
120     if (clientRequest.firstPartyForCookies().isNull()) {
121         if (Document* document = m_frame->document())
122             clientRequest.setFirstPartyForCookies(document->firstPartyForCookies());
123     }
124
125     willSendRequest(clientRequest, ResourceResponse());
126     if (clientRequest.isNull()) {
127         didFail(cancelledError());
128         return false;
129     }
130
131     m_originalRequest = m_request = clientRequest;
132     return true;
133 }
134
135 void ResourceLoader::start()
136 {
137     ASSERT(!m_handle);
138     ASSERT(!m_request.isNull());
139     ASSERT(m_deferredRequest.isNull());
140
141 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
142     if (m_documentLoader->scheduleArchiveLoad(this, m_request, m_request.url()))
143         return;
144 #endif
145     
146 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
147     if (m_documentLoader->applicationCacheHost()->maybeLoadResource(this, m_request, m_request.url()))
148         return;
149 #endif
150
151     if (m_defersLoading) {
152         m_deferredRequest = m_request;
153         return;
154     }
155
156     if (!m_reachedTerminalState)
157         m_handle = ResourceHandle::create(m_frame->loader()->networkingContext(), m_request, this, m_defersLoading, m_options.sniffContent == SniffContent);
158 }
159
160 void ResourceLoader::setDefersLoading(bool defers)
161 {
162     m_defersLoading = defers;
163     if (m_handle)
164         m_handle->setDefersLoading(defers);
165     if (!defers && !m_deferredRequest.isNull()) {
166         m_request = m_deferredRequest;
167         m_deferredRequest = ResourceRequest();
168         start();
169     }
170 }
171
172 FrameLoader* ResourceLoader::frameLoader() const
173 {
174     if (!m_frame)
175         return 0;
176     return m_frame->loader();
177 }
178
179 void ResourceLoader::setShouldBufferData(DataBufferingPolicy shouldBufferData)
180
181     m_options.shouldBufferData = shouldBufferData; 
182
183     // Reset any already buffered data
184     if (!shouldBufferData)
185         m_resourceData = 0;
186 }
187     
188
189 void ResourceLoader::addData(const char* data, int length, bool allAtOnce)
190 {
191     if (m_options.shouldBufferData == DoNotBufferData)
192         return;
193
194     if (allAtOnce) {
195         m_resourceData = SharedBuffer::create(data, length);
196         return;
197     }
198         
199     if (!m_resourceData)
200         m_resourceData = SharedBuffer::create(data, length);
201     else
202         m_resourceData->append(data, length);
203 }
204
205 void ResourceLoader::clearResourceData()
206 {
207     if (m_resourceData)
208         m_resourceData->clear();
209 }
210
211 void ResourceLoader::willSendRequest(ResourceRequest& request, const ResourceResponse& redirectResponse)
212 {
213 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
214     if (!fastMallocSize(documentLoader()->applicationCacheHost()))
215         CRASH();
216 #endif
217     if (!fastMallocSize(documentLoader()->frame()))
218         CRASH();
219     // Protect this in this delegate method since the additional processing can do
220     // anything including possibly derefing this; one example of this is Radar 3266216.
221     RefPtr<ResourceLoader> protector(this);
222
223     ASSERT(!m_reachedTerminalState);
224
225     if (m_options.sendLoadCallbacks == SendCallbacks) {
226         if (!m_identifier) {
227             m_identifier = m_frame->page()->progress()->createUniqueIdentifier();
228             frameLoader()->notifier()->assignIdentifierToInitialRequest(m_identifier, documentLoader(), request);
229         }
230
231         frameLoader()->notifier()->willSendRequest(this, request, redirectResponse);
232     }
233
234     if (!redirectResponse.isNull())
235         resourceLoadScheduler()->crossOriginRedirectReceived(this, request.url());
236     m_request = request;
237 }
238
239 void ResourceLoader::didSendData(unsigned long long, unsigned long long)
240 {
241 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
242     if (!fastMallocSize(documentLoader()->applicationCacheHost()))
243         CRASH();
244 #endif
245     if (!fastMallocSize(documentLoader()->frame()))
246         CRASH();
247 }
248
249 void ResourceLoader::didReceiveResponse(const ResourceResponse& r)
250 {
251 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
252     if (!fastMallocSize(documentLoader()->applicationCacheHost()))
253         CRASH();
254 #endif
255     if (!fastMallocSize(documentLoader()->frame()))
256         CRASH();
257     ASSERT(!m_reachedTerminalState);
258
259     // Protect this in this delegate method since the additional processing can do
260     // anything including possibly derefing this; one example of this is Radar 3266216.
261     RefPtr<ResourceLoader> protector(this);
262
263     m_response = r;
264
265     if (FormData* data = m_request.httpBody())
266         data->removeGeneratedFilesIfNeeded();
267         
268     if (m_options.sendLoadCallbacks == SendCallbacks)
269         frameLoader()->notifier()->didReceiveResponse(this, m_response);
270 }
271
272 void ResourceLoader::didReceiveData(const char* data, int length, long long encodedDataLength, bool allAtOnce)
273 {
274 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
275     if (!m_cancelled && !fastMallocSize(documentLoader()->applicationCacheHost()))
276         CRASH();
277 #endif
278     if (!m_cancelled && !fastMallocSize(documentLoader()->frame()))
279         CRASH();
280     // The following assertions are not quite valid here, since a subclass
281     // might override didReceiveData in a way that invalidates them. This
282     // happens with the steps listed in 3266216
283     // ASSERT(con == connection);
284     // ASSERT(!m_reachedTerminalState);
285
286     // Protect this in this delegate method since the additional processing can do
287     // anything including possibly derefing this; one example of this is Radar 3266216.
288     RefPtr<ResourceLoader> protector(this);
289
290     addData(data, length, allAtOnce);
291     // FIXME: If we get a resource with more than 2B bytes, this code won't do the right thing.
292     // However, with today's computers and networking speeds, this won't happen in practice.
293     // Could be an issue with a giant local file.
294     if (m_options.sendLoadCallbacks == SendCallbacks && m_frame)
295         frameLoader()->notifier()->didReceiveData(this, data, length, static_cast<int>(encodedDataLength));
296 }
297
298 void ResourceLoader::willStopBufferingData(const char* data, int length)
299 {
300     if (m_options.shouldBufferData == DoNotBufferData)
301         return;
302
303     ASSERT(!m_resourceData);
304     m_resourceData = SharedBuffer::create(data, length);
305 }
306
307 void ResourceLoader::didFinishLoading(double finishTime)
308 {
309     // If load has been cancelled after finishing (which could happen with a 
310     // JavaScript that changes the window location), do nothing.
311     if (m_cancelled)
312         return;
313     ASSERT(!m_reachedTerminalState);
314
315     didFinishLoadingOnePart(finishTime);
316     releaseResources();
317 }
318
319 void ResourceLoader::didFinishLoadingOnePart(double finishTime)
320 {
321     if (m_cancelled)
322         return;
323     ASSERT(!m_reachedTerminalState);
324
325     if (m_calledDidFinishLoad)
326         return;
327     m_calledDidFinishLoad = true;
328     if (m_options.sendLoadCallbacks == SendCallbacks)
329         frameLoader()->notifier()->didFinishLoad(this, finishTime);
330 }
331
332 void ResourceLoader::didFail(const ResourceError& error)
333 {
334     if (m_cancelled)
335         return;
336     ASSERT(!m_reachedTerminalState);
337
338     // Protect this in this delegate method since the additional processing can do
339     // anything including possibly derefing this; one example of this is Radar 3266216.
340     RefPtr<ResourceLoader> protector(this);
341
342     if (FormData* data = m_request.httpBody())
343         data->removeGeneratedFilesIfNeeded();
344
345     if (m_options.sendLoadCallbacks == SendCallbacks && !m_calledDidFinishLoad)
346         frameLoader()->notifier()->didFailToLoad(this, error);
347
348     releaseResources();
349 }
350
351 void ResourceLoader::cancel()
352 {
353     cancel(ResourceError());
354 }
355
356 void ResourceLoader::cancel(const ResourceError& error)
357 {
358     // If the load has already completed - succeeded, failed, or previously cancelled - do nothing.
359     if (m_reachedTerminalState)
360         return;
361        
362     ResourceError nonNullError = error.isNull() ? cancelledError() : error;
363     
364     // willCancel() and didFailToLoad() both call out to clients that might do 
365     // something causing the last reference to this object to go away.
366     RefPtr<ResourceLoader> protector(this);
367     
368     // If we re-enter cancel() from inside willCancel(), we want to pick up from where we left 
369     // off without re-running willCancel()
370     if (!m_calledWillCancel) {
371         m_calledWillCancel = true;
372         
373         willCancel(nonNullError);
374     }
375
376     // If we re-enter cancel() from inside didFailToLoad(), we want to pick up from where we 
377     // left off without redoing any of this work.
378     if (!m_cancelled) {
379         m_cancelled = true;
380         
381         if (FormData* data = m_request.httpBody())
382             data->removeGeneratedFilesIfNeeded();
383
384         if (m_handle)
385             m_handle->clearAuthentication();
386
387         m_documentLoader->cancelPendingSubstituteLoad(this);
388         if (m_handle) {
389             m_handle->cancel();
390             m_handle = 0;
391         }
392
393         if (m_options.sendLoadCallbacks == SendCallbacks && m_identifier && !m_calledDidFinishLoad)
394             frameLoader()->notifier()->didFailToLoad(this, nonNullError);
395     }
396
397     // If cancel() completed from within the call to willCancel() or didFailToLoad(),
398     // we don't want to redo didCancel() or releasesResources().
399     if (m_reachedTerminalState)
400         return;
401
402     didCancel(nonNullError);
403             
404     releaseResources();
405 }
406
407 ResourceError ResourceLoader::cancelledError()
408 {
409     return frameLoader()->cancelledError(m_request);
410 }
411
412 ResourceError ResourceLoader::blockedError()
413 {
414     return frameLoader()->client()->blockedError(m_request);
415 }
416
417 ResourceError ResourceLoader::cannotShowURLError()
418 {
419     return frameLoader()->client()->cannotShowURLError(m_request);
420 }
421
422 void ResourceLoader::willSendRequest(ResourceHandle*, ResourceRequest& request, const ResourceResponse& redirectResponse)
423 {
424 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
425     if (documentLoader()->applicationCacheHost()->maybeLoadFallbackForRedirect(this, request, redirectResponse))
426         return;
427 #endif
428     willSendRequest(request, redirectResponse);
429 }
430
431 void ResourceLoader::didSendData(ResourceHandle*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
432 {
433     didSendData(bytesSent, totalBytesToBeSent);
434 }
435
436 void ResourceLoader::didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
437 {
438 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
439     if (documentLoader()->applicationCacheHost()->maybeLoadFallbackForResponse(this, response))
440         return;
441 #endif
442     didReceiveResponse(response);
443 }
444
445 void ResourceLoader::didReceiveData(ResourceHandle*, const char* data, int length, int encodedDataLength)
446 {
447     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceData(m_frame.get(), identifier());
448     didReceiveData(data, length, encodedDataLength, false);
449     InspectorInstrumentation::didReceiveResourceData(cookie);
450 }
451
452 void ResourceLoader::didFinishLoading(ResourceHandle*, double finishTime)
453 {
454 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
455     if (!fastMallocSize(documentLoader()->applicationCacheHost()))
456         CRASH();
457 #endif
458     if (!fastMallocSize(documentLoader()->frame()))
459         CRASH();
460     didFinishLoading(finishTime);
461 }
462
463 void ResourceLoader::didFail(ResourceHandle*, const ResourceError& error)
464 {
465 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
466     if (!fastMallocSize(documentLoader()->applicationCacheHost()))
467         CRASH();
468 #endif
469     if (!fastMallocSize(documentLoader()->frame()))
470         CRASH();
471 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
472     if (documentLoader()->applicationCacheHost()->maybeLoadFallbackForError(this, error))
473         return;
474 #endif
475     didFail(error);
476 }
477
478 void ResourceLoader::wasBlocked(ResourceHandle*)
479 {
480 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
481     if (!fastMallocSize(documentLoader()->applicationCacheHost()))
482         CRASH();
483 #endif
484     if (!fastMallocSize(documentLoader()->frame()))
485         CRASH();
486     didFail(blockedError());
487 }
488
489 void ResourceLoader::cannotShowURL(ResourceHandle*)
490 {
491 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
492     if (!fastMallocSize(documentLoader()->applicationCacheHost()))
493         CRASH();
494 #endif
495     if (!fastMallocSize(documentLoader()->frame()))
496         CRASH();
497     didFail(cannotShowURLError());
498 }
499
500 bool ResourceLoader::shouldUseCredentialStorage()
501 {
502 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
503     if (!fastMallocSize(documentLoader()->applicationCacheHost()))
504         CRASH();
505 #endif
506     if (!fastMallocSize(documentLoader()->frame()))
507         CRASH();
508
509     if (m_options.allowCredentials == DoNotAllowStoredCredentials)
510         return false;
511     
512     RefPtr<ResourceLoader> protector(this);
513     return frameLoader()->client()->shouldUseCredentialStorage(documentLoader(), identifier());
514 }
515
516 void ResourceLoader::didReceiveAuthenticationChallenge(const AuthenticationChallenge& challenge)
517 {
518     // Protect this in this delegate method since the additional processing can do
519     // anything including possibly derefing this; one example of this is Radar 3266216.
520     RefPtr<ResourceLoader> protector(this);
521     frameLoader()->notifier()->didReceiveAuthenticationChallenge(this, challenge);
522 }
523
524 void ResourceLoader::didCancelAuthenticationChallenge(const AuthenticationChallenge& challenge)
525 {
526     // Protect this in this delegate method since the additional processing can do
527     // anything including possibly derefing this; one example of this is Radar 3266216.
528     RefPtr<ResourceLoader> protector(this);
529     frameLoader()->notifier()->didCancelAuthenticationChallenge(this, challenge);
530 }
531
532 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
533 bool ResourceLoader::canAuthenticateAgainstProtectionSpace(const ProtectionSpace& protectionSpace)
534 {
535     RefPtr<ResourceLoader> protector(this);
536     return frameLoader()->client()->canAuthenticateAgainstProtectionSpace(documentLoader(), identifier(), protectionSpace);
537 }
538 #endif
539
540 void ResourceLoader::receivedCancellation(const AuthenticationChallenge&)
541 {
542     cancel();
543 }
544
545 void ResourceLoader::willCacheResponse(ResourceHandle*, CacheStoragePolicy& policy)
546 {
547 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
548     if (!fastMallocSize(documentLoader()->applicationCacheHost()))
549         CRASH();
550 #endif
551     if (!fastMallocSize(documentLoader()->frame()))
552         CRASH();
553     // <rdar://problem/7249553> - There are reports of crashes with this method being called
554     // with a null m_frame->settings(), which can only happen if the frame doesn't have a page.
555     // Sadly we have no reproducible cases of this.
556     // We think that any frame without a page shouldn't have any loads happening in it, yet
557     // there is at least one code path where that is not true.
558     ASSERT(m_frame->settings());
559     
560     // When in private browsing mode, prevent caching to disk
561     if (policy == StorageAllowed && m_frame->settings() && m_frame->settings()->privateBrowsingEnabled())
562         policy = StorageAllowedInMemoryOnly;    
563 }
564
565 #if ENABLE(BLOB)
566 AsyncFileStream* ResourceLoader::createAsyncFileStream(FileStreamClient* client)
567 {
568     // It is OK to simply return a pointer since FileStreamProxy::create adds an extra ref.
569     return FileStreamProxy::create(m_frame->document()->scriptExecutionContext(), client).get();
570 }
571 #endif
572
573 }