blob: 6bbdd9355c73bc33f3a8aa4cae4b53992e75149a [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"
[email protected]d2a8fb72010-01-21 05:31:4219#include "build/build_config.h"
initial.commit09911bf2008-07-26 23:55:2920#include "chrome/browser/browser_list.h"
21#include "chrome/browser/browser_process.h"
[email protected]d83d03aa2009-11-02 21:44:3722#include "chrome/browser/chrome_thread.h"
[email protected]cdaa8652008-09-13 02:48:5923#include "chrome/browser/download/download_file.h"
[email protected]e9ef0a62009-08-11 22:50:1324#include "chrome/browser/download/download_util.h"
[email protected]866930682009-08-18 22:53:4725#include "chrome/browser/extensions/crx_installer.h"
[email protected]2a464a92009-08-01 17:58:3526#include "chrome/browser/extensions/extension_install_ui.h"
[email protected]8f783752009-04-01 23:33:4527#include "chrome/browser/extensions/extensions_service.h"
[email protected]be180c802009-10-23 06:33:3128#include "chrome/browser/net/chrome_url_request_context.h"
initial.commit09911bf2008-07-26 23:55:2929#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:2630#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2531#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]e3c404b2008-12-23 01:07:3232#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
[email protected]57c6a652009-05-04 07:58:3433#include "chrome/browser/tab_contents/tab_contents.h"
[email protected]d2a8fb72010-01-21 05:31:4234#include "chrome/browser/tab_contents/tab_util.h"
[email protected]4a0380c2009-07-26 07:25:3235#include "chrome/common/chrome_constants.h"
initial.commit09911bf2008-07-26 23:55:2936#include "chrome/common/chrome_paths.h"
[email protected]5b1a0e22009-05-26 19:00:5837#include "chrome/common/extensions/extension.h"
[email protected]6657afa62009-11-04 02:15:2038#include "chrome/common/extensions/user_script.h"
[email protected]91e1bd82009-09-03 22:04:4039#include "chrome/common/notification_service.h"
40#include "chrome/common/notification_type.h"
[email protected]076700e62009-04-01 18:41:2341#include "chrome/common/platform_util.h"
initial.commit09911bf2008-07-26 23:55:2942#include "chrome/common/pref_names.h"
43#include "chrome/common/pref_service.h"
[email protected]46072d42008-07-28 14:49:3544#include "googleurl/src/gurl.h"
[email protected]d81706b82009-04-03 20:28:4445#include "grit/chromium_strings.h"
[email protected]34ac8f32009-02-22 23:03:2746#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2947#include "net/base/mime_util.h"
48#include "net/base/net_util.h"
49#include "net/url_request/url_request_context.h"
50
[email protected]b7f05882009-02-22 01:21:5651#if defined(OS_WIN)
[email protected]4a0765a2009-05-08 23:12:2552#include "app/win_util.h"
[email protected]b7f05882009-02-22 01:21:5653#include "base/registry.h"
54#include "base/win_util.h"
[email protected]a0a9577b2009-05-27 23:52:3255#endif
56
initial.commit09911bf2008-07-26 23:55:2957// Periodically update our observers.
58class DownloadItemUpdateTask : public Task {
59 public:
60 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
61 void Run() { if (item_) item_->UpdateObservers(); }
62
63 private:
64 DownloadItem* item_;
65};
66
67// Update frequency (milliseconds).
68static const int kUpdateTimeMs = 1000;
69
70// Our download table ID starts at 1, so we use 0 to represent a download that
71// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2272// database handles in incognito mode starting at -1 and progressively getting
73// more negative.
initial.commit09911bf2008-07-26 23:55:2974static const int kUninitializedHandle = 0;
75
[email protected]7a256ea2008-10-17 17:34:1676// Appends the passed the number between parenthesis the path before the
77// extension.
[email protected]7ae7c2cb2009-01-06 23:31:4178static void AppendNumberToPath(FilePath* path, int number) {
79 file_util::InsertBeforeExtension(path,
80 StringPrintf(FILE_PATH_LITERAL(" (%d)"), number));
[email protected]7a256ea2008-10-17 17:34:1681}
82
83// Attempts to find a number that can be appended to that path to make it
84// unique. If |path| does not exist, 0 is returned. If it fails to find such
85// a number, -1 is returned.
[email protected]7ae7c2cb2009-01-06 23:31:4186static int GetUniquePathNumber(const FilePath& path) {
initial.commit09911bf2008-07-26 23:55:2987 const int kMaxAttempts = 100;
88
[email protected]7a256ea2008-10-17 17:34:1689 if (!file_util::PathExists(path))
90 return 0;
initial.commit09911bf2008-07-26 23:55:2991
[email protected]7ae7c2cb2009-01-06 23:31:4192 FilePath new_path;
initial.commit09911bf2008-07-26 23:55:2993 for (int count = 1; count <= kMaxAttempts; ++count) {
[email protected]7ae7c2cb2009-01-06 23:31:4194 new_path = FilePath(path);
[email protected]7a256ea2008-10-17 17:34:1695 AppendNumberToPath(&new_path, count);
initial.commit09911bf2008-07-26 23:55:2996
[email protected]7a256ea2008-10-17 17:34:1697 if (!file_util::PathExists(new_path))
98 return count;
initial.commit09911bf2008-07-26 23:55:2999 }
100
[email protected]7a256ea2008-10-17 17:34:16101 return -1;
initial.commit09911bf2008-07-26 23:55:29102}
103
[email protected]7ae7c2cb2009-01-06 23:31:41104static bool DownloadPathIsDangerous(const FilePath& download_path) {
105 FilePath desktop_dir;
[email protected]f052118e2008-09-05 02:25:32106 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
107 NOTREACHED();
108 return false;
109 }
110 return (download_path == desktop_dir);
111}
112
initial.commit09911bf2008-07-26 23:55:29113// DownloadItem implementation -------------------------------------------------
114
115// Constructor for reading from the history service.
116DownloadItem::DownloadItem(const DownloadCreateInfo& info)
117 : id_(-1),
118 full_path_(info.path),
119 url_(info.url),
[email protected]e435d6b72009-07-25 03:15:58120 referrer_url_(info.referrer_url),
121 mime_type_(info.mime_type),
initial.commit09911bf2008-07-26 23:55:29122 total_bytes_(info.total_bytes),
123 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56124 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29125 state_(static_cast<DownloadState>(info.state)),
126 start_time_(info.start_time),
127 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29128 manager_(NULL),
129 is_paused_(false),
130 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56131 safety_state_(SAFE),
[email protected]0aad67b2009-07-15 20:34:28132 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56133 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29134 render_process_id_(-1),
[email protected]6aa4a1c02010-01-15 18:49:58135 request_id_(-1),
136 save_as_(false),
[email protected]5748eb82010-01-20 15:12:37137 is_extension_install_(info.is_extension_install),
[email protected]6aa4a1c02010-01-15 18:49:58138 name_finalized_(false),
139 is_temporary_(false) {
initial.commit09911bf2008-07-26 23:55:29140 if (state_ == IN_PROGRESS)
141 state_ = CANCELLED;
142 Init(false /* don't start progress timer */);
143}
144
145// Constructor for DownloadItem created via user action in the main thread.
146DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41147 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16148 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32149 const GURL& url,
[email protected]494c06e2009-07-25 01:06:42150 const GURL& referrer_url,
[email protected]e435d6b72009-07-25 03:15:58151 const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:41152 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59153 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29154 int64 download_size,
155 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32156 int request_id,
[email protected]67f373a2009-09-22 02:44:51157 bool is_dangerous,
[email protected]a60c8ae2009-12-25 06:50:57158 bool save_as,
[email protected]6aa4a1c02010-01-15 18:49:58159 bool is_extension_install,
160 bool is_temporary)
initial.commit09911bf2008-07-26 23:55:29161 : id_(download_id),
162 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16163 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29164 url_(url),
[email protected]494c06e2009-07-25 01:06:42165 referrer_url_(referrer_url),
[email protected]e435d6b72009-07-25 03:15:58166 mime_type_(mime_type),
initial.commit09911bf2008-07-26 23:55:29167 total_bytes_(download_size),
168 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56169 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29170 state_(IN_PROGRESS),
171 start_time_(start_time),
172 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29173 manager_(NULL),
174 is_paused_(false),
175 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56176 safety_state_(is_dangerous ? DANGEROUS : SAFE),
[email protected]0aad67b2009-07-15 20:34:28177 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56178 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29179 render_process_id_(render_process_id),
[email protected]67f373a2009-09-22 02:44:51180 request_id_(request_id),
[email protected]a60c8ae2009-12-25 06:50:57181 save_as_(save_as),
[email protected]6aa4a1c02010-01-15 18:49:58182 is_extension_install_(is_extension_install),
183 name_finalized_(false),
184 is_temporary_(is_temporary) {
initial.commit09911bf2008-07-26 23:55:29185 Init(true /* start progress timer */);
186}
187
188void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41189 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29190 if (start_timer)
191 StartProgressTimer();
192}
193
194DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29195 state_ = REMOVING;
196 UpdateObservers();
197}
198
199void DownloadItem::AddObserver(Observer* observer) {
200 observers_.AddObserver(observer);
201}
202
203void DownloadItem::RemoveObserver(Observer* observer) {
204 observers_.RemoveObserver(observer);
205}
206
207void DownloadItem::UpdateObservers() {
208 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
209}
210
[email protected]6aa4a1c02010-01-15 18:49:58211void DownloadItem::NotifyObserversDownloadFileCompleted() {
212 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadFileCompleted(this));
213}
214
[email protected]45e3c122009-04-07 19:58:03215void DownloadItem::NotifyObserversDownloadOpened() {
216 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadOpened(this));
217}
218
initial.commit09911bf2008-07-26 23:55:29219// If we've received more data than we were expecting (bad server info?), revert
220// to 'unknown size mode'.
221void DownloadItem::UpdateSize(int64 bytes_so_far) {
222 received_bytes_ = bytes_so_far;
223 if (received_bytes_ > total_bytes_)
224 total_bytes_ = 0;
225}
226
227// Updates from the download thread may have been posted while this download
228// was being cancelled in the UI thread, so we'll accept them unless we're
229// complete.
230void DownloadItem::Update(int64 bytes_so_far) {
231 if (state_ == COMPLETE) {
232 NOTREACHED();
233 return;
234 }
235 UpdateSize(bytes_so_far);
236 UpdateObservers();
237}
238
[email protected]6cade212008-12-03 00:32:22239// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29240void DownloadItem::Cancel(bool update_history) {
241 if (state_ != IN_PROGRESS) {
242 // Small downloads might be complete before this method has a chance to run.
243 return;
244 }
245 state_ = CANCELLED;
246 UpdateObservers();
247 StopProgressTimer();
248 if (update_history)
249 manager_->DownloadCancelled(id_);
250}
251
252void DownloadItem::Finished(int64 size) {
253 state_ = COMPLETE;
254 UpdateSize(size);
initial.commit09911bf2008-07-26 23:55:29255 StopProgressTimer();
256}
257
[email protected]9ccbb372008-10-10 18:50:32258void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29259 Cancel(true);
260 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32261 if (delete_on_disk)
262 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29263 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22264 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29265}
266
267void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59268 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14269 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29270}
271
272void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14273 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29274}
275
[email protected]e93d2822009-01-30 05:59:59276bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29277 if (total_bytes_ <= 0)
278 return false; // We never received the content_length for this download.
279
280 int64 speed = CurrentSpeed();
281 if (speed == 0)
282 return false;
283
284 *remaining =
[email protected]e93d2822009-01-30 05:59:59285 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29286 return true;
287}
288
289int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56290 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
291 int64 diff_ms = diff.InMilliseconds();
292 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29293}
294
295int DownloadItem::PercentComplete() const {
296 int percent = -1;
297 if (total_bytes_ > 0)
298 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
299 return percent;
300}
301
[email protected]7ae7c2cb2009-01-06 23:31:41302void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29303 DCHECK(!full_path.empty());
304 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41305 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29306}
307
308void DownloadItem::TogglePause() {
309 DCHECK(state_ == IN_PROGRESS);
310 manager_->PauseDownload(id_, !is_paused_);
311 is_paused_ = !is_paused_;
312 UpdateObservers();
313}
314
[email protected]7ae7c2cb2009-01-06 23:31:41315FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32316 if (safety_state_ == DownloadItem::SAFE)
317 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16318 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41319 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16320 AppendNumberToPath(&name, path_uniquifier_);
321 return name;
322 }
[email protected]9ccbb372008-10-10 18:50:32323 return original_name_;
324}
325
initial.commit09911bf2008-07-26 23:55:29326// DownloadManager implementation ----------------------------------------------
327
328// static
329void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
330 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
331 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32332 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
333
334 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41335 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12336 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
337 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32338 NOTREACHED();
339 }
[email protected]2403fd62010-01-25 18:18:20340 if (DownloadPathIsDangerous(default_download_path)) {
341 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS_SAFE,
342 &default_download_path)) {
343 NOTREACHED();
344 }
345 }
[email protected]b9636002009-03-04 00:05:25346 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
347 default_download_path);
[email protected]f052118e2008-09-05 02:25:32348
349 // If the download path is dangerous we forcefully reset it. But if we do
350 // so we set a flag to make sure we only do it once, to avoid fighting
351 // the user if he really wants it on an unsafe place such as the desktop.
352
353 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41354 FilePath current_download_dir = FilePath::FromWStringHack(
355 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32356 if (DownloadPathIsDangerous(current_download_dir)) {
357 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41358 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32359 }
360 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
361 }
initial.commit09911bf2008-07-26 23:55:29362}
363
364DownloadManager::DownloadManager()
365 : shutdown_needed_(false),
366 profile_(NULL),
[email protected]d2a8fb72010-01-21 05:31:42367 file_manager_(NULL),
368 fake_db_handle_(kUninitializedHandle - 1) {
initial.commit09911bf2008-07-26 23:55:29369}
370
371DownloadManager::~DownloadManager() {
372 if (shutdown_needed_)
373 Shutdown();
374}
375
376void DownloadManager::Shutdown() {
377 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
378
379 // Stop receiving download updates
380 file_manager_->RemoveDownloadManager(this);
381
382 // Stop making history service requests
383 cancelable_consumer_.CancelAllRequests();
384
385 // 'in_progress_' may contain DownloadItems that have not finished the start
386 // complete (from the history service) and thus aren't in downloads_.
387 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32388 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29389 for (; it != in_progress_.end(); ++it) {
390 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32391 if (download->safety_state() == DownloadItem::DANGEROUS) {
392 // Forget about any download that the user did not approve.
393 // Note that we cannot call download->Remove() this would invalidate our
394 // iterator.
395 to_remove.insert(download);
396 continue;
initial.commit09911bf2008-07-26 23:55:29397 }
[email protected]9ccbb372008-10-10 18:50:32398 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
399 download->Cancel(false);
400 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29401 if (download->db_handle() == kUninitializedHandle) {
402 // An invalid handle means that 'download' does not yet exist in
403 // 'downloads_', so we have to delete it here.
404 delete download;
405 }
406 }
407
[email protected]9ccbb372008-10-10 18:50:32408 // 'dangerous_finished_' contains all complete downloads that have not been
409 // approved. They should be removed.
410 it = dangerous_finished_.begin();
411 for (; it != dangerous_finished_.end(); ++it)
412 to_remove.insert(it->second);
413
414 // Remove the dangerous download that are not approved.
415 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
416 rm_it != to_remove.end(); ++rm_it) {
417 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32418 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32419 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32420 // Same as above, delete the download if it is not in 'downloads_' (as the
421 // Remove() call above won't have deleted it).
422 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32423 delete download;
424 }
425 to_remove.clear();
426
initial.commit09911bf2008-07-26 23:55:29427 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32428 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29429 STLDeleteValues(&downloads_);
430
431 file_manager_ = NULL;
432
433 // Save our file extensions to auto open.
434 SaveAutoOpens();
435
436 // Make sure the save as dialog doesn't notify us back if we're gone before
437 // it returns.
438 if (select_file_dialog_.get())
439 select_file_dialog_->ListenerDestroyed();
440
441 shutdown_needed_ = false;
442}
443
444// Issue a history query for downloads matching 'search_text'. If 'search_text'
445// is empty, return all downloads that we know about.
446void DownloadManager::GetDownloads(Observer* observer,
447 const std::wstring& search_text) {
448 DCHECK(observer);
449
450 // Return a empty list if we've not yet received the set of downloads from the
451 // history system (we'll update all observers once we get that list in
452 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
453 std::vector<DownloadItem*> download_copy;
454 if (downloads_.empty()) {
455 observer->SetDownloads(download_copy);
456 return;
457 }
458
459 // We already know all the downloads and there is no filter, so just return a
460 // copy to the observer.
461 if (search_text.empty()) {
462 download_copy.reserve(downloads_.size());
463 for (DownloadMap::iterator it = downloads_.begin();
464 it != downloads_.end(); ++it) {
[email protected]67f373a2009-09-22 02:44:51465 if (it->second->db_handle() > kUninitializedHandle)
466 download_copy.push_back(it->second);
initial.commit09911bf2008-07-26 23:55:29467 }
468
469 // We retain ownership of the DownloadItems.
470 observer->SetDownloads(download_copy);
471 return;
472 }
473
474 // Issue a request to the history service for a list of downloads matching
475 // our search text.
476 HistoryService* hs =
477 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
478 if (hs) {
479 HistoryService::Handle h =
480 hs->SearchDownloads(search_text,
481 &cancelable_consumer_,
482 NewCallback(this,
483 &DownloadManager::OnSearchComplete));
484 cancelable_consumer_.SetClientData(hs, h, observer);
485 }
486}
487
[email protected]6aa4a1c02010-01-15 18:49:58488void DownloadManager::GetTemporaryDownloads(Observer* observer,
489 const FilePath& dir_path) {
490 DCHECK(observer);
491
492 std::vector<DownloadItem*> download_copy;
493
494 for (DownloadMap::iterator it = downloads_.begin();
495 it != downloads_.end(); ++it) {
496 if (it->second->is_temporary() &&
497 it->second->full_path().DirName() == dir_path)
498 download_copy.push_back(it->second);
499 }
500
501 observer->SetDownloads(download_copy);
502}
503
initial.commit09911bf2008-07-26 23:55:29504// Query the history service for information about all persisted downloads.
505bool DownloadManager::Init(Profile* profile) {
506 DCHECK(profile);
507 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
508 shutdown_needed_ = true;
509
510 profile_ = profile;
[email protected]be180c802009-10-23 06:33:31511 request_context_getter_ = profile_->GetRequestContext();
initial.commit09911bf2008-07-26 23:55:29512
513 // 'incognito mode' will have access to past downloads, but we won't store
514 // information about new downloads while in that mode.
515 QueryHistoryForDownloads();
516
517 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
518 if (!rdh) {
519 NOTREACHED();
520 return false;
521 }
522
523 file_manager_ = rdh->download_file_manager();
524 if (!file_manager_) {
525 NOTREACHED();
526 return false;
527 }
528
initial.commit09911bf2008-07-26 23:55:29529 // Get our user preference state.
530 PrefService* prefs = profile_->GetPrefs();
531 DCHECK(prefs);
532 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
533
initial.commit09911bf2008-07-26 23:55:29534 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
535
[email protected]bb69e9b32008-08-14 23:08:14536 // Ensure that the download directory specified in the preferences exists.
[email protected]d83d03aa2009-11-02 21:44:37537 ChromeThread::PostTask(
538 ChromeThread::FILE, FROM_HERE,
[email protected]309b7642009-12-09 03:08:50539 NewRunnableFunction(&file_util::CreateDirectory, download_path()));
initial.commit09911bf2008-07-26 23:55:29540
[email protected]2b2f8f72009-02-24 22:42:05541 // We store any file extension that should be opened automatically at
542 // download completion in this pref.
initial.commit09911bf2008-07-26 23:55:29543 std::wstring extensions_to_open =
544 prefs->GetString(prefs::kDownloadExtensionsToOpen);
545 std::vector<std::wstring> extensions;
546 SplitString(extensions_to_open, L':', &extensions);
547 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]eccb9d12009-10-28 05:40:09548 if (!extensions[i].empty() && !IsExecutableFile(
549 FilePath::FromWStringHack(extensions[i])))
[email protected]b7f05882009-02-22 01:21:56550 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29551 }
552
553 return true;
554}
555
556void DownloadManager::QueryHistoryForDownloads() {
557 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
558 if (hs) {
559 hs->QueryDownloads(
560 &cancelable_consumer_,
561 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
562 }
563}
564
565// We have received a message from DownloadFileManager about a new download. We
566// create a download item and store it in our download map, and inform the
567// history system of a new download. Since this method can be called while the
568// history service thread is still reading the persistent state, we do not
569// insert the new DownloadItem into 'downloads_' or inform our observers at this
570// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
571// download creation as a callback from the history thread.
572void DownloadManager::StartDownload(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37573 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29574 DCHECK(info);
575
[email protected]a60c8ae2009-12-25 06:50:57576 // Check whether this download is for an extension install or not.
577 if (!info->save_as) { // Allow extensions to be explicitly saved.
578 if (UserScript::HasUserScriptFileExtension(info->url) ||
579 info->mime_type == Extension::kMimeType)
580 info->is_extension_install = true;
581 }
582
[email protected]7d3851d82008-12-12 03:26:07583 // Freeze the user's preference for showing a Save As dialog. We're going to
584 // bounce around a bunch of threads and we don't want to worry about race
585 // conditions where the user changes this pref out from under us.
[email protected]7bc4f702009-09-25 22:12:38586 if (*prompt_for_download_) {
587 // But never obey the preference for extension installation. Note that we
588 // only care here about the case where an extension is installed, not when
589 // one is downloaded with "save as...".
[email protected]a60c8ae2009-12-25 06:50:57590 if (!info->is_extension_install)
[email protected]7bc4f702009-09-25 22:12:38591 info->save_as = true;
592 }
[email protected]7d3851d82008-12-12 03:26:07593
[email protected]6aa4a1c02010-01-15 18:49:58594 // Determine the proper path for a download, by either one of the following:
595 // 1) using the provided save file path.
596 // 2) using the default download directory.
597 // 3) prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41598 FilePath generated_name;
[email protected]6aa4a1c02010-01-15 18:49:58599 GenerateFileNameFromInfo(info, &generated_name);
600 if (!info->save_file_path.empty())
601 info->suggested_path = info->save_file_path;
602 else if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29603 info->suggested_path = last_download_path_;
604 else
[email protected]7ae7c2cb2009-01-06 23:31:41605 info->suggested_path = download_path();
606 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29607
[email protected]6aa4a1c02010-01-15 18:49:58608 if (!info->save_as && info->save_file_path.empty()) {
[email protected]4289d9b2009-07-25 21:17:34609 // Downloads can be marked as dangerous for two reasons:
610 // a) They have a dangerous-looking filename
611 // b) They are an extension that is not from the gallery
612 if (IsDangerous(info->suggested_path.BaseName()))
613 info->is_dangerous = true;
[email protected]a60c8ae2009-12-25 06:50:57614 else if (info->is_extension_install &&
[email protected]b7c2f252009-12-08 00:47:23615 !ExtensionsService::IsDownloadFromGallery(info->url,
616 info->referrer_url)) {
[email protected]4289d9b2009-07-25 21:17:34617 info->is_dangerous = true;
618 }
[email protected]e9ebf3fc2008-10-17 22:06:58619 }
620
initial.commit09911bf2008-07-26 23:55:29621 // We need to move over to the download thread because we don't want to stat
622 // the suggested path on the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37623 ChromeThread::PostTask(
624 ChromeThread::FILE, FROM_HERE,
625 NewRunnableMethod(
626 this, &DownloadManager::CheckIfSuggestedPathExists, info));
initial.commit09911bf2008-07-26 23:55:29627}
628
629void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
630 DCHECK(info);
631
632 // Check writability of the suggested path. If we can't write to it, default
633 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41634 FilePath dir = info->suggested_path.DirName();
635 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32636 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29637 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29638 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41639 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29640 }
641
[email protected]7a256ea2008-10-17 17:34:16642 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29643
[email protected]6cade212008-12-03 00:32:22644 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58645 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41646 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32647 // Create a temporary file to hold the file until the user approves its
648 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41649 FilePath::StringType file_name;
650 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32651 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41652 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32653 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41654 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07655 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41656 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32657 }
658 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16659 } else {
660 // We know the final path, build it if necessary.
661 if (info->path_uniquifier > 0) {
662 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
663 // Setting path_uniquifier to 0 to make sure we don't try to unique it
664 // later on.
665 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07666 } else if (info->path_uniquifier == -1) {
667 // We failed to find a unique path. We have to prompt the user.
668 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16669 }
[email protected]9ccbb372008-10-10 18:50:32670 }
671
[email protected]7d3851d82008-12-12 03:26:07672 if (!info->save_as) {
673 // Create an empty file at the suggested path so that we don't allocate the
674 // same "non-existant" path to multiple downloads.
675 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ff3f632009-10-13 18:43:35676 file_util::WriteFile(info->suggested_path, "", 0);
[email protected]7d3851d82008-12-12 03:26:07677 }
678
initial.commit09911bf2008-07-26 23:55:29679 // Now we return to the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37680 ChromeThread::PostTask(
681 ChromeThread::UI, FROM_HERE,
initial.commit09911bf2008-07-26 23:55:29682 NewRunnableMethod(this,
683 &DownloadManager::OnPathExistenceAvailable,
684 info));
685}
686
687void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37688 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29689 DCHECK(info);
690
[email protected]7d3851d82008-12-12 03:26:07691 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29692 // We must ask the user for the place to put the download.
693 if (!select_file_dialog_.get())
694 select_file_dialog_ = SelectFileDialog::Create(this);
695
[email protected]76543b92009-08-31 17:27:45696 TabContents* contents = tab_util::GetTabContentsByID(info->child_id,
697 info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08698 SelectFileDialog::FileTypeInfo file_type_info;
699 file_type_info.extensions.resize(1);
700 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24701 if (!file_type_info.extensions[0][0].empty())
702 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08703 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23704 gfx::NativeWindow owning_window =
705 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29706 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34707 string16(),
708 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08709 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30710 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29711 } else {
712 // No prompting for download, just continue with the suggested name.
713 ContinueStartDownload(info, info->suggested_path);
714 }
715}
716
717void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41718 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29719 scoped_ptr<DownloadCreateInfo> infop(info);
720 info->path = target_path;
721
722 DownloadItem* download = NULL;
723 DownloadMap::iterator it = in_progress_.find(info->download_id);
724 if (it == in_progress_.end()) {
725 download = new DownloadItem(info->download_id,
726 info->path,
[email protected]7a256ea2008-10-17 17:34:16727 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29728 info->url,
[email protected]494c06e2009-07-25 01:06:42729 info->referrer_url,
[email protected]e435d6b72009-07-25 03:15:58730 info->mime_type,
[email protected]9ccbb372008-10-10 18:50:32731 info->original_name,
initial.commit09911bf2008-07-26 23:55:29732 info->start_time,
733 info->total_bytes,
[email protected]76543b92009-08-31 17:27:45734 info->child_id,
[email protected]9ccbb372008-10-10 18:50:32735 info->request_id,
[email protected]67f373a2009-09-22 02:44:51736 info->is_dangerous,
[email protected]a60c8ae2009-12-25 06:50:57737 info->save_as,
[email protected]6aa4a1c02010-01-15 18:49:58738 info->is_extension_install,
739 !info->save_file_path.empty());
initial.commit09911bf2008-07-26 23:55:29740 download->set_manager(this);
741 in_progress_[info->download_id] = download;
742 } else {
743 NOTREACHED(); // Should not exist!
744 return;
745 }
746
[email protected]6b323782009-03-27 18:43:08747 // Called before DownloadFinished in order to avoid a race condition where we
748 // attempt to open a completed download before it has been renamed.
[email protected]d83d03aa2009-11-02 21:44:37749 ChromeThread::PostTask(
750 ChromeThread::FILE, FROM_HERE,
751 NewRunnableMethod(
752 file_manager_, &DownloadFileManager::OnFinalDownloadName,
753 download->id(), target_path, this));
[email protected]6b323782009-03-27 18:43:08754
initial.commit09911bf2008-07-26 23:55:29755 // If the download already completed by the time we reached this point, then
756 // notify observers that it did.
757 PendingFinishedMap::iterator pending_it =
758 pending_finished_downloads_.find(info->download_id);
759 if (pending_it != pending_finished_downloads_.end())
760 DownloadFinished(pending_it->first, pending_it->second);
761
762 download->Rename(target_path);
763
[email protected]67f373a2009-09-22 02:44:51764 // Do not store the download in the history database for a few special cases:
765 // - incognito mode (that is the point of this mode)
766 // - extensions (users don't think of extension installation as 'downloading')
[email protected]6aa4a1c02010-01-15 18:49:58767 // - temporary download, like in drag-and-drop
[email protected]67f373a2009-09-22 02:44:51768 // We have to make sure that these handles don't collide with normal db
769 // handles, so we use a negative value. Eventually, they could overlap, but
770 // you'd have to do enough downloading that your ISP would likely stab you in
771 // the neck first. YMMV.
[email protected]6aa4a1c02010-01-15 18:49:58772 if (profile_->IsOffTheRecord() || download->is_extension_install() ||
773 download->is_temporary()) {
[email protected]d2a8fb72010-01-21 05:31:42774 OnCreateDownloadEntryComplete(*info, fake_db_handle_.GetNext());
initial.commit09911bf2008-07-26 23:55:29775 } else {
776 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22777 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29778 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
779 if (hs) {
780 hs->CreateDownload(
781 *info, &cancelable_consumer_,
782 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
783 }
784 }
785}
786
787// Convenience function for updating the history service for a download.
788void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
789 DCHECK(download);
790
791 // Don't store info in the database if the download was initiated while in
792 // incognito mode or if it hasn't been initialized in our database table.
793 if (download->db_handle() <= kUninitializedHandle)
794 return;
795
[email protected]6cade212008-12-03 00:32:22796 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29797 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
798 if (hs) {
799 hs->UpdateDownload(download->received_bytes(),
800 download->state(),
801 download->db_handle());
802 }
803}
804
805void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
806 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22807 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29808 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
809 if (download->db_handle() > kUninitializedHandle && hs)
810 hs->RemoveDownload(download->db_handle());
811}
812
[email protected]e93d2822009-01-30 05:59:59813void DownloadManager::RemoveDownloadsFromHistoryBetween(
814 const base::Time remove_begin,
815 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22816 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29817 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
818 if (hs)
819 hs->RemoveDownloadsBetween(remove_begin, remove_end);
820}
821
822void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
823 DownloadMap::iterator it = in_progress_.find(download_id);
824 if (it != in_progress_.end()) {
825 DownloadItem* download = it->second;
826 download->Update(size);
827 UpdateHistoryForDownload(download);
828 }
829}
830
831void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
832 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32833 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29834 // The download is done, but the user hasn't selected a final location for
835 // it yet (the Save As dialog box is probably still showing), so just keep
836 // track of the fact that this download id is complete, when the
837 // DownloadItem is constructed later we'll notify its completion then.
838 PendingFinishedMap::iterator erase_it =
839 pending_finished_downloads_.find(download_id);
840 DCHECK(erase_it == pending_finished_downloads_.end());
841 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32842 return;
initial.commit09911bf2008-07-26 23:55:29843 }
[email protected]9ccbb372008-10-10 18:50:32844
845 // Remove the id from the list of pending ids.
846 PendingFinishedMap::iterator erase_it =
847 pending_finished_downloads_.find(download_id);
848 if (erase_it != pending_finished_downloads_.end())
849 pending_finished_downloads_.erase(erase_it);
850
851 DownloadItem* download = it->second;
852 download->Finished(size);
853
854 // Clean up will happen when the history system create callback runs if we
855 // don't have a valid db_handle yet.
856 if (download->db_handle() != kUninitializedHandle) {
857 in_progress_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32858 UpdateHistoryForDownload(download);
859 }
860
861 // If this a dangerous download not yet validated by the user, don't do
862 // anything. When the user notifies us, it will trigger a call to
863 // ProceedWithFinishedDangerousDownload.
864 if (download->safety_state() == DownloadItem::DANGEROUS) {
865 dangerous_finished_[download_id] = download;
866 return;
867 }
868
869 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22870 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32871 // its final name before we can continue.
[email protected]d83d03aa2009-11-02 21:44:37872 ChromeThread::PostTask(
873 ChromeThread::FILE, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32874 NewRunnableMethod(
875 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
876 download->db_handle(),
877 download->full_path(), download->original_name()));
878 return;
879 }
880 ContinueDownloadFinished(download);
881}
882
[email protected]8f783752009-04-01 23:33:45883void DownloadManager::DownloadRenamedToFinalName(int download_id,
884 const FilePath& full_path) {
[email protected]6aa4a1c02010-01-15 18:49:58885 DownloadMap::iterator it = downloads_.begin();
886 while (it != downloads_.end()) {
887 DownloadItem* download = it->second;
888 if (download->id() == download_id) {
889 // The download file is meant to be completed if both the filename is
890 // finalized and the file data is downloaded. The ordering of these two
891 // actions is indeterministic. Thus, if we are still in downloading the
892 // file, delay the notification.
893 download->set_name_finalized(true);
894 if (download->state() == DownloadItem::COMPLETE)
895 download->NotifyObserversDownloadFileCompleted();
896 return;
897 }
898 it++;
899 }
[email protected]8f783752009-04-01 23:33:45900}
901
[email protected]9ccbb372008-10-10 18:50:32902void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
903 // If this was a dangerous download, it has now been approved and must be
904 // removed from dangerous_finished_ so it does not get deleted on shutdown.
905 DownloadMap::iterator it = dangerous_finished_.find(download->id());
906 if (it != dangerous_finished_.end())
907 dangerous_finished_.erase(it);
908
[email protected]0aad67b2009-07-15 20:34:28909 // Handle chrome extensions explicitly and skip the shell execute.
[email protected]a60c8ae2009-12-25 06:50:57910 if (download->is_extension_install()) {
[email protected]494c06e2009-07-25 01:06:42911 OpenChromeExtension(download->full_path(), download->url(),
912 download->referrer_url());
[email protected]0aad67b2009-07-15 20:34:28913 download->set_auto_opened(true);
914 } else if (download->open_when_complete() ||
[email protected]6aa4a1c02010-01-15 18:49:58915 ShouldOpenFileBasedOnExtension(download->full_path()) ||
916 download->is_temporary()) {
917 // If the download is temporary, like in drag-and-drop, do not open it but
918 // we still need to set it auto-opened so that it can be removed from the
919 // download shelf.
920 if (!download->is_temporary())
921 OpenDownloadInShell(download, NULL);
[email protected]0aad67b2009-07-15 20:34:28922 download->set_auto_opened(true);
923 }
[email protected]9ccbb372008-10-10 18:50:32924
[email protected]0aad67b2009-07-15 20:34:28925 // Notify our observers that we are complete (the call to Finished() set the
926 // state to complete but did not notify).
927 download->UpdateObservers();
[email protected]6aa4a1c02010-01-15 18:49:58928
929 // The download file is meant to be completed if both the filename is
930 // finalized and the file data is downloaded. The ordering of these two
931 // actions is indeterministic. Thus, if the filename is not finalized yet,
932 // delay the notification.
933 if (download->name_finalized())
934 download->NotifyObserversDownloadFileCompleted();
[email protected]0aad67b2009-07-15 20:34:28935}
[email protected]eccb9d12009-10-28 05:40:09936
[email protected]9ccbb372008-10-10 18:50:32937// Called on the file thread. Renames the downloaded file to its original name.
938void DownloadManager::ProceedWithFinishedDangerousDownload(
939 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41940 const FilePath& path,
941 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32942 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41943 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16944 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32945 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24946 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16947 // Make our name unique at this point, as if a dangerous file is downloading
948 // and a 2nd download is started for a file with the same name, they would
949 // have the same path. This is because we uniquify the name on download
950 // start, and at that time the first file does not exists yet, so the second
951 // file gets the same name.
952 uniquifier = GetUniquePathNumber(new_path);
953 if (uniquifier > 0)
954 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32955 success = file_util::Move(path, new_path);
956 } else {
957 NOTREACHED();
958 }
[email protected]6cade212008-12-03 00:32:22959
[email protected]d83d03aa2009-11-02 21:44:37960 ChromeThread::PostTask(
961 ChromeThread::UI, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32962 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16963 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32964}
965
966// Call from the file thread when the finished dangerous download was renamed.
967void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
968 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41969 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16970 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32971 DownloadMap::iterator it = downloads_.find(download_handle);
972 if (it == downloads_.end()) {
973 NOTREACHED();
974 return;
975 }
976
977 DownloadItem* download = it->second;
978 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16979 if (success) {
980 // We need to update the path uniquifier so that the UI shows the right
981 // name when calling GetFileName().
982 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32983 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16984 }
[email protected]9ccbb372008-10-10 18:50:32985
986 // Continue the download finished sequence.
987 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29988}
989
990// static
initial.commit09911bf2008-07-26 23:55:29991void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
992 int render_process_id,
993 int request_id) {
[email protected]d85cf072009-10-27 03:59:31994 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
initial.commit09911bf2008-07-26 23:55:29995 rdh->CancelRequest(render_process_id, request_id, false);
996}
997
998void DownloadManager::DownloadCancelled(int32 download_id) {
999 DownloadMap::iterator it = in_progress_.find(download_id);
1000 if (it == in_progress_.end())
1001 return;
1002 DownloadItem* download = it->second;
1003
initial.commit09911bf2008-07-26 23:55:291004 // Clean up will happen when the history system create callback runs if we
1005 // don't have a valid db_handle yet.
1006 if (download->db_handle() != kUninitializedHandle) {
1007 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291008 UpdateHistoryForDownload(download);
1009 }
1010
[email protected]d7d1c5c2009-08-05 23:52:501011 DownloadCancelledInternal(download_id,
1012 download->render_process_id(),
1013 download->request_id());
1014}
1015
1016void DownloadManager::DownloadCancelledInternal(int download_id,
1017 int render_process_id,
1018 int request_id) {
[email protected]d85cf072009-10-27 03:59:311019 // Cancel the network request. RDH is guaranteed to outlive the IO thread.
1020 ChromeThread::PostTask(
1021 ChromeThread::IO, FROM_HERE,
1022 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
1023 g_browser_process->resource_dispatcher_host(),
1024 render_process_id,
1025 request_id));
[email protected]d7d1c5c2009-08-05 23:52:501026
initial.commit09911bf2008-07-26 23:55:291027 // Tell the file manager to cancel the download.
[email protected]d7d1c5c2009-08-05 23:52:501028 file_manager_->RemoveDownload(download_id, this); // On the UI thread
[email protected]d83d03aa2009-11-02 21:44:371029 ChromeThread::PostTask(
1030 ChromeThread::FILE, FROM_HERE,
1031 NewRunnableMethod(
1032 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:291033}
1034
1035void DownloadManager::PauseDownload(int32 download_id, bool pause) {
1036 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]d85cf072009-10-27 03:59:311037 if (it == in_progress_.end())
1038 return;
initial.commit09911bf2008-07-26 23:55:291039
[email protected]d85cf072009-10-27 03:59:311040 DownloadItem* download = it->second;
1041 if (pause == download->is_paused())
1042 return;
initial.commit09911bf2008-07-26 23:55:291043
[email protected]d85cf072009-10-27 03:59:311044 // Inform the ResourceDispatcherHost of the new pause state.
1045 ChromeThread::PostTask(
1046 ChromeThread::IO, FROM_HERE,
1047 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
1048 g_browser_process->resource_dispatcher_host(),
1049 download->render_process_id(),
1050 download->request_id(),
1051 pause));
initial.commit09911bf2008-07-26 23:55:291052}
1053
1054// static
1055void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
1056 int render_process_id,
1057 int request_id,
1058 bool pause) {
1059 rdh->PauseRequest(render_process_id, request_id, pause);
1060}
1061
[email protected]7ae7c2cb2009-01-06 23:31:411062bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:321063 // TODO(jcampan): Improve me.
[email protected]eccb9d12009-10-28 05:40:091064 return IsExecutableFile(file_name);
[email protected]9ccbb372008-10-10 18:50:321065}
1066
1067void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:411068 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:321069 download->Rename(new_path);
1070
1071 // Update the history.
1072
1073 // No update necessary if the download was initiated while in incognito mode.
1074 if (download->db_handle() <= kUninitializedHandle)
1075 return;
1076
[email protected]6cade212008-12-03 00:32:221077 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:321078 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1079 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:411080 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:321081}
1082
initial.commit09911bf2008-07-26 23:55:291083void DownloadManager::RemoveDownload(int64 download_handle) {
1084 DownloadMap::iterator it = downloads_.find(download_handle);
1085 if (it == downloads_.end())
1086 return;
1087
1088 // Make history update.
1089 DownloadItem* download = it->second;
1090 RemoveDownloadFromHistory(download);
1091
1092 // Remove from our tables and delete.
1093 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321094 it = dangerous_finished_.find(download->id());
1095 if (it != dangerous_finished_.end())
1096 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291097
1098 // Tell observers to refresh their views.
1099 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:361100
1101 delete download;
initial.commit09911bf2008-07-26 23:55:291102}
1103
[email protected]e93d2822009-01-30 05:59:591104int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1105 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291106 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1107
initial.commit09911bf2008-07-26 23:55:291108 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:281109 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:291110 while (it != downloads_.end()) {
1111 DownloadItem* download = it->second;
1112 DownloadItem::DownloadState state = download->state();
1113 if (download->start_time() >= remove_begin &&
1114 (remove_end.is_null() || download->start_time() < remove_end) &&
1115 (state == DownloadItem::COMPLETE ||
1116 state == DownloadItem::CANCELLED)) {
1117 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561118 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581119
1120 // Also remove it from any completed dangerous downloads.
1121 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1122 if (dit != dangerous_finished_.end())
1123 dangerous_finished_.erase(dit);
1124
[email protected]78b8fcc92009-03-31 17:36:281125 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:291126
initial.commit09911bf2008-07-26 23:55:291127 continue;
1128 }
1129
1130 ++it;
1131 }
1132
1133 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281134 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291135 if (num_deleted > 0)
1136 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1137
[email protected]78b8fcc92009-03-31 17:36:281138 // Delete the download items after updating the observers.
1139 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1140 pending_deletes.clear();
1141
initial.commit09911bf2008-07-26 23:55:291142 return num_deleted;
1143}
1144
[email protected]e93d2822009-01-30 05:59:591145int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1146 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291147}
1148
[email protected]d41355e6f2009-04-07 21:21:121149int DownloadManager::RemoveAllDownloads() {
1150 // The null times make the date range unbounded.
1151 return RemoveDownloadsBetween(base::Time(), base::Time());
1152}
1153
initial.commit09911bf2008-07-26 23:55:291154// Initiate a download of a specific URL. We send the request to the
1155// ResourceDispatcherHost, and let it send us responses like a regular
1156// download.
1157void DownloadManager::DownloadUrl(const GURL& url,
1158 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:501159 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:341160 TabContents* tab_contents) {
[email protected]6aa4a1c02010-01-15 18:49:581161 file_manager_->DownloadUrl(url,
1162 referrer,
1163 referrer_charset,
1164 FilePath(),
1165 tab_contents->process()->id(),
1166 tab_contents->render_view_host()->routing_id(),
1167 request_context_getter_);
1168}
1169
1170void DownloadManager::DownloadUrlToFile(const GURL& url,
1171 const GURL& referrer,
1172 const std::string& referrer_charset,
1173 const FilePath& save_file_path,
1174 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:341175 DCHECK(tab_contents);
initial.commit09911bf2008-07-26 23:55:291176 file_manager_->DownloadUrl(url,
1177 referrer,
[email protected]be180c802009-10-23 06:33:311178 referrer_charset,
[email protected]6aa4a1c02010-01-15 18:49:581179 save_file_path,
[email protected]76543b92009-08-31 17:27:451180 tab_contents->process()->id(),
[email protected]57c6a652009-05-04 07:58:341181 tab_contents->render_view_host()->routing_id(),
[email protected]be180c802009-10-23 06:33:311182 request_context_getter_);
initial.commit09911bf2008-07-26 23:55:291183}
1184
[email protected]7ae7c2cb2009-01-06 23:31:411185void DownloadManager::GenerateExtension(
1186 const FilePath& file_name,
1187 const std::string& mime_type,
1188 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291189 // We're worried about three things here:
1190 //
1191 // 1) Security. Many sites let users upload content, such as buddy icons, to
1192 // their web sites. We want to mitigate the case where an attacker
1193 // supplies a malicious executable with an executable file extension but an
1194 // honest site serves the content with a benign content type, such as
1195 // image/jpeg.
1196 //
1197 // 2) Usability. If the site fails to provide a file extension, we want to
1198 // guess a reasonable file extension based on the content type.
1199 //
1200 // 3) Shell integration. Some file extensions automatically integrate with
1201 // the shell. We block these extensions to prevent a malicious web site
1202 // from integrating with the user's shell.
1203
[email protected]7ae7c2cb2009-01-06 23:31:411204 static const FilePath::CharType default_extension[] =
1205 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291206
1207 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411208 FilePath::StringType extension(
1209 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291210
[email protected]b7f05882009-02-22 01:21:561211#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291212 // Rename shell-integrated extensions.
1213 if (win_util::IsShellIntegratedExtension(extension))
1214 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561215#endif
initial.commit09911bf2008-07-26 23:55:291216
1217 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411218 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411219 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291220 if (mime_type == mime_type_from_extension) {
1221 // The hinted extension matches the mime type. It looks like a winner.
1222 generated_extension->swap(extension);
1223 return;
1224 }
1225
[email protected]eccb9d12009-10-28 05:40:091226 if (IsExecutableExtension(extension) && !IsExecutableMimeType(mime_type)) {
initial.commit09911bf2008-07-26 23:55:291227 // We want to be careful about executable extensions. The worry here is
1228 // that a trusted web site could be tricked into dropping an executable file
1229 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101230 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291231 // We couldn't find a good extension for this content type. Use a dummy
1232 // extension instead.
1233 extension.assign(default_extension);
1234 }
1235 }
1236
1237 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101238 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291239 } else {
[email protected]6cade212008-12-03 00:32:221240 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291241 // 1. New extension is not ".txt"
1242 // 2. New extension is not the same as the already existing extension.
1243 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411244 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291245 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1246 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371247 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1248 // servers, i.e. bug 5772.
[email protected]e32642f62009-09-11 21:58:291249 // 5. The original extension is not ".tgz" & the new extension is not "gz".
[email protected]7ae7c2cb2009-01-06 23:31:411250 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101251 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171252 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411253 append_extension != extension &&
[email protected]eccb9d12009-10-28 05:40:091254 !IsExecutableExtension(append_extension) &&
[email protected]e32642f62009-09-11 21:58:291255 !(append_extension == FILE_PATH_LITERAL("gz") &&
1256 extension == FILE_PATH_LITERAL("tgz")) &&
[email protected]e106457b2009-03-25 22:43:371257 (append_extension != FILE_PATH_LITERAL("tar") ||
1258 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171259 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291260 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171261 }
initial.commit09911bf2008-07-26 23:55:291262 }
1263 }
1264
1265 generated_extension->swap(extension);
1266}
1267
[email protected]6aa4a1c02010-01-15 18:49:581268void DownloadManager::GenerateFileNameFromInfo(DownloadCreateInfo* info,
1269 FilePath* generated_name) {
1270 GenerateFileName(GURL(info->url),
1271 info->content_disposition,
1272 info->referrer_charset,
1273 info->mime_type,
1274 generated_name);
1275}
1276
1277void DownloadManager::GenerateFileName(const GURL& url,
1278 const std::string& content_disposition,
1279 const std::string& referrer_charset,
1280 const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411281 FilePath* generated_name) {
[email protected]630947c2009-11-04 18:37:311282 std::wstring default_name =
1283 l10n_util::GetString(IDS_DEFAULT_DOWNLOAD_FILENAME);
1284#if defined(OS_WIN)
1285 FilePath default_file_path(default_name);
1286#elif defined(OS_POSIX)
1287 FilePath default_file_path(base::SysWideToNativeMB(default_name));
1288#endif
1289
[email protected]6aa4a1c02010-01-15 18:49:581290 *generated_name = net::GetSuggestedFilename(GURL(url),
1291 content_disposition,
1292 referrer_charset,
[email protected]630947c2009-11-04 18:37:311293 default_file_path);
1294
[email protected]7ae7c2cb2009-01-06 23:31:411295 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291296
[email protected]6aa4a1c02010-01-15 18:49:581297 GenerateSafeFileName(mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291298}
1299
1300void DownloadManager::AddObserver(Observer* observer) {
1301 observers_.AddObserver(observer);
1302 observer->ModelChanged();
1303}
1304
1305void DownloadManager::RemoveObserver(Observer* observer) {
1306 observers_.RemoveObserver(observer);
1307}
1308
1309// Post Windows Shell operations to the Download thread, to avoid blocking the
1310// user interface.
1311void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1312 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:371313 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:581314#if defined(OS_MACOSX)
1315 // Mac needs to run this operation on the UI thread.
1316 platform_util::ShowItemInFolder(download->full_path());
1317#else
[email protected]d83d03aa2009-11-02 21:44:371318 ChromeThread::PostTask(
1319 ChromeThread::FILE, FROM_HERE,
1320 NewRunnableMethod(
1321 file_manager_, &DownloadFileManager::OnShowDownloadInShell,
1322 FilePath(download->full_path())));
[email protected]8b6ff012009-08-18 22:29:581323#endif
initial.commit09911bf2008-07-26 23:55:291324}
1325
[email protected]8f783752009-04-01 23:33:451326void DownloadManager::OpenDownload(const DownloadItem* download,
1327 gfx::NativeView parent_window) {
[email protected]0e34d7892009-06-05 19:17:401328 // Open Chrome extensions with ExtensionsService. For everything else do shell
[email protected]8f783752009-04-01 23:33:451329 // execute.
[email protected]a60c8ae2009-12-25 06:50:571330 if (download->is_extension_install()) {
[email protected]494c06e2009-07-25 01:06:421331 OpenChromeExtension(download->full_path(), download->url(),
1332 download->referrer_url());
[email protected]8f783752009-04-01 23:33:451333 } else {
1334 OpenDownloadInShell(download, parent_window);
1335 }
1336}
1337
[email protected]c1e432a2009-07-22 21:21:481338void DownloadManager::OpenChromeExtension(const FilePath& full_path,
[email protected]494c06e2009-07-25 01:06:421339 const GURL& download_url,
1340 const GURL& referrer_url) {
[email protected]6ef635e42009-07-26 06:16:121341 // We don't support extensions in OTR mode.
[email protected]2a464a92009-08-01 17:58:351342 ExtensionsService* service = profile_->GetExtensionsService();
1343 if (service) {
[email protected]91e1bd82009-09-03 22:04:401344 NotificationService* nservice = NotificationService::current();
[email protected]ac025282009-12-16 19:16:381345 GURL nonconst_download_url = download_url;
[email protected]91e1bd82009-09-03 22:04:401346 nservice->Notify(NotificationType::EXTENSION_READY_FOR_INSTALL,
1347 Source<DownloadManager>(this),
[email protected]ac025282009-12-16 19:16:381348 Details<GURL>(&nonconst_download_url));
[email protected]a050d712009-11-06 00:40:101349 if (UserScript::HasUserScriptFileExtension(download_url)) {
[email protected]6657afa62009-11-04 02:15:201350 CrxInstaller::InstallUserScript(
1351 full_path,
1352 download_url,
1353 service->install_directory(),
1354 true, // please delete crx on completion
1355 service,
1356 new ExtensionInstallUI(profile_));
1357 } else {
1358 CrxInstaller::Start(
1359 full_path,
1360 service->install_directory(),
1361 Extension::INTERNAL,
1362 "", // no expected id
1363 true, // please delete crx on completion
1364 true, // privilege increase allowed
1365 service,
1366 new ExtensionInstallUI(profile_));
1367 }
[email protected]2a464a92009-08-01 17:58:351368 }
[email protected]8f783752009-04-01 23:33:451369}
1370
initial.commit09911bf2008-07-26 23:55:291371void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591372 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291373 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:371374 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:581375#if defined(OS_MACOSX)
1376 // Mac OS X requires opening downloads on the UI thread.
1377 platform_util::OpenItem(download->full_path());
1378#else
[email protected]d83d03aa2009-11-02 21:44:371379 ChromeThread::PostTask(
1380 ChromeThread::FILE, FROM_HERE,
1381 NewRunnableMethod(
1382 file_manager_, &DownloadFileManager::OnOpenDownloadInShell,
1383 download->full_path(), download->url(), parent_window));
[email protected]8b6ff012009-08-18 22:29:581384#endif
initial.commit09911bf2008-07-26 23:55:291385}
1386
[email protected]eccb9d12009-10-28 05:40:091387void DownloadManager::OpenFilesBasedOnExtension(
1388 const FilePath& path, bool open) {
1389 FilePath::StringType extension = path.Extension();
1390 if (extension.empty())
1391 return;
1392 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1393 extension.erase(0, 1);
1394 if (open && !IsExecutableExtension(extension))
initial.commit09911bf2008-07-26 23:55:291395 auto_open_.insert(extension);
1396 else
1397 auto_open_.erase(extension);
1398 SaveAutoOpens();
1399}
1400
[email protected]eccb9d12009-10-28 05:40:091401bool DownloadManager::ShouldOpenFileBasedOnExtension(
1402 const FilePath& path) const {
[email protected]eccb9d12009-10-28 05:40:091403 FilePath::StringType extension = path.Extension();
1404 if (extension.empty())
1405 return false;
1406 if (IsExecutableExtension(extension))
1407 return false;
[email protected]92e11c82010-01-13 06:39:561408 if (Extension::IsExtension(path))
1409 return false;
[email protected]eccb9d12009-10-28 05:40:091410 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1411 extension.erase(0, 1);
[email protected]92e11c82010-01-13 06:39:561412 if (auto_open_.find(extension) != auto_open_.end())
[email protected]8c756ac2009-01-30 23:36:411413 return true;
initial.commit09911bf2008-07-26 23:55:291414 return false;
1415}
1416
[email protected]7b73d992008-12-15 20:56:461417static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291418 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461419 "text/javascript",
1420 "text/javascript;version=*",
[email protected]54d8d452009-04-08 17:29:241421 // Registry files can cause critical changes to the MS OS behavior.
1422 // Addition of this mimetype also addresses bug 7337.
1423 "text/x-registry",
[email protected]60ff8f912008-12-05 07:58:391424 // Some sites use binary/octet-stream to mean application/octet-stream.
1425 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461426 "binary/octet-stream"
1427};
initial.commit09911bf2008-07-26 23:55:291428
[email protected]7b73d992008-12-15 20:56:461429static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291430 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461431 "application/*+xml",
1432 "application/xml"
1433};
initial.commit09911bf2008-07-26 23:55:291434
[email protected]7b73d992008-12-15 20:56:461435// static
1436bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411437 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461438 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1439 return true;
1440 }
[email protected]bae0ea12009-02-14 01:20:411441 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461442 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1443 return false;
1444 }
1445 // We consider only other application types to be executable.
1446 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291447}
1448
[email protected]eccb9d12009-10-28 05:40:091449bool DownloadManager::IsExecutableFile(const FilePath& path) const {
1450 return IsExecutableExtension(path.Extension());
1451}
1452
1453bool DownloadManager::IsExecutableExtension(
[email protected]6aa4a1c02010-01-15 18:49:581454 const FilePath::StringType& extension) {
[email protected]eccb9d12009-10-28 05:40:091455 if (extension.empty())
1456 return false;
[email protected]64da0b932009-02-24 02:30:041457 if (!IsStringASCII(extension))
1458 return false;
[email protected]a0a9577b2009-05-27 23:52:321459#if defined(OS_WIN)
[email protected]64da0b932009-02-24 02:30:041460 std::string ascii_extension = WideToASCII(extension);
[email protected]e9ef0a62009-08-11 22:50:131461#elif defined(OS_POSIX)
[email protected]a0a9577b2009-05-27 23:52:321462 std::string ascii_extension = extension;
1463#endif
[email protected]64da0b932009-02-24 02:30:041464
[email protected]eccb9d12009-10-28 05:40:091465 // Strip out leading dot if it's still there
1466 if (ascii_extension[0] == FilePath::kExtensionSeparator)
1467 ascii_extension.erase(0, 1);
1468
[email protected]6aa4a1c02010-01-15 18:49:581469 return download_util::IsExecutableExtension(ascii_extension);
initial.commit09911bf2008-07-26 23:55:291470}
1471
1472void DownloadManager::ResetAutoOpenFiles() {
1473 auto_open_.clear();
1474 SaveAutoOpens();
1475}
1476
1477bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1478 return !auto_open_.empty();
1479}
1480
1481void DownloadManager::SaveAutoOpens() {
1482 PrefService* prefs = profile_->GetPrefs();
1483 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411484 FilePath::StringType extensions;
[email protected]eccb9d12009-10-28 05:40:091485 for (AutoOpenSet::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291486 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411487 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291488 }
1489 if (!extensions.empty())
1490 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561491
1492 std::wstring extensions_w;
1493#if defined(OS_WIN)
1494 extensions_w = extensions;
1495#elif defined(OS_POSIX)
[email protected]1b5044d2009-02-24 00:04:141496 extensions_w = base::SysNativeMBToWide(extensions);
[email protected]b7f05882009-02-22 01:21:561497#endif
1498
1499 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291500 }
1501}
1502
[email protected]561abe62009-04-06 18:08:341503void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361504 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291505 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071506 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411507 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291508 ContinueStartDownload(info, path);
1509}
1510
1511void DownloadManager::FileSelectionCanceled(void* params) {
1512 // The user didn't pick a place to save the file, so need to cancel the
1513 // download that's already in progress to the temporary location.
1514 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]d7d1c5c2009-08-05 23:52:501515 DownloadCancelledInternal(info->download_id,
[email protected]76543b92009-08-31 17:27:451516 info->child_id,
[email protected]d7d1c5c2009-08-05 23:52:501517 info->request_id);
initial.commit09911bf2008-07-26 23:55:291518}
1519
[email protected]7ae7c2cb2009-01-06 23:31:411520void DownloadManager::DeleteDownload(const FilePath& path) {
[email protected]d83d03aa2009-11-02 21:44:371521 ChromeThread::PostTask(
1522 ChromeThread::FILE, FROM_HERE,
1523 NewRunnableFunction(&DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321524}
1525
1526
1527void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1528 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1529 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1530 download->UpdateObservers();
1531
1532 // If the download is not complete, nothing to do. The required
1533 // post-processing will be performed when it does complete.
1534 if (download->state() != DownloadItem::COMPLETE)
1535 return;
1536
[email protected]d83d03aa2009-11-02 21:44:371537 ChromeThread::PostTask(
1538 ChromeThread::FILE, FROM_HERE,
1539 NewRunnableMethod(
1540 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
1541 download->db_handle(), download->full_path(),
1542 download->original_name()));
[email protected]9ccbb372008-10-10 18:50:321543}
1544
[email protected]6aa4a1c02010-01-15 18:49:581545void DownloadManager::GenerateSafeFileName(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411546 FilePath* file_name) {
1547 // Make sure we get the right file extension
1548 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391549 GenerateExtension(*file_name, mime_type, &extension);
1550 file_util::ReplaceExtension(file_name, extension);
1551
[email protected]2b2f8f72009-02-24 22:42:051552#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391553 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411554 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391555 DCHECK(!leaf_name.empty());
1556 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411557 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1558 *file_name = file_name->DirName();
1559 if (file_name->value() == FilePath::kCurrentDirectory) {
1560 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391561 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411562 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391563 }
1564 }
[email protected]b7f05882009-02-22 01:21:561565#endif
[email protected]763f946a2009-01-06 19:04:391566}
1567
initial.commit09911bf2008-07-26 23:55:291568// Operations posted to us from the history service ----------------------------
1569
1570// The history service has retrieved all download entries. 'entries' contains
1571// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1572void DownloadManager::OnQueryDownloadEntriesComplete(
1573 std::vector<DownloadCreateInfo>* entries) {
1574 for (size_t i = 0; i < entries->size(); ++i) {
1575 DownloadItem* download = new DownloadItem(entries->at(i));
1576 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1577 downloads_[download->db_handle()] = download;
1578 download->set_manager(this);
1579 }
1580 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1581}
1582
initial.commit09911bf2008-07-26 23:55:291583// Once the new DownloadItem's creation info has been committed to the history
1584// service, we associate the DownloadItem with the db handle, update our
1585// 'downloads_' map and inform observers.
1586void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1587 int64 db_handle) {
1588 DownloadMap::iterator it = in_progress_.find(info.download_id);
1589 DCHECK(it != in_progress_.end());
1590
1591 DownloadItem* download = it->second;
[email protected]d2a8fb72010-01-21 05:31:421592
1593 // It's not immediately obvious, but HistoryBackend::CreateDownload() can
1594 // call this function with an invalid |db_handle|. For instance, this can
1595 // happen when the history database is offline. We cannot have multiple
1596 // DownloadItems with the same invalid db_handle, so we need to assign a
1597 // unique |db_handle| here.
1598 if (db_handle == kUninitializedHandle)
1599 db_handle = fake_db_handle_.GetNext();
1600
initial.commit09911bf2008-07-26 23:55:291601 DCHECK(download->db_handle() == kUninitializedHandle);
1602 download->set_db_handle(db_handle);
1603
1604 // Insert into our full map.
1605 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1606 downloads_[download->db_handle()] = download;
1607
[email protected]5e595482009-05-06 20:16:531608 // Show in the appropropriate browser UI.
1609 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291610
1611 // Inform interested objects about the new download.
1612 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
initial.commit09911bf2008-07-26 23:55:291613
1614 // If this download has been completed before we've received the db handle,
1615 // post one final message to the history service so that it can be properly
1616 // in sync with the DownloadItem's completion status, and also inform any
1617 // observers so that they get more than just the start notification.
1618 if (download->state() != DownloadItem::IN_PROGRESS) {
1619 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291620 UpdateHistoryForDownload(download);
1621 download->UpdateObservers();
1622 }
1623}
1624
1625// Called when the history service has retrieved the list of downloads that
1626// match the search text.
1627void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1628 std::vector<int64>* results) {
1629 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1630 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1631 if (!requestor)
1632 return;
1633
1634 std::vector<DownloadItem*> searched_downloads;
1635 for (std::vector<int64>::iterator it = results->begin();
1636 it != results->end(); ++it) {
1637 DownloadMap::iterator dit = downloads_.find(*it);
1638 if (dit != downloads_.end())
1639 searched_downloads.push_back(dit->second);
1640 }
1641
1642 requestor->SetDownloads(searched_downloads);
1643}
[email protected]905a08d2008-11-19 07:24:121644
[email protected]5e595482009-05-06 20:16:531645void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1646 DownloadItem* download) {
[email protected]5e595482009-05-06 20:16:531647 // The 'contents' may no longer exist if the user closed the tab before we get
1648 // this start completion event. If it does, tell the origin TabContents to
1649 // display its download shelf.
[email protected]76543b92009-08-31 17:27:451650 TabContents* contents = tab_util::GetTabContentsByID(info.child_id,
1651 info.render_view_id);
[email protected]5e595482009-05-06 20:16:531652
1653 // If the contents no longer exists, we start the download in the last active
1654 // browser. This is not ideal but better than fully hiding the download from
1655 // the user.
1656 if (!contents) {
1657 Browser* last_active = BrowserList::GetLastActive();
1658 if (last_active)
1659 contents = last_active->GetSelectedTabContents();
1660 }
1661
1662 if (contents)
1663 contents->OnStartDownload(download);
1664}
1665
[email protected]6cade212008-12-03 00:32:221666// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121667void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411668 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381669}