blob: e2f998a5b06eed5313183797233c2cf369702f42 [file] [log] [blame]
[email protected]d41355e6f2009-04-07 21:21:121// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// 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
[email protected]a92b8642009-05-05 23:38:567#include "app/l10n_util.h"
initial.commit09911bf2008-07-26 23:55:298#include "base/file_util.h"
9#include "base/logging.h"
10#include "base/message_loop.h"
11#include "base/path_service.h"
[email protected]1b5044d2009-02-24 00:04:1412#include "base/rand_util.h"
[email protected]807204142009-05-05 03:31:4413#include "base/stl_util-inl.h"
initial.commit09911bf2008-07-26 23:55:2914#include "base/string_util.h"
[email protected]1b5044d2009-02-24 00:04:1415#include "base/sys_string_conversions.h"
initial.commit09911bf2008-07-26 23:55:2916#include "base/task.h"
17#include "base/thread.h"
18#include "base/timer.h"
initial.commit09911bf2008-07-26 23:55:2919#include "chrome/browser/browser_list.h"
20#include "chrome/browser/browser_process.h"
[email protected]cdaa8652008-09-13 02:48:5921#include "chrome/browser/download/download_file.h"
[email protected]e9ef0a62009-08-11 22:50:1322#include "chrome/browser/download/download_util.h"
[email protected]866930682009-08-18 22:53:4723#include "chrome/browser/extensions/crx_installer.h"
[email protected]2a464a92009-08-01 17:58:3524#include "chrome/browser/extensions/extension_install_ui.h"
[email protected]8f783752009-04-01 23:33:4525#include "chrome/browser/extensions/extensions_service.h"
[email protected]be180c802009-10-23 06:33:3126#include "chrome/browser/net/chrome_url_request_context.h"
initial.commit09911bf2008-07-26 23:55:2927#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:2628#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2529#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]e3c404b2008-12-23 01:07:3230#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
[email protected]f3ec7742009-01-15 00:59:1631#include "chrome/browser/tab_contents/tab_util.h"
[email protected]57c6a652009-05-04 07:58:3432#include "chrome/browser/tab_contents/tab_contents.h"
[email protected]4a0380c2009-07-26 07:25:3233#include "chrome/common/chrome_constants.h"
initial.commit09911bf2008-07-26 23:55:2934#include "chrome/common/chrome_paths.h"
[email protected]5b1a0e22009-05-26 19:00:5835#include "chrome/common/extensions/extension.h"
[email protected]91e1bd82009-09-03 22:04:4036#include "chrome/common/notification_service.h"
37#include "chrome/common/notification_type.h"
[email protected]076700e62009-04-01 18:41:2338#include "chrome/common/platform_util.h"
initial.commit09911bf2008-07-26 23:55:2939#include "chrome/common/pref_names.h"
40#include "chrome/common/pref_service.h"
[email protected]46072d42008-07-28 14:49:3541#include "googleurl/src/gurl.h"
[email protected]d81706b82009-04-03 20:28:4442#include "grit/chromium_strings.h"
[email protected]34ac8f32009-02-22 23:03:2743#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2944#include "net/base/mime_util.h"
45#include "net/base/net_util.h"
46#include "net/url_request/url_request_context.h"
47
[email protected]b7f05882009-02-22 01:21:5648#if defined(OS_WIN)
[email protected]4a0765a2009-05-08 23:12:2549#include "app/win_util.h"
[email protected]b7f05882009-02-22 01:21:5650#include "base/registry.h"
51#include "base/win_util.h"
[email protected]a0a9577b2009-05-27 23:52:3252#endif
53
[email protected]0f44d3e2009-03-12 23:36:3054#if defined(OS_LINUX)
55#include <gtk/gtk.h>
56#endif
57
initial.commit09911bf2008-07-26 23:55:2958// Periodically update our observers.
59class DownloadItemUpdateTask : public Task {
60 public:
61 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
62 void Run() { if (item_) item_->UpdateObservers(); }
63
64 private:
65 DownloadItem* item_;
66};
67
68// Update frequency (milliseconds).
69static const int kUpdateTimeMs = 1000;
70
71// Our download table ID starts at 1, so we use 0 to represent a download that
72// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2273// database handles in incognito mode starting at -1 and progressively getting
74// more negative.
initial.commit09911bf2008-07-26 23:55:2975static const int kUninitializedHandle = 0;
76
[email protected]7a256ea2008-10-17 17:34:1677// Appends the passed the number between parenthesis the path before the
78// extension.
[email protected]7ae7c2cb2009-01-06 23:31:4179static void AppendNumberToPath(FilePath* path, int number) {
80 file_util::InsertBeforeExtension(path,
81 StringPrintf(FILE_PATH_LITERAL(" (%d)"), number));
[email protected]7a256ea2008-10-17 17:34:1682}
83
84// Attempts to find a number that can be appended to that path to make it
85// unique. If |path| does not exist, 0 is returned. If it fails to find such
86// a number, -1 is returned.
[email protected]7ae7c2cb2009-01-06 23:31:4187static int GetUniquePathNumber(const FilePath& path) {
initial.commit09911bf2008-07-26 23:55:2988 const int kMaxAttempts = 100;
89
[email protected]7a256ea2008-10-17 17:34:1690 if (!file_util::PathExists(path))
91 return 0;
initial.commit09911bf2008-07-26 23:55:2992
[email protected]7ae7c2cb2009-01-06 23:31:4193 FilePath new_path;
initial.commit09911bf2008-07-26 23:55:2994 for (int count = 1; count <= kMaxAttempts; ++count) {
[email protected]7ae7c2cb2009-01-06 23:31:4195 new_path = FilePath(path);
[email protected]7a256ea2008-10-17 17:34:1696 AppendNumberToPath(&new_path, count);
initial.commit09911bf2008-07-26 23:55:2997
[email protected]7a256ea2008-10-17 17:34:1698 if (!file_util::PathExists(new_path))
99 return count;
initial.commit09911bf2008-07-26 23:55:29100 }
101
[email protected]7a256ea2008-10-17 17:34:16102 return -1;
initial.commit09911bf2008-07-26 23:55:29103}
104
[email protected]7ae7c2cb2009-01-06 23:31:41105static bool DownloadPathIsDangerous(const FilePath& download_path) {
106 FilePath desktop_dir;
[email protected]f052118e2008-09-05 02:25:32107 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
108 NOTREACHED();
109 return false;
110 }
111 return (download_path == desktop_dir);
112}
113
initial.commit09911bf2008-07-26 23:55:29114// DownloadItem implementation -------------------------------------------------
115
116// Constructor for reading from the history service.
117DownloadItem::DownloadItem(const DownloadCreateInfo& info)
118 : id_(-1),
119 full_path_(info.path),
120 url_(info.url),
[email protected]e435d6b72009-07-25 03:15:58121 referrer_url_(info.referrer_url),
122 mime_type_(info.mime_type),
initial.commit09911bf2008-07-26 23:55:29123 total_bytes_(info.total_bytes),
124 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56125 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29126 state_(static_cast<DownloadState>(info.state)),
127 start_time_(info.start_time),
128 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29129 manager_(NULL),
130 is_paused_(false),
131 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56132 safety_state_(SAFE),
[email protected]0aad67b2009-07-15 20:34:28133 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56134 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29135 render_process_id_(-1),
136 request_id_(-1) {
137 if (state_ == IN_PROGRESS)
138 state_ = CANCELLED;
139 Init(false /* don't start progress timer */);
140}
141
142// Constructor for DownloadItem created via user action in the main thread.
143DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41144 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16145 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32146 const GURL& url,
[email protected]494c06e2009-07-25 01:06:42147 const GURL& referrer_url,
[email protected]e435d6b72009-07-25 03:15:58148 const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:41149 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59150 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29151 int64 download_size,
152 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32153 int request_id,
[email protected]67f373a2009-09-22 02:44:51154 bool is_dangerous,
155 bool save_as)
initial.commit09911bf2008-07-26 23:55:29156 : id_(download_id),
157 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16158 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29159 url_(url),
[email protected]494c06e2009-07-25 01:06:42160 referrer_url_(referrer_url),
[email protected]e435d6b72009-07-25 03:15:58161 mime_type_(mime_type),
initial.commit09911bf2008-07-26 23:55:29162 total_bytes_(download_size),
163 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56164 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29165 state_(IN_PROGRESS),
166 start_time_(start_time),
167 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29168 manager_(NULL),
169 is_paused_(false),
170 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56171 safety_state_(is_dangerous ? DANGEROUS : SAFE),
[email protected]0aad67b2009-07-15 20:34:28172 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56173 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29174 render_process_id_(render_process_id),
[email protected]67f373a2009-09-22 02:44:51175 request_id_(request_id),
176 save_as_(save_as) {
initial.commit09911bf2008-07-26 23:55:29177 Init(true /* start progress timer */);
178}
179
180void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41181 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29182 if (start_timer)
183 StartProgressTimer();
184}
185
186DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29187 state_ = REMOVING;
188 UpdateObservers();
189}
190
191void DownloadItem::AddObserver(Observer* observer) {
192 observers_.AddObserver(observer);
193}
194
195void DownloadItem::RemoveObserver(Observer* observer) {
196 observers_.RemoveObserver(observer);
197}
198
199void DownloadItem::UpdateObservers() {
200 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
201}
202
[email protected]45e3c122009-04-07 19:58:03203void DownloadItem::NotifyObserversDownloadOpened() {
204 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadOpened(this));
205}
206
initial.commit09911bf2008-07-26 23:55:29207// If we've received more data than we were expecting (bad server info?), revert
208// to 'unknown size mode'.
209void DownloadItem::UpdateSize(int64 bytes_so_far) {
210 received_bytes_ = bytes_so_far;
211 if (received_bytes_ > total_bytes_)
212 total_bytes_ = 0;
213}
214
215// Updates from the download thread may have been posted while this download
216// was being cancelled in the UI thread, so we'll accept them unless we're
217// complete.
218void DownloadItem::Update(int64 bytes_so_far) {
219 if (state_ == COMPLETE) {
220 NOTREACHED();
221 return;
222 }
223 UpdateSize(bytes_so_far);
224 UpdateObservers();
225}
226
[email protected]6cade212008-12-03 00:32:22227// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29228void DownloadItem::Cancel(bool update_history) {
229 if (state_ != IN_PROGRESS) {
230 // Small downloads might be complete before this method has a chance to run.
231 return;
232 }
233 state_ = CANCELLED;
234 UpdateObservers();
235 StopProgressTimer();
236 if (update_history)
237 manager_->DownloadCancelled(id_);
238}
239
240void DownloadItem::Finished(int64 size) {
241 state_ = COMPLETE;
242 UpdateSize(size);
[email protected]22fbe5a2008-10-29 22:20:40243 UpdateObservers();
initial.commit09911bf2008-07-26 23:55:29244 StopProgressTimer();
245}
246
[email protected]9ccbb372008-10-10 18:50:32247void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29248 Cancel(true);
249 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32250 if (delete_on_disk)
251 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29252 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22253 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29254}
255
256void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59257 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14258 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29259}
260
261void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14262 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29263}
264
[email protected]e93d2822009-01-30 05:59:59265bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29266 if (total_bytes_ <= 0)
267 return false; // We never received the content_length for this download.
268
269 int64 speed = CurrentSpeed();
270 if (speed == 0)
271 return false;
272
273 *remaining =
[email protected]e93d2822009-01-30 05:59:59274 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29275 return true;
276}
277
278int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56279 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
280 int64 diff_ms = diff.InMilliseconds();
281 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29282}
283
284int DownloadItem::PercentComplete() const {
285 int percent = -1;
286 if (total_bytes_ > 0)
287 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
288 return percent;
289}
290
[email protected]7ae7c2cb2009-01-06 23:31:41291void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29292 DCHECK(!full_path.empty());
293 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41294 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29295}
296
297void DownloadItem::TogglePause() {
298 DCHECK(state_ == IN_PROGRESS);
299 manager_->PauseDownload(id_, !is_paused_);
300 is_paused_ = !is_paused_;
301 UpdateObservers();
302}
303
[email protected]7ae7c2cb2009-01-06 23:31:41304FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32305 if (safety_state_ == DownloadItem::SAFE)
306 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16307 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41308 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16309 AppendNumberToPath(&name, path_uniquifier_);
310 return name;
311 }
[email protected]9ccbb372008-10-10 18:50:32312 return original_name_;
313}
314
initial.commit09911bf2008-07-26 23:55:29315// DownloadManager implementation ----------------------------------------------
316
317// static
318void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
319 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
320 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32321 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
322
323 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41324 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12325 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
326 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32327 NOTREACHED();
328 }
[email protected]b9636002009-03-04 00:05:25329 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
330 default_download_path);
[email protected]f052118e2008-09-05 02:25:32331
332 // If the download path is dangerous we forcefully reset it. But if we do
333 // so we set a flag to make sure we only do it once, to avoid fighting
334 // the user if he really wants it on an unsafe place such as the desktop.
335
336 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41337 FilePath current_download_dir = FilePath::FromWStringHack(
338 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32339 if (DownloadPathIsDangerous(current_download_dir)) {
340 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41341 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32342 }
343 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
344 }
initial.commit09911bf2008-07-26 23:55:29345}
346
347DownloadManager::DownloadManager()
348 : shutdown_needed_(false),
349 profile_(NULL),
350 file_manager_(NULL),
351 ui_loop_(MessageLoop::current()),
352 file_loop_(NULL) {
353}
354
355DownloadManager::~DownloadManager() {
356 if (shutdown_needed_)
357 Shutdown();
358}
359
360void DownloadManager::Shutdown() {
361 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
362
363 // Stop receiving download updates
364 file_manager_->RemoveDownloadManager(this);
365
366 // Stop making history service requests
367 cancelable_consumer_.CancelAllRequests();
368
369 // 'in_progress_' may contain DownloadItems that have not finished the start
370 // complete (from the history service) and thus aren't in downloads_.
371 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32372 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29373 for (; it != in_progress_.end(); ++it) {
374 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32375 if (download->safety_state() == DownloadItem::DANGEROUS) {
376 // Forget about any download that the user did not approve.
377 // Note that we cannot call download->Remove() this would invalidate our
378 // iterator.
379 to_remove.insert(download);
380 continue;
initial.commit09911bf2008-07-26 23:55:29381 }
[email protected]9ccbb372008-10-10 18:50:32382 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
383 download->Cancel(false);
384 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29385 if (download->db_handle() == kUninitializedHandle) {
386 // An invalid handle means that 'download' does not yet exist in
387 // 'downloads_', so we have to delete it here.
388 delete download;
389 }
390 }
391
[email protected]9ccbb372008-10-10 18:50:32392 // 'dangerous_finished_' contains all complete downloads that have not been
393 // approved. They should be removed.
394 it = dangerous_finished_.begin();
395 for (; it != dangerous_finished_.end(); ++it)
396 to_remove.insert(it->second);
397
398 // Remove the dangerous download that are not approved.
399 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
400 rm_it != to_remove.end(); ++rm_it) {
401 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32402 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32403 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32404 // Same as above, delete the download if it is not in 'downloads_' (as the
405 // Remove() call above won't have deleted it).
406 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32407 delete download;
408 }
409 to_remove.clear();
410
initial.commit09911bf2008-07-26 23:55:29411 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32412 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29413 STLDeleteValues(&downloads_);
414
415 file_manager_ = NULL;
416
417 // Save our file extensions to auto open.
418 SaveAutoOpens();
419
420 // Make sure the save as dialog doesn't notify us back if we're gone before
421 // it returns.
422 if (select_file_dialog_.get())
423 select_file_dialog_->ListenerDestroyed();
424
425 shutdown_needed_ = false;
426}
427
428// Issue a history query for downloads matching 'search_text'. If 'search_text'
429// is empty, return all downloads that we know about.
430void DownloadManager::GetDownloads(Observer* observer,
431 const std::wstring& search_text) {
432 DCHECK(observer);
433
434 // Return a empty list if we've not yet received the set of downloads from the
435 // history system (we'll update all observers once we get that list in
436 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
437 std::vector<DownloadItem*> download_copy;
438 if (downloads_.empty()) {
439 observer->SetDownloads(download_copy);
440 return;
441 }
442
443 // We already know all the downloads and there is no filter, so just return a
444 // copy to the observer.
445 if (search_text.empty()) {
446 download_copy.reserve(downloads_.size());
447 for (DownloadMap::iterator it = downloads_.begin();
448 it != downloads_.end(); ++it) {
[email protected]67f373a2009-09-22 02:44:51449 if (it->second->db_handle() > kUninitializedHandle)
450 download_copy.push_back(it->second);
initial.commit09911bf2008-07-26 23:55:29451 }
452
453 // We retain ownership of the DownloadItems.
454 observer->SetDownloads(download_copy);
455 return;
456 }
457
458 // Issue a request to the history service for a list of downloads matching
459 // our search text.
460 HistoryService* hs =
461 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
462 if (hs) {
463 HistoryService::Handle h =
464 hs->SearchDownloads(search_text,
465 &cancelable_consumer_,
466 NewCallback(this,
467 &DownloadManager::OnSearchComplete));
468 cancelable_consumer_.SetClientData(hs, h, observer);
469 }
470}
471
472// Query the history service for information about all persisted downloads.
473bool DownloadManager::Init(Profile* profile) {
474 DCHECK(profile);
475 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
476 shutdown_needed_ = true;
477
478 profile_ = profile;
[email protected]be180c802009-10-23 06:33:31479 request_context_getter_ = profile_->GetRequestContext();
initial.commit09911bf2008-07-26 23:55:29480
481 // 'incognito mode' will have access to past downloads, but we won't store
482 // information about new downloads while in that mode.
483 QueryHistoryForDownloads();
484
485 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
486 if (!rdh) {
487 NOTREACHED();
488 return false;
489 }
490
491 file_manager_ = rdh->download_file_manager();
492 if (!file_manager_) {
493 NOTREACHED();
494 return false;
495 }
496
497 file_loop_ = g_browser_process->file_thread()->message_loop();
498 if (!file_loop_) {
499 NOTREACHED();
500 return false;
501 }
502
503 // Get our user preference state.
504 PrefService* prefs = profile_->GetPrefs();
505 DCHECK(prefs);
506 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
507
initial.commit09911bf2008-07-26 23:55:29508 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
509
[email protected]7ae7c2cb2009-01-06 23:31:41510 // This variable is needed to resolve which CreateDirectory we want to point
511 // to. Without it, the NewRunnableFunction cannot resolve the ambiguity.
512 // TODO(estade): when file_util::CreateDirectory(wstring) is removed,
513 // get rid of |CreateDirectoryPtr|.
514 bool (*CreateDirectoryPtr)(const FilePath&) = &file_util::CreateDirectory;
[email protected]bb69e9b32008-08-14 23:08:14515 // Ensure that the download directory specified in the preferences exists.
[email protected]7ae7c2cb2009-01-06 23:31:41516 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
517 CreateDirectoryPtr, download_path()));
initial.commit09911bf2008-07-26 23:55:29518
[email protected]a0a9577b2009-05-27 23:52:32519 // We use this to determine possibly dangerous downloads.
[email protected]2b2f8f72009-02-24 22:42:05520 download_util::InitializeExeTypes(&exe_types_);
[email protected]2b2f8f72009-02-24 22:42:05521
522 // We store any file extension that should be opened automatically at
523 // download completion in this pref.
initial.commit09911bf2008-07-26 23:55:29524 std::wstring extensions_to_open =
525 prefs->GetString(prefs::kDownloadExtensionsToOpen);
526 std::vector<std::wstring> extensions;
527 SplitString(extensions_to_open, L':', &extensions);
528 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]b7f05882009-02-22 01:21:56529 if (!extensions[i].empty() && !IsExecutable(
530 FilePath::FromWStringHack(extensions[i]).value()))
531 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29532 }
533
534 return true;
535}
536
537void DownloadManager::QueryHistoryForDownloads() {
538 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
539 if (hs) {
540 hs->QueryDownloads(
541 &cancelable_consumer_,
542 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
543 }
544}
545
546// We have received a message from DownloadFileManager about a new download. We
547// create a download item and store it in our download map, and inform the
548// history system of a new download. Since this method can be called while the
549// history service thread is still reading the persistent state, we do not
550// insert the new DownloadItem into 'downloads_' or inform our observers at this
551// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
552// download creation as a callback from the history thread.
553void DownloadManager::StartDownload(DownloadCreateInfo* info) {
554 DCHECK(MessageLoop::current() == ui_loop_);
555 DCHECK(info);
556
[email protected]7d3851d82008-12-12 03:26:07557 // Freeze the user's preference for showing a Save As dialog. We're going to
558 // bounce around a bunch of threads and we don't want to worry about race
559 // conditions where the user changes this pref out from under us.
[email protected]7bc4f702009-09-25 22:12:38560 if (*prompt_for_download_) {
561 // But never obey the preference for extension installation. Note that we
562 // only care here about the case where an extension is installed, not when
563 // one is downloaded with "save as...".
564 if (!IsExtensionInstall(info))
565 info->save_as = true;
566 }
[email protected]7d3851d82008-12-12 03:26:07567
initial.commit09911bf2008-07-26 23:55:29568 // Determine the proper path for a download, by choosing either the default
569 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41570 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29571 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07572 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29573 info->suggested_path = last_download_path_;
574 else
[email protected]7ae7c2cb2009-01-06 23:31:41575 info->suggested_path = download_path();
576 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29577
[email protected]7d3851d82008-12-12 03:26:07578 if (!info->save_as) {
[email protected]4289d9b2009-07-25 21:17:34579 // Downloads can be marked as dangerous for two reasons:
580 // a) They have a dangerous-looking filename
581 // b) They are an extension that is not from the gallery
582 if (IsDangerous(info->suggested_path.BaseName()))
583 info->is_dangerous = true;
[email protected]67f373a2009-09-22 02:44:51584 else if (IsExtensionInstall(info) &&
[email protected]4289d9b2009-07-25 21:17:34585 !ExtensionsService::IsDownloadFromGallery(info->url,
586 info->referrer_url)) {
587 info->is_dangerous = true;
588 }
[email protected]e9ebf3fc2008-10-17 22:06:58589 }
590
initial.commit09911bf2008-07-26 23:55:29591 // We need to move over to the download thread because we don't want to stat
592 // the suggested path on the UI thread.
593 file_loop_->PostTask(FROM_HERE,
594 NewRunnableMethod(this,
595 &DownloadManager::CheckIfSuggestedPathExists,
596 info));
597}
598
599void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
600 DCHECK(info);
601
602 // Check writability of the suggested path. If we can't write to it, default
603 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41604 FilePath dir = info->suggested_path.DirName();
605 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32606 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29607 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29608 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41609 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29610 }
611
[email protected]7a256ea2008-10-17 17:34:16612 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29613
[email protected]6cade212008-12-03 00:32:22614 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58615 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41616 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32617 // Create a temporary file to hold the file until the user approves its
618 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41619 FilePath::StringType file_name;
620 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32621 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41622 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32623 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41624 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07625 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41626 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32627 }
628 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16629 } else {
630 // We know the final path, build it if necessary.
631 if (info->path_uniquifier > 0) {
632 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
633 // Setting path_uniquifier to 0 to make sure we don't try to unique it
634 // later on.
635 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07636 } else if (info->path_uniquifier == -1) {
637 // We failed to find a unique path. We have to prompt the user.
638 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16639 }
[email protected]9ccbb372008-10-10 18:50:32640 }
641
[email protected]7d3851d82008-12-12 03:26:07642 if (!info->save_as) {
643 // Create an empty file at the suggested path so that we don't allocate the
644 // same "non-existant" path to multiple downloads.
645 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ff3f632009-10-13 18:43:35646 file_util::WriteFile(info->suggested_path, "", 0);
[email protected]7d3851d82008-12-12 03:26:07647 }
648
initial.commit09911bf2008-07-26 23:55:29649 // Now we return to the UI thread.
650 ui_loop_->PostTask(FROM_HERE,
651 NewRunnableMethod(this,
652 &DownloadManager::OnPathExistenceAvailable,
653 info));
654}
655
656void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
657 DCHECK(MessageLoop::current() == ui_loop_);
658 DCHECK(info);
659
[email protected]7d3851d82008-12-12 03:26:07660 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29661 // We must ask the user for the place to put the download.
662 if (!select_file_dialog_.get())
663 select_file_dialog_ = SelectFileDialog::Create(this);
664
[email protected]76543b92009-08-31 17:27:45665 TabContents* contents = tab_util::GetTabContentsByID(info->child_id,
666 info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08667 SelectFileDialog::FileTypeInfo file_type_info;
668 file_type_info.extensions.resize(1);
669 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24670 if (!file_type_info.extensions[0][0].empty())
671 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08672 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23673 gfx::NativeWindow owning_window =
674 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29675 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34676 string16(),
677 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08678 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30679 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29680 } else {
681 // No prompting for download, just continue with the suggested name.
682 ContinueStartDownload(info, info->suggested_path);
683 }
684}
685
686void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41687 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29688 scoped_ptr<DownloadCreateInfo> infop(info);
689 info->path = target_path;
690
691 DownloadItem* download = NULL;
692 DownloadMap::iterator it = in_progress_.find(info->download_id);
693 if (it == in_progress_.end()) {
694 download = new DownloadItem(info->download_id,
695 info->path,
[email protected]7a256ea2008-10-17 17:34:16696 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29697 info->url,
[email protected]494c06e2009-07-25 01:06:42698 info->referrer_url,
[email protected]e435d6b72009-07-25 03:15:58699 info->mime_type,
[email protected]9ccbb372008-10-10 18:50:32700 info->original_name,
initial.commit09911bf2008-07-26 23:55:29701 info->start_time,
702 info->total_bytes,
[email protected]76543b92009-08-31 17:27:45703 info->child_id,
[email protected]9ccbb372008-10-10 18:50:32704 info->request_id,
[email protected]67f373a2009-09-22 02:44:51705 info->is_dangerous,
706 info->save_as);
initial.commit09911bf2008-07-26 23:55:29707 download->set_manager(this);
708 in_progress_[info->download_id] = download;
709 } else {
710 NOTREACHED(); // Should not exist!
711 return;
712 }
713
[email protected]6b323782009-03-27 18:43:08714 // Called before DownloadFinished in order to avoid a race condition where we
715 // attempt to open a completed download before it has been renamed.
716 file_loop_->PostTask(FROM_HERE,
717 NewRunnableMethod(file_manager_,
718 &DownloadFileManager::OnFinalDownloadName,
719 download->id(),
[email protected]8f783752009-04-01 23:33:45720 target_path,
721 this));
[email protected]6b323782009-03-27 18:43:08722
initial.commit09911bf2008-07-26 23:55:29723 // If the download already completed by the time we reached this point, then
724 // notify observers that it did.
725 PendingFinishedMap::iterator pending_it =
726 pending_finished_downloads_.find(info->download_id);
727 if (pending_it != pending_finished_downloads_.end())
728 DownloadFinished(pending_it->first, pending_it->second);
729
730 download->Rename(target_path);
731
[email protected]67f373a2009-09-22 02:44:51732 // Do not store the download in the history database for a few special cases:
733 // - incognito mode (that is the point of this mode)
734 // - extensions (users don't think of extension installation as 'downloading')
735 // We have to make sure that these handles don't collide with normal db
736 // handles, so we use a negative value. Eventually, they could overlap, but
737 // you'd have to do enough downloading that your ISP would likely stab you in
738 // the neck first. YMMV.
739 if (profile_->IsOffTheRecord() || IsExtensionInstall(download)) {
initial.commit09911bf2008-07-26 23:55:29740 static int64 fake_db_handle = kUninitializedHandle - 1;
741 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
742 } else {
743 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22744 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29745 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
746 if (hs) {
747 hs->CreateDownload(
748 *info, &cancelable_consumer_,
749 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
750 }
751 }
752}
753
754// Convenience function for updating the history service for a download.
755void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
756 DCHECK(download);
757
758 // Don't store info in the database if the download was initiated while in
759 // incognito mode or if it hasn't been initialized in our database table.
760 if (download->db_handle() <= kUninitializedHandle)
761 return;
762
[email protected]6cade212008-12-03 00:32:22763 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29764 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
765 if (hs) {
766 hs->UpdateDownload(download->received_bytes(),
767 download->state(),
768 download->db_handle());
769 }
770}
771
772void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
773 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22774 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29775 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
776 if (download->db_handle() > kUninitializedHandle && hs)
777 hs->RemoveDownload(download->db_handle());
778}
779
[email protected]e93d2822009-01-30 05:59:59780void DownloadManager::RemoveDownloadsFromHistoryBetween(
781 const base::Time remove_begin,
782 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22783 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29784 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
785 if (hs)
786 hs->RemoveDownloadsBetween(remove_begin, remove_end);
787}
788
789void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
790 DownloadMap::iterator it = in_progress_.find(download_id);
791 if (it != in_progress_.end()) {
792 DownloadItem* download = it->second;
793 download->Update(size);
794 UpdateHistoryForDownload(download);
795 }
796}
797
798void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
799 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32800 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29801 // The download is done, but the user hasn't selected a final location for
802 // it yet (the Save As dialog box is probably still showing), so just keep
803 // track of the fact that this download id is complete, when the
804 // DownloadItem is constructed later we'll notify its completion then.
805 PendingFinishedMap::iterator erase_it =
806 pending_finished_downloads_.find(download_id);
807 DCHECK(erase_it == pending_finished_downloads_.end());
808 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32809 return;
initial.commit09911bf2008-07-26 23:55:29810 }
[email protected]9ccbb372008-10-10 18:50:32811
812 // Remove the id from the list of pending ids.
813 PendingFinishedMap::iterator erase_it =
814 pending_finished_downloads_.find(download_id);
815 if (erase_it != pending_finished_downloads_.end())
816 pending_finished_downloads_.erase(erase_it);
817
818 DownloadItem* download = it->second;
819 download->Finished(size);
820
821 // Clean up will happen when the history system create callback runs if we
822 // don't have a valid db_handle yet.
823 if (download->db_handle() != kUninitializedHandle) {
824 in_progress_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32825 UpdateHistoryForDownload(download);
826 }
827
828 // If this a dangerous download not yet validated by the user, don't do
829 // anything. When the user notifies us, it will trigger a call to
830 // ProceedWithFinishedDangerousDownload.
831 if (download->safety_state() == DownloadItem::DANGEROUS) {
832 dangerous_finished_[download_id] = download;
833 return;
834 }
835
836 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22837 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32838 // its final name before we can continue.
839 file_loop_->PostTask(FROM_HERE,
840 NewRunnableMethod(
841 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
842 download->db_handle(),
843 download->full_path(), download->original_name()));
844 return;
845 }
846 ContinueDownloadFinished(download);
847}
848
[email protected]8f783752009-04-01 23:33:45849void DownloadManager::DownloadRenamedToFinalName(int download_id,
850 const FilePath& full_path) {
[email protected]8f783752009-04-01 23:33:45851}
852
[email protected]9ccbb372008-10-10 18:50:32853void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
854 // If this was a dangerous download, it has now been approved and must be
855 // removed from dangerous_finished_ so it does not get deleted on shutdown.
856 DownloadMap::iterator it = dangerous_finished_.find(download->id());
857 if (it != dangerous_finished_.end())
858 dangerous_finished_.erase(it);
859
[email protected]5a102892009-07-15 19:59:30860 // Open the download if the user or user prefs indicate it should be.
861 FilePath::StringType extension = download->full_path().Extension();
862 // Drop the leading period. (The auto-open list is period-less.)
863 if (extension.size() > 0)
864 extension = extension.substr(1);
865
[email protected]0aad67b2009-07-15 20:34:28866 // Handle chrome extensions explicitly and skip the shell execute.
[email protected]67f373a2009-09-22 02:44:51867 if (IsExtensionInstall(download)) {
[email protected]494c06e2009-07-25 01:06:42868 OpenChromeExtension(download->full_path(), download->url(),
869 download->referrer_url());
[email protected]0aad67b2009-07-15 20:34:28870 download->set_auto_opened(true);
871 } else if (download->open_when_complete() ||
872 ShouldOpenFileExtension(extension)) {
[email protected]9ccbb372008-10-10 18:50:32873 OpenDownloadInShell(download, NULL);
[email protected]0aad67b2009-07-15 20:34:28874 download->set_auto_opened(true);
875 }
[email protected]9ccbb372008-10-10 18:50:32876
[email protected]0aad67b2009-07-15 20:34:28877 // Notify our observers that we are complete (the call to Finished() set the
878 // state to complete but did not notify).
879 download->UpdateObservers();
880}
[email protected]9ccbb372008-10-10 18:50:32881// Called on the file thread. Renames the downloaded file to its original name.
882void DownloadManager::ProceedWithFinishedDangerousDownload(
883 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41884 const FilePath& path,
885 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32886 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41887 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16888 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32889 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24890 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16891 // Make our name unique at this point, as if a dangerous file is downloading
892 // and a 2nd download is started for a file with the same name, they would
893 // have the same path. This is because we uniquify the name on download
894 // start, and at that time the first file does not exists yet, so the second
895 // file gets the same name.
896 uniquifier = GetUniquePathNumber(new_path);
897 if (uniquifier > 0)
898 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32899 success = file_util::Move(path, new_path);
900 } else {
901 NOTREACHED();
902 }
[email protected]6cade212008-12-03 00:32:22903
[email protected]9ccbb372008-10-10 18:50:32904 ui_loop_->PostTask(FROM_HERE,
905 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16906 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32907}
908
909// Call from the file thread when the finished dangerous download was renamed.
910void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
911 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41912 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16913 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32914 DownloadMap::iterator it = downloads_.find(download_handle);
915 if (it == downloads_.end()) {
916 NOTREACHED();
917 return;
918 }
919
920 DownloadItem* download = it->second;
921 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16922 if (success) {
923 // We need to update the path uniquifier so that the UI shows the right
924 // name when calling GetFileName().
925 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32926 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16927 }
[email protected]9ccbb372008-10-10 18:50:32928
929 // Continue the download finished sequence.
930 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29931}
932
933// static
initial.commit09911bf2008-07-26 23:55:29934void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
935 int render_process_id,
936 int request_id) {
[email protected]d85cf072009-10-27 03:59:31937 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
initial.commit09911bf2008-07-26 23:55:29938 rdh->CancelRequest(render_process_id, request_id, false);
939}
940
941void DownloadManager::DownloadCancelled(int32 download_id) {
942 DownloadMap::iterator it = in_progress_.find(download_id);
943 if (it == in_progress_.end())
944 return;
945 DownloadItem* download = it->second;
946
initial.commit09911bf2008-07-26 23:55:29947 // Clean up will happen when the history system create callback runs if we
948 // don't have a valid db_handle yet.
949 if (download->db_handle() != kUninitializedHandle) {
950 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:29951 UpdateHistoryForDownload(download);
952 }
953
[email protected]d7d1c5c2009-08-05 23:52:50954 DownloadCancelledInternal(download_id,
955 download->render_process_id(),
956 download->request_id());
957}
958
959void DownloadManager::DownloadCancelledInternal(int download_id,
960 int render_process_id,
961 int request_id) {
[email protected]d85cf072009-10-27 03:59:31962 // Cancel the network request. RDH is guaranteed to outlive the IO thread.
963 ChromeThread::PostTask(
964 ChromeThread::IO, FROM_HERE,
965 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
966 g_browser_process->resource_dispatcher_host(),
967 render_process_id,
968 request_id));
[email protected]d7d1c5c2009-08-05 23:52:50969
initial.commit09911bf2008-07-26 23:55:29970 // Tell the file manager to cancel the download.
[email protected]d7d1c5c2009-08-05 23:52:50971 file_manager_->RemoveDownload(download_id, this); // On the UI thread
initial.commit09911bf2008-07-26 23:55:29972 file_loop_->PostTask(FROM_HERE,
973 NewRunnableMethod(file_manager_,
974 &DownloadFileManager::CancelDownload,
[email protected]d7d1c5c2009-08-05 23:52:50975 download_id));
initial.commit09911bf2008-07-26 23:55:29976}
977
978void DownloadManager::PauseDownload(int32 download_id, bool pause) {
979 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]d85cf072009-10-27 03:59:31980 if (it == in_progress_.end())
981 return;
initial.commit09911bf2008-07-26 23:55:29982
[email protected]d85cf072009-10-27 03:59:31983 DownloadItem* download = it->second;
984 if (pause == download->is_paused())
985 return;
initial.commit09911bf2008-07-26 23:55:29986
[email protected]d85cf072009-10-27 03:59:31987 // Inform the ResourceDispatcherHost of the new pause state.
988 ChromeThread::PostTask(
989 ChromeThread::IO, FROM_HERE,
990 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
991 g_browser_process->resource_dispatcher_host(),
992 download->render_process_id(),
993 download->request_id(),
994 pause));
initial.commit09911bf2008-07-26 23:55:29995}
996
997// static
998void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
999 int render_process_id,
1000 int request_id,
1001 bool pause) {
1002 rdh->PauseRequest(render_process_id, request_id, pause);
1003}
1004
[email protected]7ae7c2cb2009-01-06 23:31:411005bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:321006 // TODO(jcampan): Improve me.
[email protected]2001fe82009-02-23 23:53:141007 FilePath::StringType extension = file_name.Extension();
1008 // Drop the leading period.
1009 if (extension.size() > 0)
1010 extension = extension.substr(1);
1011 return IsExecutable(extension);
[email protected]9ccbb372008-10-10 18:50:321012}
1013
1014void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:411015 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:321016 download->Rename(new_path);
1017
1018 // Update the history.
1019
1020 // No update necessary if the download was initiated while in incognito mode.
1021 if (download->db_handle() <= kUninitializedHandle)
1022 return;
1023
[email protected]6cade212008-12-03 00:32:221024 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:321025 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1026 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:411027 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:321028}
1029
initial.commit09911bf2008-07-26 23:55:291030void DownloadManager::RemoveDownload(int64 download_handle) {
1031 DownloadMap::iterator it = downloads_.find(download_handle);
1032 if (it == downloads_.end())
1033 return;
1034
1035 // Make history update.
1036 DownloadItem* download = it->second;
1037 RemoveDownloadFromHistory(download);
1038
1039 // Remove from our tables and delete.
1040 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321041 it = dangerous_finished_.find(download->id());
1042 if (it != dangerous_finished_.end())
1043 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291044
1045 // Tell observers to refresh their views.
1046 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:361047
1048 delete download;
initial.commit09911bf2008-07-26 23:55:291049}
1050
[email protected]e93d2822009-01-30 05:59:591051int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1052 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291053 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1054
initial.commit09911bf2008-07-26 23:55:291055 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:281056 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:291057 while (it != downloads_.end()) {
1058 DownloadItem* download = it->second;
1059 DownloadItem::DownloadState state = download->state();
1060 if (download->start_time() >= remove_begin &&
1061 (remove_end.is_null() || download->start_time() < remove_end) &&
1062 (state == DownloadItem::COMPLETE ||
1063 state == DownloadItem::CANCELLED)) {
1064 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561065 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581066
1067 // Also remove it from any completed dangerous downloads.
1068 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1069 if (dit != dangerous_finished_.end())
1070 dangerous_finished_.erase(dit);
1071
[email protected]78b8fcc92009-03-31 17:36:281072 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:291073
initial.commit09911bf2008-07-26 23:55:291074 continue;
1075 }
1076
1077 ++it;
1078 }
1079
1080 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281081 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291082 if (num_deleted > 0)
1083 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1084
[email protected]78b8fcc92009-03-31 17:36:281085 // Delete the download items after updating the observers.
1086 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1087 pending_deletes.clear();
1088
initial.commit09911bf2008-07-26 23:55:291089 return num_deleted;
1090}
1091
[email protected]e93d2822009-01-30 05:59:591092int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1093 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291094}
1095
[email protected]d41355e6f2009-04-07 21:21:121096int DownloadManager::RemoveAllDownloads() {
1097 // The null times make the date range unbounded.
1098 return RemoveDownloadsBetween(base::Time(), base::Time());
1099}
1100
initial.commit09911bf2008-07-26 23:55:291101// Initiate a download of a specific URL. We send the request to the
1102// ResourceDispatcherHost, and let it send us responses like a regular
1103// download.
1104void DownloadManager::DownloadUrl(const GURL& url,
1105 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:501106 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:341107 TabContents* tab_contents) {
1108 DCHECK(tab_contents);
initial.commit09911bf2008-07-26 23:55:291109 file_manager_->DownloadUrl(url,
1110 referrer,
[email protected]be180c802009-10-23 06:33:311111 referrer_charset,
[email protected]76543b92009-08-31 17:27:451112 tab_contents->process()->id(),
[email protected]57c6a652009-05-04 07:58:341113 tab_contents->render_view_host()->routing_id(),
[email protected]be180c802009-10-23 06:33:311114 request_context_getter_);
initial.commit09911bf2008-07-26 23:55:291115}
1116
[email protected]7ae7c2cb2009-01-06 23:31:411117void DownloadManager::GenerateExtension(
1118 const FilePath& file_name,
1119 const std::string& mime_type,
1120 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291121 // We're worried about three things here:
1122 //
1123 // 1) Security. Many sites let users upload content, such as buddy icons, to
1124 // their web sites. We want to mitigate the case where an attacker
1125 // supplies a malicious executable with an executable file extension but an
1126 // honest site serves the content with a benign content type, such as
1127 // image/jpeg.
1128 //
1129 // 2) Usability. If the site fails to provide a file extension, we want to
1130 // guess a reasonable file extension based on the content type.
1131 //
1132 // 3) Shell integration. Some file extensions automatically integrate with
1133 // the shell. We block these extensions to prevent a malicious web site
1134 // from integrating with the user's shell.
1135
[email protected]7ae7c2cb2009-01-06 23:31:411136 static const FilePath::CharType default_extension[] =
1137 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291138
1139 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411140 FilePath::StringType extension(
1141 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291142
[email protected]b7f05882009-02-22 01:21:561143#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291144 // Rename shell-integrated extensions.
1145 if (win_util::IsShellIntegratedExtension(extension))
1146 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561147#endif
initial.commit09911bf2008-07-26 23:55:291148
1149 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411150 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411151 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291152 if (mime_type == mime_type_from_extension) {
1153 // The hinted extension matches the mime type. It looks like a winner.
1154 generated_extension->swap(extension);
1155 return;
1156 }
1157
1158 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1159 // We want to be careful about executable extensions. The worry here is
1160 // that a trusted web site could be tricked into dropping an executable file
1161 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101162 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291163 // We couldn't find a good extension for this content type. Use a dummy
1164 // extension instead.
1165 extension.assign(default_extension);
1166 }
1167 }
1168
1169 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101170 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291171 } else {
[email protected]6cade212008-12-03 00:32:221172 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291173 // 1. New extension is not ".txt"
1174 // 2. New extension is not the same as the already existing extension.
1175 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411176 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291177 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1178 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371179 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1180 // servers, i.e. bug 5772.
[email protected]e32642f62009-09-11 21:58:291181 // 5. The original extension is not ".tgz" & the new extension is not "gz".
[email protected]7ae7c2cb2009-01-06 23:31:411182 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101183 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171184 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411185 append_extension != extension &&
[email protected]e106457b2009-03-25 22:43:371186 !IsExecutable(append_extension) &&
[email protected]e32642f62009-09-11 21:58:291187 !(append_extension == FILE_PATH_LITERAL("gz") &&
1188 extension == FILE_PATH_LITERAL("tgz")) &&
[email protected]e106457b2009-03-25 22:43:371189 (append_extension != FILE_PATH_LITERAL("tar") ||
1190 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171191 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291192 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171193 }
initial.commit09911bf2008-07-26 23:55:291194 }
1195 }
1196
1197 generated_extension->swap(extension);
1198}
1199
1200void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411201 FilePath* generated_name) {
[email protected]de2943352009-10-22 23:06:121202 *generated_name = net::GetSuggestedFilename(GURL(info->url),
1203 info->content_disposition,
1204 info->referrer_charset,
1205 "download");
[email protected]7ae7c2cb2009-01-06 23:31:411206 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291207
[email protected]7ae7c2cb2009-01-06 23:31:411208 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291209}
1210
1211void DownloadManager::AddObserver(Observer* observer) {
1212 observers_.AddObserver(observer);
1213 observer->ModelChanged();
1214}
1215
1216void DownloadManager::RemoveObserver(Observer* observer) {
1217 observers_.RemoveObserver(observer);
1218}
1219
1220// Post Windows Shell operations to the Download thread, to avoid blocking the
1221// user interface.
1222void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1223 DCHECK(file_manager_);
[email protected]8b6ff012009-08-18 22:29:581224 DCHECK(MessageLoop::current() == ui_loop_);
1225#if defined(OS_MACOSX)
1226 // Mac needs to run this operation on the UI thread.
1227 platform_util::ShowItemInFolder(download->full_path());
1228#else
initial.commit09911bf2008-07-26 23:55:291229 file_loop_->PostTask(FROM_HERE,
1230 NewRunnableMethod(file_manager_,
1231 &DownloadFileManager::OnShowDownloadInShell,
[email protected]7ae7c2cb2009-01-06 23:31:411232 FilePath(download->full_path())));
[email protected]8b6ff012009-08-18 22:29:581233#endif
initial.commit09911bf2008-07-26 23:55:291234}
1235
[email protected]8f783752009-04-01 23:33:451236void DownloadManager::OpenDownload(const DownloadItem* download,
1237 gfx::NativeView parent_window) {
[email protected]0e34d7892009-06-05 19:17:401238 // Open Chrome extensions with ExtensionsService. For everything else do shell
[email protected]8f783752009-04-01 23:33:451239 // execute.
[email protected]67f373a2009-09-22 02:44:511240 if (IsExtensionInstall(download)) {
[email protected]494c06e2009-07-25 01:06:421241 OpenChromeExtension(download->full_path(), download->url(),
1242 download->referrer_url());
[email protected]8f783752009-04-01 23:33:451243 } else {
1244 OpenDownloadInShell(download, parent_window);
1245 }
1246}
1247
[email protected]c1e432a2009-07-22 21:21:481248void DownloadManager::OpenChromeExtension(const FilePath& full_path,
[email protected]494c06e2009-07-25 01:06:421249 const GURL& download_url,
1250 const GURL& referrer_url) {
[email protected]6ef635e42009-07-26 06:16:121251 // We don't support extensions in OTR mode.
[email protected]2a464a92009-08-01 17:58:351252 ExtensionsService* service = profile_->GetExtensionsService();
1253 if (service) {
[email protected]91e1bd82009-09-03 22:04:401254 NotificationService* nservice = NotificationService::current();
1255 nservice->Notify(NotificationType::EXTENSION_READY_FOR_INSTALL,
1256 Source<DownloadManager>(this),
1257 NotificationService::NoDetails());
[email protected]2a464a92009-08-01 17:58:351258 CrxInstaller::Start(full_path,
1259 service->install_directory(),
1260 Extension::INTERNAL,
1261 "", // no expected id
1262 true, // please delete crx on completion
[email protected]2a409532009-08-28 19:39:441263 true, // privilege increase allowed
[email protected]2a464a92009-08-01 17:58:351264 g_browser_process->file_thread()->message_loop(),
1265 service,
1266 new ExtensionInstallUI(profile_));
1267 }
[email protected]8f783752009-04-01 23:33:451268}
1269
initial.commit09911bf2008-07-26 23:55:291270void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591271 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291272 DCHECK(file_manager_);
[email protected]8b6ff012009-08-18 22:29:581273 DCHECK(MessageLoop::current() == ui_loop_);
1274#if defined(OS_MACOSX)
1275 // Mac OS X requires opening downloads on the UI thread.
1276 platform_util::OpenItem(download->full_path());
1277#else
initial.commit09911bf2008-07-26 23:55:291278 file_loop_->PostTask(FROM_HERE,
1279 NewRunnableMethod(file_manager_,
1280 &DownloadFileManager::OnOpenDownloadInShell,
1281 download->full_path(), download->url(), parent_window));
[email protected]8b6ff012009-08-18 22:29:581282#endif
initial.commit09911bf2008-07-26 23:55:291283}
1284
[email protected]7ae7c2cb2009-01-06 23:31:411285void DownloadManager::OpenFilesOfExtension(
1286 const FilePath::StringType& extension, bool open) {
initial.commit09911bf2008-07-26 23:55:291287 if (open && !IsExecutable(extension))
1288 auto_open_.insert(extension);
1289 else
1290 auto_open_.erase(extension);
1291 SaveAutoOpens();
1292}
1293
[email protected]7ae7c2cb2009-01-06 23:31:411294bool DownloadManager::ShouldOpenFileExtension(
1295 const FilePath::StringType& extension) {
[email protected]8c756ac2009-01-30 23:36:411296 // Special-case Chrome extensions as always-open.
initial.commit09911bf2008-07-26 23:55:291297 if (!IsExecutable(extension) &&
[email protected]8c756ac2009-01-30 23:36:411298 (auto_open_.find(extension) != auto_open_.end() ||
[email protected]f1ce6e62009-06-29 20:31:291299 Extension::IsExtension(FilePath(extension))))
[email protected]8c756ac2009-01-30 23:36:411300 return true;
initial.commit09911bf2008-07-26 23:55:291301 return false;
1302}
1303
[email protected]7b73d992008-12-15 20:56:461304static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291305 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461306 "text/javascript",
1307 "text/javascript;version=*",
[email protected]54d8d452009-04-08 17:29:241308 // Registry files can cause critical changes to the MS OS behavior.
1309 // Addition of this mimetype also addresses bug 7337.
1310 "text/x-registry",
[email protected]60ff8f912008-12-05 07:58:391311 // Some sites use binary/octet-stream to mean application/octet-stream.
1312 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461313 "binary/octet-stream"
1314};
initial.commit09911bf2008-07-26 23:55:291315
[email protected]7b73d992008-12-15 20:56:461316static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291317 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461318 "application/*+xml",
1319 "application/xml"
1320};
initial.commit09911bf2008-07-26 23:55:291321
[email protected]7b73d992008-12-15 20:56:461322// static
1323bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411324 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461325 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1326 return true;
1327 }
[email protected]bae0ea12009-02-14 01:20:411328 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461329 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1330 return false;
1331 }
1332 // We consider only other application types to be executable.
1333 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291334}
1335
[email protected]7ae7c2cb2009-01-06 23:31:411336bool DownloadManager::IsExecutable(const FilePath::StringType& extension) {
[email protected]64da0b932009-02-24 02:30:041337 if (!IsStringASCII(extension))
1338 return false;
[email protected]a0a9577b2009-05-27 23:52:321339#if defined(OS_WIN)
[email protected]64da0b932009-02-24 02:30:041340 std::string ascii_extension = WideToASCII(extension);
[email protected]e9ef0a62009-08-11 22:50:131341#elif defined(OS_POSIX)
[email protected]a0a9577b2009-05-27 23:52:321342 std::string ascii_extension = extension;
1343#endif
[email protected]64da0b932009-02-24 02:30:041344 StringToLowerASCII(&ascii_extension);
1345
1346 return exe_types_.find(ascii_extension) != exe_types_.end();
initial.commit09911bf2008-07-26 23:55:291347}
1348
1349void DownloadManager::ResetAutoOpenFiles() {
1350 auto_open_.clear();
1351 SaveAutoOpens();
1352}
1353
1354bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1355 return !auto_open_.empty();
1356}
1357
1358void DownloadManager::SaveAutoOpens() {
1359 PrefService* prefs = profile_->GetPrefs();
1360 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411361 FilePath::StringType extensions;
1362 for (std::set<FilePath::StringType>::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291363 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411364 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291365 }
1366 if (!extensions.empty())
1367 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561368
1369 std::wstring extensions_w;
1370#if defined(OS_WIN)
1371 extensions_w = extensions;
1372#elif defined(OS_POSIX)
[email protected]1b5044d2009-02-24 00:04:141373 extensions_w = base::SysNativeMBToWide(extensions);
[email protected]b7f05882009-02-22 01:21:561374#endif
1375
1376 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291377 }
1378}
1379
[email protected]561abe62009-04-06 18:08:341380void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361381 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291382 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071383 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411384 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291385 ContinueStartDownload(info, path);
1386}
1387
1388void DownloadManager::FileSelectionCanceled(void* params) {
1389 // The user didn't pick a place to save the file, so need to cancel the
1390 // download that's already in progress to the temporary location.
1391 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]d7d1c5c2009-08-05 23:52:501392 DownloadCancelledInternal(info->download_id,
[email protected]76543b92009-08-31 17:27:451393 info->child_id,
[email protected]d7d1c5c2009-08-05 23:52:501394 info->request_id);
initial.commit09911bf2008-07-26 23:55:291395}
1396
[email protected]7ae7c2cb2009-01-06 23:31:411397void DownloadManager::DeleteDownload(const FilePath& path) {
1398 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
1399 &DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321400}
1401
1402
1403void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1404 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1405 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1406 download->UpdateObservers();
1407
1408 // If the download is not complete, nothing to do. The required
1409 // post-processing will be performed when it does complete.
1410 if (download->state() != DownloadItem::COMPLETE)
1411 return;
1412
1413 file_loop_->PostTask(FROM_HERE,
1414 NewRunnableMethod(this,
1415 &DownloadManager::ProceedWithFinishedDangerousDownload,
1416 download->db_handle(), download->full_path(),
1417 download->original_name()));
1418}
1419
[email protected]763f946a2009-01-06 19:04:391420void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411421 FilePath* file_name) {
1422 // Make sure we get the right file extension
1423 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391424 GenerateExtension(*file_name, mime_type, &extension);
1425 file_util::ReplaceExtension(file_name, extension);
1426
[email protected]2b2f8f72009-02-24 22:42:051427#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391428 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411429 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391430 DCHECK(!leaf_name.empty());
1431 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411432 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1433 *file_name = file_name->DirName();
1434 if (file_name->value() == FilePath::kCurrentDirectory) {
1435 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391436 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411437 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391438 }
1439 }
[email protected]b7f05882009-02-22 01:21:561440#endif
[email protected]763f946a2009-01-06 19:04:391441}
1442
[email protected]f1b11d32009-10-09 22:51:391443bool DownloadManager::IsExtensionInstall(const DownloadItem* item) {
1444 return item->mime_type() == Extension::kMimeType && !item->save_as();
1445}
1446
1447bool DownloadManager::IsExtensionInstall(const DownloadCreateInfo* info) {
1448 return info->mime_type == Extension::kMimeType && !info->save_as;
1449}
1450
initial.commit09911bf2008-07-26 23:55:291451// Operations posted to us from the history service ----------------------------
1452
1453// The history service has retrieved all download entries. 'entries' contains
1454// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1455void DownloadManager::OnQueryDownloadEntriesComplete(
1456 std::vector<DownloadCreateInfo>* entries) {
1457 for (size_t i = 0; i < entries->size(); ++i) {
1458 DownloadItem* download = new DownloadItem(entries->at(i));
1459 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1460 downloads_[download->db_handle()] = download;
1461 download->set_manager(this);
1462 }
1463 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1464}
1465
initial.commit09911bf2008-07-26 23:55:291466// Once the new DownloadItem's creation info has been committed to the history
1467// service, we associate the DownloadItem with the db handle, update our
1468// 'downloads_' map and inform observers.
1469void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1470 int64 db_handle) {
1471 DownloadMap::iterator it = in_progress_.find(info.download_id);
1472 DCHECK(it != in_progress_.end());
1473
1474 DownloadItem* download = it->second;
1475 DCHECK(download->db_handle() == kUninitializedHandle);
1476 download->set_db_handle(db_handle);
1477
1478 // Insert into our full map.
1479 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1480 downloads_[download->db_handle()] = download;
1481
[email protected]5e595482009-05-06 20:16:531482 // Show in the appropropriate browser UI.
1483 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291484
1485 // Inform interested objects about the new download.
1486 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
initial.commit09911bf2008-07-26 23:55:291487
1488 // If this download has been completed before we've received the db handle,
1489 // post one final message to the history service so that it can be properly
1490 // in sync with the DownloadItem's completion status, and also inform any
1491 // observers so that they get more than just the start notification.
1492 if (download->state() != DownloadItem::IN_PROGRESS) {
1493 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291494 UpdateHistoryForDownload(download);
1495 download->UpdateObservers();
1496 }
1497}
1498
1499// Called when the history service has retrieved the list of downloads that
1500// match the search text.
1501void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1502 std::vector<int64>* results) {
1503 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1504 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1505 if (!requestor)
1506 return;
1507
1508 std::vector<DownloadItem*> searched_downloads;
1509 for (std::vector<int64>::iterator it = results->begin();
1510 it != results->end(); ++it) {
1511 DownloadMap::iterator dit = downloads_.find(*it);
1512 if (dit != downloads_.end())
1513 searched_downloads.push_back(dit->second);
1514 }
1515
1516 requestor->SetDownloads(searched_downloads);
1517}
[email protected]905a08d2008-11-19 07:24:121518
[email protected]5e595482009-05-06 20:16:531519void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1520 DownloadItem* download) {
[email protected]5e595482009-05-06 20:16:531521 // The 'contents' may no longer exist if the user closed the tab before we get
1522 // this start completion event. If it does, tell the origin TabContents to
1523 // display its download shelf.
[email protected]76543b92009-08-31 17:27:451524 TabContents* contents = tab_util::GetTabContentsByID(info.child_id,
1525 info.render_view_id);
[email protected]5e595482009-05-06 20:16:531526
1527 // If the contents no longer exists, we start the download in the last active
1528 // browser. This is not ideal but better than fully hiding the download from
1529 // the user.
1530 if (!contents) {
1531 Browser* last_active = BrowserList::GetLastActive();
1532 if (last_active)
1533 contents = last_active->GetSelectedTabContents();
1534 }
1535
1536 if (contents)
1537 contents->OnStartDownload(download);
1538}
1539
[email protected]6cade212008-12-03 00:32:221540// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121541void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411542 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381543}
1544