1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // File method ordering: Methods in this file are in the same order as
6 // in download_item_impl.h, with the following exception: The public
7 // interface Start is placed in chronological order with the other
8 // (private) routines that together define a DownloadItem's state
9 // transitions as the download progresses. See "Download progression
10 // cascade" later in this file.
12 // A regular DownloadItem (created for a download in this session of the
13 // browser) normally goes through the following states:
14 // * Created (when download starts)
15 // * Destination filename determined
16 // * Entered into the history database.
17 // * Made visible in the download shelf.
18 // * All the data is saved. Note that the actual data download occurs
19 // in parallel with the above steps, but until those steps are
20 // complete, the state of the data save will be ignored.
21 // * Download file is renamed to its final name, and possibly
24 #include "content/browser/download/download_item_impl.h"
28 #include "base/basictypes.h"
29 #include "base/bind.h"
30 #include "base/command_line.h"
31 #include "base/files/file_util.h"
32 #include "base/format_macros.h"
33 #include "base/logging.h"
34 #include "base/metrics/histogram.h"
35 #include "base/stl_util.h"
36 #include "base/strings/stringprintf.h"
37 #include "base/strings/utf_string_conversions.h"
38 #include "content/browser/download/download_create_info.h"
39 #include "content/browser/download/download_file.h"
40 #include "content/browser/download/download_interrupt_reasons_impl.h"
41 #include "content/browser/download/download_item_impl_delegate.h"
42 #include "content/browser/download/download_request_handle.h"
43 #include "content/browser/download/download_stats.h"
44 #include "content/browser/renderer_host/render_view_host_impl.h"
45 #include "content/browser/web_contents/web_contents_impl.h"
46 #include "content/public/browser/browser_context.h"
47 #include "content/public/browser/browser_thread.h"
48 #include "content/public/browser/content_browser_client.h"
49 #include "content/public/browser/download_danger_type.h"
50 #include "content/public/browser/download_interrupt_reasons.h"
51 #include "content/public/browser/download_url_parameters.h"
52 #include "content/public/common/content_switches.h"
53 #include "content/public/common/referrer.h"
54 #include "net/base/net_util.h"
60 bool DeleteDownloadedFile(const base::FilePath
& path
) {
61 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
63 // Make sure we only delete files.
64 if (base::DirectoryExists(path
))
66 return base::DeleteFile(path
, false);
69 void DeleteDownloadedFileDone(
70 base::WeakPtr
<DownloadItemImpl
> item
,
71 const base::Callback
<void(bool)>& callback
,
73 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
74 if (success
&& item
.get())
75 item
->OnDownloadedFileRemoved();
76 callback
.Run(success
);
79 // Wrapper around DownloadFile::Detach and DownloadFile::Cancel that
80 // takes ownership of the DownloadFile and hence implicitly destroys it
81 // at the end of the function.
82 static base::FilePath
DownloadFileDetach(
83 scoped_ptr
<DownloadFile
> download_file
) {
84 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
85 base::FilePath full_path
= download_file
->FullPath();
86 download_file
->Detach();
90 static void DownloadFileCancel(scoped_ptr
<DownloadFile
> download_file
) {
91 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
92 download_file
->Cancel();
95 bool IsDownloadResumptionEnabled() {
96 return base::CommandLine::ForCurrentProcess()->HasSwitch(
97 switches::kEnableDownloadResumption
);
102 const uint32
DownloadItem::kInvalidId
= 0;
104 const char DownloadItem::kEmptyFileHash
[] = "";
106 // The maximum number of attempts we will make to resume automatically.
107 const int DownloadItemImpl::kMaxAutoResumeAttempts
= 5;
109 // Constructor for reading from the history service.
110 DownloadItemImpl::DownloadItemImpl(DownloadItemImplDelegate
* delegate
,
112 const base::FilePath
& current_path
,
113 const base::FilePath
& target_path
,
114 const std::vector
<GURL
>& url_chain
,
115 const GURL
& referrer_url
,
116 const std::string
& mime_type
,
117 const std::string
& original_mime_type
,
118 const base::Time
& start_time
,
119 const base::Time
& end_time
,
120 const std::string
& etag
,
121 const std::string
& last_modified
,
122 int64 received_bytes
,
124 DownloadItem::DownloadState state
,
125 DownloadDangerType danger_type
,
126 DownloadInterruptReason interrupt_reason
,
128 const net::BoundNetLog
& bound_net_log
)
129 : is_save_package_download_(false),
130 download_id_(download_id
),
131 current_path_(current_path
),
132 target_path_(target_path
),
133 target_disposition_(TARGET_DISPOSITION_OVERWRITE
),
134 url_chain_(url_chain
),
135 referrer_url_(referrer_url
),
136 transition_type_(ui::PAGE_TRANSITION_LINK
),
137 has_user_gesture_(false),
138 mime_type_(mime_type
),
139 original_mime_type_(original_mime_type
),
140 total_bytes_(total_bytes
),
141 received_bytes_(received_bytes
),
143 last_modified_time_(last_modified
),
145 last_reason_(interrupt_reason
),
146 start_tick_(base::TimeTicks()),
147 state_(ExternalToInternalState(state
)),
148 danger_type_(danger_type
),
149 start_time_(start_time
),
153 auto_resume_count_(0),
154 open_when_complete_(false),
155 file_externally_removed_(false),
157 is_temporary_(false),
158 all_data_saved_(state
== COMPLETE
),
159 destination_error_(content::DOWNLOAD_INTERRUPT_REASON_NONE
),
161 delegate_delayed_complete_(false),
162 bound_net_log_(bound_net_log
),
163 weak_ptr_factory_(this) {
165 DCHECK_NE(IN_PROGRESS_INTERNAL
, state_
);
166 Init(false /* not actively downloading */, SRC_HISTORY_IMPORT
);
169 // Constructing for a regular download:
170 DownloadItemImpl::DownloadItemImpl(
171 DownloadItemImplDelegate
* delegate
,
173 const DownloadCreateInfo
& info
,
174 const net::BoundNetLog
& bound_net_log
)
175 : is_save_package_download_(false),
176 download_id_(download_id
),
178 (info
.save_info
->prompt_for_save_location
) ?
179 TARGET_DISPOSITION_PROMPT
: TARGET_DISPOSITION_OVERWRITE
),
180 url_chain_(info
.url_chain
),
181 referrer_url_(info
.referrer_url
),
182 tab_url_(info
.tab_url
),
183 tab_referrer_url_(info
.tab_referrer_url
),
184 suggested_filename_(base::UTF16ToUTF8(info
.save_info
->suggested_name
)),
185 forced_file_path_(info
.save_info
->file_path
),
186 transition_type_(info
.transition_type
),
187 has_user_gesture_(info
.has_user_gesture
),
188 content_disposition_(info
.content_disposition
),
189 mime_type_(info
.mime_type
),
190 original_mime_type_(info
.original_mime_type
),
191 remote_address_(info
.remote_address
),
192 total_bytes_(info
.total_bytes
),
195 last_modified_time_(info
.last_modified
),
197 last_reason_(DOWNLOAD_INTERRUPT_REASON_NONE
),
198 start_tick_(base::TimeTicks::Now()),
199 state_(IN_PROGRESS_INTERNAL
),
200 danger_type_(DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS
),
201 start_time_(info
.start_time
),
204 auto_resume_count_(0),
205 open_when_complete_(false),
206 file_externally_removed_(false),
208 is_temporary_(!info
.save_info
->file_path
.empty()),
209 all_data_saved_(false),
210 destination_error_(content::DOWNLOAD_INTERRUPT_REASON_NONE
),
212 delegate_delayed_complete_(false),
213 bound_net_log_(bound_net_log
),
214 weak_ptr_factory_(this) {
216 Init(true /* actively downloading */, SRC_ACTIVE_DOWNLOAD
);
218 // Link the event sources.
219 bound_net_log_
.AddEvent(
220 net::NetLog::TYPE_DOWNLOAD_URL_REQUEST
,
221 info
.request_bound_net_log
.source().ToEventParametersCallback());
223 info
.request_bound_net_log
.AddEvent(
224 net::NetLog::TYPE_DOWNLOAD_STARTED
,
225 bound_net_log_
.source().ToEventParametersCallback());
228 // Constructing for the "Save Page As..." feature:
229 DownloadItemImpl::DownloadItemImpl(
230 DownloadItemImplDelegate
* delegate
,
232 const base::FilePath
& path
,
234 const std::string
& mime_type
,
235 scoped_ptr
<DownloadRequestHandleInterface
> request_handle
,
236 const net::BoundNetLog
& bound_net_log
)
237 : is_save_package_download_(true),
238 request_handle_(request_handle
.Pass()),
239 download_id_(download_id
),
242 target_disposition_(TARGET_DISPOSITION_OVERWRITE
),
244 referrer_url_(GURL()),
245 transition_type_(ui::PAGE_TRANSITION_LINK
),
246 has_user_gesture_(false),
247 mime_type_(mime_type
),
248 original_mime_type_(mime_type
),
252 last_reason_(DOWNLOAD_INTERRUPT_REASON_NONE
),
253 start_tick_(base::TimeTicks::Now()),
254 state_(IN_PROGRESS_INTERNAL
),
255 danger_type_(DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS
),
256 start_time_(base::Time::Now()),
259 auto_resume_count_(0),
260 open_when_complete_(false),
261 file_externally_removed_(false),
263 is_temporary_(false),
264 all_data_saved_(false),
265 destination_error_(content::DOWNLOAD_INTERRUPT_REASON_NONE
),
267 delegate_delayed_complete_(false),
268 bound_net_log_(bound_net_log
),
269 weak_ptr_factory_(this) {
271 Init(true /* actively downloading */, SRC_SAVE_PAGE_AS
);
274 DownloadItemImpl::~DownloadItemImpl() {
275 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
277 // Should always have been nuked before now, at worst in
278 // DownloadManager shutdown.
279 DCHECK(!download_file_
.get());
281 FOR_EACH_OBSERVER(Observer
, observers_
, OnDownloadDestroyed(this));
282 delegate_
->AssertStateConsistent(this);
286 void DownloadItemImpl::AddObserver(Observer
* observer
) {
287 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
289 observers_
.AddObserver(observer
);
292 void DownloadItemImpl::RemoveObserver(Observer
* observer
) {
293 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
295 observers_
.RemoveObserver(observer
);
298 void DownloadItemImpl::UpdateObservers() {
299 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
301 FOR_EACH_OBSERVER(Observer
, observers_
, OnDownloadUpdated(this));
304 void DownloadItemImpl::ValidateDangerousDownload() {
305 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
307 DCHECK(IsDangerous());
309 DVLOG(20) << __FUNCTION__
<< " download=" << DebugString(true);
311 if (IsDone() || !IsDangerous())
314 RecordDangerousDownloadAccept(GetDangerType(),
315 GetTargetFilePath());
317 danger_type_
= DOWNLOAD_DANGER_TYPE_USER_VALIDATED
;
319 bound_net_log_
.AddEvent(
320 net::NetLog::TYPE_DOWNLOAD_ITEM_SAFETY_STATE_UPDATED
,
321 base::Bind(&ItemCheckedNetLogCallback
, GetDangerType()));
325 MaybeCompleteDownload();
328 void DownloadItemImpl::StealDangerousDownload(
329 const AcquireFileCallback
& callback
) {
330 DVLOG(20) << __FUNCTION__
<< "() download = " << DebugString(true);
331 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
332 DCHECK(IsDangerous());
333 if (download_file_
) {
334 BrowserThread::PostTaskAndReplyWithResult(
337 base::Bind(&DownloadFileDetach
, base::Passed(&download_file_
)),
340 callback
.Run(current_path_
);
342 current_path_
.clear();
344 // We have now been deleted.
347 void DownloadItemImpl::Pause() {
348 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
350 // Ignore irrelevant states.
351 if (state_
!= IN_PROGRESS_INTERNAL
|| is_paused_
)
354 request_handle_
->PauseRequest();
359 void DownloadItemImpl::Resume() {
360 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
362 case IN_PROGRESS_INTERNAL
:
365 request_handle_
->ResumeRequest();
370 case COMPLETING_INTERNAL
:
371 case COMPLETE_INTERNAL
:
372 case CANCELLED_INTERNAL
:
373 case RESUMING_INTERNAL
:
376 case INTERRUPTED_INTERNAL
:
377 auto_resume_count_
= 0; // User input resets the counter.
378 ResumeInterruptedDownload();
381 case MAX_DOWNLOAD_INTERNAL_STATE
:
386 void DownloadItemImpl::Cancel(bool user_cancel
) {
387 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
389 DVLOG(20) << __FUNCTION__
<< "() download = " << DebugString(true);
390 if (state_
!= IN_PROGRESS_INTERNAL
&&
391 state_
!= INTERRUPTED_INTERNAL
&&
392 state_
!= RESUMING_INTERNAL
) {
393 // Small downloads might be complete before this method has a chance to run.
398 RecordDangerousDownloadDiscard(
399 user_cancel
? DOWNLOAD_DISCARD_DUE_TO_USER_ACTION
400 : DOWNLOAD_DISCARD_DUE_TO_SHUTDOWN
,
402 GetTargetFilePath());
405 last_reason_
= user_cancel
? DOWNLOAD_INTERRUPT_REASON_USER_CANCELED
406 : DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN
;
408 RecordDownloadCount(CANCELLED_COUNT
);
410 // TODO(rdsmith/benjhayden): Remove condition as part of
411 // |SavePackage| integration.
412 // |download_file_| can be NULL if Interrupt() is called after the
413 // download file has been released.
414 if (!is_save_package_download_
&& download_file_
)
415 ReleaseDownloadFile(true);
417 if (state_
== IN_PROGRESS_INTERNAL
) {
418 // Cancel the originating URL request unless it's already been cancelled
420 request_handle_
->CancelRequest();
423 // Remove the intermediate file if we are cancelling an interrupted download.
424 // Continuable interruptions leave the intermediate file around.
425 if ((state_
== INTERRUPTED_INTERNAL
|| state_
== RESUMING_INTERNAL
) &&
426 !current_path_
.empty()) {
427 BrowserThread::PostTask(
428 BrowserThread::FILE, FROM_HERE
,
429 base::Bind(base::IgnoreResult(&DeleteDownloadedFile
), current_path_
));
430 current_path_
.clear();
433 TransitionTo(CANCELLED_INTERNAL
, UPDATE_OBSERVERS
);
436 void DownloadItemImpl::Remove() {
437 DVLOG(20) << __FUNCTION__
<< "() download = " << DebugString(true);
438 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
440 delegate_
->AssertStateConsistent(this);
442 delegate_
->AssertStateConsistent(this);
445 delegate_
->DownloadRemoved(this);
446 // We have now been deleted.
449 void DownloadItemImpl::OpenDownload() {
450 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
453 // We don't honor the open_when_complete_ flag for temporary
454 // downloads. Don't set it because it shows up in the UI.
456 open_when_complete_
= !open_when_complete_
;
460 if (state_
!= COMPLETE_INTERNAL
|| file_externally_removed_
)
463 // Ideally, we want to detect errors in opening and report them, but we
464 // don't generally have the proper interface for that to the external
465 // program that opens the file. So instead we spawn a check to update
466 // the UI if the file has been deleted in parallel with the open.
467 delegate_
->CheckForFileRemoval(this);
468 RecordOpen(GetEndTime(), !GetOpened());
470 FOR_EACH_OBSERVER(Observer
, observers_
, OnDownloadOpened(this));
471 delegate_
->OpenDownload(this);
474 void DownloadItemImpl::ShowDownloadInShell() {
475 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
477 delegate_
->ShowDownloadInShell(this);
480 uint32
DownloadItemImpl::GetId() const {
484 DownloadItem::DownloadState
DownloadItemImpl::GetState() const {
485 return InternalToExternalState(state_
);
488 DownloadInterruptReason
DownloadItemImpl::GetLastReason() const {
492 bool DownloadItemImpl::IsPaused() const {
496 bool DownloadItemImpl::IsTemporary() const {
497 return is_temporary_
;
500 bool DownloadItemImpl::CanResume() const {
501 if ((GetState() == IN_PROGRESS
) && IsPaused())
504 if (state_
!= INTERRUPTED_INTERNAL
)
507 // Downloads that don't have a WebContents should still be resumable, but this
508 // isn't currently the case. See ResumeInterruptedDownload().
509 if (!GetWebContents())
512 ResumeMode resume_mode
= GetResumeMode();
513 return IsDownloadResumptionEnabled() &&
514 (resume_mode
== RESUME_MODE_USER_RESTART
||
515 resume_mode
== RESUME_MODE_USER_CONTINUE
);
518 bool DownloadItemImpl::IsDone() const {
520 case IN_PROGRESS_INTERNAL
:
521 case COMPLETING_INTERNAL
:
524 case COMPLETE_INTERNAL
:
525 case CANCELLED_INTERNAL
:
528 case INTERRUPTED_INTERNAL
:
531 case RESUMING_INTERNAL
:
534 case MAX_DOWNLOAD_INTERNAL_STATE
:
541 const GURL
& DownloadItemImpl::GetURL() const {
542 return url_chain_
.empty() ? GURL::EmptyGURL() : url_chain_
.back();
545 const std::vector
<GURL
>& DownloadItemImpl::GetUrlChain() const {
549 const GURL
& DownloadItemImpl::GetOriginalUrl() const {
550 // Be careful about taking the front() of possibly-empty vectors!
551 // http://crbug.com/190096
552 return url_chain_
.empty() ? GURL::EmptyGURL() : url_chain_
.front();
555 const GURL
& DownloadItemImpl::GetReferrerUrl() const {
556 return referrer_url_
;
559 const GURL
& DownloadItemImpl::GetTabUrl() const {
563 const GURL
& DownloadItemImpl::GetTabReferrerUrl() const {
564 return tab_referrer_url_
;
567 std::string
DownloadItemImpl::GetSuggestedFilename() const {
568 return suggested_filename_
;
571 std::string
DownloadItemImpl::GetContentDisposition() const {
572 return content_disposition_
;
575 std::string
DownloadItemImpl::GetMimeType() const {
579 std::string
DownloadItemImpl::GetOriginalMimeType() const {
580 return original_mime_type_
;
583 std::string
DownloadItemImpl::GetRemoteAddress() const {
584 return remote_address_
;
587 bool DownloadItemImpl::HasUserGesture() const {
588 return has_user_gesture_
;
591 ui::PageTransition
DownloadItemImpl::GetTransitionType() const {
592 return transition_type_
;
595 const std::string
& DownloadItemImpl::GetLastModifiedTime() const {
596 return last_modified_time_
;
599 const std::string
& DownloadItemImpl::GetETag() const {
603 bool DownloadItemImpl::IsSavePackageDownload() const {
604 return is_save_package_download_
;
607 const base::FilePath
& DownloadItemImpl::GetFullPath() const {
608 return current_path_
;
611 const base::FilePath
& DownloadItemImpl::GetTargetFilePath() const {
615 const base::FilePath
& DownloadItemImpl::GetForcedFilePath() const {
616 // TODO(asanka): Get rid of GetForcedFilePath(). We should instead just
617 // require that clients respect GetTargetFilePath() if it is already set.
618 return forced_file_path_
;
621 base::FilePath
DownloadItemImpl::GetFileNameToReportUser() const {
622 if (!display_name_
.empty())
623 return display_name_
;
624 return target_path_
.BaseName();
627 DownloadItem::TargetDisposition
DownloadItemImpl::GetTargetDisposition() const {
628 return target_disposition_
;
631 const std::string
& DownloadItemImpl::GetHash() const {
635 const std::string
& DownloadItemImpl::GetHashState() const {
639 bool DownloadItemImpl::GetFileExternallyRemoved() const {
640 return file_externally_removed_
;
643 void DownloadItemImpl::DeleteFile(const base::Callback
<void(bool)>& callback
) {
644 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
645 if (GetState() != DownloadItem::COMPLETE
) {
646 // Pass a null WeakPtr so it doesn't call OnDownloadedFileRemoved.
647 BrowserThread::PostTask(
648 BrowserThread::UI
, FROM_HERE
,
649 base::Bind(&DeleteDownloadedFileDone
,
650 base::WeakPtr
<DownloadItemImpl
>(), callback
, false));
653 if (current_path_
.empty() || file_externally_removed_
) {
654 // Pass a null WeakPtr so it doesn't call OnDownloadedFileRemoved.
655 BrowserThread::PostTask(
656 BrowserThread::UI
, FROM_HERE
,
657 base::Bind(&DeleteDownloadedFileDone
,
658 base::WeakPtr
<DownloadItemImpl
>(), callback
, true));
661 BrowserThread::PostTaskAndReplyWithResult(
662 BrowserThread::FILE, FROM_HERE
,
663 base::Bind(&DeleteDownloadedFile
, current_path_
),
664 base::Bind(&DeleteDownloadedFileDone
,
665 weak_ptr_factory_
.GetWeakPtr(), callback
));
668 bool DownloadItemImpl::IsDangerous() const {
670 // TODO(noelutz): At this point only the windows views UI supports
671 // warnings based on dangerous content.
672 return (danger_type_
== DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE
||
673 danger_type_
== DOWNLOAD_DANGER_TYPE_DANGEROUS_URL
||
674 danger_type_
== DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT
||
675 danger_type_
== DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT
||
676 danger_type_
== DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST
||
677 danger_type_
== DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED
);
679 return (danger_type_
== DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE
||
680 danger_type_
== DOWNLOAD_DANGER_TYPE_DANGEROUS_URL
);
684 DownloadDangerType
DownloadItemImpl::GetDangerType() const {
688 bool DownloadItemImpl::TimeRemaining(base::TimeDelta
* remaining
) const {
689 if (total_bytes_
<= 0)
690 return false; // We never received the content_length for this download.
692 int64 speed
= CurrentSpeed();
696 *remaining
= base::TimeDelta::FromSeconds(
697 (total_bytes_
- received_bytes_
) / speed
);
701 int64
DownloadItemImpl::CurrentSpeed() const {
704 return bytes_per_sec_
;
707 int DownloadItemImpl::PercentComplete() const {
708 // If the delegate is delaying completion of the download, then we have no
709 // idea how long it will take.
710 if (delegate_delayed_complete_
|| total_bytes_
<= 0)
713 return static_cast<int>(received_bytes_
* 100.0 / total_bytes_
);
716 bool DownloadItemImpl::AllDataSaved() const {
717 return all_data_saved_
;
720 int64
DownloadItemImpl::GetTotalBytes() const {
724 int64
DownloadItemImpl::GetReceivedBytes() const {
725 return received_bytes_
;
728 base::Time
DownloadItemImpl::GetStartTime() const {
732 base::Time
DownloadItemImpl::GetEndTime() const {
736 bool DownloadItemImpl::CanShowInFolder() {
737 // A download can be shown in the folder if the downloaded file is in a known
739 return CanOpenDownload() && !GetFullPath().empty();
742 bool DownloadItemImpl::CanOpenDownload() {
743 // We can open the file or mark it for opening on completion if the download
744 // is expected to complete successfully. Exclude temporary downloads, since
745 // they aren't owned by the download system.
746 const bool is_complete
= GetState() == DownloadItem::COMPLETE
;
747 return (!IsDone() || is_complete
) && !IsTemporary() &&
748 !file_externally_removed_
;
751 bool DownloadItemImpl::ShouldOpenFileBasedOnExtension() {
752 return delegate_
->ShouldOpenFileBasedOnExtension(GetTargetFilePath());
755 bool DownloadItemImpl::GetOpenWhenComplete() const {
756 return open_when_complete_
;
759 bool DownloadItemImpl::GetAutoOpened() {
763 bool DownloadItemImpl::GetOpened() const {
767 BrowserContext
* DownloadItemImpl::GetBrowserContext() const {
768 return delegate_
->GetBrowserContext();
771 WebContents
* DownloadItemImpl::GetWebContents() const {
772 // TODO(rdsmith): Remove null check after removing GetWebContents() from
773 // paths that might be used by DownloadItems created from history import.
774 // Currently such items have null request_handle_s, where other items
775 // (regular and SavePackage downloads) have actual objects off the pointer.
777 return request_handle_
->GetWebContents();
781 void DownloadItemImpl::OnContentCheckCompleted(DownloadDangerType danger_type
) {
782 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
783 DCHECK(AllDataSaved());
784 DVLOG(20) << __FUNCTION__
<< " danger_type=" << danger_type
785 << " download=" << DebugString(true);
786 SetDangerType(danger_type
);
790 void DownloadItemImpl::SetOpenWhenComplete(bool open
) {
791 open_when_complete_
= open
;
794 void DownloadItemImpl::SetIsTemporary(bool temporary
) {
795 is_temporary_
= temporary
;
798 void DownloadItemImpl::SetOpened(bool opened
) {
802 void DownloadItemImpl::SetDisplayName(const base::FilePath
& name
) {
803 display_name_
= name
;
806 std::string
DownloadItemImpl::DebugString(bool verbose
) const {
807 std::string description
=
808 base::StringPrintf("{ id = %d"
811 DebugDownloadStateString(state_
));
813 // Construct a string of the URL chain.
814 std::string
url_list("<none>");
815 if (!url_chain_
.empty()) {
816 std::vector
<GURL
>::const_iterator iter
= url_chain_
.begin();
817 std::vector
<GURL
>::const_iterator last
= url_chain_
.end();
818 url_list
= (*iter
).is_valid() ? (*iter
).spec() : "<invalid>";
820 for ( ; verbose
&& (iter
!= last
); ++iter
) {
821 url_list
+= " ->\n\t";
822 const GURL
& next_url
= *iter
;
823 url_list
+= next_url
.is_valid() ? next_url
.spec() : "<invalid>";
828 description
+= base::StringPrintf(
830 " received = %" PRId64
834 " auto_resume_count = %d"
836 " all_data_saved = %c"
837 " last_modified = '%s'"
839 " has_download_file = %s"
840 " url_chain = \n\t\"%s\"\n\t"
841 " full_path = \"%" PRFilePath
"\"\n\t"
842 " target_path = \"%" PRFilePath
"\"",
845 DownloadInterruptReasonToString(last_reason_
).c_str(),
846 IsPaused() ? 'T' : 'F',
847 DebugResumeModeString(GetResumeMode()),
850 AllDataSaved() ? 'T' : 'F',
851 GetLastModifiedTime().c_str(),
853 download_file_
.get() ? "true" : "false",
855 GetFullPath().value().c_str(),
856 GetTargetFilePath().value().c_str());
858 description
+= base::StringPrintf(" url = \"%s\"", url_list
.c_str());
866 DownloadItemImpl::ResumeMode
DownloadItemImpl::GetResumeMode() const {
867 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
868 // We can't continue without a handle on the intermediate file.
869 // We also can't continue if we don't have some verifier to make sure
870 // we're getting the same file.
871 const bool force_restart
=
872 (current_path_
.empty() || (etag_
.empty() && last_modified_time_
.empty()));
874 // We won't auto-restart if we've used up our attempts or the
875 // download has been paused by user action.
876 const bool force_user
=
877 (auto_resume_count_
>= kMaxAutoResumeAttempts
|| is_paused_
);
879 ResumeMode mode
= RESUME_MODE_INVALID
;
881 switch(last_reason_
) {
882 case DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR
:
883 case DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT
:
884 if (force_restart
&& force_user
)
885 mode
= RESUME_MODE_USER_RESTART
;
886 else if (force_restart
)
887 mode
= RESUME_MODE_IMMEDIATE_RESTART
;
889 mode
= RESUME_MODE_USER_CONTINUE
;
891 mode
= RESUME_MODE_IMMEDIATE_CONTINUE
;
894 case DOWNLOAD_INTERRUPT_REASON_SERVER_PRECONDITION
:
895 case DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE
:
896 case DOWNLOAD_INTERRUPT_REASON_FILE_TOO_SHORT
:
898 mode
= RESUME_MODE_USER_RESTART
;
900 mode
= RESUME_MODE_IMMEDIATE_RESTART
;
903 case DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED
:
904 case DOWNLOAD_INTERRUPT_REASON_NETWORK_DISCONNECTED
:
905 case DOWNLOAD_INTERRUPT_REASON_NETWORK_SERVER_DOWN
:
906 case DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST
:
907 case DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED
:
908 case DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN
:
909 case DOWNLOAD_INTERRUPT_REASON_CRASH
:
911 mode
= RESUME_MODE_USER_RESTART
;
913 mode
= RESUME_MODE_USER_CONTINUE
;
916 case DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
:
917 case DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED
:
918 case DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
:
919 case DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG
:
920 case DOWNLOAD_INTERRUPT_REASON_FILE_TOO_LARGE
:
921 mode
= RESUME_MODE_USER_RESTART
;
924 case DOWNLOAD_INTERRUPT_REASON_NONE
:
925 case DOWNLOAD_INTERRUPT_REASON_FILE_VIRUS_INFECTED
:
926 case DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT
:
927 case DOWNLOAD_INTERRUPT_REASON_USER_CANCELED
:
928 case DOWNLOAD_INTERRUPT_REASON_FILE_BLOCKED
:
929 case DOWNLOAD_INTERRUPT_REASON_FILE_SECURITY_CHECK_FAILED
:
930 case DOWNLOAD_INTERRUPT_REASON_SERVER_UNAUTHORIZED
:
931 case DOWNLOAD_INTERRUPT_REASON_SERVER_CERT_PROBLEM
:
932 mode
= RESUME_MODE_INVALID
;
939 void DownloadItemImpl::MergeOriginInfoOnResume(
940 const DownloadCreateInfo
& new_create_info
) {
941 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
942 DCHECK_EQ(RESUMING_INTERNAL
, state_
);
943 DCHECK(!new_create_info
.url_chain
.empty());
945 // We are going to tack on any new redirects to our list of redirects.
946 // When a download is resumed, the URL used for the resumption request is the
947 // one at the end of the previous redirect chain. Tacking additional redirects
948 // to the end of this chain ensures that:
949 // - If the download needs to be resumed again, the ETag/Last-Modified headers
950 // will be used with the last server that sent them to us.
951 // - The redirect chain contains all the servers that were involved in this
952 // download since the initial request, in order.
953 std::vector
<GURL
>::const_iterator chain_iter
=
954 new_create_info
.url_chain
.begin();
955 if (*chain_iter
== url_chain_
.back())
958 // Record some stats. If the precondition failed (the server returned
959 // HTTP_PRECONDITION_FAILED), then the download will automatically retried as
960 // a full request rather than a partial. Full restarts clobber validators.
961 int origin_state
= 0;
962 if (chain_iter
!= new_create_info
.url_chain
.end())
963 origin_state
|= ORIGIN_STATE_ON_RESUMPTION_ADDITIONAL_REDIRECTS
;
964 if (etag_
!= new_create_info
.etag
||
965 last_modified_time_
!= new_create_info
.last_modified
)
966 origin_state
|= ORIGIN_STATE_ON_RESUMPTION_VALIDATORS_CHANGED
;
967 if (content_disposition_
!= new_create_info
.content_disposition
)
968 origin_state
|= ORIGIN_STATE_ON_RESUMPTION_CONTENT_DISPOSITION_CHANGED
;
969 RecordOriginStateOnResumption(new_create_info
.save_info
->offset
!= 0,
973 url_chain_
.end(), chain_iter
, new_create_info
.url_chain
.end());
974 etag_
= new_create_info
.etag
;
975 last_modified_time_
= new_create_info
.last_modified
;
976 content_disposition_
= new_create_info
.content_disposition
;
978 // Don't update observers. This method is expected to be called just before a
979 // DownloadFile is created and Start() is called. The observers will be
980 // notified when the download transitions to the IN_PROGRESS state.
983 void DownloadItemImpl::NotifyRemoved() {
984 FOR_EACH_OBSERVER(Observer
, observers_
, OnDownloadRemoved(this));
987 void DownloadItemImpl::OnDownloadedFileRemoved() {
988 file_externally_removed_
= true;
989 DVLOG(20) << __FUNCTION__
<< " download=" << DebugString(true);
993 base::WeakPtr
<DownloadDestinationObserver
>
994 DownloadItemImpl::DestinationObserverAsWeakPtr() {
995 return weak_ptr_factory_
.GetWeakPtr();
998 const net::BoundNetLog
& DownloadItemImpl::GetBoundNetLog() const {
999 return bound_net_log_
;
1002 void DownloadItemImpl::SetTotalBytes(int64 total_bytes
) {
1003 total_bytes_
= total_bytes
;
1006 void DownloadItemImpl::OnAllDataSaved(const std::string
& final_hash
) {
1007 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1009 DCHECK_EQ(IN_PROGRESS_INTERNAL
, state_
);
1010 DCHECK(!all_data_saved_
);
1011 all_data_saved_
= true;
1012 DVLOG(20) << __FUNCTION__
<< " download=" << DebugString(true);
1014 // Store final hash and null out intermediate serialized hash state.
1021 void DownloadItemImpl::MarkAsComplete() {
1022 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1024 DCHECK(all_data_saved_
);
1025 end_time_
= base::Time::Now();
1026 TransitionTo(COMPLETE_INTERNAL
, UPDATE_OBSERVERS
);
1029 void DownloadItemImpl::DestinationUpdate(int64 bytes_so_far
,
1030 int64 bytes_per_sec
,
1031 const std::string
& hash_state
) {
1032 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1033 DVLOG(20) << __FUNCTION__
<< " so_far=" << bytes_so_far
1034 << " per_sec=" << bytes_per_sec
<< " download="
1035 << DebugString(true);
1037 if (GetState() != IN_PROGRESS
) {
1038 // Ignore if we're no longer in-progress. This can happen if we race a
1039 // Cancel on the UI thread with an update on the FILE thread.
1041 // TODO(rdsmith): Arguably we should let this go through, as this means
1042 // the download really did get further than we know before it was
1043 // cancelled. But the gain isn't very large, and the code is more
1044 // fragile if it has to support in progress updates in a non-in-progress
1045 // state. This issue should be readdressed when we revamp performance
1049 bytes_per_sec_
= bytes_per_sec
;
1050 hash_state_
= hash_state
;
1051 received_bytes_
= bytes_so_far
;
1053 // If we've received more data than we were expecting (bad server info?),
1054 // revert to 'unknown size mode'.
1055 if (received_bytes_
> total_bytes_
)
1058 if (bound_net_log_
.IsLogging()) {
1059 bound_net_log_
.AddEvent(
1060 net::NetLog::TYPE_DOWNLOAD_ITEM_UPDATED
,
1061 net::NetLog::Int64Callback("bytes_so_far", received_bytes_
));
1067 void DownloadItemImpl::DestinationError(DownloadInterruptReason reason
) {
1068 // Postpone recognition of this error until after file name determination
1069 // has completed and the intermediate file has been renamed to simplify
1070 // resumption conditions.
1071 if (current_path_
.empty() || target_path_
.empty())
1072 destination_error_
= reason
;
1077 void DownloadItemImpl::DestinationCompleted(const std::string
& final_hash
) {
1078 DVLOG(20) << __FUNCTION__
<< " download=" << DebugString(true);
1079 if (GetState() != IN_PROGRESS
)
1081 OnAllDataSaved(final_hash
);
1082 MaybeCompleteDownload();
1085 // **** Download progression cascade
1087 void DownloadItemImpl::Init(bool active
,
1088 DownloadType download_type
) {
1089 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1092 RecordDownloadCount(START_COUNT
);
1094 std::string file_name
;
1095 if (download_type
== SRC_HISTORY_IMPORT
) {
1096 // target_path_ works for History and Save As versions.
1097 file_name
= target_path_
.AsUTF8Unsafe();
1099 // See if it's set programmatically.
1100 file_name
= forced_file_path_
.AsUTF8Unsafe();
1101 // Possibly has a 'download' attribute for the anchor.
1102 if (file_name
.empty())
1103 file_name
= suggested_filename_
;
1104 // From the URL file name.
1105 if (file_name
.empty())
1106 file_name
= GetURL().ExtractFileName();
1109 base::Callback
<base::Value
*(net::NetLog::LogLevel
)> active_data
= base::Bind(
1110 &ItemActivatedNetLogCallback
, this, download_type
, &file_name
);
1112 bound_net_log_
.BeginEvent(
1113 net::NetLog::TYPE_DOWNLOAD_ITEM_ACTIVE
, active_data
);
1115 bound_net_log_
.AddEvent(
1116 net::NetLog::TYPE_DOWNLOAD_ITEM_ACTIVE
, active_data
);
1119 DVLOG(20) << __FUNCTION__
<< "() " << DebugString(true);
1122 // We're starting the download.
1123 void DownloadItemImpl::Start(
1124 scoped_ptr
<DownloadFile
> file
,
1125 scoped_ptr
<DownloadRequestHandleInterface
> req_handle
) {
1126 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1127 DCHECK(!download_file_
.get());
1129 DCHECK(req_handle
.get());
1131 download_file_
= file
.Pass();
1132 request_handle_
= req_handle
.Pass();
1134 if (GetState() == CANCELLED
) {
1135 // The download was in the process of resuming when it was cancelled. Don't
1137 ReleaseDownloadFile(true);
1138 request_handle_
->CancelRequest();
1142 TransitionTo(IN_PROGRESS_INTERNAL
, UPDATE_OBSERVERS
);
1144 BrowserThread::PostTask(
1145 BrowserThread::FILE, FROM_HERE
,
1146 base::Bind(&DownloadFile::Initialize
,
1147 // Safe because we control download file lifetime.
1148 base::Unretained(download_file_
.get()),
1149 base::Bind(&DownloadItemImpl::OnDownloadFileInitialized
,
1150 weak_ptr_factory_
.GetWeakPtr())));
1153 void DownloadItemImpl::OnDownloadFileInitialized(
1154 DownloadInterruptReason result
) {
1155 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1156 if (result
!= DOWNLOAD_INTERRUPT_REASON_NONE
) {
1158 // TODO(rdsmith/asanka): Arguably we should show this in the UI, but
1159 // it's not at all clear what to show--we haven't done filename
1160 // determination, so we don't know what name to display. OTOH,
1161 // the failure mode of not showing the DI if the file initialization
1162 // fails isn't a good one. Can we hack up a name based on the
1163 // URLRequest? We'll need to make sure that initialization happens
1164 // properly. Possibly the right thing is to have the UI handle
1165 // this case specially.
1169 delegate_
->DetermineDownloadTarget(
1170 this, base::Bind(&DownloadItemImpl::OnDownloadTargetDetermined
,
1171 weak_ptr_factory_
.GetWeakPtr()));
1174 // Called by delegate_ when the download target path has been
1176 void DownloadItemImpl::OnDownloadTargetDetermined(
1177 const base::FilePath
& target_path
,
1178 TargetDisposition disposition
,
1179 DownloadDangerType danger_type
,
1180 const base::FilePath
& intermediate_path
) {
1181 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1183 // If the |target_path| is empty, then we consider this download to be
1185 if (target_path
.empty()) {
1190 // TODO(rdsmith,asanka): We are ignoring the possibility that the download
1191 // has been interrupted at this point until we finish the intermediate
1192 // rename and set the full path. That's dangerous, because we might race
1193 // with resumption, either manual (because the interrupt is visible to the
1194 // UI) or automatic. If we keep the "ignore an error on download until file
1195 // name determination complete" semantics, we need to make sure that the
1196 // error is kept completely invisible until that point.
1198 DVLOG(20) << __FUNCTION__
<< " " << target_path
.value() << " " << disposition
1199 << " " << danger_type
<< " " << DebugString(true);
1201 target_path_
= target_path
;
1202 target_disposition_
= disposition
;
1203 SetDangerType(danger_type
);
1205 // We want the intermediate and target paths to refer to the same directory so
1206 // that they are both on the same device and subject to same
1207 // space/permission/availability constraints.
1208 DCHECK(intermediate_path
.DirName() == target_path
.DirName());
1210 // During resumption, we may choose to proceed with the same intermediate
1211 // file. No rename is necessary if our intermediate file already has the
1214 // The intermediate name may change from its original value during filename
1215 // determination on resumption, for example if the reason for the interruption
1216 // was the download target running out space, resulting in a user prompt.
1217 if (intermediate_path
== current_path_
) {
1218 OnDownloadRenamedToIntermediateName(DOWNLOAD_INTERRUPT_REASON_NONE
,
1223 // Rename to intermediate name.
1224 // TODO(asanka): Skip this rename if AllDataSaved() is true. This avoids a
1225 // spurious rename when we can just rename to the final
1226 // filename. Unnecessary renames may cause bugs like
1227 // http://crbug.com/74187.
1228 DCHECK(!is_save_package_download_
);
1229 DCHECK(download_file_
.get());
1230 DownloadFile::RenameCompletionCallback callback
=
1231 base::Bind(&DownloadItemImpl::OnDownloadRenamedToIntermediateName
,
1232 weak_ptr_factory_
.GetWeakPtr());
1233 BrowserThread::PostTask(
1234 BrowserThread::FILE, FROM_HERE
,
1235 base::Bind(&DownloadFile::RenameAndUniquify
,
1236 // Safe because we control download file lifetime.
1237 base::Unretained(download_file_
.get()),
1238 intermediate_path
, callback
));
1241 void DownloadItemImpl::OnDownloadRenamedToIntermediateName(
1242 DownloadInterruptReason reason
,
1243 const base::FilePath
& full_path
) {
1244 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1245 DVLOG(20) << __FUNCTION__
<< " download=" << DebugString(true);
1247 if (DOWNLOAD_INTERRUPT_REASON_NONE
!= destination_error_
) {
1248 // Process destination error. If both |reason| and |destination_error_|
1249 // refer to actual errors, we want to use the |destination_error_| as the
1250 // argument to the Interrupt() routine, as it happened first.
1251 if (reason
== DOWNLOAD_INTERRUPT_REASON_NONE
)
1252 SetFullPath(full_path
);
1253 Interrupt(destination_error_
);
1254 destination_error_
= DOWNLOAD_INTERRUPT_REASON_NONE
;
1255 } else if (DOWNLOAD_INTERRUPT_REASON_NONE
!= reason
) {
1257 // All file errors result in file deletion above; no need to cleanup. The
1258 // current_path_ should be empty. Resuming this download will force a
1259 // restart and a re-doing of filename determination.
1260 DCHECK(current_path_
.empty());
1262 SetFullPath(full_path
);
1264 MaybeCompleteDownload();
1268 // When SavePackage downloads MHTML to GData (see
1269 // SavePackageFilePickerChromeOS), GData calls MaybeCompleteDownload() like it
1270 // does for non-SavePackage downloads, but SavePackage downloads never satisfy
1271 // IsDownloadReadyForCompletion(). GDataDownloadObserver manually calls
1272 // DownloadItem::UpdateObservers() when the upload completes so that SavePackage
1273 // notices that the upload has completed and runs its normal Finish() pathway.
1274 // MaybeCompleteDownload() is never the mechanism by which SavePackage completes
1275 // downloads. SavePackage always uses its own Finish() to mark downloads
1277 void DownloadItemImpl::MaybeCompleteDownload() {
1278 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1279 DCHECK(!is_save_package_download_
);
1281 if (!IsDownloadReadyForCompletion(
1282 base::Bind(&DownloadItemImpl::MaybeCompleteDownload
,
1283 weak_ptr_factory_
.GetWeakPtr())))
1286 // TODO(rdsmith): DCHECK that we only pass through this point
1287 // once per download. The natural way to do this is by a state
1288 // transition on the DownloadItem.
1290 // Confirm we're in the proper set of states to be here;
1291 // have all data, have a history handle, (validated or safe).
1292 DCHECK_EQ(IN_PROGRESS_INTERNAL
, state_
);
1293 DCHECK(!IsDangerous());
1294 DCHECK(all_data_saved_
);
1296 OnDownloadCompleting();
1299 // Called by MaybeCompleteDownload() when it has determined that the download
1300 // is ready for completion.
1301 void DownloadItemImpl::OnDownloadCompleting() {
1302 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1304 if (state_
!= IN_PROGRESS_INTERNAL
)
1307 DVLOG(20) << __FUNCTION__
<< "()"
1308 << " " << DebugString(true);
1309 DCHECK(!GetTargetFilePath().empty());
1310 DCHECK(!IsDangerous());
1312 // TODO(rdsmith/benjhayden): Remove as part of SavePackage integration.
1313 if (is_save_package_download_
) {
1314 // Avoid doing anything on the file thread; there's nothing we control
1316 // Strictly speaking, this skips giving the embedder a chance to open
1317 // the download. But on a save package download, there's no real
1318 // concept of opening.
1323 DCHECK(download_file_
.get());
1324 // Unilaterally rename; even if it already has the right name,
1325 // we need theannotation.
1326 DownloadFile::RenameCompletionCallback callback
=
1327 base::Bind(&DownloadItemImpl::OnDownloadRenamedToFinalName
,
1328 weak_ptr_factory_
.GetWeakPtr());
1329 BrowserThread::PostTask(
1330 BrowserThread::FILE, FROM_HERE
,
1331 base::Bind(&DownloadFile::RenameAndAnnotate
,
1332 base::Unretained(download_file_
.get()),
1333 GetTargetFilePath(), callback
));
1336 void DownloadItemImpl::OnDownloadRenamedToFinalName(
1337 DownloadInterruptReason reason
,
1338 const base::FilePath
& full_path
) {
1339 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1340 DCHECK(!is_save_package_download_
);
1342 // If a cancel or interrupt hit, we'll cancel the DownloadFile, which
1343 // will result in deleting the file on the file thread. So we don't
1344 // care about the name having been changed.
1345 if (state_
!= IN_PROGRESS_INTERNAL
)
1348 DVLOG(20) << __FUNCTION__
<< "()"
1349 << " full_path = \"" << full_path
.value() << "\""
1350 << " " << DebugString(false);
1352 if (DOWNLOAD_INTERRUPT_REASON_NONE
!= reason
) {
1355 // All file errors should have resulted in in file deletion above. On
1356 // resumption we will need to re-do filename determination.
1357 DCHECK(current_path_
.empty());
1361 DCHECK(target_path_
== full_path
);
1363 if (full_path
!= current_path_
) {
1364 // full_path is now the current and target file path.
1365 DCHECK(!full_path
.empty());
1366 SetFullPath(full_path
);
1369 // Complete the download and release the DownloadFile.
1370 DCHECK(download_file_
.get());
1371 ReleaseDownloadFile(false);
1373 // We're not completely done with the download item yet, but at this
1374 // point we're committed to complete the download. Cancels (or Interrupts,
1375 // though it's not clear how they could happen) after this point will be
1377 TransitionTo(COMPLETING_INTERNAL
, DONT_UPDATE_OBSERVERS
);
1379 if (delegate_
->ShouldOpenDownload(
1380 this, base::Bind(&DownloadItemImpl::DelayedDownloadOpened
,
1381 weak_ptr_factory_
.GetWeakPtr()))) {
1384 delegate_delayed_complete_
= true;
1389 void DownloadItemImpl::DelayedDownloadOpened(bool auto_opened
) {
1390 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1392 auto_opened_
= auto_opened
;
1396 void DownloadItemImpl::Completed() {
1397 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1399 DVLOG(20) << __FUNCTION__
<< "() " << DebugString(false);
1401 DCHECK(all_data_saved_
);
1402 end_time_
= base::Time::Now();
1403 TransitionTo(COMPLETE_INTERNAL
, UPDATE_OBSERVERS
);
1404 RecordDownloadCompleted(start_tick_
, received_bytes_
);
1407 // If it was already handled by the delegate, do nothing.
1408 } else if (GetOpenWhenComplete() ||
1409 ShouldOpenFileBasedOnExtension() ||
1411 // If the download is temporary, like in drag-and-drop, do not open it but
1412 // we still need to set it auto-opened so that it can be removed from the
1417 auto_opened_
= true;
1422 void DownloadItemImpl::OnResumeRequestStarted(
1424 DownloadInterruptReason interrupt_reason
) {
1425 // If |item| is not NULL, then Start() has been called already, and nothing
1426 // more needs to be done here.
1428 DCHECK_EQ(DOWNLOAD_INTERRUPT_REASON_NONE
, interrupt_reason
);
1429 DCHECK_EQ(static_cast<DownloadItem
*>(this), item
);
1432 // Otherwise, the request failed without passing through
1433 // DownloadResourceHandler::OnResponseStarted.
1434 DCHECK_NE(DOWNLOAD_INTERRUPT_REASON_NONE
, interrupt_reason
);
1435 Interrupt(interrupt_reason
);
1438 // **** End of Download progression cascade
1440 // An error occurred somewhere.
1441 void DownloadItemImpl::Interrupt(DownloadInterruptReason reason
) {
1442 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1443 DCHECK_NE(DOWNLOAD_INTERRUPT_REASON_NONE
, reason
);
1445 // Somewhat counter-intuitively, it is possible for us to receive an
1446 // interrupt after we've already been interrupted. The generation of
1447 // interrupts from the file thread Renames and the generation of
1448 // interrupts from disk writes go through two different mechanisms (driven
1449 // by rename requests from UI thread and by write requests from IO thread,
1450 // respectively), and since we choose not to keep state on the File thread,
1451 // this is the place where the races collide. It's also possible for
1452 // interrupts to race with cancels.
1454 // Whatever happens, the first one to hit the UI thread wins.
1455 if (state_
!= IN_PROGRESS_INTERNAL
&& state_
!= RESUMING_INTERNAL
)
1458 last_reason_
= reason
;
1460 ResumeMode resume_mode
= GetResumeMode();
1462 if (state_
== IN_PROGRESS_INTERNAL
) {
1463 // Cancel (delete file) if:
1464 // 1) we're going to restart.
1465 // 2) Resumption isn't possible (download was cancelled or blocked due to
1466 // security restrictions).
1467 // 3) Resumption isn't enabled.
1468 // No point in leaving data around we aren't going to use.
1469 ReleaseDownloadFile(resume_mode
== RESUME_MODE_IMMEDIATE_RESTART
||
1470 resume_mode
== RESUME_MODE_USER_RESTART
||
1471 resume_mode
== RESUME_MODE_INVALID
||
1472 !IsDownloadResumptionEnabled());
1474 // Cancel the originating URL request.
1475 request_handle_
->CancelRequest();
1477 DCHECK(!download_file_
.get());
1480 // Reset all data saved, as even if we did save all the data we're going
1481 // to go through another round of downloading when we resume.
1482 // There's a potential problem here in the abstract, as if we did download
1483 // all the data and then run into a continuable error, on resumption we
1484 // won't download any more data. However, a) there are currently no
1485 // continuable errors that can occur after we download all the data, and
1486 // b) if there were, that would probably simply result in a null range
1487 // request, which would generate a DestinationCompleted() notification
1488 // from the DownloadFile, which would behave properly with setting
1489 // all_data_saved_ to false here.
1490 all_data_saved_
= false;
1492 TransitionTo(INTERRUPTED_INTERNAL
, DONT_UPDATE_OBSERVERS
);
1493 RecordDownloadInterrupted(reason
, received_bytes_
, total_bytes_
);
1494 if (!GetWebContents())
1495 RecordDownloadCount(INTERRUPTED_WITHOUT_WEBCONTENTS
);
1497 AutoResumeIfValid();
1501 void DownloadItemImpl::ReleaseDownloadFile(bool destroy_file
) {
1502 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1505 BrowserThread::PostTask(
1506 BrowserThread::FILE, FROM_HERE
,
1507 // Will be deleted at end of task execution.
1508 base::Bind(&DownloadFileCancel
, base::Passed(&download_file_
)));
1509 // Avoid attempting to reuse the intermediate file by clearing out
1511 current_path_
.clear();
1513 BrowserThread::PostTask(
1514 BrowserThread::FILE,
1516 base::Bind(base::IgnoreResult(&DownloadFileDetach
),
1517 // Will be deleted at end of task execution.
1518 base::Passed(&download_file_
)));
1520 // Don't accept any more messages from the DownloadFile, and null
1521 // out any previous "all data received". This also breaks links to
1522 // other entities we've given out weak pointers to.
1523 weak_ptr_factory_
.InvalidateWeakPtrs();
1526 bool DownloadItemImpl::IsDownloadReadyForCompletion(
1527 const base::Closure
& state_change_notification
) {
1528 // If we don't have all the data, the download is not ready for
1530 if (!AllDataSaved())
1533 // If the download is dangerous, but not yet validated, it's not ready for
1538 // If the download isn't active (e.g. has been cancelled) it's not
1539 // ready for completion.
1540 if (state_
!= IN_PROGRESS_INTERNAL
)
1543 // If the target filename hasn't been determined, then it's not ready for
1544 // completion. This is checked in ReadyForDownloadCompletionDone().
1545 if (GetTargetFilePath().empty())
1548 // This is checked in NeedsRename(). Without this conditional,
1549 // browser_tests:DownloadTest.DownloadMimeType fails the DCHECK.
1550 if (target_path_
.DirName() != current_path_
.DirName())
1553 // Give the delegate a chance to hold up a stop sign. It'll call
1554 // use back through the passed callback if it does and that state changes.
1555 if (!delegate_
->ShouldCompleteDownload(this, state_change_notification
))
1561 void DownloadItemImpl::TransitionTo(DownloadInternalState new_state
,
1562 ShouldUpdateObservers notify_action
) {
1563 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1565 if (state_
== new_state
)
1568 DownloadInternalState old_state
= state_
;
1572 case COMPLETING_INTERNAL
:
1573 bound_net_log_
.AddEvent(
1574 net::NetLog::TYPE_DOWNLOAD_ITEM_COMPLETING
,
1575 base::Bind(&ItemCompletingNetLogCallback
, received_bytes_
, &hash_
));
1577 case COMPLETE_INTERNAL
:
1578 bound_net_log_
.AddEvent(
1579 net::NetLog::TYPE_DOWNLOAD_ITEM_FINISHED
,
1580 base::Bind(&ItemFinishedNetLogCallback
, auto_opened_
));
1582 case INTERRUPTED_INTERNAL
:
1583 bound_net_log_
.AddEvent(
1584 net::NetLog::TYPE_DOWNLOAD_ITEM_INTERRUPTED
,
1585 base::Bind(&ItemInterruptedNetLogCallback
, last_reason_
,
1586 received_bytes_
, &hash_state_
));
1588 case IN_PROGRESS_INTERNAL
:
1589 if (old_state
== INTERRUPTED_INTERNAL
) {
1590 bound_net_log_
.AddEvent(
1591 net::NetLog::TYPE_DOWNLOAD_ITEM_RESUMED
,
1592 base::Bind(&ItemResumingNetLogCallback
,
1593 false, last_reason_
, received_bytes_
, &hash_state_
));
1596 case CANCELLED_INTERNAL
:
1597 bound_net_log_
.AddEvent(
1598 net::NetLog::TYPE_DOWNLOAD_ITEM_CANCELED
,
1599 base::Bind(&ItemCanceledNetLogCallback
, received_bytes_
,
1606 DVLOG(20) << " " << __FUNCTION__
<< "()" << " this = " << DebugString(true)
1607 << " " << InternalToExternalState(old_state
)
1608 << " " << InternalToExternalState(state_
);
1610 bool is_done
= (state_
!= IN_PROGRESS_INTERNAL
&&
1611 state_
!= COMPLETING_INTERNAL
);
1612 bool was_done
= (old_state
!= IN_PROGRESS_INTERNAL
&&
1613 old_state
!= COMPLETING_INTERNAL
);
1615 if (is_done
&& !was_done
)
1616 bound_net_log_
.EndEvent(net::NetLog::TYPE_DOWNLOAD_ITEM_ACTIVE
);
1619 if (was_done
&& !is_done
) {
1620 std::string
file_name(target_path_
.BaseName().AsUTF8Unsafe());
1621 bound_net_log_
.BeginEvent(net::NetLog::TYPE_DOWNLOAD_ITEM_ACTIVE
,
1622 base::Bind(&ItemActivatedNetLogCallback
,
1623 this, SRC_ACTIVE_DOWNLOAD
,
1627 if (notify_action
== UPDATE_OBSERVERS
)
1631 void DownloadItemImpl::SetDangerType(DownloadDangerType danger_type
) {
1632 if (danger_type
!= danger_type_
) {
1633 bound_net_log_
.AddEvent(
1634 net::NetLog::TYPE_DOWNLOAD_ITEM_SAFETY_STATE_UPDATED
,
1635 base::Bind(&ItemCheckedNetLogCallback
, danger_type
));
1637 // Only record the Malicious UMA stat if it's going from {not malicious} ->
1639 if ((danger_type_
== DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS
||
1640 danger_type_
== DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE
||
1641 danger_type_
== DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT
||
1642 danger_type_
== DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT
) &&
1643 (danger_type
== DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST
||
1644 danger_type
== DOWNLOAD_DANGER_TYPE_DANGEROUS_URL
||
1645 danger_type
== DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT
||
1646 danger_type
== DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED
)) {
1647 RecordMaliciousDownloadClassified(danger_type
);
1649 danger_type_
= danger_type
;
1652 void DownloadItemImpl::SetFullPath(const base::FilePath
& new_path
) {
1653 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1654 DVLOG(20) << __FUNCTION__
<< "()"
1655 << " new_path = \"" << new_path
.value() << "\""
1656 << " " << DebugString(true);
1657 DCHECK(!new_path
.empty());
1659 bound_net_log_
.AddEvent(
1660 net::NetLog::TYPE_DOWNLOAD_ITEM_RENAMED
,
1661 base::Bind(&ItemRenamedNetLogCallback
, ¤t_path_
, &new_path
));
1663 current_path_
= new_path
;
1666 void DownloadItemImpl::AutoResumeIfValid() {
1667 DVLOG(20) << __FUNCTION__
<< "() " << DebugString(true);
1668 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1669 ResumeMode mode
= GetResumeMode();
1671 if (mode
!= RESUME_MODE_IMMEDIATE_RESTART
&&
1672 mode
!= RESUME_MODE_IMMEDIATE_CONTINUE
) {
1676 auto_resume_count_
++;
1678 ResumeInterruptedDownload();
1681 void DownloadItemImpl::ResumeInterruptedDownload() {
1682 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1684 // If the flag for downloads resumption isn't enabled, ignore
1686 const base::CommandLine
& command_line
=
1687 *base::CommandLine::ForCurrentProcess();
1688 if (!command_line
.HasSwitch(switches::kEnableDownloadResumption
))
1691 // If we're not interrupted, ignore the request; our caller is drunk.
1692 if (state_
!= INTERRUPTED_INTERNAL
)
1695 // If we can't get a web contents, we can't resume the download.
1696 // TODO(rdsmith): Find some alternative web contents to use--this
1697 // means we can't restart a download if it's a download imported
1698 // from the history.
1699 if (!GetWebContents())
1702 // Reset the appropriate state if restarting.
1703 ResumeMode mode
= GetResumeMode();
1704 if (mode
== RESUME_MODE_IMMEDIATE_RESTART
||
1705 mode
== RESUME_MODE_USER_RESTART
) {
1706 received_bytes_
= 0;
1708 last_modified_time_
= "";
1712 scoped_ptr
<DownloadUrlParameters
> download_params(
1713 DownloadUrlParameters::FromWebContents(GetWebContents(),
1716 download_params
->set_file_path(GetFullPath());
1717 download_params
->set_offset(GetReceivedBytes());
1718 download_params
->set_hash_state(GetHashState());
1719 download_params
->set_last_modified(GetLastModifiedTime());
1720 download_params
->set_etag(GetETag());
1721 download_params
->set_callback(
1722 base::Bind(&DownloadItemImpl::OnResumeRequestStarted
,
1723 weak_ptr_factory_
.GetWeakPtr()));
1725 delegate_
->ResumeInterruptedDownload(download_params
.Pass(), GetId());
1726 // Just in case we were interrupted while paused.
1729 TransitionTo(RESUMING_INTERNAL
, DONT_UPDATE_OBSERVERS
);
1733 DownloadItem::DownloadState
DownloadItemImpl::InternalToExternalState(
1734 DownloadInternalState internal_state
) {
1735 switch (internal_state
) {
1736 case IN_PROGRESS_INTERNAL
:
1738 case COMPLETING_INTERNAL
:
1740 case COMPLETE_INTERNAL
:
1742 case CANCELLED_INTERNAL
:
1744 case INTERRUPTED_INTERNAL
:
1746 case RESUMING_INTERNAL
:
1748 case MAX_DOWNLOAD_INTERNAL_STATE
:
1752 return MAX_DOWNLOAD_STATE
;
1756 DownloadItemImpl::DownloadInternalState
1757 DownloadItemImpl::ExternalToInternalState(
1758 DownloadState external_state
) {
1759 switch (external_state
) {
1761 return IN_PROGRESS_INTERNAL
;
1763 return COMPLETE_INTERNAL
;
1765 return CANCELLED_INTERNAL
;
1767 return INTERRUPTED_INTERNAL
;
1771 return MAX_DOWNLOAD_INTERNAL_STATE
;
1774 const char* DownloadItemImpl::DebugDownloadStateString(
1775 DownloadInternalState state
) {
1777 case IN_PROGRESS_INTERNAL
:
1778 return "IN_PROGRESS";
1779 case COMPLETING_INTERNAL
:
1780 return "COMPLETING";
1781 case COMPLETE_INTERNAL
:
1783 case CANCELLED_INTERNAL
:
1785 case INTERRUPTED_INTERNAL
:
1786 return "INTERRUPTED";
1787 case RESUMING_INTERNAL
:
1789 case MAX_DOWNLOAD_INTERNAL_STATE
:
1792 NOTREACHED() << "Unknown download state " << state
;
1796 const char* DownloadItemImpl::DebugResumeModeString(ResumeMode mode
) {
1798 case RESUME_MODE_INVALID
:
1800 case RESUME_MODE_IMMEDIATE_CONTINUE
:
1801 return "IMMEDIATE_CONTINUE";
1802 case RESUME_MODE_IMMEDIATE_RESTART
:
1803 return "IMMEDIATE_RESTART";
1804 case RESUME_MODE_USER_CONTINUE
:
1805 return "USER_CONTINUE";
1806 case RESUME_MODE_USER_RESTART
:
1807 return "USER_RESTART";
1809 NOTREACHED() << "Unknown resume mode " << mode
;
1813 } // namespace content