Add ICU message format support
[chromium-blink-merge.git] / content / browser / download / download_item_impl.cc
blob1e5d53aef0060beec28545dbea5d5b0dc3a64969
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
22 // auto-opened.
24 #include "content/browser/download/download_item_impl.h"
26 #include <vector>
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"
56 namespace content {
58 namespace {
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))
65 return true;
66 return base::DeleteFile(path, false);
69 void DeleteDownloadedFileDone(
70 base::WeakPtr<DownloadItemImpl> item,
71 const base::Callback<void(bool)>& callback,
72 bool success) {
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();
87 return full_path;
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);
100 } // namespace
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,
111 uint32 download_id,
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,
123 int64 total_bytes,
124 DownloadItem::DownloadState state,
125 DownloadDangerType danger_type,
126 DownloadInterruptReason interrupt_reason,
127 bool opened,
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),
142 bytes_per_sec_(0),
143 last_modified_time_(last_modified),
144 etag_(etag),
145 last_reason_(interrupt_reason),
146 start_tick_(base::TimeTicks()),
147 state_(ExternalToInternalState(state)),
148 danger_type_(danger_type),
149 start_time_(start_time),
150 end_time_(end_time),
151 delegate_(delegate),
152 is_paused_(false),
153 auto_resume_count_(0),
154 open_when_complete_(false),
155 file_externally_removed_(false),
156 auto_opened_(false),
157 is_temporary_(false),
158 all_data_saved_(state == COMPLETE),
159 destination_error_(content::DOWNLOAD_INTERRUPT_REASON_NONE),
160 opened_(opened),
161 delegate_delayed_complete_(false),
162 bound_net_log_(bound_net_log),
163 weak_ptr_factory_(this) {
164 delegate_->Attach();
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,
172 uint32 download_id,
173 const DownloadCreateInfo& info,
174 const net::BoundNetLog& bound_net_log)
175 : is_save_package_download_(false),
176 download_id_(download_id),
177 target_disposition_(
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),
193 received_bytes_(0),
194 bytes_per_sec_(0),
195 last_modified_time_(info.last_modified),
196 etag_(info.etag),
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),
202 delegate_(delegate),
203 is_paused_(false),
204 auto_resume_count_(0),
205 open_when_complete_(false),
206 file_externally_removed_(false),
207 auto_opened_(false),
208 is_temporary_(!info.save_info->file_path.empty()),
209 all_data_saved_(false),
210 destination_error_(content::DOWNLOAD_INTERRUPT_REASON_NONE),
211 opened_(false),
212 delegate_delayed_complete_(false),
213 bound_net_log_(bound_net_log),
214 weak_ptr_factory_(this) {
215 delegate_->Attach();
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,
231 uint32 download_id,
232 const base::FilePath& path,
233 const GURL& url,
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),
240 current_path_(path),
241 target_path_(path),
242 target_disposition_(TARGET_DISPOSITION_OVERWRITE),
243 url_chain_(1, url),
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),
249 total_bytes_(0),
250 received_bytes_(0),
251 bytes_per_sec_(0),
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()),
257 delegate_(delegate),
258 is_paused_(false),
259 auto_resume_count_(0),
260 open_when_complete_(false),
261 file_externally_removed_(false),
262 auto_opened_(false),
263 is_temporary_(false),
264 all_data_saved_(false),
265 destination_error_(content::DOWNLOAD_INTERRUPT_REASON_NONE),
266 opened_(false),
267 delegate_delayed_complete_(false),
268 bound_net_log_(bound_net_log),
269 weak_ptr_factory_(this) {
270 delegate_->Attach();
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);
283 delegate_->Detach();
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);
306 DCHECK(!IsDone());
307 DCHECK(IsDangerous());
309 DVLOG(20) << __FUNCTION__ << " download=" << DebugString(true);
311 if (IsDone() || !IsDangerous())
312 return;
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()));
323 UpdateObservers();
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(
335 BrowserThread::FILE,
336 FROM_HERE,
337 base::Bind(&DownloadFileDetach, base::Passed(&download_file_)),
338 callback);
339 } else {
340 callback.Run(current_path_);
342 current_path_.clear();
343 Remove();
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_)
352 return;
354 request_handle_->PauseRequest();
355 is_paused_ = true;
356 UpdateObservers();
359 void DownloadItemImpl::Resume() {
360 DCHECK_CURRENTLY_ON(BrowserThread::UI);
361 switch (state_) {
362 case IN_PROGRESS_INTERNAL:
363 if (!is_paused_)
364 return;
365 request_handle_->ResumeRequest();
366 is_paused_ = false;
367 UpdateObservers();
368 return;
370 case COMPLETING_INTERNAL:
371 case COMPLETE_INTERNAL:
372 case CANCELLED_INTERNAL:
373 case RESUMING_INTERNAL:
374 return;
376 case INTERRUPTED_INTERNAL:
377 auto_resume_count_ = 0; // User input resets the counter.
378 ResumeInterruptedDownload();
379 return;
381 case MAX_DOWNLOAD_INTERNAL_STATE:
382 NOTREACHED();
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.
394 return;
397 if (IsDangerous()) {
398 RecordDangerousDownloadDiscard(
399 user_cancel ? DOWNLOAD_DISCARD_DUE_TO_USER_ACTION
400 : DOWNLOAD_DISCARD_DUE_TO_SHUTDOWN,
401 GetDangerType(),
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
419 // by interrupt.
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);
441 Cancel(true);
442 delegate_->AssertStateConsistent(this);
444 NotifyRemoved();
445 delegate_->DownloadRemoved(this);
446 // We have now been deleted.
449 void DownloadItemImpl::OpenDownload() {
450 DCHECK_CURRENTLY_ON(BrowserThread::UI);
452 if (!IsDone()) {
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.
455 if (!IsTemporary())
456 open_when_complete_ = !open_when_complete_;
457 return;
460 if (state_ != COMPLETE_INTERNAL || file_externally_removed_)
461 return;
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());
469 opened_ = true;
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 {
481 return download_id_;
484 DownloadItem::DownloadState DownloadItemImpl::GetState() const {
485 return InternalToExternalState(state_);
488 DownloadInterruptReason DownloadItemImpl::GetLastReason() const {
489 return last_reason_;
492 bool DownloadItemImpl::IsPaused() const {
493 return is_paused_;
496 bool DownloadItemImpl::IsTemporary() const {
497 return is_temporary_;
500 bool DownloadItemImpl::CanResume() const {
501 if ((GetState() == IN_PROGRESS) && IsPaused())
502 return true;
504 if (state_ != INTERRUPTED_INTERNAL)
505 return false;
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())
510 return false;
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 {
519 switch (state_) {
520 case IN_PROGRESS_INTERNAL:
521 case COMPLETING_INTERNAL:
522 return false;
524 case COMPLETE_INTERNAL:
525 case CANCELLED_INTERNAL:
526 return true;
528 case INTERRUPTED_INTERNAL:
529 return !CanResume();
531 case RESUMING_INTERNAL:
532 return false;
534 case MAX_DOWNLOAD_INTERNAL_STATE:
535 break;
537 NOTREACHED();
538 return true;
541 const GURL& DownloadItemImpl::GetURL() const {
542 return url_chain_.empty() ? GURL::EmptyGURL() : url_chain_.back();
545 const std::vector<GURL>& DownloadItemImpl::GetUrlChain() const {
546 return url_chain_;
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 {
560 return tab_url_;
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 {
576 return mime_type_;
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 {
600 return etag_;
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 {
612 return target_path_;
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 {
632 return hash_;
635 const std::string& DownloadItemImpl::GetHashState() const {
636 return hash_state_;
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));
651 return;
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));
659 return;
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 {
669 #if defined(OS_WIN) || defined(OS_MACOSX)
670 // TODO(noelutz): At this point only the windows views and OSX 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);
678 #else
679 return (danger_type_ == DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE ||
680 danger_type_ == DOWNLOAD_DANGER_TYPE_DANGEROUS_URL);
681 #endif
684 DownloadDangerType DownloadItemImpl::GetDangerType() const {
685 return danger_type_;
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();
693 if (speed == 0)
694 return false;
696 *remaining = base::TimeDelta::FromSeconds(
697 (total_bytes_ - received_bytes_) / speed);
698 return true;
701 int64 DownloadItemImpl::CurrentSpeed() const {
702 if (is_paused_)
703 return 0;
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)
711 return -1;
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 {
721 return total_bytes_;
724 int64 DownloadItemImpl::GetReceivedBytes() const {
725 return received_bytes_;
728 base::Time DownloadItemImpl::GetStartTime() const {
729 return start_time_;
732 base::Time DownloadItemImpl::GetEndTime() const {
733 return end_time_;
736 bool DownloadItemImpl::CanShowInFolder() {
737 // A download can be shown in the folder if the downloaded file is in a known
738 // location.
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() {
760 return auto_opened_;
763 bool DownloadItemImpl::GetOpened() const {
764 return opened_;
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.
776 if (request_handle_)
777 return request_handle_->GetWebContents();
778 return NULL;
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);
787 UpdateObservers();
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) {
799 opened_ = 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"
809 " state = %s",
810 download_id_,
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>";
819 ++iter;
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>";
827 if (verbose) {
828 description += base::StringPrintf(
829 " total = %" PRId64
830 " received = %" PRId64
831 " reason = %s"
832 " paused = %c"
833 " resume_mode = %s"
834 " auto_resume_count = %d"
835 " danger = %d"
836 " all_data_saved = %c"
837 " last_modified = '%s'"
838 " etag = '%s'"
839 " has_download_file = %s"
840 " url_chain = \n\t\"%s\"\n\t"
841 " full_path = \"%" PRFilePath "\"\n\t"
842 " target_path = \"%" PRFilePath "\"",
843 GetTotalBytes(),
844 GetReceivedBytes(),
845 DownloadInterruptReasonToString(last_reason_).c_str(),
846 IsPaused() ? 'T' : 'F',
847 DebugResumeModeString(GetResumeMode()),
848 auto_resume_count_,
849 GetDangerType(),
850 AllDataSaved() ? 'T' : 'F',
851 GetLastModifiedTime().c_str(),
852 GetETag().c_str(),
853 download_file_.get() ? "true" : "false",
854 url_list.c_str(),
855 GetFullPath().value().c_str(),
856 GetTargetFilePath().value().c_str());
857 } else {
858 description += base::StringPrintf(" url = \"%s\"", url_list.c_str());
861 description += " }";
863 return description;
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;
888 else if (force_user)
889 mode = RESUME_MODE_USER_CONTINUE;
890 else
891 mode = RESUME_MODE_IMMEDIATE_CONTINUE;
892 break;
894 case DOWNLOAD_INTERRUPT_REASON_SERVER_PRECONDITION:
895 case DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE:
896 case DOWNLOAD_INTERRUPT_REASON_FILE_TOO_SHORT:
897 if (force_user)
898 mode = RESUME_MODE_USER_RESTART;
899 else
900 mode = RESUME_MODE_IMMEDIATE_RESTART;
901 break;
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:
910 if (force_restart)
911 mode = RESUME_MODE_USER_RESTART;
912 else
913 mode = RESUME_MODE_USER_CONTINUE;
914 break;
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;
922 break;
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 case DOWNLOAD_INTERRUPT_REASON_SERVER_FORBIDDEN:
933 mode = RESUME_MODE_INVALID;
934 break;
937 return mode;
940 void DownloadItemImpl::MergeOriginInfoOnResume(
941 const DownloadCreateInfo& new_create_info) {
942 DCHECK_CURRENTLY_ON(BrowserThread::UI);
943 DCHECK_EQ(RESUMING_INTERNAL, state_);
944 DCHECK(!new_create_info.url_chain.empty());
946 // We are going to tack on any new redirects to our list of redirects.
947 // When a download is resumed, the URL used for the resumption request is the
948 // one at the end of the previous redirect chain. Tacking additional redirects
949 // to the end of this chain ensures that:
950 // - If the download needs to be resumed again, the ETag/Last-Modified headers
951 // will be used with the last server that sent them to us.
952 // - The redirect chain contains all the servers that were involved in this
953 // download since the initial request, in order.
954 std::vector<GURL>::const_iterator chain_iter =
955 new_create_info.url_chain.begin();
956 if (*chain_iter == url_chain_.back())
957 ++chain_iter;
959 // Record some stats. If the precondition failed (the server returned
960 // HTTP_PRECONDITION_FAILED), then the download will automatically retried as
961 // a full request rather than a partial. Full restarts clobber validators.
962 int origin_state = 0;
963 if (chain_iter != new_create_info.url_chain.end())
964 origin_state |= ORIGIN_STATE_ON_RESUMPTION_ADDITIONAL_REDIRECTS;
965 if (etag_ != new_create_info.etag ||
966 last_modified_time_ != new_create_info.last_modified)
967 origin_state |= ORIGIN_STATE_ON_RESUMPTION_VALIDATORS_CHANGED;
968 if (content_disposition_ != new_create_info.content_disposition)
969 origin_state |= ORIGIN_STATE_ON_RESUMPTION_CONTENT_DISPOSITION_CHANGED;
970 RecordOriginStateOnResumption(new_create_info.save_info->offset != 0,
971 origin_state);
973 url_chain_.insert(
974 url_chain_.end(), chain_iter, new_create_info.url_chain.end());
975 etag_ = new_create_info.etag;
976 last_modified_time_ = new_create_info.last_modified;
977 content_disposition_ = new_create_info.content_disposition;
979 // Don't update observers. This method is expected to be called just before a
980 // DownloadFile is created and Start() is called. The observers will be
981 // notified when the download transitions to the IN_PROGRESS state.
984 void DownloadItemImpl::NotifyRemoved() {
985 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadRemoved(this));
988 void DownloadItemImpl::OnDownloadedFileRemoved() {
989 file_externally_removed_ = true;
990 DVLOG(20) << __FUNCTION__ << " download=" << DebugString(true);
991 UpdateObservers();
994 base::WeakPtr<DownloadDestinationObserver>
995 DownloadItemImpl::DestinationObserverAsWeakPtr() {
996 return weak_ptr_factory_.GetWeakPtr();
999 const net::BoundNetLog& DownloadItemImpl::GetBoundNetLog() const {
1000 return bound_net_log_;
1003 void DownloadItemImpl::SetTotalBytes(int64 total_bytes) {
1004 total_bytes_ = total_bytes;
1007 void DownloadItemImpl::OnAllDataSaved(const std::string& final_hash) {
1008 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1010 DCHECK_EQ(IN_PROGRESS_INTERNAL, state_);
1011 DCHECK(!all_data_saved_);
1012 all_data_saved_ = true;
1013 DVLOG(20) << __FUNCTION__ << " download=" << DebugString(true);
1015 // Store final hash and null out intermediate serialized hash state.
1016 hash_ = final_hash;
1017 hash_state_ = "";
1019 UpdateObservers();
1022 void DownloadItemImpl::MarkAsComplete() {
1023 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1025 DCHECK(all_data_saved_);
1026 end_time_ = base::Time::Now();
1027 TransitionTo(COMPLETE_INTERNAL, UPDATE_OBSERVERS);
1030 void DownloadItemImpl::DestinationUpdate(int64 bytes_so_far,
1031 int64 bytes_per_sec,
1032 const std::string& hash_state) {
1033 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1034 DVLOG(20) << __FUNCTION__ << " so_far=" << bytes_so_far
1035 << " per_sec=" << bytes_per_sec << " download="
1036 << DebugString(true);
1038 if (GetState() != IN_PROGRESS) {
1039 // Ignore if we're no longer in-progress. This can happen if we race a
1040 // Cancel on the UI thread with an update on the FILE thread.
1042 // TODO(rdsmith): Arguably we should let this go through, as this means
1043 // the download really did get further than we know before it was
1044 // cancelled. But the gain isn't very large, and the code is more
1045 // fragile if it has to support in progress updates in a non-in-progress
1046 // state. This issue should be readdressed when we revamp performance
1047 // reporting.
1048 return;
1050 bytes_per_sec_ = bytes_per_sec;
1051 hash_state_ = hash_state;
1052 received_bytes_ = bytes_so_far;
1054 // If we've received more data than we were expecting (bad server info?),
1055 // revert to 'unknown size mode'.
1056 if (received_bytes_ > total_bytes_)
1057 total_bytes_ = 0;
1059 if (bound_net_log_.IsCapturing()) {
1060 bound_net_log_.AddEvent(
1061 net::NetLog::TYPE_DOWNLOAD_ITEM_UPDATED,
1062 net::NetLog::Int64Callback("bytes_so_far", received_bytes_));
1065 UpdateObservers();
1068 void DownloadItemImpl::DestinationError(DownloadInterruptReason reason) {
1069 // Postpone recognition of this error until after file name determination
1070 // has completed and the intermediate file has been renamed to simplify
1071 // resumption conditions.
1072 if (current_path_.empty() || target_path_.empty())
1073 destination_error_ = reason;
1074 else
1075 Interrupt(reason);
1078 void DownloadItemImpl::DestinationCompleted(const std::string& final_hash) {
1079 DVLOG(20) << __FUNCTION__ << " download=" << DebugString(true);
1080 if (GetState() != IN_PROGRESS)
1081 return;
1082 OnAllDataSaved(final_hash);
1083 MaybeCompleteDownload();
1086 // **** Download progression cascade
1088 void DownloadItemImpl::Init(bool active,
1089 DownloadType download_type) {
1090 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1092 if (active)
1093 RecordDownloadCount(START_COUNT);
1095 std::string file_name;
1096 if (download_type == SRC_HISTORY_IMPORT) {
1097 // target_path_ works for History and Save As versions.
1098 file_name = target_path_.AsUTF8Unsafe();
1099 } else {
1100 // See if it's set programmatically.
1101 file_name = forced_file_path_.AsUTF8Unsafe();
1102 // Possibly has a 'download' attribute for the anchor.
1103 if (file_name.empty())
1104 file_name = suggested_filename_;
1105 // From the URL file name.
1106 if (file_name.empty())
1107 file_name = GetURL().ExtractFileName();
1110 net::NetLog::ParametersCallback active_data =
1111 base::Bind(&ItemActivatedNetLogCallback, this, download_type, &file_name);
1112 if (active) {
1113 bound_net_log_.BeginEvent(
1114 net::NetLog::TYPE_DOWNLOAD_ITEM_ACTIVE, active_data);
1115 } else {
1116 bound_net_log_.AddEvent(
1117 net::NetLog::TYPE_DOWNLOAD_ITEM_ACTIVE, active_data);
1120 DVLOG(20) << __FUNCTION__ << "() " << DebugString(true);
1123 // We're starting the download.
1124 void DownloadItemImpl::Start(
1125 scoped_ptr<DownloadFile> file,
1126 scoped_ptr<DownloadRequestHandleInterface> req_handle) {
1127 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1128 DCHECK(!download_file_.get());
1129 DCHECK(file.get());
1130 DCHECK(req_handle.get());
1132 download_file_ = file.Pass();
1133 request_handle_ = req_handle.Pass();
1135 if (GetState() == CANCELLED) {
1136 // The download was in the process of resuming when it was cancelled. Don't
1137 // proceed.
1138 ReleaseDownloadFile(true);
1139 request_handle_->CancelRequest();
1140 return;
1143 TransitionTo(IN_PROGRESS_INTERNAL, UPDATE_OBSERVERS);
1145 BrowserThread::PostTask(
1146 BrowserThread::FILE, FROM_HERE,
1147 base::Bind(&DownloadFile::Initialize,
1148 // Safe because we control download file lifetime.
1149 base::Unretained(download_file_.get()),
1150 base::Bind(&DownloadItemImpl::OnDownloadFileInitialized,
1151 weak_ptr_factory_.GetWeakPtr())));
1154 void DownloadItemImpl::OnDownloadFileInitialized(
1155 DownloadInterruptReason result) {
1156 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1157 if (result != DOWNLOAD_INTERRUPT_REASON_NONE) {
1158 Interrupt(result);
1159 // TODO(rdsmith/asanka): Arguably we should show this in the UI, but
1160 // it's not at all clear what to show--we haven't done filename
1161 // determination, so we don't know what name to display. OTOH,
1162 // the failure mode of not showing the DI if the file initialization
1163 // fails isn't a good one. Can we hack up a name based on the
1164 // URLRequest? We'll need to make sure that initialization happens
1165 // properly. Possibly the right thing is to have the UI handle
1166 // this case specially.
1167 return;
1170 delegate_->DetermineDownloadTarget(
1171 this, base::Bind(&DownloadItemImpl::OnDownloadTargetDetermined,
1172 weak_ptr_factory_.GetWeakPtr()));
1175 // Called by delegate_ when the download target path has been
1176 // determined.
1177 void DownloadItemImpl::OnDownloadTargetDetermined(
1178 const base::FilePath& target_path,
1179 TargetDisposition disposition,
1180 DownloadDangerType danger_type,
1181 const base::FilePath& intermediate_path) {
1182 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1184 // If the |target_path| is empty, then we consider this download to be
1185 // canceled.
1186 if (target_path.empty()) {
1187 Cancel(true);
1188 return;
1191 // TODO(rdsmith,asanka): We are ignoring the possibility that the download
1192 // has been interrupted at this point until we finish the intermediate
1193 // rename and set the full path. That's dangerous, because we might race
1194 // with resumption, either manual (because the interrupt is visible to the
1195 // UI) or automatic. If we keep the "ignore an error on download until file
1196 // name determination complete" semantics, we need to make sure that the
1197 // error is kept completely invisible until that point.
1199 DVLOG(20) << __FUNCTION__ << " " << target_path.value() << " " << disposition
1200 << " " << danger_type << " " << DebugString(true);
1202 target_path_ = target_path;
1203 target_disposition_ = disposition;
1204 SetDangerType(danger_type);
1206 // We want the intermediate and target paths to refer to the same directory so
1207 // that they are both on the same device and subject to same
1208 // space/permission/availability constraints.
1209 DCHECK(intermediate_path.DirName() == target_path.DirName());
1211 // During resumption, we may choose to proceed with the same intermediate
1212 // file. No rename is necessary if our intermediate file already has the
1213 // correct name.
1215 // The intermediate name may change from its original value during filename
1216 // determination on resumption, for example if the reason for the interruption
1217 // was the download target running out space, resulting in a user prompt.
1218 if (intermediate_path == current_path_) {
1219 OnDownloadRenamedToIntermediateName(DOWNLOAD_INTERRUPT_REASON_NONE,
1220 intermediate_path);
1221 return;
1224 // Rename to intermediate name.
1225 // TODO(asanka): Skip this rename if AllDataSaved() is true. This avoids a
1226 // spurious rename when we can just rename to the final
1227 // filename. Unnecessary renames may cause bugs like
1228 // http://crbug.com/74187.
1229 DCHECK(!is_save_package_download_);
1230 DCHECK(download_file_.get());
1231 DownloadFile::RenameCompletionCallback callback =
1232 base::Bind(&DownloadItemImpl::OnDownloadRenamedToIntermediateName,
1233 weak_ptr_factory_.GetWeakPtr());
1234 BrowserThread::PostTask(
1235 BrowserThread::FILE, FROM_HERE,
1236 base::Bind(&DownloadFile::RenameAndUniquify,
1237 // Safe because we control download file lifetime.
1238 base::Unretained(download_file_.get()),
1239 intermediate_path, callback));
1242 void DownloadItemImpl::OnDownloadRenamedToIntermediateName(
1243 DownloadInterruptReason reason,
1244 const base::FilePath& full_path) {
1245 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1246 DVLOG(20) << __FUNCTION__ << " download=" << DebugString(true);
1248 if (DOWNLOAD_INTERRUPT_REASON_NONE != destination_error_) {
1249 // Process destination error. If both |reason| and |destination_error_|
1250 // refer to actual errors, we want to use the |destination_error_| as the
1251 // argument to the Interrupt() routine, as it happened first.
1252 if (reason == DOWNLOAD_INTERRUPT_REASON_NONE)
1253 SetFullPath(full_path);
1254 Interrupt(destination_error_);
1255 destination_error_ = DOWNLOAD_INTERRUPT_REASON_NONE;
1256 } else if (DOWNLOAD_INTERRUPT_REASON_NONE != reason) {
1257 Interrupt(reason);
1258 // All file errors result in file deletion above; no need to cleanup. The
1259 // current_path_ should be empty. Resuming this download will force a
1260 // restart and a re-doing of filename determination.
1261 DCHECK(current_path_.empty());
1262 } else {
1263 SetFullPath(full_path);
1264 UpdateObservers();
1265 MaybeCompleteDownload();
1269 // When SavePackage downloads MHTML to GData (see
1270 // SavePackageFilePickerChromeOS), GData calls MaybeCompleteDownload() like it
1271 // does for non-SavePackage downloads, but SavePackage downloads never satisfy
1272 // IsDownloadReadyForCompletion(). GDataDownloadObserver manually calls
1273 // DownloadItem::UpdateObservers() when the upload completes so that SavePackage
1274 // notices that the upload has completed and runs its normal Finish() pathway.
1275 // MaybeCompleteDownload() is never the mechanism by which SavePackage completes
1276 // downloads. SavePackage always uses its own Finish() to mark downloads
1277 // complete.
1278 void DownloadItemImpl::MaybeCompleteDownload() {
1279 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1280 DCHECK(!is_save_package_download_);
1282 if (!IsDownloadReadyForCompletion(
1283 base::Bind(&DownloadItemImpl::MaybeCompleteDownload,
1284 weak_ptr_factory_.GetWeakPtr())))
1285 return;
1287 // TODO(rdsmith): DCHECK that we only pass through this point
1288 // once per download. The natural way to do this is by a state
1289 // transition on the DownloadItem.
1291 // Confirm we're in the proper set of states to be here;
1292 // have all data, have a history handle, (validated or safe).
1293 DCHECK_EQ(IN_PROGRESS_INTERNAL, state_);
1294 DCHECK(!IsDangerous());
1295 DCHECK(all_data_saved_);
1297 OnDownloadCompleting();
1300 // Called by MaybeCompleteDownload() when it has determined that the download
1301 // is ready for completion.
1302 void DownloadItemImpl::OnDownloadCompleting() {
1303 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1305 if (state_ != IN_PROGRESS_INTERNAL)
1306 return;
1308 DVLOG(20) << __FUNCTION__ << "()"
1309 << " " << DebugString(true);
1310 DCHECK(!GetTargetFilePath().empty());
1311 DCHECK(!IsDangerous());
1313 // TODO(rdsmith/benjhayden): Remove as part of SavePackage integration.
1314 if (is_save_package_download_) {
1315 // Avoid doing anything on the file thread; there's nothing we control
1316 // there.
1317 // Strictly speaking, this skips giving the embedder a chance to open
1318 // the download. But on a save package download, there's no real
1319 // concept of opening.
1320 Completed();
1321 return;
1324 DCHECK(download_file_.get());
1325 // Unilaterally rename; even if it already has the right name,
1326 // we need theannotation.
1327 DownloadFile::RenameCompletionCallback callback =
1328 base::Bind(&DownloadItemImpl::OnDownloadRenamedToFinalName,
1329 weak_ptr_factory_.GetWeakPtr());
1330 BrowserThread::PostTask(
1331 BrowserThread::FILE, FROM_HERE,
1332 base::Bind(&DownloadFile::RenameAndAnnotate,
1333 base::Unretained(download_file_.get()),
1334 GetTargetFilePath(), callback));
1337 void DownloadItemImpl::OnDownloadRenamedToFinalName(
1338 DownloadInterruptReason reason,
1339 const base::FilePath& full_path) {
1340 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1341 DCHECK(!is_save_package_download_);
1343 // If a cancel or interrupt hit, we'll cancel the DownloadFile, which
1344 // will result in deleting the file on the file thread. So we don't
1345 // care about the name having been changed.
1346 if (state_ != IN_PROGRESS_INTERNAL)
1347 return;
1349 DVLOG(20) << __FUNCTION__ << "()"
1350 << " full_path = \"" << full_path.value() << "\""
1351 << " " << DebugString(false);
1353 if (DOWNLOAD_INTERRUPT_REASON_NONE != reason) {
1354 Interrupt(reason);
1356 // All file errors should have resulted in in file deletion above. On
1357 // resumption we will need to re-do filename determination.
1358 DCHECK(current_path_.empty());
1359 return;
1362 DCHECK(target_path_ == full_path);
1364 if (full_path != current_path_) {
1365 // full_path is now the current and target file path.
1366 DCHECK(!full_path.empty());
1367 SetFullPath(full_path);
1370 // Complete the download and release the DownloadFile.
1371 DCHECK(download_file_.get());
1372 ReleaseDownloadFile(false);
1374 // We're not completely done with the download item yet, but at this
1375 // point we're committed to complete the download. Cancels (or Interrupts,
1376 // though it's not clear how they could happen) after this point will be
1377 // ignored.
1378 TransitionTo(COMPLETING_INTERNAL, DONT_UPDATE_OBSERVERS);
1380 if (delegate_->ShouldOpenDownload(
1381 this, base::Bind(&DownloadItemImpl::DelayedDownloadOpened,
1382 weak_ptr_factory_.GetWeakPtr()))) {
1383 Completed();
1384 } else {
1385 delegate_delayed_complete_ = true;
1386 UpdateObservers();
1390 void DownloadItemImpl::DelayedDownloadOpened(bool auto_opened) {
1391 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1393 auto_opened_ = auto_opened;
1394 Completed();
1397 void DownloadItemImpl::Completed() {
1398 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1400 DVLOG(20) << __FUNCTION__ << "() " << DebugString(false);
1402 DCHECK(all_data_saved_);
1403 end_time_ = base::Time::Now();
1404 TransitionTo(COMPLETE_INTERNAL, UPDATE_OBSERVERS);
1405 RecordDownloadCompleted(start_tick_, received_bytes_);
1407 if (auto_opened_) {
1408 // If it was already handled by the delegate, do nothing.
1409 } else if (GetOpenWhenComplete() ||
1410 ShouldOpenFileBasedOnExtension() ||
1411 IsTemporary()) {
1412 // If the download is temporary, like in drag-and-drop, do not open it but
1413 // we still need to set it auto-opened so that it can be removed from the
1414 // download shelf.
1415 if (!IsTemporary())
1416 OpenDownload();
1418 auto_opened_ = true;
1419 UpdateObservers();
1423 void DownloadItemImpl::OnResumeRequestStarted(
1424 DownloadItem* item,
1425 DownloadInterruptReason interrupt_reason) {
1426 // If |item| is not NULL, then Start() has been called already, and nothing
1427 // more needs to be done here.
1428 if (item) {
1429 DCHECK_EQ(DOWNLOAD_INTERRUPT_REASON_NONE, interrupt_reason);
1430 DCHECK_EQ(static_cast<DownloadItem*>(this), item);
1431 return;
1433 // Otherwise, the request failed without passing through
1434 // DownloadResourceHandler::OnResponseStarted.
1435 DCHECK_NE(DOWNLOAD_INTERRUPT_REASON_NONE, interrupt_reason);
1436 Interrupt(interrupt_reason);
1439 // **** End of Download progression cascade
1441 // An error occurred somewhere.
1442 void DownloadItemImpl::Interrupt(DownloadInterruptReason reason) {
1443 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1444 DCHECK_NE(DOWNLOAD_INTERRUPT_REASON_NONE, reason);
1446 // Somewhat counter-intuitively, it is possible for us to receive an
1447 // interrupt after we've already been interrupted. The generation of
1448 // interrupts from the file thread Renames and the generation of
1449 // interrupts from disk writes go through two different mechanisms (driven
1450 // by rename requests from UI thread and by write requests from IO thread,
1451 // respectively), and since we choose not to keep state on the File thread,
1452 // this is the place where the races collide. It's also possible for
1453 // interrupts to race with cancels.
1455 // Whatever happens, the first one to hit the UI thread wins.
1456 if (state_ != IN_PROGRESS_INTERNAL && state_ != RESUMING_INTERNAL)
1457 return;
1459 last_reason_ = reason;
1461 ResumeMode resume_mode = GetResumeMode();
1463 if (state_ == IN_PROGRESS_INTERNAL) {
1464 // Cancel (delete file) if:
1465 // 1) we're going to restart.
1466 // 2) Resumption isn't possible (download was cancelled or blocked due to
1467 // security restrictions).
1468 // 3) Resumption isn't enabled.
1469 // No point in leaving data around we aren't going to use.
1470 ReleaseDownloadFile(resume_mode == RESUME_MODE_IMMEDIATE_RESTART ||
1471 resume_mode == RESUME_MODE_USER_RESTART ||
1472 resume_mode == RESUME_MODE_INVALID ||
1473 !IsDownloadResumptionEnabled());
1475 // Cancel the originating URL request.
1476 request_handle_->CancelRequest();
1477 } else {
1478 DCHECK(!download_file_.get());
1481 // Reset all data saved, as even if we did save all the data we're going
1482 // to go through another round of downloading when we resume.
1483 // There's a potential problem here in the abstract, as if we did download
1484 // all the data and then run into a continuable error, on resumption we
1485 // won't download any more data. However, a) there are currently no
1486 // continuable errors that can occur after we download all the data, and
1487 // b) if there were, that would probably simply result in a null range
1488 // request, which would generate a DestinationCompleted() notification
1489 // from the DownloadFile, which would behave properly with setting
1490 // all_data_saved_ to false here.
1491 all_data_saved_ = false;
1493 TransitionTo(INTERRUPTED_INTERNAL, DONT_UPDATE_OBSERVERS);
1494 RecordDownloadInterrupted(reason, received_bytes_, total_bytes_);
1495 if (!GetWebContents())
1496 RecordDownloadCount(INTERRUPTED_WITHOUT_WEBCONTENTS);
1498 AutoResumeIfValid();
1499 UpdateObservers();
1502 void DownloadItemImpl::ReleaseDownloadFile(bool destroy_file) {
1503 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1505 if (destroy_file) {
1506 BrowserThread::PostTask(
1507 BrowserThread::FILE, FROM_HERE,
1508 // Will be deleted at end of task execution.
1509 base::Bind(&DownloadFileCancel, base::Passed(&download_file_)));
1510 // Avoid attempting to reuse the intermediate file by clearing out
1511 // current_path_.
1512 current_path_.clear();
1513 } else {
1514 BrowserThread::PostTask(
1515 BrowserThread::FILE,
1516 FROM_HERE,
1517 base::Bind(base::IgnoreResult(&DownloadFileDetach),
1518 // Will be deleted at end of task execution.
1519 base::Passed(&download_file_)));
1521 // Don't accept any more messages from the DownloadFile, and null
1522 // out any previous "all data received". This also breaks links to
1523 // other entities we've given out weak pointers to.
1524 weak_ptr_factory_.InvalidateWeakPtrs();
1527 bool DownloadItemImpl::IsDownloadReadyForCompletion(
1528 const base::Closure& state_change_notification) {
1529 // If we don't have all the data, the download is not ready for
1530 // completion.
1531 if (!AllDataSaved())
1532 return false;
1534 // If the download is dangerous, but not yet validated, it's not ready for
1535 // completion.
1536 if (IsDangerous())
1537 return false;
1539 // If the download isn't active (e.g. has been cancelled) it's not
1540 // ready for completion.
1541 if (state_ != IN_PROGRESS_INTERNAL)
1542 return false;
1544 // If the target filename hasn't been determined, then it's not ready for
1545 // completion. This is checked in ReadyForDownloadCompletionDone().
1546 if (GetTargetFilePath().empty())
1547 return false;
1549 // This is checked in NeedsRename(). Without this conditional,
1550 // browser_tests:DownloadTest.DownloadMimeType fails the DCHECK.
1551 if (target_path_.DirName() != current_path_.DirName())
1552 return false;
1554 // Give the delegate a chance to hold up a stop sign. It'll call
1555 // use back through the passed callback if it does and that state changes.
1556 if (!delegate_->ShouldCompleteDownload(this, state_change_notification))
1557 return false;
1559 return true;
1562 void DownloadItemImpl::TransitionTo(DownloadInternalState new_state,
1563 ShouldUpdateObservers notify_action) {
1564 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1566 if (state_ == new_state)
1567 return;
1569 DownloadInternalState old_state = state_;
1570 state_ = new_state;
1572 switch (state_) {
1573 case COMPLETING_INTERNAL:
1574 bound_net_log_.AddEvent(
1575 net::NetLog::TYPE_DOWNLOAD_ITEM_COMPLETING,
1576 base::Bind(&ItemCompletingNetLogCallback, received_bytes_, &hash_));
1577 break;
1578 case COMPLETE_INTERNAL:
1579 bound_net_log_.AddEvent(
1580 net::NetLog::TYPE_DOWNLOAD_ITEM_FINISHED,
1581 base::Bind(&ItemFinishedNetLogCallback, auto_opened_));
1582 break;
1583 case INTERRUPTED_INTERNAL:
1584 bound_net_log_.AddEvent(
1585 net::NetLog::TYPE_DOWNLOAD_ITEM_INTERRUPTED,
1586 base::Bind(&ItemInterruptedNetLogCallback, last_reason_,
1587 received_bytes_, &hash_state_));
1588 break;
1589 case IN_PROGRESS_INTERNAL:
1590 if (old_state == INTERRUPTED_INTERNAL) {
1591 bound_net_log_.AddEvent(
1592 net::NetLog::TYPE_DOWNLOAD_ITEM_RESUMED,
1593 base::Bind(&ItemResumingNetLogCallback,
1594 false, last_reason_, received_bytes_, &hash_state_));
1596 break;
1597 case CANCELLED_INTERNAL:
1598 bound_net_log_.AddEvent(
1599 net::NetLog::TYPE_DOWNLOAD_ITEM_CANCELED,
1600 base::Bind(&ItemCanceledNetLogCallback, received_bytes_,
1601 &hash_state_));
1602 break;
1603 default:
1604 break;
1607 DVLOG(20) << " " << __FUNCTION__ << "()" << " this = " << DebugString(true)
1608 << " " << InternalToExternalState(old_state)
1609 << " " << InternalToExternalState(state_);
1611 bool is_done = (state_ != IN_PROGRESS_INTERNAL &&
1612 state_ != COMPLETING_INTERNAL);
1613 bool was_done = (old_state != IN_PROGRESS_INTERNAL &&
1614 old_state != COMPLETING_INTERNAL);
1615 // Termination
1616 if (is_done && !was_done)
1617 bound_net_log_.EndEvent(net::NetLog::TYPE_DOWNLOAD_ITEM_ACTIVE);
1619 // Resumption
1620 if (was_done && !is_done) {
1621 std::string file_name(target_path_.BaseName().AsUTF8Unsafe());
1622 bound_net_log_.BeginEvent(net::NetLog::TYPE_DOWNLOAD_ITEM_ACTIVE,
1623 base::Bind(&ItemActivatedNetLogCallback,
1624 this, SRC_ACTIVE_DOWNLOAD,
1625 &file_name));
1628 if (notify_action == UPDATE_OBSERVERS)
1629 UpdateObservers();
1632 void DownloadItemImpl::SetDangerType(DownloadDangerType danger_type) {
1633 if (danger_type != danger_type_) {
1634 bound_net_log_.AddEvent(
1635 net::NetLog::TYPE_DOWNLOAD_ITEM_SAFETY_STATE_UPDATED,
1636 base::Bind(&ItemCheckedNetLogCallback, danger_type));
1638 // Only record the Malicious UMA stat if it's going from {not malicious} ->
1639 // {malicious}.
1640 if ((danger_type_ == DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS ||
1641 danger_type_ == DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE ||
1642 danger_type_ == DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT ||
1643 danger_type_ == DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT) &&
1644 (danger_type == DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST ||
1645 danger_type == DOWNLOAD_DANGER_TYPE_DANGEROUS_URL ||
1646 danger_type == DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT ||
1647 danger_type == DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED)) {
1648 RecordMaliciousDownloadClassified(danger_type);
1650 danger_type_ = danger_type;
1653 void DownloadItemImpl::SetFullPath(const base::FilePath& new_path) {
1654 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1655 DVLOG(20) << __FUNCTION__ << "()"
1656 << " new_path = \"" << new_path.value() << "\""
1657 << " " << DebugString(true);
1658 DCHECK(!new_path.empty());
1660 bound_net_log_.AddEvent(
1661 net::NetLog::TYPE_DOWNLOAD_ITEM_RENAMED,
1662 base::Bind(&ItemRenamedNetLogCallback, &current_path_, &new_path));
1664 current_path_ = new_path;
1667 void DownloadItemImpl::AutoResumeIfValid() {
1668 DVLOG(20) << __FUNCTION__ << "() " << DebugString(true);
1669 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1670 ResumeMode mode = GetResumeMode();
1672 if (mode != RESUME_MODE_IMMEDIATE_RESTART &&
1673 mode != RESUME_MODE_IMMEDIATE_CONTINUE) {
1674 return;
1677 auto_resume_count_++;
1679 ResumeInterruptedDownload();
1682 void DownloadItemImpl::ResumeInterruptedDownload() {
1683 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1685 // If the flag for downloads resumption isn't enabled, ignore
1686 // this request.
1687 const base::CommandLine& command_line =
1688 *base::CommandLine::ForCurrentProcess();
1689 if (!command_line.HasSwitch(switches::kEnableDownloadResumption))
1690 return;
1692 // If we're not interrupted, ignore the request; our caller is drunk.
1693 if (state_ != INTERRUPTED_INTERNAL)
1694 return;
1696 // If we can't get a web contents, we can't resume the download.
1697 // TODO(rdsmith): Find some alternative web contents to use--this
1698 // means we can't restart a download if it's a download imported
1699 // from the history.
1700 if (!GetWebContents())
1701 return;
1703 // Reset the appropriate state if restarting.
1704 ResumeMode mode = GetResumeMode();
1705 if (mode == RESUME_MODE_IMMEDIATE_RESTART ||
1706 mode == RESUME_MODE_USER_RESTART) {
1707 received_bytes_ = 0;
1708 hash_state_ = "";
1709 last_modified_time_ = "";
1710 etag_ = "";
1713 scoped_ptr<DownloadUrlParameters> download_params(
1714 DownloadUrlParameters::FromWebContents(GetWebContents(),
1715 GetOriginalUrl()));
1717 download_params->set_file_path(GetFullPath());
1718 download_params->set_offset(GetReceivedBytes());
1719 download_params->set_hash_state(GetHashState());
1720 download_params->set_last_modified(GetLastModifiedTime());
1721 download_params->set_etag(GetETag());
1722 download_params->set_callback(
1723 base::Bind(&DownloadItemImpl::OnResumeRequestStarted,
1724 weak_ptr_factory_.GetWeakPtr()));
1726 delegate_->ResumeInterruptedDownload(download_params.Pass(), GetId());
1727 // Just in case we were interrupted while paused.
1728 is_paused_ = false;
1730 TransitionTo(RESUMING_INTERNAL, DONT_UPDATE_OBSERVERS);
1733 // static
1734 DownloadItem::DownloadState DownloadItemImpl::InternalToExternalState(
1735 DownloadInternalState internal_state) {
1736 switch (internal_state) {
1737 case IN_PROGRESS_INTERNAL:
1738 return IN_PROGRESS;
1739 case COMPLETING_INTERNAL:
1740 return IN_PROGRESS;
1741 case COMPLETE_INTERNAL:
1742 return COMPLETE;
1743 case CANCELLED_INTERNAL:
1744 return CANCELLED;
1745 case INTERRUPTED_INTERNAL:
1746 return INTERRUPTED;
1747 case RESUMING_INTERNAL:
1748 return INTERRUPTED;
1749 case MAX_DOWNLOAD_INTERNAL_STATE:
1750 break;
1752 NOTREACHED();
1753 return MAX_DOWNLOAD_STATE;
1756 // static
1757 DownloadItemImpl::DownloadInternalState
1758 DownloadItemImpl::ExternalToInternalState(
1759 DownloadState external_state) {
1760 switch (external_state) {
1761 case IN_PROGRESS:
1762 return IN_PROGRESS_INTERNAL;
1763 case COMPLETE:
1764 return COMPLETE_INTERNAL;
1765 case CANCELLED:
1766 return CANCELLED_INTERNAL;
1767 case INTERRUPTED:
1768 return INTERRUPTED_INTERNAL;
1769 default:
1770 NOTREACHED();
1772 return MAX_DOWNLOAD_INTERNAL_STATE;
1775 const char* DownloadItemImpl::DebugDownloadStateString(
1776 DownloadInternalState state) {
1777 switch (state) {
1778 case IN_PROGRESS_INTERNAL:
1779 return "IN_PROGRESS";
1780 case COMPLETING_INTERNAL:
1781 return "COMPLETING";
1782 case COMPLETE_INTERNAL:
1783 return "COMPLETE";
1784 case CANCELLED_INTERNAL:
1785 return "CANCELLED";
1786 case INTERRUPTED_INTERNAL:
1787 return "INTERRUPTED";
1788 case RESUMING_INTERNAL:
1789 return "RESUMING";
1790 case MAX_DOWNLOAD_INTERNAL_STATE:
1791 break;
1793 NOTREACHED() << "Unknown download state " << state;
1794 return "unknown";
1797 const char* DownloadItemImpl::DebugResumeModeString(ResumeMode mode) {
1798 switch (mode) {
1799 case RESUME_MODE_INVALID:
1800 return "INVALID";
1801 case RESUME_MODE_IMMEDIATE_CONTINUE:
1802 return "IMMEDIATE_CONTINUE";
1803 case RESUME_MODE_IMMEDIATE_RESTART:
1804 return "IMMEDIATE_RESTART";
1805 case RESUME_MODE_USER_CONTINUE:
1806 return "USER_CONTINUE";
1807 case RESUME_MODE_USER_RESTART:
1808 return "USER_RESTART";
1810 NOTREACHED() << "Unknown resume mode " << mode;
1811 return "unknown";
1814 } // namespace content