blob: 86c61152ee4974e2392887f7b1015045cc4cd0f8 [file] [log] [blame]
license.botbf09a502008-08-24 00:55:551// Copyright (c) 2006-2008 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.
initial.commit09911bf2008-07-26 23:55:294
[email protected]cdaa8652008-09-13 02:48:595#include "chrome/browser/download/download_manager.h"
initial.commit09911bf2008-07-26 23:55:296
7#include "base/file_util.h"
8#include "base/logging.h"
9#include "base/message_loop.h"
10#include "base/path_service.h"
initial.commit09911bf2008-07-26 23:55:2911#include "base/string_util.h"
12#include "base/task.h"
13#include "base/thread.h"
14#include "base/timer.h"
[email protected]9ccbb372008-10-10 18:50:3215#include "base/rand_util.h"
initial.commit09911bf2008-07-26 23:55:2916#include "chrome/browser/browser_list.h"
17#include "chrome/browser/browser_process.h"
[email protected]cdaa8652008-09-13 02:48:5918#include "chrome/browser/download/download_file.h"
[email protected]8c756ac2009-01-30 23:36:4119#include "chrome/browser/extensions/extension.h"
initial.commit09911bf2008-07-26 23:55:2920#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:2621#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2522#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]e3c404b2008-12-23 01:07:3223#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
[email protected]f3ec7742009-01-15 00:59:1624#include "chrome/browser/tab_contents/tab_util.h"
25#include "chrome/browser/tab_contents/web_contents.h"
[email protected]8c756ac2009-01-30 23:36:4126#include "chrome/common/chrome_constants.h"
initial.commit09911bf2008-07-26 23:55:2927#include "chrome/common/chrome_paths.h"
28#include "chrome/common/l10n_util.h"
29#include "chrome/common/notification_service.h"
30#include "chrome/common/pref_names.h"
31#include "chrome/common/pref_service.h"
32#include "chrome/common/stl_util-inl.h"
[email protected]46072d42008-07-28 14:49:3533#include "googleurl/src/gurl.h"
initial.commit09911bf2008-07-26 23:55:2934#include "net/base/mime_util.h"
35#include "net/base/net_util.h"
36#include "net/url_request/url_request_context.h"
37
[email protected]b7f05882009-02-22 01:21:5638#if defined(OS_WIN)
39// TODO(port): some of these need porting.
40#include "base/registry.h"
41#include "base/win_util.h"
42#include "chrome/browser/download/download_util.h"
43#include "chrome/common/win_util.h"
44#endif
45
initial.commit09911bf2008-07-26 23:55:2946#include "generated_resources.h"
47
48// Periodically update our observers.
49class DownloadItemUpdateTask : public Task {
50 public:
51 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
52 void Run() { if (item_) item_->UpdateObservers(); }
53
54 private:
55 DownloadItem* item_;
56};
57
58// Update frequency (milliseconds).
59static const int kUpdateTimeMs = 1000;
60
61// Our download table ID starts at 1, so we use 0 to represent a download that
62// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2263// database handles in incognito mode starting at -1 and progressively getting
64// more negative.
initial.commit09911bf2008-07-26 23:55:2965static const int kUninitializedHandle = 0;
66
[email protected]7a256ea2008-10-17 17:34:1667// Appends the passed the number between parenthesis the path before the
68// extension.
[email protected]7ae7c2cb2009-01-06 23:31:4169static void AppendNumberToPath(FilePath* path, int number) {
70 file_util::InsertBeforeExtension(path,
71 StringPrintf(FILE_PATH_LITERAL(" (%d)"), number));
[email protected]7a256ea2008-10-17 17:34:1672}
73
74// Attempts to find a number that can be appended to that path to make it
75// unique. If |path| does not exist, 0 is returned. If it fails to find such
76// a number, -1 is returned.
[email protected]7ae7c2cb2009-01-06 23:31:4177static int GetUniquePathNumber(const FilePath& path) {
initial.commit09911bf2008-07-26 23:55:2978 const int kMaxAttempts = 100;
79
[email protected]7a256ea2008-10-17 17:34:1680 if (!file_util::PathExists(path))
81 return 0;
initial.commit09911bf2008-07-26 23:55:2982
[email protected]7ae7c2cb2009-01-06 23:31:4183 FilePath new_path;
initial.commit09911bf2008-07-26 23:55:2984 for (int count = 1; count <= kMaxAttempts; ++count) {
[email protected]7ae7c2cb2009-01-06 23:31:4185 new_path = FilePath(path);
[email protected]7a256ea2008-10-17 17:34:1686 AppendNumberToPath(&new_path, count);
initial.commit09911bf2008-07-26 23:55:2987
[email protected]7a256ea2008-10-17 17:34:1688 if (!file_util::PathExists(new_path))
89 return count;
initial.commit09911bf2008-07-26 23:55:2990 }
91
[email protected]7a256ea2008-10-17 17:34:1692 return -1;
initial.commit09911bf2008-07-26 23:55:2993}
94
[email protected]b7f05882009-02-22 01:21:5695#if defined(OS_WIN)
[email protected]7ae7c2cb2009-01-06 23:31:4196static bool DownloadPathIsDangerous(const FilePath& download_path) {
97 FilePath desktop_dir;
[email protected]f052118e2008-09-05 02:25:3298 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
99 NOTREACHED();
100 return false;
101 }
102 return (download_path == desktop_dir);
103}
[email protected]b7f05882009-02-22 01:21:56104#endif
[email protected]f052118e2008-09-05 02:25:32105
initial.commit09911bf2008-07-26 23:55:29106// DownloadItem implementation -------------------------------------------------
107
108// Constructor for reading from the history service.
109DownloadItem::DownloadItem(const DownloadCreateInfo& info)
110 : id_(-1),
111 full_path_(info.path),
initial.commit09911bf2008-07-26 23:55:29112 url_(info.url),
113 total_bytes_(info.total_bytes),
114 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56115 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29116 state_(static_cast<DownloadState>(info.state)),
117 start_time_(info.start_time),
118 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29119 manager_(NULL),
initial.commit09911bf2008-07-26 23:55:29120 is_paused_(false),
121 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56122 safety_state_(SAFE),
123 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29124 render_process_id_(-1),
125 request_id_(-1) {
126 if (state_ == IN_PROGRESS)
127 state_ = CANCELLED;
128 Init(false /* don't start progress timer */);
129}
130
131// Constructor for DownloadItem created via user action in the main thread.
132DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41133 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16134 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32135 const GURL& url,
[email protected]7ae7c2cb2009-01-06 23:31:41136 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59137 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29138 int64 download_size,
139 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32140 int request_id,
141 bool is_dangerous)
initial.commit09911bf2008-07-26 23:55:29142 : id_(download_id),
143 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16144 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29145 url_(url),
initial.commit09911bf2008-07-26 23:55:29146 total_bytes_(download_size),
147 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56148 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29149 state_(IN_PROGRESS),
150 start_time_(start_time),
151 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29152 manager_(NULL),
initial.commit09911bf2008-07-26 23:55:29153 is_paused_(false),
154 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56155 safety_state_(is_dangerous ? DANGEROUS : SAFE),
156 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29157 render_process_id_(render_process_id),
158 request_id_(request_id) {
159 Init(true /* start progress timer */);
160}
161
162void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41163 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29164 if (start_timer)
165 StartProgressTimer();
166}
167
168DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29169 state_ = REMOVING;
170 UpdateObservers();
171}
172
173void DownloadItem::AddObserver(Observer* observer) {
174 observers_.AddObserver(observer);
175}
176
177void DownloadItem::RemoveObserver(Observer* observer) {
178 observers_.RemoveObserver(observer);
179}
180
181void DownloadItem::UpdateObservers() {
182 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
183}
184
185// If we've received more data than we were expecting (bad server info?), revert
186// to 'unknown size mode'.
187void DownloadItem::UpdateSize(int64 bytes_so_far) {
188 received_bytes_ = bytes_so_far;
189 if (received_bytes_ > total_bytes_)
190 total_bytes_ = 0;
191}
192
193// Updates from the download thread may have been posted while this download
194// was being cancelled in the UI thread, so we'll accept them unless we're
195// complete.
196void DownloadItem::Update(int64 bytes_so_far) {
197 if (state_ == COMPLETE) {
198 NOTREACHED();
199 return;
200 }
201 UpdateSize(bytes_so_far);
202 UpdateObservers();
203}
204
[email protected]6cade212008-12-03 00:32:22205// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29206void DownloadItem::Cancel(bool update_history) {
207 if (state_ != IN_PROGRESS) {
208 // Small downloads might be complete before this method has a chance to run.
209 return;
210 }
211 state_ = CANCELLED;
212 UpdateObservers();
213 StopProgressTimer();
214 if (update_history)
215 manager_->DownloadCancelled(id_);
216}
217
218void DownloadItem::Finished(int64 size) {
219 state_ = COMPLETE;
220 UpdateSize(size);
[email protected]22fbe5a2008-10-29 22:20:40221 UpdateObservers();
initial.commit09911bf2008-07-26 23:55:29222 StopProgressTimer();
223}
224
[email protected]9ccbb372008-10-10 18:50:32225void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29226 Cancel(true);
227 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32228 if (delete_on_disk)
229 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29230 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22231 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29232}
233
234void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59235 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14236 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29237}
238
239void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14240 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29241}
242
[email protected]e93d2822009-01-30 05:59:59243bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29244 if (total_bytes_ <= 0)
245 return false; // We never received the content_length for this download.
246
247 int64 speed = CurrentSpeed();
248 if (speed == 0)
249 return false;
250
251 *remaining =
[email protected]e93d2822009-01-30 05:59:59252 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29253 return true;
254}
255
256int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56257 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
258 int64 diff_ms = diff.InMilliseconds();
259 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29260}
261
262int DownloadItem::PercentComplete() const {
263 int percent = -1;
264 if (total_bytes_ > 0)
265 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
266 return percent;
267}
268
[email protected]7ae7c2cb2009-01-06 23:31:41269void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29270 DCHECK(!full_path.empty());
271 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41272 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29273}
274
275void DownloadItem::TogglePause() {
276 DCHECK(state_ == IN_PROGRESS);
277 manager_->PauseDownload(id_, !is_paused_);
278 is_paused_ = !is_paused_;
279 UpdateObservers();
280}
281
[email protected]7ae7c2cb2009-01-06 23:31:41282FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32283 if (safety_state_ == DownloadItem::SAFE)
284 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16285 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41286 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16287 AppendNumberToPath(&name, path_uniquifier_);
288 return name;
289 }
[email protected]9ccbb372008-10-10 18:50:32290 return original_name_;
291}
292
initial.commit09911bf2008-07-26 23:55:29293// DownloadManager implementation ----------------------------------------------
294
295// static
296void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
297 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
298 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32299 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
300
[email protected]b7f05882009-02-22 01:21:56301// TODO(port): port the necessary bits of chrome_paths.
302#if defined(OS_WIN)
[email protected]f052118e2008-09-05 02:25:32303 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41304 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12305 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
306 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32307 NOTREACHED();
308 }
[email protected]f052118e2008-09-05 02:25:32309 prefs->RegisterStringPref(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41310 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32311
312 // If the download path is dangerous we forcefully reset it. But if we do
313 // so we set a flag to make sure we only do it once, to avoid fighting
314 // the user if he really wants it on an unsafe place such as the desktop.
315
316 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41317 FilePath current_download_dir = FilePath::FromWStringHack(
318 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32319 if (DownloadPathIsDangerous(current_download_dir)) {
320 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41321 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32322 }
323 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
324 }
[email protected]b7f05882009-02-22 01:21:56325#endif
initial.commit09911bf2008-07-26 23:55:29326}
327
328DownloadManager::DownloadManager()
329 : shutdown_needed_(false),
330 profile_(NULL),
331 file_manager_(NULL),
332 ui_loop_(MessageLoop::current()),
333 file_loop_(NULL) {
334}
335
336DownloadManager::~DownloadManager() {
337 if (shutdown_needed_)
338 Shutdown();
339}
340
341void DownloadManager::Shutdown() {
342 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
343
344 // Stop receiving download updates
345 file_manager_->RemoveDownloadManager(this);
346
347 // Stop making history service requests
348 cancelable_consumer_.CancelAllRequests();
349
350 // 'in_progress_' may contain DownloadItems that have not finished the start
351 // complete (from the history service) and thus aren't in downloads_.
352 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32353 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29354 for (; it != in_progress_.end(); ++it) {
355 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32356 if (download->safety_state() == DownloadItem::DANGEROUS) {
357 // Forget about any download that the user did not approve.
358 // Note that we cannot call download->Remove() this would invalidate our
359 // iterator.
360 to_remove.insert(download);
361 continue;
initial.commit09911bf2008-07-26 23:55:29362 }
[email protected]9ccbb372008-10-10 18:50:32363 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
364 download->Cancel(false);
365 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29366 if (download->db_handle() == kUninitializedHandle) {
367 // An invalid handle means that 'download' does not yet exist in
368 // 'downloads_', so we have to delete it here.
369 delete download;
370 }
371 }
372
[email protected]9ccbb372008-10-10 18:50:32373 // 'dangerous_finished_' contains all complete downloads that have not been
374 // approved. They should be removed.
375 it = dangerous_finished_.begin();
376 for (; it != dangerous_finished_.end(); ++it)
377 to_remove.insert(it->second);
378
379 // Remove the dangerous download that are not approved.
380 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
381 rm_it != to_remove.end(); ++rm_it) {
382 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32383 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32384 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32385 // Same as above, delete the download if it is not in 'downloads_' (as the
386 // Remove() call above won't have deleted it).
387 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32388 delete download;
389 }
390 to_remove.clear();
391
initial.commit09911bf2008-07-26 23:55:29392 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32393 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29394 STLDeleteValues(&downloads_);
395
396 file_manager_ = NULL;
397
398 // Save our file extensions to auto open.
399 SaveAutoOpens();
400
401 // Make sure the save as dialog doesn't notify us back if we're gone before
402 // it returns.
403 if (select_file_dialog_.get())
404 select_file_dialog_->ListenerDestroyed();
405
406 shutdown_needed_ = false;
407}
408
409// Issue a history query for downloads matching 'search_text'. If 'search_text'
410// is empty, return all downloads that we know about.
411void DownloadManager::GetDownloads(Observer* observer,
412 const std::wstring& search_text) {
413 DCHECK(observer);
414
415 // Return a empty list if we've not yet received the set of downloads from the
416 // history system (we'll update all observers once we get that list in
417 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
418 std::vector<DownloadItem*> download_copy;
419 if (downloads_.empty()) {
420 observer->SetDownloads(download_copy);
421 return;
422 }
423
424 // We already know all the downloads and there is no filter, so just return a
425 // copy to the observer.
426 if (search_text.empty()) {
427 download_copy.reserve(downloads_.size());
428 for (DownloadMap::iterator it = downloads_.begin();
429 it != downloads_.end(); ++it) {
430 download_copy.push_back(it->second);
431 }
432
433 // We retain ownership of the DownloadItems.
434 observer->SetDownloads(download_copy);
435 return;
436 }
437
438 // Issue a request to the history service for a list of downloads matching
439 // our search text.
440 HistoryService* hs =
441 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
442 if (hs) {
443 HistoryService::Handle h =
444 hs->SearchDownloads(search_text,
445 &cancelable_consumer_,
446 NewCallback(this,
447 &DownloadManager::OnSearchComplete));
448 cancelable_consumer_.SetClientData(hs, h, observer);
449 }
450}
451
452// Query the history service for information about all persisted downloads.
453bool DownloadManager::Init(Profile* profile) {
454 DCHECK(profile);
455 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
456 shutdown_needed_ = true;
457
458 profile_ = profile;
459 request_context_ = profile_->GetRequestContext();
460
461 // 'incognito mode' will have access to past downloads, but we won't store
462 // information about new downloads while in that mode.
463 QueryHistoryForDownloads();
464
465 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
466 if (!rdh) {
467 NOTREACHED();
468 return false;
469 }
470
471 file_manager_ = rdh->download_file_manager();
472 if (!file_manager_) {
473 NOTREACHED();
474 return false;
475 }
476
477 file_loop_ = g_browser_process->file_thread()->message_loop();
478 if (!file_loop_) {
479 NOTREACHED();
480 return false;
481 }
482
483 // Get our user preference state.
484 PrefService* prefs = profile_->GetPrefs();
485 DCHECK(prefs);
486 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
487
[email protected]b7f05882009-02-22 01:21:56488// TODO(port): enable this after implementing chrome_paths for posix.
489#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29490 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
491
[email protected]7ae7c2cb2009-01-06 23:31:41492 // This variable is needed to resolve which CreateDirectory we want to point
493 // to. Without it, the NewRunnableFunction cannot resolve the ambiguity.
494 // TODO(estade): when file_util::CreateDirectory(wstring) is removed,
495 // get rid of |CreateDirectoryPtr|.
496 bool (*CreateDirectoryPtr)(const FilePath&) = &file_util::CreateDirectory;
[email protected]bb69e9b32008-08-14 23:08:14497 // Ensure that the download directory specified in the preferences exists.
[email protected]7ae7c2cb2009-01-06 23:31:41498 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
499 CreateDirectoryPtr, download_path()));
[email protected]bb69e9b32008-08-14 23:08:14500
initial.commit09911bf2008-07-26 23:55:29501 // We store any file extension that should be opened automatically at
502 // download completion in this pref.
503 download_util::InitializeExeTypes(&exe_types_);
[email protected]b7f05882009-02-22 01:21:56504#elif defined(OS_POSIX)
505 NOTIMPLEMENTED();
506#endif
initial.commit09911bf2008-07-26 23:55:29507
508 std::wstring extensions_to_open =
509 prefs->GetString(prefs::kDownloadExtensionsToOpen);
510 std::vector<std::wstring> extensions;
511 SplitString(extensions_to_open, L':', &extensions);
512 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]b7f05882009-02-22 01:21:56513 if (!extensions[i].empty() && !IsExecutable(
514 FilePath::FromWStringHack(extensions[i]).value()))
515 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29516 }
517
518 return true;
519}
520
521void DownloadManager::QueryHistoryForDownloads() {
522 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
523 if (hs) {
524 hs->QueryDownloads(
525 &cancelable_consumer_,
526 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
527 }
528}
529
530// We have received a message from DownloadFileManager about a new download. We
531// create a download item and store it in our download map, and inform the
532// history system of a new download. Since this method can be called while the
533// history service thread is still reading the persistent state, we do not
534// insert the new DownloadItem into 'downloads_' or inform our observers at this
535// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
536// download creation as a callback from the history thread.
537void DownloadManager::StartDownload(DownloadCreateInfo* info) {
538 DCHECK(MessageLoop::current() == ui_loop_);
539 DCHECK(info);
540
[email protected]7d3851d82008-12-12 03:26:07541 // Freeze the user's preference for showing a Save As dialog. We're going to
542 // bounce around a bunch of threads and we don't want to worry about race
543 // conditions where the user changes this pref out from under us.
544 if (*prompt_for_download_)
545 info->save_as = true;
546
initial.commit09911bf2008-07-26 23:55:29547 // Determine the proper path for a download, by choosing either the default
548 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41549 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29550 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07551 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29552 info->suggested_path = last_download_path_;
553 else
[email protected]7ae7c2cb2009-01-06 23:31:41554 info->suggested_path = download_path();
555 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29556
[email protected]7d3851d82008-12-12 03:26:07557 if (!info->save_as) {
558 // Let's check if this download is dangerous, based on its name.
[email protected]7ae7c2cb2009-01-06 23:31:41559 info->is_dangerous = IsDangerous(info->suggested_path.BaseName());
[email protected]e9ebf3fc2008-10-17 22:06:58560 }
561
initial.commit09911bf2008-07-26 23:55:29562 // We need to move over to the download thread because we don't want to stat
563 // the suggested path on the UI thread.
564 file_loop_->PostTask(FROM_HERE,
565 NewRunnableMethod(this,
566 &DownloadManager::CheckIfSuggestedPathExists,
567 info));
568}
569
570void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
571 DCHECK(info);
572
573 // Check writability of the suggested path. If we can't write to it, default
574 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41575 FilePath dir = info->suggested_path.DirName();
576 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32577 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29578 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29579 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41580 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29581 }
582
[email protected]7a256ea2008-10-17 17:34:16583 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29584
[email protected]6cade212008-12-03 00:32:22585 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58586 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41587 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32588 // Create a temporary file to hold the file until the user approves its
589 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41590 FilePath::StringType file_name;
591 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32592 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41593 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32594 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41595 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07596 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41597 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32598 }
599 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16600 } else {
601 // We know the final path, build it if necessary.
602 if (info->path_uniquifier > 0) {
603 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
604 // Setting path_uniquifier to 0 to make sure we don't try to unique it
605 // later on.
606 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07607 } else if (info->path_uniquifier == -1) {
608 // We failed to find a unique path. We have to prompt the user.
609 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16610 }
[email protected]9ccbb372008-10-10 18:50:32611 }
612
[email protected]7d3851d82008-12-12 03:26:07613 if (!info->save_as) {
614 // Create an empty file at the suggested path so that we don't allocate the
615 // same "non-existant" path to multiple downloads.
616 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ae7c2cb2009-01-06 23:31:41617 file_util::WriteFile(info->suggested_path.ToWStringHack(), "", 0);
[email protected]7d3851d82008-12-12 03:26:07618 }
619
initial.commit09911bf2008-07-26 23:55:29620 // Now we return to the UI thread.
621 ui_loop_->PostTask(FROM_HERE,
622 NewRunnableMethod(this,
623 &DownloadManager::OnPathExistenceAvailable,
624 info));
625}
626
627void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]b7f05882009-02-22 01:21:56628#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29629 DCHECK(MessageLoop::current() == ui_loop_);
630 DCHECK(info);
631
[email protected]7d3851d82008-12-12 03:26:07632 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29633 // We must ask the user for the place to put the download.
634 if (!select_file_dialog_.get())
635 select_file_dialog_ = SelectFileDialog::Create(this);
636
[email protected]a3a1d142008-12-19 00:42:30637 WebContents* contents = tab_util::GetWebContentsByID(
initial.commit09911bf2008-07-26 23:55:29638 info->render_process_id, info->render_view_id);
[email protected]7ae7c2cb2009-01-06 23:31:41639 std::wstring filter =
640 win_util::GetFileFilterFromPath(info->suggested_path.value());
initial.commit09911bf2008-07-26 23:55:29641 HWND owning_hwnd =
[email protected]92edc472009-02-10 20:32:06642 contents ? GetAncestor(contents->GetNativeView(), GA_ROOT) : NULL;
initial.commit09911bf2008-07-26 23:55:29643 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]7ae7c2cb2009-01-06 23:31:41644 std::wstring(),
645 info->suggested_path.ToWStringHack(),
[email protected]6cade212008-12-03 00:32:22646 filter, std::wstring(),
initial.commit09911bf2008-07-26 23:55:29647 owning_hwnd, info);
648 } else {
649 // No prompting for download, just continue with the suggested name.
650 ContinueStartDownload(info, info->suggested_path);
651 }
[email protected]b7f05882009-02-22 01:21:56652#elif defined(OS_POSIX)
653 // TODO(port): port this file -- need dialogs.
654 NOTIMPLEMENTED();
655#endif
initial.commit09911bf2008-07-26 23:55:29656}
657
658void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41659 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29660 scoped_ptr<DownloadCreateInfo> infop(info);
661 info->path = target_path;
662
663 DownloadItem* download = NULL;
664 DownloadMap::iterator it = in_progress_.find(info->download_id);
665 if (it == in_progress_.end()) {
666 download = new DownloadItem(info->download_id,
667 info->path,
[email protected]7a256ea2008-10-17 17:34:16668 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29669 info->url,
[email protected]9ccbb372008-10-10 18:50:32670 info->original_name,
initial.commit09911bf2008-07-26 23:55:29671 info->start_time,
672 info->total_bytes,
673 info->render_process_id,
[email protected]9ccbb372008-10-10 18:50:32674 info->request_id,
675 info->is_dangerous);
initial.commit09911bf2008-07-26 23:55:29676 download->set_manager(this);
677 in_progress_[info->download_id] = download;
678 } else {
679 NOTREACHED(); // Should not exist!
680 return;
681 }
682
683 // If the download already completed by the time we reached this point, then
684 // notify observers that it did.
685 PendingFinishedMap::iterator pending_it =
686 pending_finished_downloads_.find(info->download_id);
687 if (pending_it != pending_finished_downloads_.end())
688 DownloadFinished(pending_it->first, pending_it->second);
689
690 download->Rename(target_path);
691
692 file_loop_->PostTask(FROM_HERE,
693 NewRunnableMethod(file_manager_,
694 &DownloadFileManager::OnFinalDownloadName,
695 download->id(),
696 target_path));
697
698 if (profile_->IsOffTheRecord()) {
699 // Fake a db handle for incognito mode, since nothing is actually stored in
700 // the database in this mode. We have to make sure that these handles don't
701 // collide with normal db handles, so we use a negative value. Eventually,
702 // they could overlap, but you'd have to do enough downloading that your ISP
703 // would likely stab you in the neck first. YMMV.
704 static int64 fake_db_handle = kUninitializedHandle - 1;
705 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
706 } else {
707 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22708 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29709 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
710 if (hs) {
711 hs->CreateDownload(
712 *info, &cancelable_consumer_,
713 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
714 }
715 }
716}
717
718// Convenience function for updating the history service for a download.
719void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
720 DCHECK(download);
721
722 // Don't store info in the database if the download was initiated while in
723 // incognito mode or if it hasn't been initialized in our database table.
724 if (download->db_handle() <= kUninitializedHandle)
725 return;
726
[email protected]6cade212008-12-03 00:32:22727 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29728 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
729 if (hs) {
730 hs->UpdateDownload(download->received_bytes(),
731 download->state(),
732 download->db_handle());
733 }
734}
735
736void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
737 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22738 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29739 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
740 if (download->db_handle() > kUninitializedHandle && hs)
741 hs->RemoveDownload(download->db_handle());
742}
743
[email protected]e93d2822009-01-30 05:59:59744void DownloadManager::RemoveDownloadsFromHistoryBetween(
745 const base::Time remove_begin,
746 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22747 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29748 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
749 if (hs)
750 hs->RemoveDownloadsBetween(remove_begin, remove_end);
751}
752
753void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
754 DownloadMap::iterator it = in_progress_.find(download_id);
755 if (it != in_progress_.end()) {
756 DownloadItem* download = it->second;
757 download->Update(size);
758 UpdateHistoryForDownload(download);
759 }
760}
761
762void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
763 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32764 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29765 // The download is done, but the user hasn't selected a final location for
766 // it yet (the Save As dialog box is probably still showing), so just keep
767 // track of the fact that this download id is complete, when the
768 // DownloadItem is constructed later we'll notify its completion then.
769 PendingFinishedMap::iterator erase_it =
770 pending_finished_downloads_.find(download_id);
771 DCHECK(erase_it == pending_finished_downloads_.end());
772 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32773 return;
initial.commit09911bf2008-07-26 23:55:29774 }
[email protected]9ccbb372008-10-10 18:50:32775
776 // Remove the id from the list of pending ids.
777 PendingFinishedMap::iterator erase_it =
778 pending_finished_downloads_.find(download_id);
779 if (erase_it != pending_finished_downloads_.end())
780 pending_finished_downloads_.erase(erase_it);
781
782 DownloadItem* download = it->second;
783 download->Finished(size);
784
785 // Clean up will happen when the history system create callback runs if we
786 // don't have a valid db_handle yet.
787 if (download->db_handle() != kUninitializedHandle) {
788 in_progress_.erase(it);
789 NotifyAboutDownloadStop();
790 UpdateHistoryForDownload(download);
791 }
792
793 // If this a dangerous download not yet validated by the user, don't do
794 // anything. When the user notifies us, it will trigger a call to
795 // ProceedWithFinishedDangerousDownload.
796 if (download->safety_state() == DownloadItem::DANGEROUS) {
797 dangerous_finished_[download_id] = download;
798 return;
799 }
800
801 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22802 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32803 // its final name before we can continue.
804 file_loop_->PostTask(FROM_HERE,
805 NewRunnableMethod(
806 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
807 download->db_handle(),
808 download->full_path(), download->original_name()));
809 return;
810 }
811 ContinueDownloadFinished(download);
812}
813
814void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
815 // If this was a dangerous download, it has now been approved and must be
816 // removed from dangerous_finished_ so it does not get deleted on shutdown.
817 DownloadMap::iterator it = dangerous_finished_.find(download->id());
818 if (it != dangerous_finished_.end())
819 dangerous_finished_.erase(it);
820
821 // Notify our observers that we are complete (the call to Finished() set the
822 // state to complete but did not notify).
823 download->UpdateObservers();
824
825 // Open the download if the user or user prefs indicate it should be.
[email protected]b7f05882009-02-22 01:21:56826 const FilePath::StringType extension = download->full_path().Extension();
[email protected]9ccbb372008-10-10 18:50:32827 if (download->open_when_complete() || ShouldOpenFileExtension(extension))
828 OpenDownloadInShell(download, NULL);
829}
830
831// Called on the file thread. Renames the downloaded file to its original name.
832void DownloadManager::ProceedWithFinishedDangerousDownload(
833 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41834 const FilePath& path,
835 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32836 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41837 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16838 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32839 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24840 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16841 // Make our name unique at this point, as if a dangerous file is downloading
842 // and a 2nd download is started for a file with the same name, they would
843 // have the same path. This is because we uniquify the name on download
844 // start, and at that time the first file does not exists yet, so the second
845 // file gets the same name.
846 uniquifier = GetUniquePathNumber(new_path);
847 if (uniquifier > 0)
848 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32849 success = file_util::Move(path, new_path);
850 } else {
851 NOTREACHED();
852 }
[email protected]6cade212008-12-03 00:32:22853
[email protected]9ccbb372008-10-10 18:50:32854 ui_loop_->PostTask(FROM_HERE,
855 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16856 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32857}
858
859// Call from the file thread when the finished dangerous download was renamed.
860void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
861 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41862 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16863 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32864 DownloadMap::iterator it = downloads_.find(download_handle);
865 if (it == downloads_.end()) {
866 NOTREACHED();
867 return;
868 }
869
870 DownloadItem* download = it->second;
871 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16872 if (success) {
873 // We need to update the path uniquifier so that the UI shows the right
874 // name when calling GetFileName().
875 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32876 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16877 }
[email protected]9ccbb372008-10-10 18:50:32878
879 // Continue the download finished sequence.
880 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29881}
882
883// static
884// We have to tell the ResourceDispatcherHost to cancel the download from this
[email protected]6cade212008-12-03 00:32:22885// thread, since we can't forward tasks from the file thread to the IO thread
initial.commit09911bf2008-07-26 23:55:29886// reliably (crash on shutdown race condition).
887void DownloadManager::CancelDownloadRequest(int render_process_id,
888 int request_id) {
889 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]ab820df2008-08-26 05:55:10890 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29891 if (!io_thread || !rdh)
892 return;
893 io_thread->message_loop()->PostTask(FROM_HERE,
894 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
895 rdh,
896 render_process_id,
897 request_id));
898}
899
900// static
901void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
902 int render_process_id,
903 int request_id) {
904 rdh->CancelRequest(render_process_id, request_id, false);
905}
906
907void DownloadManager::DownloadCancelled(int32 download_id) {
908 DownloadMap::iterator it = in_progress_.find(download_id);
909 if (it == in_progress_.end())
910 return;
911 DownloadItem* download = it->second;
912
913 CancelDownloadRequest(download->render_process_id(), download->request_id());
914
915 // Clean up will happen when the history system create callback runs if we
916 // don't have a valid db_handle yet.
917 if (download->db_handle() != kUninitializedHandle) {
918 in_progress_.erase(it);
919 NotifyAboutDownloadStop();
920 UpdateHistoryForDownload(download);
921 }
922
923 // Tell the file manager to cancel the download.
924 file_manager_->RemoveDownload(download->id(), this); // On the UI thread
925 file_loop_->PostTask(FROM_HERE,
926 NewRunnableMethod(file_manager_,
927 &DownloadFileManager::CancelDownload,
928 download->id()));
929}
930
931void DownloadManager::PauseDownload(int32 download_id, bool pause) {
932 DownloadMap::iterator it = in_progress_.find(download_id);
933 if (it != in_progress_.end()) {
934 DownloadItem* download = it->second;
935 if (pause == download->is_paused())
936 return;
937
938 // Inform the ResourceDispatcherHost of the new pause state.
[email protected]ab820df2008-08-26 05:55:10939 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29940 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
941 if (!io_thread || !rdh)
942 return;
943
944 io_thread->message_loop()->PostTask(FROM_HERE,
945 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
946 rdh,
947 download->render_process_id(),
948 download->request_id(),
949 pause));
950 }
951}
952
953// static
954void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
955 int render_process_id,
956 int request_id,
957 bool pause) {
958 rdh->PauseRequest(render_process_id, request_id, pause);
959}
960
[email protected]7ae7c2cb2009-01-06 23:31:41961bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:32962 // TODO(jcampan): Improve me.
[email protected]b7f05882009-02-22 01:21:56963 return IsExecutable(file_name.Extension());
[email protected]9ccbb372008-10-10 18:50:32964}
965
966void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:41967 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:32968 download->Rename(new_path);
969
970 // Update the history.
971
972 // No update necessary if the download was initiated while in incognito mode.
973 if (download->db_handle() <= kUninitializedHandle)
974 return;
975
[email protected]6cade212008-12-03 00:32:22976 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:32977 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
978 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:41979 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:32980}
981
initial.commit09911bf2008-07-26 23:55:29982void DownloadManager::RemoveDownload(int64 download_handle) {
983 DownloadMap::iterator it = downloads_.find(download_handle);
984 if (it == downloads_.end())
985 return;
986
987 // Make history update.
988 DownloadItem* download = it->second;
989 RemoveDownloadFromHistory(download);
990
991 // Remove from our tables and delete.
992 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32993 it = dangerous_finished_.find(download->id());
994 if (it != dangerous_finished_.end())
995 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:29996
997 // Tell observers to refresh their views.
998 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:36999
1000 delete download;
initial.commit09911bf2008-07-26 23:55:291001}
1002
[email protected]e93d2822009-01-30 05:59:591003int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1004 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291005 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1006
1007 int num_deleted = 0;
1008 DownloadMap::iterator it = downloads_.begin();
1009 while (it != downloads_.end()) {
1010 DownloadItem* download = it->second;
1011 DownloadItem::DownloadState state = download->state();
1012 if (download->start_time() >= remove_begin &&
1013 (remove_end.is_null() || download->start_time() < remove_end) &&
1014 (state == DownloadItem::COMPLETE ||
1015 state == DownloadItem::CANCELLED)) {
1016 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561017 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581018
1019 // Also remove it from any completed dangerous downloads.
1020 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1021 if (dit != dangerous_finished_.end())
1022 dangerous_finished_.erase(dit);
1023
initial.commit09911bf2008-07-26 23:55:291024 delete download;
1025
1026 ++num_deleted;
1027 continue;
1028 }
1029
1030 ++it;
1031 }
1032
1033 // Tell observers to refresh their views.
1034 if (num_deleted > 0)
1035 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1036
1037 return num_deleted;
1038}
1039
[email protected]e93d2822009-01-30 05:59:591040int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1041 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291042}
1043
1044// Initiate a download of a specific URL. We send the request to the
1045// ResourceDispatcherHost, and let it send us responses like a regular
1046// download.
1047void DownloadManager::DownloadUrl(const GURL& url,
1048 const GURL& referrer,
1049 WebContents* web_contents) {
1050 DCHECK(web_contents);
1051 file_manager_->DownloadUrl(url,
1052 referrer,
1053 web_contents->process()->host_id(),
1054 web_contents->render_view_host()->routing_id(),
1055 request_context_.get());
1056}
1057
1058void DownloadManager::NotifyAboutDownloadStart() {
[email protected]bfd04a62009-02-01 18:16:561059 NotificationService::current()->Notify(
1060 NotificationType::DOWNLOAD_START,
1061 NotificationService::AllSources(),
1062 NotificationService::NoDetails());
initial.commit09911bf2008-07-26 23:55:291063}
1064
1065void DownloadManager::NotifyAboutDownloadStop() {
[email protected]bfd04a62009-02-01 18:16:561066 NotificationService::current()->Notify(
1067 NotificationType::DOWNLOAD_STOP,
1068 NotificationService::AllSources(),
1069 NotificationService::NoDetails());
initial.commit09911bf2008-07-26 23:55:291070}
1071
[email protected]7ae7c2cb2009-01-06 23:31:411072void DownloadManager::GenerateExtension(
1073 const FilePath& file_name,
1074 const std::string& mime_type,
1075 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291076 // We're worried about three things here:
1077 //
1078 // 1) Security. Many sites let users upload content, such as buddy icons, to
1079 // their web sites. We want to mitigate the case where an attacker
1080 // supplies a malicious executable with an executable file extension but an
1081 // honest site serves the content with a benign content type, such as
1082 // image/jpeg.
1083 //
1084 // 2) Usability. If the site fails to provide a file extension, we want to
1085 // guess a reasonable file extension based on the content type.
1086 //
1087 // 3) Shell integration. Some file extensions automatically integrate with
1088 // the shell. We block these extensions to prevent a malicious web site
1089 // from integrating with the user's shell.
1090
[email protected]7ae7c2cb2009-01-06 23:31:411091 static const FilePath::CharType default_extension[] =
1092 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291093
1094 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411095 FilePath::StringType extension(
1096 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291097
[email protected]b7f05882009-02-22 01:21:561098#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291099 // Rename shell-integrated extensions.
1100 if (win_util::IsShellIntegratedExtension(extension))
1101 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561102#endif
initial.commit09911bf2008-07-26 23:55:291103
1104 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411105 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411106 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291107 if (mime_type == mime_type_from_extension) {
1108 // The hinted extension matches the mime type. It looks like a winner.
1109 generated_extension->swap(extension);
1110 return;
1111 }
1112
1113 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1114 // We want to be careful about executable extensions. The worry here is
1115 // that a trusted web site could be tricked into dropping an executable file
1116 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101117 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291118 // We couldn't find a good extension for this content type. Use a dummy
1119 // extension instead.
1120 extension.assign(default_extension);
1121 }
1122 }
1123
1124 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101125 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291126 } else {
[email protected]6cade212008-12-03 00:32:221127 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291128 // 1. New extension is not ".txt"
1129 // 2. New extension is not the same as the already existing extension.
1130 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411131 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291132 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1133 // application/x-javascript.
[email protected]7ae7c2cb2009-01-06 23:31:411134 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101135 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171136 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411137 append_extension != extension &&
[email protected]3f156552009-02-09 19:44:171138 !IsExecutable(append_extension)) {
1139 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291140 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171141 }
initial.commit09911bf2008-07-26 23:55:291142 }
1143 }
1144
1145 generated_extension->swap(extension);
1146}
1147
1148void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411149 FilePath* generated_name) {
1150 *generated_name = FilePath::FromWStringHack(
[email protected]8ac1a752008-07-31 19:40:371151 net::GetSuggestedFilename(GURL(info->url),
1152 info->content_disposition,
[email protected]7ae7c2cb2009-01-06 23:31:411153 L"download"));
1154 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291155
[email protected]7ae7c2cb2009-01-06 23:31:411156 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291157}
1158
1159void DownloadManager::AddObserver(Observer* observer) {
1160 observers_.AddObserver(observer);
1161 observer->ModelChanged();
1162}
1163
1164void DownloadManager::RemoveObserver(Observer* observer) {
1165 observers_.RemoveObserver(observer);
1166}
1167
1168// Post Windows Shell operations to the Download thread, to avoid blocking the
1169// user interface.
1170void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1171 DCHECK(file_manager_);
1172 file_loop_->PostTask(FROM_HERE,
1173 NewRunnableMethod(file_manager_,
1174 &DownloadFileManager::OnShowDownloadInShell,
[email protected]7ae7c2cb2009-01-06 23:31:411175 FilePath(download->full_path())));
initial.commit09911bf2008-07-26 23:55:291176}
1177
1178void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591179 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291180 DCHECK(file_manager_);
1181 file_loop_->PostTask(FROM_HERE,
1182 NewRunnableMethod(file_manager_,
1183 &DownloadFileManager::OnOpenDownloadInShell,
1184 download->full_path(), download->url(), parent_window));
1185}
1186
[email protected]7ae7c2cb2009-01-06 23:31:411187void DownloadManager::OpenFilesOfExtension(
1188 const FilePath::StringType& extension, bool open) {
initial.commit09911bf2008-07-26 23:55:291189 if (open && !IsExecutable(extension))
1190 auto_open_.insert(extension);
1191 else
1192 auto_open_.erase(extension);
1193 SaveAutoOpens();
1194}
1195
[email protected]7ae7c2cb2009-01-06 23:31:411196bool DownloadManager::ShouldOpenFileExtension(
1197 const FilePath::StringType& extension) {
[email protected]8c756ac2009-01-30 23:36:411198 // Special-case Chrome extensions as always-open.
initial.commit09911bf2008-07-26 23:55:291199 if (!IsExecutable(extension) &&
[email protected]8c756ac2009-01-30 23:36:411200 (auto_open_.find(extension) != auto_open_.end() ||
1201 extension == chrome::kExtensionFileExtension))
1202 return true;
initial.commit09911bf2008-07-26 23:55:291203 return false;
1204}
1205
[email protected]7b73d992008-12-15 20:56:461206static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291207 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461208 "text/javascript",
1209 "text/javascript;version=*",
[email protected]60ff8f912008-12-05 07:58:391210 // Some sites use binary/octet-stream to mean application/octet-stream.
1211 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461212 "binary/octet-stream"
1213};
initial.commit09911bf2008-07-26 23:55:291214
[email protected]7b73d992008-12-15 20:56:461215static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291216 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461217 "application/*+xml",
1218 "application/xml"
1219};
initial.commit09911bf2008-07-26 23:55:291220
[email protected]7b73d992008-12-15 20:56:461221// static
1222bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411223 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461224 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1225 return true;
1226 }
[email protected]bae0ea12009-02-14 01:20:411227 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461228 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1229 return false;
1230 }
1231 // We consider only other application types to be executable.
1232 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291233}
1234
[email protected]7ae7c2cb2009-01-06 23:31:411235bool DownloadManager::IsExecutable(const FilePath::StringType& extension) {
initial.commit09911bf2008-07-26 23:55:291236 return exe_types_.find(extension) != exe_types_.end();
1237}
1238
1239void DownloadManager::ResetAutoOpenFiles() {
1240 auto_open_.clear();
1241 SaveAutoOpens();
1242}
1243
1244bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1245 return !auto_open_.empty();
1246}
1247
1248void DownloadManager::SaveAutoOpens() {
1249 PrefService* prefs = profile_->GetPrefs();
1250 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411251 FilePath::StringType extensions;
1252 for (std::set<FilePath::StringType>::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291253 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411254 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291255 }
1256 if (!extensions.empty())
1257 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561258
1259 std::wstring extensions_w;
1260#if defined(OS_WIN)
1261 extensions_w = extensions;
1262#elif defined(OS_POSIX)
1263 // TODO(port): this is not correct since FilePath::StringType is not
1264 // necessarily UTF8.
1265 extensions_w = UTF8ToWide(extensions);
1266#endif
1267
1268 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291269 }
1270}
1271
[email protected]7ae7c2cb2009-01-06 23:31:411272void DownloadManager::FileSelected(const std::wstring& path_string,
1273 void* params) {
1274 FilePath path = FilePath::FromWStringHack(path_string);
initial.commit09911bf2008-07-26 23:55:291275 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071276 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411277 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291278 ContinueStartDownload(info, path);
1279}
1280
1281void DownloadManager::FileSelectionCanceled(void* params) {
1282 // The user didn't pick a place to save the file, so need to cancel the
1283 // download that's already in progress to the temporary location.
1284 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
1285 file_loop_->PostTask(FROM_HERE,
1286 NewRunnableMethod(file_manager_, &DownloadFileManager::CancelDownload,
1287 info->download_id));
1288}
1289
[email protected]7ae7c2cb2009-01-06 23:31:411290void DownloadManager::DeleteDownload(const FilePath& path) {
1291 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
1292 &DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321293}
1294
1295
1296void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1297 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1298 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1299 download->UpdateObservers();
1300
1301 // If the download is not complete, nothing to do. The required
1302 // post-processing will be performed when it does complete.
1303 if (download->state() != DownloadItem::COMPLETE)
1304 return;
1305
1306 file_loop_->PostTask(FROM_HERE,
1307 NewRunnableMethod(this,
1308 &DownloadManager::ProceedWithFinishedDangerousDownload,
1309 download->db_handle(), download->full_path(),
1310 download->original_name()));
1311}
1312
[email protected]763f946a2009-01-06 19:04:391313void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411314 FilePath* file_name) {
1315 // Make sure we get the right file extension
1316 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391317 GenerateExtension(*file_name, mime_type, &extension);
1318 file_util::ReplaceExtension(file_name, extension);
1319
1320 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411321 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391322 DCHECK(!leaf_name.empty());
[email protected]b7f05882009-02-22 01:21:561323#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391324 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411325 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1326 *file_name = file_name->DirName();
1327 if (file_name->value() == FilePath::kCurrentDirectory) {
1328 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391329 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411330 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391331 }
1332 }
[email protected]b7f05882009-02-22 01:21:561333#elif defined(OS_POSIX)
1334 NOTIMPLEMENTED();
1335#endif
[email protected]763f946a2009-01-06 19:04:391336}
1337
initial.commit09911bf2008-07-26 23:55:291338// Operations posted to us from the history service ----------------------------
1339
1340// The history service has retrieved all download entries. 'entries' contains
1341// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1342void DownloadManager::OnQueryDownloadEntriesComplete(
1343 std::vector<DownloadCreateInfo>* entries) {
1344 for (size_t i = 0; i < entries->size(); ++i) {
1345 DownloadItem* download = new DownloadItem(entries->at(i));
1346 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1347 downloads_[download->db_handle()] = download;
1348 download->set_manager(this);
1349 }
1350 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1351}
1352
1353
1354// Once the new DownloadItem's creation info has been committed to the history
1355// service, we associate the DownloadItem with the db handle, update our
1356// 'downloads_' map and inform observers.
1357void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1358 int64 db_handle) {
1359 DownloadMap::iterator it = in_progress_.find(info.download_id);
1360 DCHECK(it != in_progress_.end());
1361
1362 DownloadItem* download = it->second;
1363 DCHECK(download->db_handle() == kUninitializedHandle);
1364 download->set_db_handle(db_handle);
1365
1366 // Insert into our full map.
1367 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1368 downloads_[download->db_handle()] = download;
1369
1370 // The 'contents' may no longer exist if the user closed the tab before we get
1371 // this start completion event. If it does, tell the origin WebContents to
1372 // display its download shelf.
1373 TabContents* contents =
[email protected]a3a1d142008-12-19 00:42:301374 tab_util::GetWebContentsByID(info.render_process_id, info.render_view_id);
initial.commit09911bf2008-07-26 23:55:291375
1376 // If the contents no longer exists or is no longer active, we start the
1377 // download in the last active browser. This is not ideal but better than
1378 // fully hiding the download from the user. Note: non active means that the
1379 // user navigated away from the tab contents. This has nothing to do with
1380 // tab selection.
1381 if (!contents || !contents->is_active()) {
1382 Browser* last_active = BrowserList::GetLastActive();
1383 if (last_active)
1384 contents = last_active->GetSelectedTabContents();
1385 }
1386
1387 if (contents)
1388 contents->OnStartDownload(download);
1389
1390 // Inform interested objects about the new download.
1391 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1392 NotifyAboutDownloadStart();
1393
1394 // If this download has been completed before we've received the db handle,
1395 // post one final message to the history service so that it can be properly
1396 // in sync with the DownloadItem's completion status, and also inform any
1397 // observers so that they get more than just the start notification.
1398 if (download->state() != DownloadItem::IN_PROGRESS) {
1399 in_progress_.erase(it);
1400 NotifyAboutDownloadStop();
1401 UpdateHistoryForDownload(download);
1402 download->UpdateObservers();
1403 }
1404}
1405
1406// Called when the history service has retrieved the list of downloads that
1407// match the search text.
1408void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1409 std::vector<int64>* results) {
1410 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1411 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1412 if (!requestor)
1413 return;
1414
1415 std::vector<DownloadItem*> searched_downloads;
1416 for (std::vector<int64>::iterator it = results->begin();
1417 it != results->end(); ++it) {
1418 DownloadMap::iterator dit = downloads_.find(*it);
1419 if (dit != downloads_.end())
1420 searched_downloads.push_back(dit->second);
1421 }
1422
1423 requestor->SetDownloads(searched_downloads);
1424}
[email protected]905a08d2008-11-19 07:24:121425
[email protected]6cade212008-12-03 00:32:221426// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121427void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411428 last_download_path_ = FilePath();
[email protected]905a08d2008-11-19 07:24:121429}