blob: 04c3b8ae8418b96e97b3c3013d528c8cd28344e5 [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]d83d03aa2009-11-02 21:44:3721#include "chrome/browser/chrome_thread.h"
[email protected]cdaa8652008-09-13 02:48:5922#include "chrome/browser/download/download_file.h"
[email protected]e9ef0a62009-08-11 22:50:1323#include "chrome/browser/download/download_util.h"
[email protected]866930682009-08-18 22:53:4724#include "chrome/browser/extensions/crx_installer.h"
[email protected]2a464a92009-08-01 17:58:3525#include "chrome/browser/extensions/extension_install_ui.h"
[email protected]8f783752009-04-01 23:33:4526#include "chrome/browser/extensions/extensions_service.h"
[email protected]be180c802009-10-23 06:33:3127#include "chrome/browser/net/chrome_url_request_context.h"
initial.commit09911bf2008-07-26 23:55:2928#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:2629#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2530#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]e3c404b2008-12-23 01:07:3231#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
[email protected]f3ec7742009-01-15 00:59:1632#include "chrome/browser/tab_contents/tab_util.h"
[email protected]57c6a652009-05-04 07:58:3433#include "chrome/browser/tab_contents/tab_contents.h"
[email protected]4a0380c2009-07-26 07:25:3234#include "chrome/common/chrome_constants.h"
initial.commit09911bf2008-07-26 23:55:2935#include "chrome/common/chrome_paths.h"
[email protected]5b1a0e22009-05-26 19:00:5836#include "chrome/common/extensions/extension.h"
[email protected]6657afa62009-11-04 02:15:2037#include "chrome/common/extensions/user_script.h"
[email protected]91e1bd82009-09-03 22:04:4038#include "chrome/common/notification_service.h"
39#include "chrome/common/notification_type.h"
[email protected]076700e62009-04-01 18:41:2340#include "chrome/common/platform_util.h"
initial.commit09911bf2008-07-26 23:55:2941#include "chrome/common/pref_names.h"
42#include "chrome/common/pref_service.h"
[email protected]46072d42008-07-28 14:49:3543#include "googleurl/src/gurl.h"
[email protected]d81706b82009-04-03 20:28:4444#include "grit/chromium_strings.h"
[email protected]34ac8f32009-02-22 23:03:2745#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2946#include "net/base/mime_util.h"
47#include "net/base/net_util.h"
48#include "net/url_request/url_request_context.h"
49
[email protected]b7f05882009-02-22 01:21:5650#if defined(OS_WIN)
[email protected]4a0765a2009-05-08 23:12:2551#include "app/win_util.h"
[email protected]b7f05882009-02-22 01:21:5652#include "base/registry.h"
53#include "base/win_util.h"
[email protected]a0a9577b2009-05-27 23:52:3254#endif
55
[email protected]0f44d3e2009-03-12 23:36:3056#if defined(OS_LINUX)
57#include <gtk/gtk.h>
58#endif
59
initial.commit09911bf2008-07-26 23:55:2960// Periodically update our observers.
61class DownloadItemUpdateTask : public Task {
62 public:
63 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
64 void Run() { if (item_) item_->UpdateObservers(); }
65
66 private:
67 DownloadItem* item_;
68};
69
70// Update frequency (milliseconds).
71static const int kUpdateTimeMs = 1000;
72
73// Our download table ID starts at 1, so we use 0 to represent a download that
74// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2275// database handles in incognito mode starting at -1 and progressively getting
76// more negative.
initial.commit09911bf2008-07-26 23:55:2977static const int kUninitializedHandle = 0;
78
[email protected]7a256ea2008-10-17 17:34:1679// Appends the passed the number between parenthesis the path before the
80// extension.
[email protected]7ae7c2cb2009-01-06 23:31:4181static void AppendNumberToPath(FilePath* path, int number) {
82 file_util::InsertBeforeExtension(path,
83 StringPrintf(FILE_PATH_LITERAL(" (%d)"), number));
[email protected]7a256ea2008-10-17 17:34:1684}
85
86// Attempts to find a number that can be appended to that path to make it
87// unique. If |path| does not exist, 0 is returned. If it fails to find such
88// a number, -1 is returned.
[email protected]7ae7c2cb2009-01-06 23:31:4189static int GetUniquePathNumber(const FilePath& path) {
initial.commit09911bf2008-07-26 23:55:2990 const int kMaxAttempts = 100;
91
[email protected]7a256ea2008-10-17 17:34:1692 if (!file_util::PathExists(path))
93 return 0;
initial.commit09911bf2008-07-26 23:55:2994
[email protected]7ae7c2cb2009-01-06 23:31:4195 FilePath new_path;
initial.commit09911bf2008-07-26 23:55:2996 for (int count = 1; count <= kMaxAttempts; ++count) {
[email protected]7ae7c2cb2009-01-06 23:31:4197 new_path = FilePath(path);
[email protected]7a256ea2008-10-17 17:34:1698 AppendNumberToPath(&new_path, count);
initial.commit09911bf2008-07-26 23:55:2999
[email protected]7a256ea2008-10-17 17:34:16100 if (!file_util::PathExists(new_path))
101 return count;
initial.commit09911bf2008-07-26 23:55:29102 }
103
[email protected]7a256ea2008-10-17 17:34:16104 return -1;
initial.commit09911bf2008-07-26 23:55:29105}
106
[email protected]7ae7c2cb2009-01-06 23:31:41107static bool DownloadPathIsDangerous(const FilePath& download_path) {
108 FilePath desktop_dir;
[email protected]f052118e2008-09-05 02:25:32109 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
110 NOTREACHED();
111 return false;
112 }
113 return (download_path == desktop_dir);
114}
115
initial.commit09911bf2008-07-26 23:55:29116// DownloadItem implementation -------------------------------------------------
117
118// Constructor for reading from the history service.
119DownloadItem::DownloadItem(const DownloadCreateInfo& info)
120 : id_(-1),
121 full_path_(info.path),
122 url_(info.url),
[email protected]e435d6b72009-07-25 03:15:58123 referrer_url_(info.referrer_url),
124 mime_type_(info.mime_type),
initial.commit09911bf2008-07-26 23:55:29125 total_bytes_(info.total_bytes),
126 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56127 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29128 state_(static_cast<DownloadState>(info.state)),
129 start_time_(info.start_time),
130 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29131 manager_(NULL),
132 is_paused_(false),
133 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56134 safety_state_(SAFE),
[email protected]0aad67b2009-07-15 20:34:28135 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56136 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29137 render_process_id_(-1),
138 request_id_(-1) {
139 if (state_ == IN_PROGRESS)
140 state_ = CANCELLED;
141 Init(false /* don't start progress timer */);
142}
143
144// Constructor for DownloadItem created via user action in the main thread.
145DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41146 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16147 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32148 const GURL& url,
[email protected]494c06e2009-07-25 01:06:42149 const GURL& referrer_url,
[email protected]e435d6b72009-07-25 03:15:58150 const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:41151 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59152 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29153 int64 download_size,
154 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32155 int request_id,
[email protected]67f373a2009-09-22 02:44:51156 bool is_dangerous,
[email protected]a60c8ae2009-12-25 06:50:57157 bool save_as,
158 bool is_extension_install)
initial.commit09911bf2008-07-26 23:55:29159 : id_(download_id),
160 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16161 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29162 url_(url),
[email protected]494c06e2009-07-25 01:06:42163 referrer_url_(referrer_url),
[email protected]e435d6b72009-07-25 03:15:58164 mime_type_(mime_type),
initial.commit09911bf2008-07-26 23:55:29165 total_bytes_(download_size),
166 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56167 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29168 state_(IN_PROGRESS),
169 start_time_(start_time),
170 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29171 manager_(NULL),
172 is_paused_(false),
173 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56174 safety_state_(is_dangerous ? DANGEROUS : SAFE),
[email protected]0aad67b2009-07-15 20:34:28175 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56176 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29177 render_process_id_(render_process_id),
[email protected]67f373a2009-09-22 02:44:51178 request_id_(request_id),
[email protected]a60c8ae2009-12-25 06:50:57179 save_as_(save_as),
180 is_extension_install_(is_extension_install) {
initial.commit09911bf2008-07-26 23:55:29181 Init(true /* start progress timer */);
182}
183
184void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41185 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29186 if (start_timer)
187 StartProgressTimer();
188}
189
190DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29191 state_ = REMOVING;
192 UpdateObservers();
193}
194
195void DownloadItem::AddObserver(Observer* observer) {
196 observers_.AddObserver(observer);
197}
198
199void DownloadItem::RemoveObserver(Observer* observer) {
200 observers_.RemoveObserver(observer);
201}
202
203void DownloadItem::UpdateObservers() {
204 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
205}
206
[email protected]45e3c122009-04-07 19:58:03207void DownloadItem::NotifyObserversDownloadOpened() {
208 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadOpened(this));
209}
210
initial.commit09911bf2008-07-26 23:55:29211// If we've received more data than we were expecting (bad server info?), revert
212// to 'unknown size mode'.
213void DownloadItem::UpdateSize(int64 bytes_so_far) {
214 received_bytes_ = bytes_so_far;
215 if (received_bytes_ > total_bytes_)
216 total_bytes_ = 0;
217}
218
219// Updates from the download thread may have been posted while this download
220// was being cancelled in the UI thread, so we'll accept them unless we're
221// complete.
222void DownloadItem::Update(int64 bytes_so_far) {
223 if (state_ == COMPLETE) {
224 NOTREACHED();
225 return;
226 }
227 UpdateSize(bytes_so_far);
228 UpdateObservers();
229}
230
[email protected]6cade212008-12-03 00:32:22231// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29232void DownloadItem::Cancel(bool update_history) {
233 if (state_ != IN_PROGRESS) {
234 // Small downloads might be complete before this method has a chance to run.
235 return;
236 }
237 state_ = CANCELLED;
238 UpdateObservers();
239 StopProgressTimer();
240 if (update_history)
241 manager_->DownloadCancelled(id_);
242}
243
244void DownloadItem::Finished(int64 size) {
245 state_ = COMPLETE;
246 UpdateSize(size);
initial.commit09911bf2008-07-26 23:55:29247 StopProgressTimer();
248}
249
[email protected]9ccbb372008-10-10 18:50:32250void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29251 Cancel(true);
252 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32253 if (delete_on_disk)
254 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29255 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22256 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29257}
258
259void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59260 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14261 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29262}
263
264void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14265 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29266}
267
[email protected]e93d2822009-01-30 05:59:59268bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29269 if (total_bytes_ <= 0)
270 return false; // We never received the content_length for this download.
271
272 int64 speed = CurrentSpeed();
273 if (speed == 0)
274 return false;
275
276 *remaining =
[email protected]e93d2822009-01-30 05:59:59277 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29278 return true;
279}
280
281int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56282 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
283 int64 diff_ms = diff.InMilliseconds();
284 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29285}
286
287int DownloadItem::PercentComplete() const {
288 int percent = -1;
289 if (total_bytes_ > 0)
290 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
291 return percent;
292}
293
[email protected]7ae7c2cb2009-01-06 23:31:41294void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29295 DCHECK(!full_path.empty());
296 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41297 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29298}
299
300void DownloadItem::TogglePause() {
301 DCHECK(state_ == IN_PROGRESS);
302 manager_->PauseDownload(id_, !is_paused_);
303 is_paused_ = !is_paused_;
304 UpdateObservers();
305}
306
[email protected]7ae7c2cb2009-01-06 23:31:41307FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32308 if (safety_state_ == DownloadItem::SAFE)
309 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16310 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41311 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16312 AppendNumberToPath(&name, path_uniquifier_);
313 return name;
314 }
[email protected]9ccbb372008-10-10 18:50:32315 return original_name_;
316}
317
initial.commit09911bf2008-07-26 23:55:29318// DownloadManager implementation ----------------------------------------------
319
320// static
321void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
322 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
323 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32324 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
325
326 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41327 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12328 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
329 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32330 NOTREACHED();
331 }
[email protected]b9636002009-03-04 00:05:25332 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
333 default_download_path);
[email protected]f052118e2008-09-05 02:25:32334
335 // If the download path is dangerous we forcefully reset it. But if we do
336 // so we set a flag to make sure we only do it once, to avoid fighting
337 // the user if he really wants it on an unsafe place such as the desktop.
338
339 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41340 FilePath current_download_dir = FilePath::FromWStringHack(
341 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32342 if (DownloadPathIsDangerous(current_download_dir)) {
343 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41344 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32345 }
346 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
347 }
initial.commit09911bf2008-07-26 23:55:29348}
349
350DownloadManager::DownloadManager()
351 : shutdown_needed_(false),
352 profile_(NULL),
[email protected]d83d03aa2009-11-02 21:44:37353 file_manager_(NULL) {
initial.commit09911bf2008-07-26 23:55:29354}
355
356DownloadManager::~DownloadManager() {
357 if (shutdown_needed_)
358 Shutdown();
359}
360
361void DownloadManager::Shutdown() {
362 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
363
364 // Stop receiving download updates
365 file_manager_->RemoveDownloadManager(this);
366
367 // Stop making history service requests
368 cancelable_consumer_.CancelAllRequests();
369
370 // 'in_progress_' may contain DownloadItems that have not finished the start
371 // complete (from the history service) and thus aren't in downloads_.
372 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32373 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29374 for (; it != in_progress_.end(); ++it) {
375 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32376 if (download->safety_state() == DownloadItem::DANGEROUS) {
377 // Forget about any download that the user did not approve.
378 // Note that we cannot call download->Remove() this would invalidate our
379 // iterator.
380 to_remove.insert(download);
381 continue;
initial.commit09911bf2008-07-26 23:55:29382 }
[email protected]9ccbb372008-10-10 18:50:32383 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
384 download->Cancel(false);
385 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29386 if (download->db_handle() == kUninitializedHandle) {
387 // An invalid handle means that 'download' does not yet exist in
388 // 'downloads_', so we have to delete it here.
389 delete download;
390 }
391 }
392
[email protected]9ccbb372008-10-10 18:50:32393 // 'dangerous_finished_' contains all complete downloads that have not been
394 // approved. They should be removed.
395 it = dangerous_finished_.begin();
396 for (; it != dangerous_finished_.end(); ++it)
397 to_remove.insert(it->second);
398
399 // Remove the dangerous download that are not approved.
400 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
401 rm_it != to_remove.end(); ++rm_it) {
402 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32403 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32404 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32405 // Same as above, delete the download if it is not in 'downloads_' (as the
406 // Remove() call above won't have deleted it).
407 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32408 delete download;
409 }
410 to_remove.clear();
411
initial.commit09911bf2008-07-26 23:55:29412 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32413 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29414 STLDeleteValues(&downloads_);
415
416 file_manager_ = NULL;
417
418 // Save our file extensions to auto open.
419 SaveAutoOpens();
420
421 // Make sure the save as dialog doesn't notify us back if we're gone before
422 // it returns.
423 if (select_file_dialog_.get())
424 select_file_dialog_->ListenerDestroyed();
425
426 shutdown_needed_ = false;
427}
428
429// Issue a history query for downloads matching 'search_text'. If 'search_text'
430// is empty, return all downloads that we know about.
431void DownloadManager::GetDownloads(Observer* observer,
432 const std::wstring& search_text) {
433 DCHECK(observer);
434
435 // Return a empty list if we've not yet received the set of downloads from the
436 // history system (we'll update all observers once we get that list in
437 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
438 std::vector<DownloadItem*> download_copy;
439 if (downloads_.empty()) {
440 observer->SetDownloads(download_copy);
441 return;
442 }
443
444 // We already know all the downloads and there is no filter, so just return a
445 // copy to the observer.
446 if (search_text.empty()) {
447 download_copy.reserve(downloads_.size());
448 for (DownloadMap::iterator it = downloads_.begin();
449 it != downloads_.end(); ++it) {
[email protected]67f373a2009-09-22 02:44:51450 if (it->second->db_handle() > kUninitializedHandle)
451 download_copy.push_back(it->second);
initial.commit09911bf2008-07-26 23:55:29452 }
453
454 // We retain ownership of the DownloadItems.
455 observer->SetDownloads(download_copy);
456 return;
457 }
458
459 // Issue a request to the history service for a list of downloads matching
460 // our search text.
461 HistoryService* hs =
462 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
463 if (hs) {
464 HistoryService::Handle h =
465 hs->SearchDownloads(search_text,
466 &cancelable_consumer_,
467 NewCallback(this,
468 &DownloadManager::OnSearchComplete));
469 cancelable_consumer_.SetClientData(hs, h, observer);
470 }
471}
472
473// Query the history service for information about all persisted downloads.
474bool DownloadManager::Init(Profile* profile) {
475 DCHECK(profile);
476 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
477 shutdown_needed_ = true;
478
479 profile_ = profile;
[email protected]be180c802009-10-23 06:33:31480 request_context_getter_ = profile_->GetRequestContext();
initial.commit09911bf2008-07-26 23:55:29481
482 // 'incognito mode' will have access to past downloads, but we won't store
483 // information about new downloads while in that mode.
484 QueryHistoryForDownloads();
485
486 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
487 if (!rdh) {
488 NOTREACHED();
489 return false;
490 }
491
492 file_manager_ = rdh->download_file_manager();
493 if (!file_manager_) {
494 NOTREACHED();
495 return false;
496 }
497
initial.commit09911bf2008-07-26 23:55:29498 // Get our user preference state.
499 PrefService* prefs = profile_->GetPrefs();
500 DCHECK(prefs);
501 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
502
initial.commit09911bf2008-07-26 23:55:29503 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
504
[email protected]bb69e9b32008-08-14 23:08:14505 // Ensure that the download directory specified in the preferences exists.
[email protected]d83d03aa2009-11-02 21:44:37506 ChromeThread::PostTask(
507 ChromeThread::FILE, FROM_HERE,
[email protected]309b7642009-12-09 03:08:50508 NewRunnableFunction(&file_util::CreateDirectory, download_path()));
initial.commit09911bf2008-07-26 23:55:29509
[email protected]a0a9577b2009-05-27 23:52:32510 // We use this to determine possibly dangerous downloads.
[email protected]2b2f8f72009-02-24 22:42:05511 download_util::InitializeExeTypes(&exe_types_);
[email protected]2b2f8f72009-02-24 22:42:05512
513 // We store any file extension that should be opened automatically at
514 // download completion in this pref.
initial.commit09911bf2008-07-26 23:55:29515 std::wstring extensions_to_open =
516 prefs->GetString(prefs::kDownloadExtensionsToOpen);
517 std::vector<std::wstring> extensions;
518 SplitString(extensions_to_open, L':', &extensions);
519 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]eccb9d12009-10-28 05:40:09520 if (!extensions[i].empty() && !IsExecutableFile(
521 FilePath::FromWStringHack(extensions[i])))
[email protected]b7f05882009-02-22 01:21:56522 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29523 }
524
525 return true;
526}
527
528void DownloadManager::QueryHistoryForDownloads() {
529 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
530 if (hs) {
531 hs->QueryDownloads(
532 &cancelable_consumer_,
533 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
534 }
535}
536
537// We have received a message from DownloadFileManager about a new download. We
538// create a download item and store it in our download map, and inform the
539// history system of a new download. Since this method can be called while the
540// history service thread is still reading the persistent state, we do not
541// insert the new DownloadItem into 'downloads_' or inform our observers at this
542// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
543// download creation as a callback from the history thread.
544void DownloadManager::StartDownload(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37545 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29546 DCHECK(info);
547
[email protected]a60c8ae2009-12-25 06:50:57548 // Check whether this download is for an extension install or not.
549 if (!info->save_as) { // Allow extensions to be explicitly saved.
550 if (UserScript::HasUserScriptFileExtension(info->url) ||
551 info->mime_type == Extension::kMimeType)
552 info->is_extension_install = true;
553 }
554
[email protected]7d3851d82008-12-12 03:26:07555 // Freeze the user's preference for showing a Save As dialog. We're going to
556 // bounce around a bunch of threads and we don't want to worry about race
557 // conditions where the user changes this pref out from under us.
[email protected]7bc4f702009-09-25 22:12:38558 if (*prompt_for_download_) {
559 // But never obey the preference for extension installation. Note that we
560 // only care here about the case where an extension is installed, not when
561 // one is downloaded with "save as...".
[email protected]a60c8ae2009-12-25 06:50:57562 if (!info->is_extension_install)
[email protected]7bc4f702009-09-25 22:12:38563 info->save_as = true;
564 }
[email protected]7d3851d82008-12-12 03:26:07565
initial.commit09911bf2008-07-26 23:55:29566 // Determine the proper path for a download, by choosing either the default
567 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41568 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29569 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07570 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29571 info->suggested_path = last_download_path_;
572 else
[email protected]7ae7c2cb2009-01-06 23:31:41573 info->suggested_path = download_path();
574 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29575
[email protected]7d3851d82008-12-12 03:26:07576 if (!info->save_as) {
[email protected]4289d9b2009-07-25 21:17:34577 // Downloads can be marked as dangerous for two reasons:
578 // a) They have a dangerous-looking filename
579 // b) They are an extension that is not from the gallery
580 if (IsDangerous(info->suggested_path.BaseName()))
581 info->is_dangerous = true;
[email protected]a60c8ae2009-12-25 06:50:57582 else if (info->is_extension_install &&
[email protected]b7c2f252009-12-08 00:47:23583 !ExtensionsService::IsDownloadFromGallery(info->url,
584 info->referrer_url)) {
[email protected]4289d9b2009-07-25 21:17:34585 info->is_dangerous = true;
586 }
[email protected]e9ebf3fc2008-10-17 22:06:58587 }
588
initial.commit09911bf2008-07-26 23:55:29589 // We need to move over to the download thread because we don't want to stat
590 // the suggested path on the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37591 ChromeThread::PostTask(
592 ChromeThread::FILE, FROM_HERE,
593 NewRunnableMethod(
594 this, &DownloadManager::CheckIfSuggestedPathExists, info));
initial.commit09911bf2008-07-26 23:55:29595}
596
597void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
598 DCHECK(info);
599
600 // Check writability of the suggested path. If we can't write to it, default
601 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41602 FilePath dir = info->suggested_path.DirName();
603 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32604 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29605 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29606 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41607 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29608 }
609
[email protected]7a256ea2008-10-17 17:34:16610 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29611
[email protected]6cade212008-12-03 00:32:22612 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58613 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41614 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32615 // Create a temporary file to hold the file until the user approves its
616 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41617 FilePath::StringType file_name;
618 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32619 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41620 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32621 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41622 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07623 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41624 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32625 }
626 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16627 } else {
628 // We know the final path, build it if necessary.
629 if (info->path_uniquifier > 0) {
630 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
631 // Setting path_uniquifier to 0 to make sure we don't try to unique it
632 // later on.
633 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07634 } else if (info->path_uniquifier == -1) {
635 // We failed to find a unique path. We have to prompt the user.
636 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16637 }
[email protected]9ccbb372008-10-10 18:50:32638 }
639
[email protected]7d3851d82008-12-12 03:26:07640 if (!info->save_as) {
641 // Create an empty file at the suggested path so that we don't allocate the
642 // same "non-existant" path to multiple downloads.
643 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ff3f632009-10-13 18:43:35644 file_util::WriteFile(info->suggested_path, "", 0);
[email protected]7d3851d82008-12-12 03:26:07645 }
646
initial.commit09911bf2008-07-26 23:55:29647 // Now we return to the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37648 ChromeThread::PostTask(
649 ChromeThread::UI, FROM_HERE,
initial.commit09911bf2008-07-26 23:55:29650 NewRunnableMethod(this,
651 &DownloadManager::OnPathExistenceAvailable,
652 info));
653}
654
655void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37656 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29657 DCHECK(info);
658
[email protected]7d3851d82008-12-12 03:26:07659 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29660 // We must ask the user for the place to put the download.
661 if (!select_file_dialog_.get())
662 select_file_dialog_ = SelectFileDialog::Create(this);
663
[email protected]76543b92009-08-31 17:27:45664 TabContents* contents = tab_util::GetTabContentsByID(info->child_id,
665 info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08666 SelectFileDialog::FileTypeInfo file_type_info;
667 file_type_info.extensions.resize(1);
668 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24669 if (!file_type_info.extensions[0][0].empty())
670 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08671 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23672 gfx::NativeWindow owning_window =
673 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29674 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34675 string16(),
676 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08677 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30678 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29679 } else {
680 // No prompting for download, just continue with the suggested name.
681 ContinueStartDownload(info, info->suggested_path);
682 }
683}
684
685void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41686 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29687 scoped_ptr<DownloadCreateInfo> infop(info);
688 info->path = target_path;
689
690 DownloadItem* download = NULL;
691 DownloadMap::iterator it = in_progress_.find(info->download_id);
692 if (it == in_progress_.end()) {
693 download = new DownloadItem(info->download_id,
694 info->path,
[email protected]7a256ea2008-10-17 17:34:16695 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29696 info->url,
[email protected]494c06e2009-07-25 01:06:42697 info->referrer_url,
[email protected]e435d6b72009-07-25 03:15:58698 info->mime_type,
[email protected]9ccbb372008-10-10 18:50:32699 info->original_name,
initial.commit09911bf2008-07-26 23:55:29700 info->start_time,
701 info->total_bytes,
[email protected]76543b92009-08-31 17:27:45702 info->child_id,
[email protected]9ccbb372008-10-10 18:50:32703 info->request_id,
[email protected]67f373a2009-09-22 02:44:51704 info->is_dangerous,
[email protected]a60c8ae2009-12-25 06:50:57705 info->save_as,
706 info->is_extension_install);
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.
[email protected]d83d03aa2009-11-02 21:44:37716 ChromeThread::PostTask(
717 ChromeThread::FILE, FROM_HERE,
718 NewRunnableMethod(
719 file_manager_, &DownloadFileManager::OnFinalDownloadName,
720 download->id(), target_path, this));
[email protected]6b323782009-03-27 18:43:08721
initial.commit09911bf2008-07-26 23:55:29722 // If the download already completed by the time we reached this point, then
723 // notify observers that it did.
724 PendingFinishedMap::iterator pending_it =
725 pending_finished_downloads_.find(info->download_id);
726 if (pending_it != pending_finished_downloads_.end())
727 DownloadFinished(pending_it->first, pending_it->second);
728
729 download->Rename(target_path);
730
[email protected]67f373a2009-09-22 02:44:51731 // Do not store the download in the history database for a few special cases:
732 // - incognito mode (that is the point of this mode)
733 // - extensions (users don't think of extension installation as 'downloading')
734 // We have to make sure that these handles don't collide with normal db
735 // handles, so we use a negative value. Eventually, they could overlap, but
736 // you'd have to do enough downloading that your ISP would likely stab you in
737 // the neck first. YMMV.
[email protected]a60c8ae2009-12-25 06:50:57738 if (profile_->IsOffTheRecord() || download->is_extension_install()) {
initial.commit09911bf2008-07-26 23:55:29739 static int64 fake_db_handle = kUninitializedHandle - 1;
740 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
741 } else {
742 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22743 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29744 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
745 if (hs) {
746 hs->CreateDownload(
747 *info, &cancelable_consumer_,
748 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
749 }
750 }
751}
752
753// Convenience function for updating the history service for a download.
754void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
755 DCHECK(download);
756
757 // Don't store info in the database if the download was initiated while in
758 // incognito mode or if it hasn't been initialized in our database table.
759 if (download->db_handle() <= kUninitializedHandle)
760 return;
761
[email protected]6cade212008-12-03 00:32:22762 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29763 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
764 if (hs) {
765 hs->UpdateDownload(download->received_bytes(),
766 download->state(),
767 download->db_handle());
768 }
769}
770
771void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
772 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22773 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29774 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
775 if (download->db_handle() > kUninitializedHandle && hs)
776 hs->RemoveDownload(download->db_handle());
777}
778
[email protected]e93d2822009-01-30 05:59:59779void DownloadManager::RemoveDownloadsFromHistoryBetween(
780 const base::Time remove_begin,
781 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22782 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29783 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
784 if (hs)
785 hs->RemoveDownloadsBetween(remove_begin, remove_end);
786}
787
788void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
789 DownloadMap::iterator it = in_progress_.find(download_id);
790 if (it != in_progress_.end()) {
791 DownloadItem* download = it->second;
792 download->Update(size);
793 UpdateHistoryForDownload(download);
794 }
795}
796
797void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
798 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32799 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29800 // The download is done, but the user hasn't selected a final location for
801 // it yet (the Save As dialog box is probably still showing), so just keep
802 // track of the fact that this download id is complete, when the
803 // DownloadItem is constructed later we'll notify its completion then.
804 PendingFinishedMap::iterator erase_it =
805 pending_finished_downloads_.find(download_id);
806 DCHECK(erase_it == pending_finished_downloads_.end());
807 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32808 return;
initial.commit09911bf2008-07-26 23:55:29809 }
[email protected]9ccbb372008-10-10 18:50:32810
811 // Remove the id from the list of pending ids.
812 PendingFinishedMap::iterator erase_it =
813 pending_finished_downloads_.find(download_id);
814 if (erase_it != pending_finished_downloads_.end())
815 pending_finished_downloads_.erase(erase_it);
816
817 DownloadItem* download = it->second;
818 download->Finished(size);
819
820 // Clean up will happen when the history system create callback runs if we
821 // don't have a valid db_handle yet.
822 if (download->db_handle() != kUninitializedHandle) {
823 in_progress_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32824 UpdateHistoryForDownload(download);
825 }
826
827 // If this a dangerous download not yet validated by the user, don't do
828 // anything. When the user notifies us, it will trigger a call to
829 // ProceedWithFinishedDangerousDownload.
830 if (download->safety_state() == DownloadItem::DANGEROUS) {
831 dangerous_finished_[download_id] = download;
832 return;
833 }
834
835 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22836 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32837 // its final name before we can continue.
[email protected]d83d03aa2009-11-02 21:44:37838 ChromeThread::PostTask(
839 ChromeThread::FILE, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32840 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]0aad67b2009-07-15 20:34:28860 // Handle chrome extensions explicitly and skip the shell execute.
[email protected]a60c8ae2009-12-25 06:50:57861 if (download->is_extension_install()) {
[email protected]494c06e2009-07-25 01:06:42862 OpenChromeExtension(download->full_path(), download->url(),
863 download->referrer_url());
[email protected]0aad67b2009-07-15 20:34:28864 download->set_auto_opened(true);
865 } else if (download->open_when_complete() ||
[email protected]eccb9d12009-10-28 05:40:09866 ShouldOpenFileBasedOnExtension(download->full_path())) {
[email protected]9ccbb372008-10-10 18:50:32867 OpenDownloadInShell(download, NULL);
[email protected]0aad67b2009-07-15 20:34:28868 download->set_auto_opened(true);
869 }
[email protected]9ccbb372008-10-10 18:50:32870
[email protected]0aad67b2009-07-15 20:34:28871 // Notify our observers that we are complete (the call to Finished() set the
872 // state to complete but did not notify).
873 download->UpdateObservers();
874}
[email protected]eccb9d12009-10-28 05:40:09875
[email protected]9ccbb372008-10-10 18:50:32876// Called on the file thread. Renames the downloaded file to its original name.
877void DownloadManager::ProceedWithFinishedDangerousDownload(
878 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41879 const FilePath& path,
880 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32881 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41882 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16883 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32884 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24885 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16886 // Make our name unique at this point, as if a dangerous file is downloading
887 // and a 2nd download is started for a file with the same name, they would
888 // have the same path. This is because we uniquify the name on download
889 // start, and at that time the first file does not exists yet, so the second
890 // file gets the same name.
891 uniquifier = GetUniquePathNumber(new_path);
892 if (uniquifier > 0)
893 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32894 success = file_util::Move(path, new_path);
895 } else {
896 NOTREACHED();
897 }
[email protected]6cade212008-12-03 00:32:22898
[email protected]d83d03aa2009-11-02 21:44:37899 ChromeThread::PostTask(
900 ChromeThread::UI, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32901 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16902 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32903}
904
905// Call from the file thread when the finished dangerous download was renamed.
906void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
907 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41908 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16909 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32910 DownloadMap::iterator it = downloads_.find(download_handle);
911 if (it == downloads_.end()) {
912 NOTREACHED();
913 return;
914 }
915
916 DownloadItem* download = it->second;
917 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16918 if (success) {
919 // We need to update the path uniquifier so that the UI shows the right
920 // name when calling GetFileName().
921 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32922 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16923 }
[email protected]9ccbb372008-10-10 18:50:32924
925 // Continue the download finished sequence.
926 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29927}
928
929// static
initial.commit09911bf2008-07-26 23:55:29930void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
931 int render_process_id,
932 int request_id) {
[email protected]d85cf072009-10-27 03:59:31933 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
initial.commit09911bf2008-07-26 23:55:29934 rdh->CancelRequest(render_process_id, request_id, false);
935}
936
937void DownloadManager::DownloadCancelled(int32 download_id) {
938 DownloadMap::iterator it = in_progress_.find(download_id);
939 if (it == in_progress_.end())
940 return;
941 DownloadItem* download = it->second;
942
initial.commit09911bf2008-07-26 23:55:29943 // Clean up will happen when the history system create callback runs if we
944 // don't have a valid db_handle yet.
945 if (download->db_handle() != kUninitializedHandle) {
946 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:29947 UpdateHistoryForDownload(download);
948 }
949
[email protected]d7d1c5c2009-08-05 23:52:50950 DownloadCancelledInternal(download_id,
951 download->render_process_id(),
952 download->request_id());
953}
954
955void DownloadManager::DownloadCancelledInternal(int download_id,
956 int render_process_id,
957 int request_id) {
[email protected]d85cf072009-10-27 03:59:31958 // Cancel the network request. RDH is guaranteed to outlive the IO thread.
959 ChromeThread::PostTask(
960 ChromeThread::IO, FROM_HERE,
961 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
962 g_browser_process->resource_dispatcher_host(),
963 render_process_id,
964 request_id));
[email protected]d7d1c5c2009-08-05 23:52:50965
initial.commit09911bf2008-07-26 23:55:29966 // Tell the file manager to cancel the download.
[email protected]d7d1c5c2009-08-05 23:52:50967 file_manager_->RemoveDownload(download_id, this); // On the UI thread
[email protected]d83d03aa2009-11-02 21:44:37968 ChromeThread::PostTask(
969 ChromeThread::FILE, FROM_HERE,
970 NewRunnableMethod(
971 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:29972}
973
974void DownloadManager::PauseDownload(int32 download_id, bool pause) {
975 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]d85cf072009-10-27 03:59:31976 if (it == in_progress_.end())
977 return;
initial.commit09911bf2008-07-26 23:55:29978
[email protected]d85cf072009-10-27 03:59:31979 DownloadItem* download = it->second;
980 if (pause == download->is_paused())
981 return;
initial.commit09911bf2008-07-26 23:55:29982
[email protected]d85cf072009-10-27 03:59:31983 // Inform the ResourceDispatcherHost of the new pause state.
984 ChromeThread::PostTask(
985 ChromeThread::IO, FROM_HERE,
986 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
987 g_browser_process->resource_dispatcher_host(),
988 download->render_process_id(),
989 download->request_id(),
990 pause));
initial.commit09911bf2008-07-26 23:55:29991}
992
993// static
994void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
995 int render_process_id,
996 int request_id,
997 bool pause) {
998 rdh->PauseRequest(render_process_id, request_id, pause);
999}
1000
[email protected]7ae7c2cb2009-01-06 23:31:411001bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:321002 // TODO(jcampan): Improve me.
[email protected]eccb9d12009-10-28 05:40:091003 return IsExecutableFile(file_name);
[email protected]9ccbb372008-10-10 18:50:321004}
1005
1006void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:411007 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:321008 download->Rename(new_path);
1009
1010 // Update the history.
1011
1012 // No update necessary if the download was initiated while in incognito mode.
1013 if (download->db_handle() <= kUninitializedHandle)
1014 return;
1015
[email protected]6cade212008-12-03 00:32:221016 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:321017 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1018 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:411019 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:321020}
1021
initial.commit09911bf2008-07-26 23:55:291022void DownloadManager::RemoveDownload(int64 download_handle) {
1023 DownloadMap::iterator it = downloads_.find(download_handle);
1024 if (it == downloads_.end())
1025 return;
1026
1027 // Make history update.
1028 DownloadItem* download = it->second;
1029 RemoveDownloadFromHistory(download);
1030
1031 // Remove from our tables and delete.
1032 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321033 it = dangerous_finished_.find(download->id());
1034 if (it != dangerous_finished_.end())
1035 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291036
1037 // Tell observers to refresh their views.
1038 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:361039
1040 delete download;
initial.commit09911bf2008-07-26 23:55:291041}
1042
[email protected]e93d2822009-01-30 05:59:591043int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1044 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291045 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1046
initial.commit09911bf2008-07-26 23:55:291047 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:281048 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:291049 while (it != downloads_.end()) {
1050 DownloadItem* download = it->second;
1051 DownloadItem::DownloadState state = download->state();
1052 if (download->start_time() >= remove_begin &&
1053 (remove_end.is_null() || download->start_time() < remove_end) &&
1054 (state == DownloadItem::COMPLETE ||
1055 state == DownloadItem::CANCELLED)) {
1056 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561057 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581058
1059 // Also remove it from any completed dangerous downloads.
1060 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1061 if (dit != dangerous_finished_.end())
1062 dangerous_finished_.erase(dit);
1063
[email protected]78b8fcc92009-03-31 17:36:281064 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:291065
initial.commit09911bf2008-07-26 23:55:291066 continue;
1067 }
1068
1069 ++it;
1070 }
1071
1072 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281073 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291074 if (num_deleted > 0)
1075 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1076
[email protected]78b8fcc92009-03-31 17:36:281077 // Delete the download items after updating the observers.
1078 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1079 pending_deletes.clear();
1080
initial.commit09911bf2008-07-26 23:55:291081 return num_deleted;
1082}
1083
[email protected]e93d2822009-01-30 05:59:591084int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1085 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291086}
1087
[email protected]d41355e6f2009-04-07 21:21:121088int DownloadManager::RemoveAllDownloads() {
1089 // The null times make the date range unbounded.
1090 return RemoveDownloadsBetween(base::Time(), base::Time());
1091}
1092
initial.commit09911bf2008-07-26 23:55:291093// Initiate a download of a specific URL. We send the request to the
1094// ResourceDispatcherHost, and let it send us responses like a regular
1095// download.
1096void DownloadManager::DownloadUrl(const GURL& url,
1097 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:501098 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:341099 TabContents* tab_contents) {
1100 DCHECK(tab_contents);
initial.commit09911bf2008-07-26 23:55:291101 file_manager_->DownloadUrl(url,
1102 referrer,
[email protected]be180c802009-10-23 06:33:311103 referrer_charset,
[email protected]76543b92009-08-31 17:27:451104 tab_contents->process()->id(),
[email protected]57c6a652009-05-04 07:58:341105 tab_contents->render_view_host()->routing_id(),
[email protected]be180c802009-10-23 06:33:311106 request_context_getter_);
initial.commit09911bf2008-07-26 23:55:291107}
1108
[email protected]7ae7c2cb2009-01-06 23:31:411109void DownloadManager::GenerateExtension(
1110 const FilePath& file_name,
1111 const std::string& mime_type,
1112 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291113 // We're worried about three things here:
1114 //
1115 // 1) Security. Many sites let users upload content, such as buddy icons, to
1116 // their web sites. We want to mitigate the case where an attacker
1117 // supplies a malicious executable with an executable file extension but an
1118 // honest site serves the content with a benign content type, such as
1119 // image/jpeg.
1120 //
1121 // 2) Usability. If the site fails to provide a file extension, we want to
1122 // guess a reasonable file extension based on the content type.
1123 //
1124 // 3) Shell integration. Some file extensions automatically integrate with
1125 // the shell. We block these extensions to prevent a malicious web site
1126 // from integrating with the user's shell.
1127
[email protected]7ae7c2cb2009-01-06 23:31:411128 static const FilePath::CharType default_extension[] =
1129 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291130
1131 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411132 FilePath::StringType extension(
1133 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291134
[email protected]b7f05882009-02-22 01:21:561135#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291136 // Rename shell-integrated extensions.
1137 if (win_util::IsShellIntegratedExtension(extension))
1138 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561139#endif
initial.commit09911bf2008-07-26 23:55:291140
1141 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411142 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411143 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291144 if (mime_type == mime_type_from_extension) {
1145 // The hinted extension matches the mime type. It looks like a winner.
1146 generated_extension->swap(extension);
1147 return;
1148 }
1149
[email protected]eccb9d12009-10-28 05:40:091150 if (IsExecutableExtension(extension) && !IsExecutableMimeType(mime_type)) {
initial.commit09911bf2008-07-26 23:55:291151 // We want to be careful about executable extensions. The worry here is
1152 // that a trusted web site could be tricked into dropping an executable file
1153 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101154 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291155 // We couldn't find a good extension for this content type. Use a dummy
1156 // extension instead.
1157 extension.assign(default_extension);
1158 }
1159 }
1160
1161 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101162 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291163 } else {
[email protected]6cade212008-12-03 00:32:221164 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291165 // 1. New extension is not ".txt"
1166 // 2. New extension is not the same as the already existing extension.
1167 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411168 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291169 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1170 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371171 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1172 // servers, i.e. bug 5772.
[email protected]e32642f62009-09-11 21:58:291173 // 5. The original extension is not ".tgz" & the new extension is not "gz".
[email protected]7ae7c2cb2009-01-06 23:31:411174 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101175 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171176 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411177 append_extension != extension &&
[email protected]eccb9d12009-10-28 05:40:091178 !IsExecutableExtension(append_extension) &&
[email protected]e32642f62009-09-11 21:58:291179 !(append_extension == FILE_PATH_LITERAL("gz") &&
1180 extension == FILE_PATH_LITERAL("tgz")) &&
[email protected]e106457b2009-03-25 22:43:371181 (append_extension != FILE_PATH_LITERAL("tar") ||
1182 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171183 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291184 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171185 }
initial.commit09911bf2008-07-26 23:55:291186 }
1187 }
1188
1189 generated_extension->swap(extension);
1190}
1191
1192void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411193 FilePath* generated_name) {
[email protected]630947c2009-11-04 18:37:311194 std::wstring default_name =
1195 l10n_util::GetString(IDS_DEFAULT_DOWNLOAD_FILENAME);
1196#if defined(OS_WIN)
1197 FilePath default_file_path(default_name);
1198#elif defined(OS_POSIX)
1199 FilePath default_file_path(base::SysWideToNativeMB(default_name));
1200#endif
1201
[email protected]de2943352009-10-22 23:06:121202 *generated_name = net::GetSuggestedFilename(GURL(info->url),
1203 info->content_disposition,
1204 info->referrer_charset,
[email protected]630947c2009-11-04 18:37:311205 default_file_path);
1206
[email protected]7ae7c2cb2009-01-06 23:31:411207 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291208
[email protected]7ae7c2cb2009-01-06 23:31:411209 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291210}
1211
1212void DownloadManager::AddObserver(Observer* observer) {
1213 observers_.AddObserver(observer);
1214 observer->ModelChanged();
1215}
1216
1217void DownloadManager::RemoveObserver(Observer* observer) {
1218 observers_.RemoveObserver(observer);
1219}
1220
1221// Post Windows Shell operations to the Download thread, to avoid blocking the
1222// user interface.
1223void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1224 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:371225 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:581226#if defined(OS_MACOSX)
1227 // Mac needs to run this operation on the UI thread.
1228 platform_util::ShowItemInFolder(download->full_path());
1229#else
[email protected]d83d03aa2009-11-02 21:44:371230 ChromeThread::PostTask(
1231 ChromeThread::FILE, FROM_HERE,
1232 NewRunnableMethod(
1233 file_manager_, &DownloadFileManager::OnShowDownloadInShell,
1234 FilePath(download->full_path())));
[email protected]8b6ff012009-08-18 22:29:581235#endif
initial.commit09911bf2008-07-26 23:55:291236}
1237
[email protected]8f783752009-04-01 23:33:451238void DownloadManager::OpenDownload(const DownloadItem* download,
1239 gfx::NativeView parent_window) {
[email protected]0e34d7892009-06-05 19:17:401240 // Open Chrome extensions with ExtensionsService. For everything else do shell
[email protected]8f783752009-04-01 23:33:451241 // execute.
[email protected]a60c8ae2009-12-25 06:50:571242 if (download->is_extension_install()) {
[email protected]494c06e2009-07-25 01:06:421243 OpenChromeExtension(download->full_path(), download->url(),
1244 download->referrer_url());
[email protected]8f783752009-04-01 23:33:451245 } else {
1246 OpenDownloadInShell(download, parent_window);
1247 }
1248}
1249
[email protected]c1e432a2009-07-22 21:21:481250void DownloadManager::OpenChromeExtension(const FilePath& full_path,
[email protected]494c06e2009-07-25 01:06:421251 const GURL& download_url,
1252 const GURL& referrer_url) {
[email protected]6ef635e42009-07-26 06:16:121253 // We don't support extensions in OTR mode.
[email protected]2a464a92009-08-01 17:58:351254 ExtensionsService* service = profile_->GetExtensionsService();
1255 if (service) {
[email protected]91e1bd82009-09-03 22:04:401256 NotificationService* nservice = NotificationService::current();
[email protected]ac025282009-12-16 19:16:381257 GURL nonconst_download_url = download_url;
[email protected]91e1bd82009-09-03 22:04:401258 nservice->Notify(NotificationType::EXTENSION_READY_FOR_INSTALL,
1259 Source<DownloadManager>(this),
[email protected]ac025282009-12-16 19:16:381260 Details<GURL>(&nonconst_download_url));
[email protected]a050d712009-11-06 00:40:101261 if (UserScript::HasUserScriptFileExtension(download_url)) {
[email protected]6657afa62009-11-04 02:15:201262 CrxInstaller::InstallUserScript(
1263 full_path,
1264 download_url,
1265 service->install_directory(),
1266 true, // please delete crx on completion
1267 service,
1268 new ExtensionInstallUI(profile_));
1269 } else {
1270 CrxInstaller::Start(
1271 full_path,
1272 service->install_directory(),
1273 Extension::INTERNAL,
1274 "", // no expected id
1275 true, // please delete crx on completion
1276 true, // privilege increase allowed
1277 service,
1278 new ExtensionInstallUI(profile_));
1279 }
[email protected]2a464a92009-08-01 17:58:351280 }
[email protected]8f783752009-04-01 23:33:451281}
1282
initial.commit09911bf2008-07-26 23:55:291283void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591284 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291285 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:371286 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:581287#if defined(OS_MACOSX)
1288 // Mac OS X requires opening downloads on the UI thread.
1289 platform_util::OpenItem(download->full_path());
1290#else
[email protected]d83d03aa2009-11-02 21:44:371291 ChromeThread::PostTask(
1292 ChromeThread::FILE, FROM_HERE,
1293 NewRunnableMethod(
1294 file_manager_, &DownloadFileManager::OnOpenDownloadInShell,
1295 download->full_path(), download->url(), parent_window));
[email protected]8b6ff012009-08-18 22:29:581296#endif
initial.commit09911bf2008-07-26 23:55:291297}
1298
[email protected]eccb9d12009-10-28 05:40:091299void DownloadManager::OpenFilesBasedOnExtension(
1300 const FilePath& path, bool open) {
1301 FilePath::StringType extension = path.Extension();
1302 if (extension.empty())
1303 return;
1304 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1305 extension.erase(0, 1);
1306 if (open && !IsExecutableExtension(extension))
initial.commit09911bf2008-07-26 23:55:291307 auto_open_.insert(extension);
1308 else
1309 auto_open_.erase(extension);
1310 SaveAutoOpens();
1311}
1312
[email protected]eccb9d12009-10-28 05:40:091313bool DownloadManager::ShouldOpenFileBasedOnExtension(
1314 const FilePath& path) const {
[email protected]eccb9d12009-10-28 05:40:091315 FilePath::StringType extension = path.Extension();
1316 if (extension.empty())
1317 return false;
1318 if (IsExecutableExtension(extension))
1319 return false;
[email protected]92e11c82010-01-13 06:39:561320 if (Extension::IsExtension(path))
1321 return false;
[email protected]eccb9d12009-10-28 05:40:091322 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1323 extension.erase(0, 1);
[email protected]92e11c82010-01-13 06:39:561324 if (auto_open_.find(extension) != auto_open_.end())
[email protected]8c756ac2009-01-30 23:36:411325 return true;
initial.commit09911bf2008-07-26 23:55:291326 return false;
1327}
1328
[email protected]7b73d992008-12-15 20:56:461329static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291330 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461331 "text/javascript",
1332 "text/javascript;version=*",
[email protected]54d8d452009-04-08 17:29:241333 // Registry files can cause critical changes to the MS OS behavior.
1334 // Addition of this mimetype also addresses bug 7337.
1335 "text/x-registry",
[email protected]60ff8f912008-12-05 07:58:391336 // Some sites use binary/octet-stream to mean application/octet-stream.
1337 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461338 "binary/octet-stream"
1339};
initial.commit09911bf2008-07-26 23:55:291340
[email protected]7b73d992008-12-15 20:56:461341static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291342 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461343 "application/*+xml",
1344 "application/xml"
1345};
initial.commit09911bf2008-07-26 23:55:291346
[email protected]7b73d992008-12-15 20:56:461347// static
1348bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411349 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461350 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1351 return true;
1352 }
[email protected]bae0ea12009-02-14 01:20:411353 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461354 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1355 return false;
1356 }
1357 // We consider only other application types to be executable.
1358 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291359}
1360
[email protected]eccb9d12009-10-28 05:40:091361bool DownloadManager::IsExecutableFile(const FilePath& path) const {
1362 return IsExecutableExtension(path.Extension());
1363}
1364
1365bool DownloadManager::IsExecutableExtension(
1366 const FilePath::StringType& extension) const {
1367 if (extension.empty())
1368 return false;
[email protected]64da0b932009-02-24 02:30:041369 if (!IsStringASCII(extension))
1370 return false;
[email protected]a0a9577b2009-05-27 23:52:321371#if defined(OS_WIN)
[email protected]64da0b932009-02-24 02:30:041372 std::string ascii_extension = WideToASCII(extension);
[email protected]e9ef0a62009-08-11 22:50:131373#elif defined(OS_POSIX)
[email protected]a0a9577b2009-05-27 23:52:321374 std::string ascii_extension = extension;
1375#endif
[email protected]64da0b932009-02-24 02:30:041376 StringToLowerASCII(&ascii_extension);
1377
[email protected]eccb9d12009-10-28 05:40:091378 // Strip out leading dot if it's still there
1379 if (ascii_extension[0] == FilePath::kExtensionSeparator)
1380 ascii_extension.erase(0, 1);
1381
[email protected]64da0b932009-02-24 02:30:041382 return exe_types_.find(ascii_extension) != exe_types_.end();
initial.commit09911bf2008-07-26 23:55:291383}
1384
1385void DownloadManager::ResetAutoOpenFiles() {
1386 auto_open_.clear();
1387 SaveAutoOpens();
1388}
1389
1390bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1391 return !auto_open_.empty();
1392}
1393
1394void DownloadManager::SaveAutoOpens() {
1395 PrefService* prefs = profile_->GetPrefs();
1396 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411397 FilePath::StringType extensions;
[email protected]eccb9d12009-10-28 05:40:091398 for (AutoOpenSet::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291399 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411400 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291401 }
1402 if (!extensions.empty())
1403 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561404
1405 std::wstring extensions_w;
1406#if defined(OS_WIN)
1407 extensions_w = extensions;
1408#elif defined(OS_POSIX)
[email protected]1b5044d2009-02-24 00:04:141409 extensions_w = base::SysNativeMBToWide(extensions);
[email protected]b7f05882009-02-22 01:21:561410#endif
1411
1412 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291413 }
1414}
1415
[email protected]561abe62009-04-06 18:08:341416void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361417 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291418 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071419 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411420 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291421 ContinueStartDownload(info, path);
1422}
1423
1424void DownloadManager::FileSelectionCanceled(void* params) {
1425 // The user didn't pick a place to save the file, so need to cancel the
1426 // download that's already in progress to the temporary location.
1427 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]d7d1c5c2009-08-05 23:52:501428 DownloadCancelledInternal(info->download_id,
[email protected]76543b92009-08-31 17:27:451429 info->child_id,
[email protected]d7d1c5c2009-08-05 23:52:501430 info->request_id);
initial.commit09911bf2008-07-26 23:55:291431}
1432
[email protected]7ae7c2cb2009-01-06 23:31:411433void DownloadManager::DeleteDownload(const FilePath& path) {
[email protected]d83d03aa2009-11-02 21:44:371434 ChromeThread::PostTask(
1435 ChromeThread::FILE, FROM_HERE,
1436 NewRunnableFunction(&DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321437}
1438
1439
1440void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1441 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1442 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1443 download->UpdateObservers();
1444
1445 // If the download is not complete, nothing to do. The required
1446 // post-processing will be performed when it does complete.
1447 if (download->state() != DownloadItem::COMPLETE)
1448 return;
1449
[email protected]d83d03aa2009-11-02 21:44:371450 ChromeThread::PostTask(
1451 ChromeThread::FILE, FROM_HERE,
1452 NewRunnableMethod(
1453 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
1454 download->db_handle(), download->full_path(),
1455 download->original_name()));
[email protected]9ccbb372008-10-10 18:50:321456}
1457
[email protected]763f946a2009-01-06 19:04:391458void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411459 FilePath* file_name) {
1460 // Make sure we get the right file extension
1461 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391462 GenerateExtension(*file_name, mime_type, &extension);
1463 file_util::ReplaceExtension(file_name, extension);
1464
[email protected]2b2f8f72009-02-24 22:42:051465#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391466 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411467 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391468 DCHECK(!leaf_name.empty());
1469 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411470 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1471 *file_name = file_name->DirName();
1472 if (file_name->value() == FilePath::kCurrentDirectory) {
1473 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391474 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411475 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391476 }
1477 }
[email protected]b7f05882009-02-22 01:21:561478#endif
[email protected]763f946a2009-01-06 19:04:391479}
1480
initial.commit09911bf2008-07-26 23:55:291481// Operations posted to us from the history service ----------------------------
1482
1483// The history service has retrieved all download entries. 'entries' contains
1484// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1485void DownloadManager::OnQueryDownloadEntriesComplete(
1486 std::vector<DownloadCreateInfo>* entries) {
1487 for (size_t i = 0; i < entries->size(); ++i) {
1488 DownloadItem* download = new DownloadItem(entries->at(i));
1489 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1490 downloads_[download->db_handle()] = download;
1491 download->set_manager(this);
1492 }
1493 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1494}
1495
initial.commit09911bf2008-07-26 23:55:291496// Once the new DownloadItem's creation info has been committed to the history
1497// service, we associate the DownloadItem with the db handle, update our
1498// 'downloads_' map and inform observers.
1499void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1500 int64 db_handle) {
1501 DownloadMap::iterator it = in_progress_.find(info.download_id);
1502 DCHECK(it != in_progress_.end());
1503
1504 DownloadItem* download = it->second;
1505 DCHECK(download->db_handle() == kUninitializedHandle);
1506 download->set_db_handle(db_handle);
1507
1508 // Insert into our full map.
1509 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1510 downloads_[download->db_handle()] = download;
1511
[email protected]5e595482009-05-06 20:16:531512 // Show in the appropropriate browser UI.
1513 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291514
1515 // Inform interested objects about the new download.
1516 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
initial.commit09911bf2008-07-26 23:55:291517
1518 // If this download has been completed before we've received the db handle,
1519 // post one final message to the history service so that it can be properly
1520 // in sync with the DownloadItem's completion status, and also inform any
1521 // observers so that they get more than just the start notification.
1522 if (download->state() != DownloadItem::IN_PROGRESS) {
1523 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291524 UpdateHistoryForDownload(download);
1525 download->UpdateObservers();
1526 }
1527}
1528
1529// Called when the history service has retrieved the list of downloads that
1530// match the search text.
1531void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1532 std::vector<int64>* results) {
1533 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1534 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1535 if (!requestor)
1536 return;
1537
1538 std::vector<DownloadItem*> searched_downloads;
1539 for (std::vector<int64>::iterator it = results->begin();
1540 it != results->end(); ++it) {
1541 DownloadMap::iterator dit = downloads_.find(*it);
1542 if (dit != downloads_.end())
1543 searched_downloads.push_back(dit->second);
1544 }
1545
1546 requestor->SetDownloads(searched_downloads);
1547}
[email protected]905a08d2008-11-19 07:24:121548
[email protected]5e595482009-05-06 20:16:531549void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1550 DownloadItem* download) {
[email protected]5e595482009-05-06 20:16:531551 // The 'contents' may no longer exist if the user closed the tab before we get
1552 // this start completion event. If it does, tell the origin TabContents to
1553 // display its download shelf.
[email protected]76543b92009-08-31 17:27:451554 TabContents* contents = tab_util::GetTabContentsByID(info.child_id,
1555 info.render_view_id);
[email protected]5e595482009-05-06 20:16:531556
1557 // If the contents no longer exists, we start the download in the last active
1558 // browser. This is not ideal but better than fully hiding the download from
1559 // the user.
1560 if (!contents) {
1561 Browser* last_active = BrowserList::GetLastActive();
1562 if (last_active)
1563 contents = last_active->GetSelectedTabContents();
1564 }
1565
1566 if (contents)
1567 contents->OnStartDownload(download);
1568}
1569
[email protected]6cade212008-12-03 00:32:221570// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121571void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411572 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381573}
1574