Remove PlatformFile from profile_browsertest
[chromium-blink-merge.git] / content / browser / download / download_item_impl.cc
blobcd2623ef98148de9e7e028abbc07a6620be9cb23
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/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(BrowserThread::CurrentlyOn(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(BrowserThread::CurrentlyOn(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(BrowserThread::CurrentlyOn(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(BrowserThread::CurrentlyOn(BrowserThread::FILE));
92 download_file->Cancel();
95 bool IsDownloadResumptionEnabled() {
96 return 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 base::Time& start_time,
117 const base::Time& end_time,
118 const std::string& etag,
119 const std::string& last_modified,
120 int64 received_bytes,
121 int64 total_bytes,
122 DownloadItem::DownloadState state,
123 DownloadDangerType danger_type,
124 DownloadInterruptReason interrupt_reason,
125 bool opened,
126 const net::BoundNetLog& bound_net_log)
127 : is_save_package_download_(false),
128 download_id_(download_id),
129 current_path_(current_path),
130 target_path_(target_path),
131 target_disposition_(TARGET_DISPOSITION_OVERWRITE),
132 url_chain_(url_chain),
133 referrer_url_(referrer_url),
134 transition_type_(PAGE_TRANSITION_LINK),
135 has_user_gesture_(false),
136 total_bytes_(total_bytes),
137 received_bytes_(received_bytes),
138 bytes_per_sec_(0),
139 last_modified_time_(last_modified),
140 etag_(etag),
141 last_reason_(interrupt_reason),
142 start_tick_(base::TimeTicks()),
143 state_(ExternalToInternalState(state)),
144 danger_type_(danger_type),
145 start_time_(start_time),
146 end_time_(end_time),
147 delegate_(delegate),
148 is_paused_(false),
149 auto_resume_count_(0),
150 open_when_complete_(false),
151 file_externally_removed_(false),
152 auto_opened_(false),
153 is_temporary_(false),
154 all_data_saved_(state == COMPLETE),
155 destination_error_(content::DOWNLOAD_INTERRUPT_REASON_NONE),
156 opened_(opened),
157 delegate_delayed_complete_(false),
158 bound_net_log_(bound_net_log),
159 weak_ptr_factory_(this) {
160 delegate_->Attach();
161 DCHECK_NE(IN_PROGRESS_INTERNAL, state_);
162 Init(false /* not actively downloading */, SRC_HISTORY_IMPORT);
165 // Constructing for a regular download:
166 DownloadItemImpl::DownloadItemImpl(
167 DownloadItemImplDelegate* delegate,
168 uint32 download_id,
169 const DownloadCreateInfo& info,
170 const net::BoundNetLog& bound_net_log)
171 : is_save_package_download_(false),
172 download_id_(download_id),
173 target_disposition_(
174 (info.save_info->prompt_for_save_location) ?
175 TARGET_DISPOSITION_PROMPT : TARGET_DISPOSITION_OVERWRITE),
176 url_chain_(info.url_chain),
177 referrer_url_(info.referrer_url),
178 tab_url_(info.tab_url),
179 tab_referrer_url_(info.tab_referrer_url),
180 suggested_filename_(base::UTF16ToUTF8(info.save_info->suggested_name)),
181 forced_file_path_(info.save_info->file_path),
182 transition_type_(info.transition_type),
183 has_user_gesture_(info.has_user_gesture),
184 content_disposition_(info.content_disposition),
185 mime_type_(info.mime_type),
186 original_mime_type_(info.original_mime_type),
187 remote_address_(info.remote_address),
188 total_bytes_(info.total_bytes),
189 received_bytes_(0),
190 bytes_per_sec_(0),
191 last_modified_time_(info.last_modified),
192 etag_(info.etag),
193 last_reason_(DOWNLOAD_INTERRUPT_REASON_NONE),
194 start_tick_(base::TimeTicks::Now()),
195 state_(IN_PROGRESS_INTERNAL),
196 danger_type_(DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS),
197 start_time_(info.start_time),
198 delegate_(delegate),
199 is_paused_(false),
200 auto_resume_count_(0),
201 open_when_complete_(false),
202 file_externally_removed_(false),
203 auto_opened_(false),
204 is_temporary_(!info.save_info->file_path.empty()),
205 all_data_saved_(false),
206 destination_error_(content::DOWNLOAD_INTERRUPT_REASON_NONE),
207 opened_(false),
208 delegate_delayed_complete_(false),
209 bound_net_log_(bound_net_log),
210 weak_ptr_factory_(this) {
211 delegate_->Attach();
212 Init(true /* actively downloading */, SRC_ACTIVE_DOWNLOAD);
214 // Link the event sources.
215 bound_net_log_.AddEvent(
216 net::NetLog::TYPE_DOWNLOAD_URL_REQUEST,
217 info.request_bound_net_log.source().ToEventParametersCallback());
219 info.request_bound_net_log.AddEvent(
220 net::NetLog::TYPE_DOWNLOAD_STARTED,
221 bound_net_log_.source().ToEventParametersCallback());
224 // Constructing for the "Save Page As..." feature:
225 DownloadItemImpl::DownloadItemImpl(
226 DownloadItemImplDelegate* delegate,
227 uint32 download_id,
228 const base::FilePath& path,
229 const GURL& url,
230 const std::string& mime_type,
231 scoped_ptr<DownloadRequestHandleInterface> request_handle,
232 const net::BoundNetLog& bound_net_log)
233 : is_save_package_download_(true),
234 request_handle_(request_handle.Pass()),
235 download_id_(download_id),
236 current_path_(path),
237 target_path_(path),
238 target_disposition_(TARGET_DISPOSITION_OVERWRITE),
239 url_chain_(1, url),
240 referrer_url_(GURL()),
241 transition_type_(PAGE_TRANSITION_LINK),
242 has_user_gesture_(false),
243 mime_type_(mime_type),
244 original_mime_type_(mime_type),
245 total_bytes_(0),
246 received_bytes_(0),
247 bytes_per_sec_(0),
248 last_reason_(DOWNLOAD_INTERRUPT_REASON_NONE),
249 start_tick_(base::TimeTicks::Now()),
250 state_(IN_PROGRESS_INTERNAL),
251 danger_type_(DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS),
252 start_time_(base::Time::Now()),
253 delegate_(delegate),
254 is_paused_(false),
255 auto_resume_count_(0),
256 open_when_complete_(false),
257 file_externally_removed_(false),
258 auto_opened_(false),
259 is_temporary_(false),
260 all_data_saved_(false),
261 destination_error_(content::DOWNLOAD_INTERRUPT_REASON_NONE),
262 opened_(false),
263 delegate_delayed_complete_(false),
264 bound_net_log_(bound_net_log),
265 weak_ptr_factory_(this) {
266 delegate_->Attach();
267 Init(true /* actively downloading */, SRC_SAVE_PAGE_AS);
270 DownloadItemImpl::~DownloadItemImpl() {
271 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
273 // Should always have been nuked before now, at worst in
274 // DownloadManager shutdown.
275 DCHECK(!download_file_.get());
277 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadDestroyed(this));
278 delegate_->AssertStateConsistent(this);
279 delegate_->Detach();
282 void DownloadItemImpl::AddObserver(Observer* observer) {
283 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
285 observers_.AddObserver(observer);
288 void DownloadItemImpl::RemoveObserver(Observer* observer) {
289 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
291 observers_.RemoveObserver(observer);
294 void DownloadItemImpl::UpdateObservers() {
295 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
297 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
300 void DownloadItemImpl::ValidateDangerousDownload() {
301 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
302 DCHECK(!IsDone());
303 DCHECK(IsDangerous());
305 VLOG(20) << __FUNCTION__ << " download=" << DebugString(true);
307 if (IsDone() || !IsDangerous())
308 return;
310 RecordDangerousDownloadAccept(GetDangerType(),
311 GetTargetFilePath());
313 danger_type_ = DOWNLOAD_DANGER_TYPE_USER_VALIDATED;
315 bound_net_log_.AddEvent(
316 net::NetLog::TYPE_DOWNLOAD_ITEM_SAFETY_STATE_UPDATED,
317 base::Bind(&ItemCheckedNetLogCallback, GetDangerType()));
319 UpdateObservers();
321 MaybeCompleteDownload();
324 void DownloadItemImpl::StealDangerousDownload(
325 const AcquireFileCallback& callback) {
326 VLOG(20) << __FUNCTION__ << "() download = " << DebugString(true);
327 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
328 DCHECK(IsDangerous());
329 if (download_file_) {
330 BrowserThread::PostTaskAndReplyWithResult(
331 BrowserThread::FILE,
332 FROM_HERE,
333 base::Bind(&DownloadFileDetach, base::Passed(&download_file_)),
334 callback);
335 } else {
336 callback.Run(current_path_);
338 current_path_.clear();
339 Remove();
340 // We have now been deleted.
343 void DownloadItemImpl::Pause() {
344 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
346 // Ignore irrelevant states.
347 if (state_ != IN_PROGRESS_INTERNAL || is_paused_)
348 return;
350 request_handle_->PauseRequest();
351 is_paused_ = true;
352 UpdateObservers();
355 void DownloadItemImpl::Resume() {
356 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
357 switch (state_) {
358 case IN_PROGRESS_INTERNAL:
359 if (!is_paused_)
360 return;
361 request_handle_->ResumeRequest();
362 is_paused_ = false;
363 UpdateObservers();
364 return;
366 case COMPLETING_INTERNAL:
367 case COMPLETE_INTERNAL:
368 case CANCELLED_INTERNAL:
369 case RESUMING_INTERNAL:
370 return;
372 case INTERRUPTED_INTERNAL:
373 auto_resume_count_ = 0; // User input resets the counter.
374 ResumeInterruptedDownload();
375 return;
377 case MAX_DOWNLOAD_INTERNAL_STATE:
378 NOTREACHED();
382 void DownloadItemImpl::Cancel(bool user_cancel) {
383 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
385 VLOG(20) << __FUNCTION__ << "() download = " << DebugString(true);
386 if (state_ != IN_PROGRESS_INTERNAL &&
387 state_ != INTERRUPTED_INTERNAL &&
388 state_ != RESUMING_INTERNAL) {
389 // Small downloads might be complete before this method has a chance to run.
390 return;
393 if (IsDangerous()) {
394 RecordDangerousDownloadDiscard(
395 user_cancel ? DOWNLOAD_DISCARD_DUE_TO_USER_ACTION
396 : DOWNLOAD_DISCARD_DUE_TO_SHUTDOWN,
397 GetDangerType(),
398 GetTargetFilePath());
401 last_reason_ = user_cancel ? DOWNLOAD_INTERRUPT_REASON_USER_CANCELED
402 : DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN;
404 RecordDownloadCount(CANCELLED_COUNT);
406 // TODO(rdsmith/benjhayden): Remove condition as part of
407 // |SavePackage| integration.
408 // |download_file_| can be NULL if Interrupt() is called after the
409 // download file has been released.
410 if (!is_save_package_download_ && download_file_)
411 ReleaseDownloadFile(true);
413 if (state_ == IN_PROGRESS_INTERNAL) {
414 // Cancel the originating URL request unless it's already been cancelled
415 // by interrupt.
416 request_handle_->CancelRequest();
419 // Remove the intermediate file if we are cancelling an interrupted download.
420 // Continuable interruptions leave the intermediate file around.
421 if ((state_ == INTERRUPTED_INTERNAL || state_ == RESUMING_INTERNAL) &&
422 !current_path_.empty()) {
423 BrowserThread::PostTask(
424 BrowserThread::FILE, FROM_HERE,
425 base::Bind(base::IgnoreResult(&DeleteDownloadedFile), current_path_));
426 current_path_.clear();
429 TransitionTo(CANCELLED_INTERNAL, UPDATE_OBSERVERS);
432 void DownloadItemImpl::Remove() {
433 VLOG(20) << __FUNCTION__ << "() download = " << DebugString(true);
434 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
436 delegate_->AssertStateConsistent(this);
437 Cancel(true);
438 delegate_->AssertStateConsistent(this);
440 NotifyRemoved();
441 delegate_->DownloadRemoved(this);
442 // We have now been deleted.
445 void DownloadItemImpl::OpenDownload() {
446 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
448 if (!IsDone()) {
449 // We don't honor the open_when_complete_ flag for temporary
450 // downloads. Don't set it because it shows up in the UI.
451 if (!IsTemporary())
452 open_when_complete_ = !open_when_complete_;
453 return;
456 if (state_ != COMPLETE_INTERNAL || file_externally_removed_)
457 return;
459 // Ideally, we want to detect errors in opening and report them, but we
460 // don't generally have the proper interface for that to the external
461 // program that opens the file. So instead we spawn a check to update
462 // the UI if the file has been deleted in parallel with the open.
463 delegate_->CheckForFileRemoval(this);
464 RecordOpen(GetEndTime(), !GetOpened());
465 opened_ = true;
466 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadOpened(this));
467 delegate_->OpenDownload(this);
470 void DownloadItemImpl::ShowDownloadInShell() {
471 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
473 delegate_->ShowDownloadInShell(this);
476 uint32 DownloadItemImpl::GetId() const {
477 return download_id_;
480 DownloadItem::DownloadState DownloadItemImpl::GetState() const {
481 return InternalToExternalState(state_);
484 DownloadInterruptReason DownloadItemImpl::GetLastReason() const {
485 return last_reason_;
488 bool DownloadItemImpl::IsPaused() const {
489 return is_paused_;
492 bool DownloadItemImpl::IsTemporary() const {
493 return is_temporary_;
496 bool DownloadItemImpl::CanResume() const {
497 if ((GetState() == IN_PROGRESS) && IsPaused())
498 return true;
500 if (state_ != INTERRUPTED_INTERNAL)
501 return false;
503 // Downloads that don't have a WebContents should still be resumable, but this
504 // isn't currently the case. See ResumeInterruptedDownload().
505 if (!GetWebContents())
506 return false;
508 ResumeMode resume_mode = GetResumeMode();
509 return IsDownloadResumptionEnabled() &&
510 (resume_mode == RESUME_MODE_USER_RESTART ||
511 resume_mode == RESUME_MODE_USER_CONTINUE);
514 bool DownloadItemImpl::IsDone() const {
515 switch (state_) {
516 case IN_PROGRESS_INTERNAL:
517 case COMPLETING_INTERNAL:
518 return false;
520 case COMPLETE_INTERNAL:
521 case CANCELLED_INTERNAL:
522 return true;
524 case INTERRUPTED_INTERNAL:
525 return !CanResume();
527 case RESUMING_INTERNAL:
528 return false;
530 case MAX_DOWNLOAD_INTERNAL_STATE:
531 break;
533 NOTREACHED();
534 return true;
537 const GURL& DownloadItemImpl::GetURL() const {
538 return url_chain_.empty() ? GURL::EmptyGURL() : url_chain_.back();
541 const std::vector<GURL>& DownloadItemImpl::GetUrlChain() const {
542 return url_chain_;
545 const GURL& DownloadItemImpl::GetOriginalUrl() const {
546 // Be careful about taking the front() of possibly-empty vectors!
547 // http://crbug.com/190096
548 return url_chain_.empty() ? GURL::EmptyGURL() : url_chain_.front();
551 const GURL& DownloadItemImpl::GetReferrerUrl() const {
552 return referrer_url_;
555 const GURL& DownloadItemImpl::GetTabUrl() const {
556 return tab_url_;
559 const GURL& DownloadItemImpl::GetTabReferrerUrl() const {
560 return tab_referrer_url_;
563 std::string DownloadItemImpl::GetSuggestedFilename() const {
564 return suggested_filename_;
567 std::string DownloadItemImpl::GetContentDisposition() const {
568 return content_disposition_;
571 std::string DownloadItemImpl::GetMimeType() const {
572 return mime_type_;
575 std::string DownloadItemImpl::GetOriginalMimeType() const {
576 return original_mime_type_;
579 std::string DownloadItemImpl::GetRemoteAddress() const {
580 return remote_address_;
583 bool DownloadItemImpl::HasUserGesture() const {
584 return has_user_gesture_;
587 PageTransition DownloadItemImpl::GetTransitionType() const {
588 return transition_type_;
591 const std::string& DownloadItemImpl::GetLastModifiedTime() const {
592 return last_modified_time_;
595 const std::string& DownloadItemImpl::GetETag() const {
596 return etag_;
599 bool DownloadItemImpl::IsSavePackageDownload() const {
600 return is_save_package_download_;
603 const base::FilePath& DownloadItemImpl::GetFullPath() const {
604 return current_path_;
607 const base::FilePath& DownloadItemImpl::GetTargetFilePath() const {
608 return target_path_;
611 const base::FilePath& DownloadItemImpl::GetForcedFilePath() const {
612 // TODO(asanka): Get rid of GetForcedFilePath(). We should instead just
613 // require that clients respect GetTargetFilePath() if it is already set.
614 return forced_file_path_;
617 base::FilePath DownloadItemImpl::GetFileNameToReportUser() const {
618 if (!display_name_.empty())
619 return display_name_;
620 return target_path_.BaseName();
623 DownloadItem::TargetDisposition DownloadItemImpl::GetTargetDisposition() const {
624 return target_disposition_;
627 const std::string& DownloadItemImpl::GetHash() const {
628 return hash_;
631 const std::string& DownloadItemImpl::GetHashState() const {
632 return hash_state_;
635 bool DownloadItemImpl::GetFileExternallyRemoved() const {
636 return file_externally_removed_;
639 void DownloadItemImpl::DeleteFile(const base::Callback<void(bool)>& callback) {
640 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
641 if (GetState() != DownloadItem::COMPLETE) {
642 // Pass a null WeakPtr so it doesn't call OnDownloadedFileRemoved.
643 BrowserThread::PostTask(
644 BrowserThread::UI, FROM_HERE,
645 base::Bind(&DeleteDownloadedFileDone,
646 base::WeakPtr<DownloadItemImpl>(), callback, false));
647 return;
649 if (current_path_.empty() || file_externally_removed_) {
650 // Pass a null WeakPtr so it doesn't call OnDownloadedFileRemoved.
651 BrowserThread::PostTask(
652 BrowserThread::UI, FROM_HERE,
653 base::Bind(&DeleteDownloadedFileDone,
654 base::WeakPtr<DownloadItemImpl>(), callback, true));
655 return;
657 BrowserThread::PostTaskAndReplyWithResult(
658 BrowserThread::FILE, FROM_HERE,
659 base::Bind(&DeleteDownloadedFile, current_path_),
660 base::Bind(&DeleteDownloadedFileDone,
661 weak_ptr_factory_.GetWeakPtr(), callback));
662 current_path_.clear();
665 bool DownloadItemImpl::IsDangerous() const {
666 #if defined(OS_WIN)
667 // TODO(noelutz): At this point only the windows views UI supports
668 // warnings based on dangerous content.
669 return (danger_type_ == DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE ||
670 danger_type_ == DOWNLOAD_DANGER_TYPE_DANGEROUS_URL ||
671 danger_type_ == DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT ||
672 danger_type_ == DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT ||
673 danger_type_ == DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST ||
674 danger_type_ == DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED);
675 #else
676 return (danger_type_ == DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE ||
677 danger_type_ == DOWNLOAD_DANGER_TYPE_DANGEROUS_URL);
678 #endif
681 DownloadDangerType DownloadItemImpl::GetDangerType() const {
682 return danger_type_;
685 bool DownloadItemImpl::TimeRemaining(base::TimeDelta* remaining) const {
686 if (total_bytes_ <= 0)
687 return false; // We never received the content_length for this download.
689 int64 speed = CurrentSpeed();
690 if (speed == 0)
691 return false;
693 *remaining = base::TimeDelta::FromSeconds(
694 (total_bytes_ - received_bytes_) / speed);
695 return true;
698 int64 DownloadItemImpl::CurrentSpeed() const {
699 if (is_paused_)
700 return 0;
701 return bytes_per_sec_;
704 int DownloadItemImpl::PercentComplete() const {
705 // If the delegate is delaying completion of the download, then we have no
706 // idea how long it will take.
707 if (delegate_delayed_complete_ || total_bytes_ <= 0)
708 return -1;
710 return static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
713 bool DownloadItemImpl::AllDataSaved() const {
714 return all_data_saved_;
717 int64 DownloadItemImpl::GetTotalBytes() const {
718 return total_bytes_;
721 int64 DownloadItemImpl::GetReceivedBytes() const {
722 return received_bytes_;
725 base::Time DownloadItemImpl::GetStartTime() const {
726 return start_time_;
729 base::Time DownloadItemImpl::GetEndTime() const {
730 return end_time_;
733 bool DownloadItemImpl::CanShowInFolder() {
734 // A download can be shown in the folder if the downloaded file is in a known
735 // location.
736 return CanOpenDownload() && !GetFullPath().empty();
739 bool DownloadItemImpl::CanOpenDownload() {
740 // We can open the file or mark it for opening on completion if the download
741 // is expected to complete successfully. Exclude temporary downloads, since
742 // they aren't owned by the download system.
743 const bool is_complete = GetState() == DownloadItem::COMPLETE;
744 return (!IsDone() || is_complete) && !IsTemporary() &&
745 !file_externally_removed_;
748 bool DownloadItemImpl::ShouldOpenFileBasedOnExtension() {
749 return delegate_->ShouldOpenFileBasedOnExtension(GetTargetFilePath());
752 bool DownloadItemImpl::GetOpenWhenComplete() const {
753 return open_when_complete_;
756 bool DownloadItemImpl::GetAutoOpened() {
757 return auto_opened_;
760 bool DownloadItemImpl::GetOpened() const {
761 return opened_;
764 BrowserContext* DownloadItemImpl::GetBrowserContext() const {
765 return delegate_->GetBrowserContext();
768 WebContents* DownloadItemImpl::GetWebContents() const {
769 // TODO(rdsmith): Remove null check after removing GetWebContents() from
770 // paths that might be used by DownloadItems created from history import.
771 // Currently such items have null request_handle_s, where other items
772 // (regular and SavePackage downloads) have actual objects off the pointer.
773 if (request_handle_)
774 return request_handle_->GetWebContents();
775 return NULL;
778 void DownloadItemImpl::OnContentCheckCompleted(DownloadDangerType danger_type) {
779 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
780 DCHECK(AllDataSaved());
781 VLOG(20) << __FUNCTION__ << " danger_type=" << danger_type
782 << " download=" << DebugString(true);
783 SetDangerType(danger_type);
784 UpdateObservers();
787 void DownloadItemImpl::SetOpenWhenComplete(bool open) {
788 open_when_complete_ = open;
791 void DownloadItemImpl::SetIsTemporary(bool temporary) {
792 is_temporary_ = temporary;
795 void DownloadItemImpl::SetOpened(bool opened) {
796 opened_ = opened;
799 void DownloadItemImpl::SetDisplayName(const base::FilePath& name) {
800 display_name_ = name;
803 std::string DownloadItemImpl::DebugString(bool verbose) const {
804 std::string description =
805 base::StringPrintf("{ id = %d"
806 " state = %s",
807 download_id_,
808 DebugDownloadStateString(state_));
810 // Construct a string of the URL chain.
811 std::string url_list("<none>");
812 if (!url_chain_.empty()) {
813 std::vector<GURL>::const_iterator iter = url_chain_.begin();
814 std::vector<GURL>::const_iterator last = url_chain_.end();
815 url_list = (*iter).is_valid() ? (*iter).spec() : "<invalid>";
816 ++iter;
817 for ( ; verbose && (iter != last); ++iter) {
818 url_list += " ->\n\t";
819 const GURL& next_url = *iter;
820 url_list += next_url.is_valid() ? next_url.spec() : "<invalid>";
824 if (verbose) {
825 description += base::StringPrintf(
826 " total = %" PRId64
827 " received = %" PRId64
828 " reason = %s"
829 " paused = %c"
830 " resume_mode = %s"
831 " auto_resume_count = %d"
832 " danger = %d"
833 " all_data_saved = %c"
834 " last_modified = '%s'"
835 " etag = '%s'"
836 " has_download_file = %s"
837 " url_chain = \n\t\"%s\"\n\t"
838 " full_path = \"%" PRFilePath "\"\n\t"
839 " target_path = \"%" PRFilePath "\"",
840 GetTotalBytes(),
841 GetReceivedBytes(),
842 DownloadInterruptReasonToString(last_reason_).c_str(),
843 IsPaused() ? 'T' : 'F',
844 DebugResumeModeString(GetResumeMode()),
845 auto_resume_count_,
846 GetDangerType(),
847 AllDataSaved() ? 'T' : 'F',
848 GetLastModifiedTime().c_str(),
849 GetETag().c_str(),
850 download_file_.get() ? "true" : "false",
851 url_list.c_str(),
852 GetFullPath().value().c_str(),
853 GetTargetFilePath().value().c_str());
854 } else {
855 description += base::StringPrintf(" url = \"%s\"", url_list.c_str());
858 description += " }";
860 return description;
863 DownloadItemImpl::ResumeMode DownloadItemImpl::GetResumeMode() const {
864 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
865 // We can't continue without a handle on the intermediate file.
866 // We also can't continue if we don't have some verifier to make sure
867 // we're getting the same file.
868 const bool force_restart =
869 (current_path_.empty() || (etag_.empty() && last_modified_time_.empty()));
871 // We won't auto-restart if we've used up our attempts or the
872 // download has been paused by user action.
873 const bool force_user =
874 (auto_resume_count_ >= kMaxAutoResumeAttempts || is_paused_);
876 ResumeMode mode = RESUME_MODE_INVALID;
878 switch(last_reason_) {
879 case DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR:
880 case DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT:
881 if (force_restart && force_user)
882 mode = RESUME_MODE_USER_RESTART;
883 else if (force_restart)
884 mode = RESUME_MODE_IMMEDIATE_RESTART;
885 else if (force_user)
886 mode = RESUME_MODE_USER_CONTINUE;
887 else
888 mode = RESUME_MODE_IMMEDIATE_CONTINUE;
889 break;
891 case DOWNLOAD_INTERRUPT_REASON_SERVER_PRECONDITION:
892 case DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE:
893 case DOWNLOAD_INTERRUPT_REASON_FILE_TOO_SHORT:
894 if (force_user)
895 mode = RESUME_MODE_USER_RESTART;
896 else
897 mode = RESUME_MODE_IMMEDIATE_RESTART;
898 break;
900 case DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED:
901 case DOWNLOAD_INTERRUPT_REASON_NETWORK_DISCONNECTED:
902 case DOWNLOAD_INTERRUPT_REASON_NETWORK_SERVER_DOWN:
903 case DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST:
904 case DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED:
905 case DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN:
906 case DOWNLOAD_INTERRUPT_REASON_CRASH:
907 if (force_restart)
908 mode = RESUME_MODE_USER_RESTART;
909 else
910 mode = RESUME_MODE_USER_CONTINUE;
911 break;
913 case DOWNLOAD_INTERRUPT_REASON_FILE_FAILED:
914 case DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED:
915 case DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE:
916 case DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG:
917 case DOWNLOAD_INTERRUPT_REASON_FILE_TOO_LARGE:
918 mode = RESUME_MODE_USER_RESTART;
919 break;
921 case DOWNLOAD_INTERRUPT_REASON_NONE:
922 case DOWNLOAD_INTERRUPT_REASON_FILE_VIRUS_INFECTED:
923 case DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT:
924 case DOWNLOAD_INTERRUPT_REASON_USER_CANCELED:
925 case DOWNLOAD_INTERRUPT_REASON_FILE_BLOCKED:
926 case DOWNLOAD_INTERRUPT_REASON_FILE_SECURITY_CHECK_FAILED:
927 mode = RESUME_MODE_INVALID;
928 break;
931 return mode;
934 void DownloadItemImpl::MergeOriginInfoOnResume(
935 const DownloadCreateInfo& new_create_info) {
936 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
937 DCHECK_EQ(RESUMING_INTERNAL, state_);
938 DCHECK(!new_create_info.url_chain.empty());
940 // We are going to tack on any new redirects to our list of redirects.
941 // When a download is resumed, the URL used for the resumption request is the
942 // one at the end of the previous redirect chain. Tacking additional redirects
943 // to the end of this chain ensures that:
944 // - If the download needs to be resumed again, the ETag/Last-Modified headers
945 // will be used with the last server that sent them to us.
946 // - The redirect chain contains all the servers that were involved in this
947 // download since the initial request, in order.
948 std::vector<GURL>::const_iterator chain_iter =
949 new_create_info.url_chain.begin();
950 if (*chain_iter == url_chain_.back())
951 ++chain_iter;
953 // Record some stats. If the precondition failed (the server returned
954 // HTTP_PRECONDITION_FAILED), then the download will automatically retried as
955 // a full request rather than a partial. Full restarts clobber validators.
956 int origin_state = 0;
957 if (chain_iter != new_create_info.url_chain.end())
958 origin_state |= ORIGIN_STATE_ON_RESUMPTION_ADDITIONAL_REDIRECTS;
959 if (etag_ != new_create_info.etag ||
960 last_modified_time_ != new_create_info.last_modified)
961 origin_state |= ORIGIN_STATE_ON_RESUMPTION_VALIDATORS_CHANGED;
962 if (content_disposition_ != new_create_info.content_disposition)
963 origin_state |= ORIGIN_STATE_ON_RESUMPTION_CONTENT_DISPOSITION_CHANGED;
964 RecordOriginStateOnResumption(new_create_info.save_info->offset != 0,
965 origin_state);
967 url_chain_.insert(
968 url_chain_.end(), chain_iter, new_create_info.url_chain.end());
969 etag_ = new_create_info.etag;
970 last_modified_time_ = new_create_info.last_modified;
971 content_disposition_ = new_create_info.content_disposition;
973 // Don't update observers. This method is expected to be called just before a
974 // DownloadFile is created and Start() is called. The observers will be
975 // notified when the download transitions to the IN_PROGRESS state.
978 void DownloadItemImpl::NotifyRemoved() {
979 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadRemoved(this));
982 void DownloadItemImpl::OnDownloadedFileRemoved() {
983 file_externally_removed_ = true;
984 VLOG(20) << __FUNCTION__ << " download=" << DebugString(true);
985 UpdateObservers();
988 base::WeakPtr<DownloadDestinationObserver>
989 DownloadItemImpl::DestinationObserverAsWeakPtr() {
990 return weak_ptr_factory_.GetWeakPtr();
993 const net::BoundNetLog& DownloadItemImpl::GetBoundNetLog() const {
994 return bound_net_log_;
997 void DownloadItemImpl::SetTotalBytes(int64 total_bytes) {
998 total_bytes_ = total_bytes;
1001 void DownloadItemImpl::OnAllDataSaved(const std::string& final_hash) {
1002 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1004 DCHECK_EQ(IN_PROGRESS_INTERNAL, state_);
1005 DCHECK(!all_data_saved_);
1006 all_data_saved_ = true;
1007 VLOG(20) << __FUNCTION__ << " download=" << DebugString(true);
1009 // Store final hash and null out intermediate serialized hash state.
1010 hash_ = final_hash;
1011 hash_state_ = "";
1013 UpdateObservers();
1016 void DownloadItemImpl::MarkAsComplete() {
1017 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1019 DCHECK(all_data_saved_);
1020 end_time_ = base::Time::Now();
1021 TransitionTo(COMPLETE_INTERNAL, UPDATE_OBSERVERS);
1024 void DownloadItemImpl::DestinationUpdate(int64 bytes_so_far,
1025 int64 bytes_per_sec,
1026 const std::string& hash_state) {
1027 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1028 VLOG(20) << __FUNCTION__ << " so_far=" << bytes_so_far
1029 << " per_sec=" << bytes_per_sec << " download=" << DebugString(true);
1031 if (GetState() != IN_PROGRESS) {
1032 // Ignore if we're no longer in-progress. This can happen if we race a
1033 // Cancel on the UI thread with an update on the FILE thread.
1035 // TODO(rdsmith): Arguably we should let this go through, as this means
1036 // the download really did get further than we know before it was
1037 // cancelled. But the gain isn't very large, and the code is more
1038 // fragile if it has to support in progress updates in a non-in-progress
1039 // state. This issue should be readdressed when we revamp performance
1040 // reporting.
1041 return;
1043 bytes_per_sec_ = bytes_per_sec;
1044 hash_state_ = hash_state;
1045 received_bytes_ = bytes_so_far;
1047 // If we've received more data than we were expecting (bad server info?),
1048 // revert to 'unknown size mode'.
1049 if (received_bytes_ > total_bytes_)
1050 total_bytes_ = 0;
1052 if (bound_net_log_.IsLogging()) {
1053 bound_net_log_.AddEvent(
1054 net::NetLog::TYPE_DOWNLOAD_ITEM_UPDATED,
1055 net::NetLog::Int64Callback("bytes_so_far", received_bytes_));
1058 UpdateObservers();
1061 void DownloadItemImpl::DestinationError(DownloadInterruptReason reason) {
1062 // Postpone recognition of this error until after file name determination
1063 // has completed and the intermediate file has been renamed to simplify
1064 // resumption conditions.
1065 if (current_path_.empty() || target_path_.empty())
1066 destination_error_ = reason;
1067 else
1068 Interrupt(reason);
1071 void DownloadItemImpl::DestinationCompleted(const std::string& final_hash) {
1072 VLOG(20) << __FUNCTION__ << " download=" << DebugString(true);
1073 if (GetState() != IN_PROGRESS)
1074 return;
1075 OnAllDataSaved(final_hash);
1076 MaybeCompleteDownload();
1079 // **** Download progression cascade
1081 void DownloadItemImpl::Init(bool active,
1082 DownloadType download_type) {
1083 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1085 if (active)
1086 RecordDownloadCount(START_COUNT);
1088 std::string file_name;
1089 if (download_type == SRC_HISTORY_IMPORT) {
1090 // target_path_ works for History and Save As versions.
1091 file_name = target_path_.AsUTF8Unsafe();
1092 } else {
1093 // See if it's set programmatically.
1094 file_name = forced_file_path_.AsUTF8Unsafe();
1095 // Possibly has a 'download' attribute for the anchor.
1096 if (file_name.empty())
1097 file_name = suggested_filename_;
1098 // From the URL file name.
1099 if (file_name.empty())
1100 file_name = GetURL().ExtractFileName();
1103 base::Callback<base::Value*(net::NetLog::LogLevel)> active_data = base::Bind(
1104 &ItemActivatedNetLogCallback, this, download_type, &file_name);
1105 if (active) {
1106 bound_net_log_.BeginEvent(
1107 net::NetLog::TYPE_DOWNLOAD_ITEM_ACTIVE, active_data);
1108 } else {
1109 bound_net_log_.AddEvent(
1110 net::NetLog::TYPE_DOWNLOAD_ITEM_ACTIVE, active_data);
1113 VLOG(20) << __FUNCTION__ << "() " << DebugString(true);
1116 // We're starting the download.
1117 void DownloadItemImpl::Start(
1118 scoped_ptr<DownloadFile> file,
1119 scoped_ptr<DownloadRequestHandleInterface> req_handle) {
1120 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1121 DCHECK(!download_file_.get());
1122 DCHECK(file.get());
1123 DCHECK(req_handle.get());
1125 download_file_ = file.Pass();
1126 request_handle_ = req_handle.Pass();
1128 if (GetState() == CANCELLED) {
1129 // The download was in the process of resuming when it was cancelled. Don't
1130 // proceed.
1131 ReleaseDownloadFile(true);
1132 request_handle_->CancelRequest();
1133 return;
1136 TransitionTo(IN_PROGRESS_INTERNAL, UPDATE_OBSERVERS);
1138 BrowserThread::PostTask(
1139 BrowserThread::FILE, FROM_HERE,
1140 base::Bind(&DownloadFile::Initialize,
1141 // Safe because we control download file lifetime.
1142 base::Unretained(download_file_.get()),
1143 base::Bind(&DownloadItemImpl::OnDownloadFileInitialized,
1144 weak_ptr_factory_.GetWeakPtr())));
1147 void DownloadItemImpl::OnDownloadFileInitialized(
1148 DownloadInterruptReason result) {
1149 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1150 if (result != DOWNLOAD_INTERRUPT_REASON_NONE) {
1151 Interrupt(result);
1152 // TODO(rdsmith/asanka): Arguably we should show this in the UI, but
1153 // it's not at all clear what to show--we haven't done filename
1154 // determination, so we don't know what name to display. OTOH,
1155 // the failure mode of not showing the DI if the file initialization
1156 // fails isn't a good one. Can we hack up a name based on the
1157 // URLRequest? We'll need to make sure that initialization happens
1158 // properly. Possibly the right thing is to have the UI handle
1159 // this case specially.
1160 return;
1163 delegate_->DetermineDownloadTarget(
1164 this, base::Bind(&DownloadItemImpl::OnDownloadTargetDetermined,
1165 weak_ptr_factory_.GetWeakPtr()));
1168 // Called by delegate_ when the download target path has been
1169 // determined.
1170 void DownloadItemImpl::OnDownloadTargetDetermined(
1171 const base::FilePath& target_path,
1172 TargetDisposition disposition,
1173 DownloadDangerType danger_type,
1174 const base::FilePath& intermediate_path) {
1175 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1177 // If the |target_path| is empty, then we consider this download to be
1178 // canceled.
1179 if (target_path.empty()) {
1180 Cancel(true);
1181 return;
1184 // TODO(rdsmith,asanka): We are ignoring the possibility that the download
1185 // has been interrupted at this point until we finish the intermediate
1186 // rename and set the full path. That's dangerous, because we might race
1187 // with resumption, either manual (because the interrupt is visible to the
1188 // UI) or automatic. If we keep the "ignore an error on download until file
1189 // name determination complete" semantics, we need to make sure that the
1190 // error is kept completely invisible until that point.
1192 VLOG(20) << __FUNCTION__ << " " << target_path.value() << " " << disposition
1193 << " " << danger_type << " " << DebugString(true);
1195 target_path_ = target_path;
1196 target_disposition_ = disposition;
1197 SetDangerType(danger_type);
1199 // We want the intermediate and target paths to refer to the same directory so
1200 // that they are both on the same device and subject to same
1201 // space/permission/availability constraints.
1202 DCHECK(intermediate_path.DirName() == target_path.DirName());
1204 // During resumption, we may choose to proceed with the same intermediate
1205 // file. No rename is necessary if our intermediate file already has the
1206 // correct name.
1208 // The intermediate name may change from its original value during filename
1209 // determination on resumption, for example if the reason for the interruption
1210 // was the download target running out space, resulting in a user prompt.
1211 if (intermediate_path == current_path_) {
1212 OnDownloadRenamedToIntermediateName(DOWNLOAD_INTERRUPT_REASON_NONE,
1213 intermediate_path);
1214 return;
1217 // Rename to intermediate name.
1218 // TODO(asanka): Skip this rename if AllDataSaved() is true. This avoids a
1219 // spurious rename when we can just rename to the final
1220 // filename. Unnecessary renames may cause bugs like
1221 // http://crbug.com/74187.
1222 DCHECK(!is_save_package_download_);
1223 DCHECK(download_file_.get());
1224 DownloadFile::RenameCompletionCallback callback =
1225 base::Bind(&DownloadItemImpl::OnDownloadRenamedToIntermediateName,
1226 weak_ptr_factory_.GetWeakPtr());
1227 BrowserThread::PostTask(
1228 BrowserThread::FILE, FROM_HERE,
1229 base::Bind(&DownloadFile::RenameAndUniquify,
1230 // Safe because we control download file lifetime.
1231 base::Unretained(download_file_.get()),
1232 intermediate_path, callback));
1235 void DownloadItemImpl::OnDownloadRenamedToIntermediateName(
1236 DownloadInterruptReason reason,
1237 const base::FilePath& full_path) {
1238 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1239 VLOG(20) << __FUNCTION__ << " download=" << DebugString(true);
1241 if (DOWNLOAD_INTERRUPT_REASON_NONE != destination_error_) {
1242 // Process destination error. If both |reason| and |destination_error_|
1243 // refer to actual errors, we want to use the |destination_error_| as the
1244 // argument to the Interrupt() routine, as it happened first.
1245 if (reason == DOWNLOAD_INTERRUPT_REASON_NONE)
1246 SetFullPath(full_path);
1247 Interrupt(destination_error_);
1248 destination_error_ = DOWNLOAD_INTERRUPT_REASON_NONE;
1249 } else if (DOWNLOAD_INTERRUPT_REASON_NONE != reason) {
1250 Interrupt(reason);
1251 // All file errors result in file deletion above; no need to cleanup. The
1252 // current_path_ should be empty. Resuming this download will force a
1253 // restart and a re-doing of filename determination.
1254 DCHECK(current_path_.empty());
1255 } else {
1256 SetFullPath(full_path);
1257 UpdateObservers();
1258 MaybeCompleteDownload();
1262 // When SavePackage downloads MHTML to GData (see
1263 // SavePackageFilePickerChromeOS), GData calls MaybeCompleteDownload() like it
1264 // does for non-SavePackage downloads, but SavePackage downloads never satisfy
1265 // IsDownloadReadyForCompletion(). GDataDownloadObserver manually calls
1266 // DownloadItem::UpdateObservers() when the upload completes so that SavePackage
1267 // notices that the upload has completed and runs its normal Finish() pathway.
1268 // MaybeCompleteDownload() is never the mechanism by which SavePackage completes
1269 // downloads. SavePackage always uses its own Finish() to mark downloads
1270 // complete.
1271 void DownloadItemImpl::MaybeCompleteDownload() {
1272 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1273 DCHECK(!is_save_package_download_);
1275 if (!IsDownloadReadyForCompletion(
1276 base::Bind(&DownloadItemImpl::MaybeCompleteDownload,
1277 weak_ptr_factory_.GetWeakPtr())))
1278 return;
1280 // TODO(rdsmith): DCHECK that we only pass through this point
1281 // once per download. The natural way to do this is by a state
1282 // transition on the DownloadItem.
1284 // Confirm we're in the proper set of states to be here;
1285 // have all data, have a history handle, (validated or safe).
1286 DCHECK_EQ(IN_PROGRESS_INTERNAL, state_);
1287 DCHECK(!IsDangerous());
1288 DCHECK(all_data_saved_);
1290 OnDownloadCompleting();
1293 // Called by MaybeCompleteDownload() when it has determined that the download
1294 // is ready for completion.
1295 void DownloadItemImpl::OnDownloadCompleting() {
1296 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1298 if (state_ != IN_PROGRESS_INTERNAL)
1299 return;
1301 VLOG(20) << __FUNCTION__ << "()"
1302 << " " << DebugString(true);
1303 DCHECK(!GetTargetFilePath().empty());
1304 DCHECK(!IsDangerous());
1306 // TODO(rdsmith/benjhayden): Remove as part of SavePackage integration.
1307 if (is_save_package_download_) {
1308 // Avoid doing anything on the file thread; there's nothing we control
1309 // there.
1310 // Strictly speaking, this skips giving the embedder a chance to open
1311 // the download. But on a save package download, there's no real
1312 // concept of opening.
1313 Completed();
1314 return;
1317 DCHECK(download_file_.get());
1318 // Unilaterally rename; even if it already has the right name,
1319 // we need theannotation.
1320 DownloadFile::RenameCompletionCallback callback =
1321 base::Bind(&DownloadItemImpl::OnDownloadRenamedToFinalName,
1322 weak_ptr_factory_.GetWeakPtr());
1323 BrowserThread::PostTask(
1324 BrowserThread::FILE, FROM_HERE,
1325 base::Bind(&DownloadFile::RenameAndAnnotate,
1326 base::Unretained(download_file_.get()),
1327 GetTargetFilePath(), callback));
1330 void DownloadItemImpl::OnDownloadRenamedToFinalName(
1331 DownloadInterruptReason reason,
1332 const base::FilePath& full_path) {
1333 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1334 DCHECK(!is_save_package_download_);
1336 // If a cancel or interrupt hit, we'll cancel the DownloadFile, which
1337 // will result in deleting the file on the file thread. So we don't
1338 // care about the name having been changed.
1339 if (state_ != IN_PROGRESS_INTERNAL)
1340 return;
1342 VLOG(20) << __FUNCTION__ << "()"
1343 << " full_path = \"" << full_path.value() << "\""
1344 << " " << DebugString(false);
1346 if (DOWNLOAD_INTERRUPT_REASON_NONE != reason) {
1347 Interrupt(reason);
1349 // All file errors should have resulted in in file deletion above. On
1350 // resumption we will need to re-do filename determination.
1351 DCHECK(current_path_.empty());
1352 return;
1355 DCHECK(target_path_ == full_path);
1357 if (full_path != current_path_) {
1358 // full_path is now the current and target file path.
1359 DCHECK(!full_path.empty());
1360 SetFullPath(full_path);
1363 // Complete the download and release the DownloadFile.
1364 DCHECK(download_file_.get());
1365 ReleaseDownloadFile(false);
1367 // We're not completely done with the download item yet, but at this
1368 // point we're committed to complete the download. Cancels (or Interrupts,
1369 // though it's not clear how they could happen) after this point will be
1370 // ignored.
1371 TransitionTo(COMPLETING_INTERNAL, DONT_UPDATE_OBSERVERS);
1373 if (delegate_->ShouldOpenDownload(
1374 this, base::Bind(&DownloadItemImpl::DelayedDownloadOpened,
1375 weak_ptr_factory_.GetWeakPtr()))) {
1376 Completed();
1377 } else {
1378 delegate_delayed_complete_ = true;
1379 UpdateObservers();
1383 void DownloadItemImpl::DelayedDownloadOpened(bool auto_opened) {
1384 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1386 auto_opened_ = auto_opened;
1387 Completed();
1390 void DownloadItemImpl::Completed() {
1391 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1393 VLOG(20) << __FUNCTION__ << "() " << DebugString(false);
1395 DCHECK(all_data_saved_);
1396 end_time_ = base::Time::Now();
1397 TransitionTo(COMPLETE_INTERNAL, UPDATE_OBSERVERS);
1398 RecordDownloadCompleted(start_tick_, received_bytes_);
1400 if (auto_opened_) {
1401 // If it was already handled by the delegate, do nothing.
1402 } else if (GetOpenWhenComplete() ||
1403 ShouldOpenFileBasedOnExtension() ||
1404 IsTemporary()) {
1405 // If the download is temporary, like in drag-and-drop, do not open it but
1406 // we still need to set it auto-opened so that it can be removed from the
1407 // download shelf.
1408 if (!IsTemporary())
1409 OpenDownload();
1411 auto_opened_ = true;
1412 UpdateObservers();
1416 void DownloadItemImpl::OnResumeRequestStarted(
1417 DownloadItem* item,
1418 DownloadInterruptReason interrupt_reason) {
1419 // If |item| is not NULL, then Start() has been called already, and nothing
1420 // more needs to be done here.
1421 if (item) {
1422 DCHECK_EQ(DOWNLOAD_INTERRUPT_REASON_NONE, interrupt_reason);
1423 DCHECK_EQ(static_cast<DownloadItem*>(this), item);
1424 return;
1426 // Otherwise, the request failed without passing through
1427 // DownloadResourceHandler::OnResponseStarted.
1428 DCHECK_NE(DOWNLOAD_INTERRUPT_REASON_NONE, interrupt_reason);
1429 Interrupt(interrupt_reason);
1432 // **** End of Download progression cascade
1434 // An error occurred somewhere.
1435 void DownloadItemImpl::Interrupt(DownloadInterruptReason reason) {
1436 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1437 DCHECK_NE(DOWNLOAD_INTERRUPT_REASON_NONE, reason);
1439 // Somewhat counter-intuitively, it is possible for us to receive an
1440 // interrupt after we've already been interrupted. The generation of
1441 // interrupts from the file thread Renames and the generation of
1442 // interrupts from disk writes go through two different mechanisms (driven
1443 // by rename requests from UI thread and by write requests from IO thread,
1444 // respectively), and since we choose not to keep state on the File thread,
1445 // this is the place where the races collide. It's also possible for
1446 // interrupts to race with cancels.
1448 // Whatever happens, the first one to hit the UI thread wins.
1449 if (state_ != IN_PROGRESS_INTERNAL && state_ != RESUMING_INTERNAL)
1450 return;
1452 last_reason_ = reason;
1454 ResumeMode resume_mode = GetResumeMode();
1456 if (state_ == IN_PROGRESS_INTERNAL) {
1457 // Cancel (delete file) if:
1458 // 1) we're going to restart.
1459 // 2) Resumption isn't possible (download was cancelled or blocked due to
1460 // security restrictions).
1461 // 3) Resumption isn't enabled.
1462 // No point in leaving data around we aren't going to use.
1463 ReleaseDownloadFile(resume_mode == RESUME_MODE_IMMEDIATE_RESTART ||
1464 resume_mode == RESUME_MODE_USER_RESTART ||
1465 resume_mode == RESUME_MODE_INVALID ||
1466 !IsDownloadResumptionEnabled());
1468 // Cancel the originating URL request.
1469 request_handle_->CancelRequest();
1470 } else {
1471 DCHECK(!download_file_.get());
1474 // Reset all data saved, as even if we did save all the data we're going
1475 // to go through another round of downloading when we resume.
1476 // There's a potential problem here in the abstract, as if we did download
1477 // all the data and then run into a continuable error, on resumption we
1478 // won't download any more data. However, a) there are currently no
1479 // continuable errors that can occur after we download all the data, and
1480 // b) if there were, that would probably simply result in a null range
1481 // request, which would generate a DestinationCompleted() notification
1482 // from the DownloadFile, which would behave properly with setting
1483 // all_data_saved_ to false here.
1484 all_data_saved_ = false;
1486 TransitionTo(INTERRUPTED_INTERNAL, DONT_UPDATE_OBSERVERS);
1487 RecordDownloadInterrupted(reason, received_bytes_, total_bytes_);
1488 if (!GetWebContents())
1489 RecordDownloadCount(INTERRUPTED_WITHOUT_WEBCONTENTS);
1491 AutoResumeIfValid();
1492 UpdateObservers();
1495 void DownloadItemImpl::ReleaseDownloadFile(bool destroy_file) {
1496 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1498 if (destroy_file) {
1499 BrowserThread::PostTask(
1500 BrowserThread::FILE, FROM_HERE,
1501 // Will be deleted at end of task execution.
1502 base::Bind(&DownloadFileCancel, base::Passed(&download_file_)));
1503 // Avoid attempting to reuse the intermediate file by clearing out
1504 // current_path_.
1505 current_path_.clear();
1506 } else {
1507 BrowserThread::PostTask(
1508 BrowserThread::FILE,
1509 FROM_HERE,
1510 base::Bind(base::IgnoreResult(&DownloadFileDetach),
1511 // Will be deleted at end of task execution.
1512 base::Passed(&download_file_)));
1514 // Don't accept any more messages from the DownloadFile, and null
1515 // out any previous "all data received". This also breaks links to
1516 // other entities we've given out weak pointers to.
1517 weak_ptr_factory_.InvalidateWeakPtrs();
1520 bool DownloadItemImpl::IsDownloadReadyForCompletion(
1521 const base::Closure& state_change_notification) {
1522 // If we don't have all the data, the download is not ready for
1523 // completion.
1524 if (!AllDataSaved())
1525 return false;
1527 // If the download is dangerous, but not yet validated, it's not ready for
1528 // completion.
1529 if (IsDangerous())
1530 return false;
1532 // If the download isn't active (e.g. has been cancelled) it's not
1533 // ready for completion.
1534 if (state_ != IN_PROGRESS_INTERNAL)
1535 return false;
1537 // If the target filename hasn't been determined, then it's not ready for
1538 // completion. This is checked in ReadyForDownloadCompletionDone().
1539 if (GetTargetFilePath().empty())
1540 return false;
1542 // This is checked in NeedsRename(). Without this conditional,
1543 // browser_tests:DownloadTest.DownloadMimeType fails the DCHECK.
1544 if (target_path_.DirName() != current_path_.DirName())
1545 return false;
1547 // Give the delegate a chance to hold up a stop sign. It'll call
1548 // use back through the passed callback if it does and that state changes.
1549 if (!delegate_->ShouldCompleteDownload(this, state_change_notification))
1550 return false;
1552 return true;
1555 void DownloadItemImpl::TransitionTo(DownloadInternalState new_state,
1556 ShouldUpdateObservers notify_action) {
1557 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1559 if (state_ == new_state)
1560 return;
1562 DownloadInternalState old_state = state_;
1563 state_ = new_state;
1565 switch (state_) {
1566 case COMPLETING_INTERNAL:
1567 bound_net_log_.AddEvent(
1568 net::NetLog::TYPE_DOWNLOAD_ITEM_COMPLETING,
1569 base::Bind(&ItemCompletingNetLogCallback, received_bytes_, &hash_));
1570 break;
1571 case COMPLETE_INTERNAL:
1572 bound_net_log_.AddEvent(
1573 net::NetLog::TYPE_DOWNLOAD_ITEM_FINISHED,
1574 base::Bind(&ItemFinishedNetLogCallback, auto_opened_));
1575 break;
1576 case INTERRUPTED_INTERNAL:
1577 bound_net_log_.AddEvent(
1578 net::NetLog::TYPE_DOWNLOAD_ITEM_INTERRUPTED,
1579 base::Bind(&ItemInterruptedNetLogCallback, last_reason_,
1580 received_bytes_, &hash_state_));
1581 break;
1582 case IN_PROGRESS_INTERNAL:
1583 if (old_state == INTERRUPTED_INTERNAL) {
1584 bound_net_log_.AddEvent(
1585 net::NetLog::TYPE_DOWNLOAD_ITEM_RESUMED,
1586 base::Bind(&ItemResumingNetLogCallback,
1587 false, last_reason_, received_bytes_, &hash_state_));
1589 break;
1590 case CANCELLED_INTERNAL:
1591 bound_net_log_.AddEvent(
1592 net::NetLog::TYPE_DOWNLOAD_ITEM_CANCELED,
1593 base::Bind(&ItemCanceledNetLogCallback, received_bytes_,
1594 &hash_state_));
1595 break;
1596 default:
1597 break;
1600 VLOG(20) << " " << __FUNCTION__ << "()" << " this = " << DebugString(true)
1601 << " " << InternalToExternalState(old_state)
1602 << " " << InternalToExternalState(state_);
1604 bool is_done = (state_ != IN_PROGRESS_INTERNAL &&
1605 state_ != COMPLETING_INTERNAL);
1606 bool was_done = (old_state != IN_PROGRESS_INTERNAL &&
1607 old_state != COMPLETING_INTERNAL);
1608 // Termination
1609 if (is_done && !was_done)
1610 bound_net_log_.EndEvent(net::NetLog::TYPE_DOWNLOAD_ITEM_ACTIVE);
1612 // Resumption
1613 if (was_done && !is_done) {
1614 std::string file_name(target_path_.BaseName().AsUTF8Unsafe());
1615 bound_net_log_.BeginEvent(net::NetLog::TYPE_DOWNLOAD_ITEM_ACTIVE,
1616 base::Bind(&ItemActivatedNetLogCallback,
1617 this, SRC_ACTIVE_DOWNLOAD,
1618 &file_name));
1621 if (notify_action == UPDATE_OBSERVERS)
1622 UpdateObservers();
1625 void DownloadItemImpl::SetDangerType(DownloadDangerType danger_type) {
1626 if (danger_type != danger_type_) {
1627 bound_net_log_.AddEvent(
1628 net::NetLog::TYPE_DOWNLOAD_ITEM_SAFETY_STATE_UPDATED,
1629 base::Bind(&ItemCheckedNetLogCallback, danger_type));
1631 // Only record the Malicious UMA stat if it's going from {not malicious} ->
1632 // {malicious}.
1633 if ((danger_type_ == DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS ||
1634 danger_type_ == DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE ||
1635 danger_type_ == DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT ||
1636 danger_type_ == DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT) &&
1637 (danger_type == DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST ||
1638 danger_type == DOWNLOAD_DANGER_TYPE_DANGEROUS_URL ||
1639 danger_type == DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT ||
1640 danger_type == DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED)) {
1641 RecordMaliciousDownloadClassified(danger_type);
1643 danger_type_ = danger_type;
1646 void DownloadItemImpl::SetFullPath(const base::FilePath& new_path) {
1647 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1648 VLOG(20) << __FUNCTION__ << "()"
1649 << " new_path = \"" << new_path.value() << "\""
1650 << " " << DebugString(true);
1651 DCHECK(!new_path.empty());
1653 bound_net_log_.AddEvent(
1654 net::NetLog::TYPE_DOWNLOAD_ITEM_RENAMED,
1655 base::Bind(&ItemRenamedNetLogCallback, &current_path_, &new_path));
1657 current_path_ = new_path;
1660 void DownloadItemImpl::AutoResumeIfValid() {
1661 DVLOG(20) << __FUNCTION__ << "() " << DebugString(true);
1662 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1663 ResumeMode mode = GetResumeMode();
1665 if (mode != RESUME_MODE_IMMEDIATE_RESTART &&
1666 mode != RESUME_MODE_IMMEDIATE_CONTINUE) {
1667 return;
1670 auto_resume_count_++;
1672 ResumeInterruptedDownload();
1675 void DownloadItemImpl::ResumeInterruptedDownload() {
1676 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1678 // If the flag for downloads resumption isn't enabled, ignore
1679 // this request.
1680 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1681 if (!command_line.HasSwitch(switches::kEnableDownloadResumption))
1682 return;
1684 // If we're not interrupted, ignore the request; our caller is drunk.
1685 if (state_ != INTERRUPTED_INTERNAL)
1686 return;
1688 // If we can't get a web contents, we can't resume the download.
1689 // TODO(rdsmith): Find some alternative web contents to use--this
1690 // means we can't restart a download if it's a download imported
1691 // from the history.
1692 if (!GetWebContents())
1693 return;
1695 // Reset the appropriate state if restarting.
1696 ResumeMode mode = GetResumeMode();
1697 if (mode == RESUME_MODE_IMMEDIATE_RESTART ||
1698 mode == RESUME_MODE_USER_RESTART) {
1699 received_bytes_ = 0;
1700 hash_state_ = "";
1701 last_modified_time_ = "";
1702 etag_ = "";
1705 scoped_ptr<DownloadUrlParameters> download_params(
1706 DownloadUrlParameters::FromWebContents(GetWebContents(),
1707 GetOriginalUrl()));
1709 download_params->set_file_path(GetFullPath());
1710 download_params->set_offset(GetReceivedBytes());
1711 download_params->set_hash_state(GetHashState());
1712 download_params->set_last_modified(GetLastModifiedTime());
1713 download_params->set_etag(GetETag());
1714 download_params->set_callback(
1715 base::Bind(&DownloadItemImpl::OnResumeRequestStarted,
1716 weak_ptr_factory_.GetWeakPtr()));
1718 delegate_->ResumeInterruptedDownload(download_params.Pass(), GetId());
1719 // Just in case we were interrupted while paused.
1720 is_paused_ = false;
1722 TransitionTo(RESUMING_INTERNAL, DONT_UPDATE_OBSERVERS);
1725 // static
1726 DownloadItem::DownloadState DownloadItemImpl::InternalToExternalState(
1727 DownloadInternalState internal_state) {
1728 switch (internal_state) {
1729 case IN_PROGRESS_INTERNAL:
1730 return IN_PROGRESS;
1731 case COMPLETING_INTERNAL:
1732 return IN_PROGRESS;
1733 case COMPLETE_INTERNAL:
1734 return COMPLETE;
1735 case CANCELLED_INTERNAL:
1736 return CANCELLED;
1737 case INTERRUPTED_INTERNAL:
1738 return INTERRUPTED;
1739 case RESUMING_INTERNAL:
1740 return INTERRUPTED;
1741 case MAX_DOWNLOAD_INTERNAL_STATE:
1742 break;
1744 NOTREACHED();
1745 return MAX_DOWNLOAD_STATE;
1748 // static
1749 DownloadItemImpl::DownloadInternalState
1750 DownloadItemImpl::ExternalToInternalState(
1751 DownloadState external_state) {
1752 switch (external_state) {
1753 case IN_PROGRESS:
1754 return IN_PROGRESS_INTERNAL;
1755 case COMPLETE:
1756 return COMPLETE_INTERNAL;
1757 case CANCELLED:
1758 return CANCELLED_INTERNAL;
1759 case INTERRUPTED:
1760 return INTERRUPTED_INTERNAL;
1761 default:
1762 NOTREACHED();
1764 return MAX_DOWNLOAD_INTERNAL_STATE;
1767 const char* DownloadItemImpl::DebugDownloadStateString(
1768 DownloadInternalState state) {
1769 switch (state) {
1770 case IN_PROGRESS_INTERNAL:
1771 return "IN_PROGRESS";
1772 case COMPLETING_INTERNAL:
1773 return "COMPLETING";
1774 case COMPLETE_INTERNAL:
1775 return "COMPLETE";
1776 case CANCELLED_INTERNAL:
1777 return "CANCELLED";
1778 case INTERRUPTED_INTERNAL:
1779 return "INTERRUPTED";
1780 case RESUMING_INTERNAL:
1781 return "RESUMING";
1782 case MAX_DOWNLOAD_INTERNAL_STATE:
1783 break;
1785 NOTREACHED() << "Unknown download state " << state;
1786 return "unknown";
1789 const char* DownloadItemImpl::DebugResumeModeString(ResumeMode mode) {
1790 switch (mode) {
1791 case RESUME_MODE_INVALID:
1792 return "INVALID";
1793 case RESUME_MODE_IMMEDIATE_CONTINUE:
1794 return "IMMEDIATE_CONTINUE";
1795 case RESUME_MODE_IMMEDIATE_RESTART:
1796 return "IMMEDIATE_RESTART";
1797 case RESUME_MODE_USER_CONTINUE:
1798 return "USER_CONTINUE";
1799 case RESUME_MODE_USER_RESTART:
1800 return "USER_RESTART";
1802 NOTREACHED() << "Unknown resume mode " << mode;
1803 return "unknown";
1806 } // namespace content