blob: 1295f25eded2266674fa271b5367a86531cd3eb9 [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,
157 bool save_as)
initial.commit09911bf2008-07-26 23:55:29158 : id_(download_id),
159 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16160 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29161 url_(url),
[email protected]494c06e2009-07-25 01:06:42162 referrer_url_(referrer_url),
[email protected]e435d6b72009-07-25 03:15:58163 mime_type_(mime_type),
initial.commit09911bf2008-07-26 23:55:29164 total_bytes_(download_size),
165 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56166 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29167 state_(IN_PROGRESS),
168 start_time_(start_time),
169 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29170 manager_(NULL),
171 is_paused_(false),
172 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56173 safety_state_(is_dangerous ? DANGEROUS : SAFE),
[email protected]0aad67b2009-07-15 20:34:28174 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56175 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29176 render_process_id_(render_process_id),
[email protected]67f373a2009-09-22 02:44:51177 request_id_(request_id),
178 save_as_(save_as) {
initial.commit09911bf2008-07-26 23:55:29179 Init(true /* start progress timer */);
180}
181
182void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41183 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29184 if (start_timer)
185 StartProgressTimer();
186}
187
188DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29189 state_ = REMOVING;
190 UpdateObservers();
191}
192
193void DownloadItem::AddObserver(Observer* observer) {
194 observers_.AddObserver(observer);
195}
196
197void DownloadItem::RemoveObserver(Observer* observer) {
198 observers_.RemoveObserver(observer);
199}
200
201void DownloadItem::UpdateObservers() {
202 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
203}
204
[email protected]45e3c122009-04-07 19:58:03205void DownloadItem::NotifyObserversDownloadOpened() {
206 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadOpened(this));
207}
208
initial.commit09911bf2008-07-26 23:55:29209// If we've received more data than we were expecting (bad server info?), revert
210// to 'unknown size mode'.
211void DownloadItem::UpdateSize(int64 bytes_so_far) {
212 received_bytes_ = bytes_so_far;
213 if (received_bytes_ > total_bytes_)
214 total_bytes_ = 0;
215}
216
217// Updates from the download thread may have been posted while this download
218// was being cancelled in the UI thread, so we'll accept them unless we're
219// complete.
220void DownloadItem::Update(int64 bytes_so_far) {
221 if (state_ == COMPLETE) {
222 NOTREACHED();
223 return;
224 }
225 UpdateSize(bytes_so_far);
226 UpdateObservers();
227}
228
[email protected]6cade212008-12-03 00:32:22229// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29230void DownloadItem::Cancel(bool update_history) {
231 if (state_ != IN_PROGRESS) {
232 // Small downloads might be complete before this method has a chance to run.
233 return;
234 }
235 state_ = CANCELLED;
236 UpdateObservers();
237 StopProgressTimer();
238 if (update_history)
239 manager_->DownloadCancelled(id_);
240}
241
242void DownloadItem::Finished(int64 size) {
243 state_ = COMPLETE;
244 UpdateSize(size);
[email protected]22fbe5a2008-10-29 22:20:40245 UpdateObservers();
initial.commit09911bf2008-07-26 23:55:29246 StopProgressTimer();
247}
248
[email protected]9ccbb372008-10-10 18:50:32249void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29250 Cancel(true);
251 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32252 if (delete_on_disk)
253 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29254 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22255 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29256}
257
258void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59259 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14260 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29261}
262
263void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14264 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29265}
266
[email protected]e93d2822009-01-30 05:59:59267bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29268 if (total_bytes_ <= 0)
269 return false; // We never received the content_length for this download.
270
271 int64 speed = CurrentSpeed();
272 if (speed == 0)
273 return false;
274
275 *remaining =
[email protected]e93d2822009-01-30 05:59:59276 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29277 return true;
278}
279
280int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56281 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
282 int64 diff_ms = diff.InMilliseconds();
283 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29284}
285
286int DownloadItem::PercentComplete() const {
287 int percent = -1;
288 if (total_bytes_ > 0)
289 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
290 return percent;
291}
292
[email protected]7ae7c2cb2009-01-06 23:31:41293void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29294 DCHECK(!full_path.empty());
295 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41296 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29297}
298
299void DownloadItem::TogglePause() {
300 DCHECK(state_ == IN_PROGRESS);
301 manager_->PauseDownload(id_, !is_paused_);
302 is_paused_ = !is_paused_;
303 UpdateObservers();
304}
305
[email protected]7ae7c2cb2009-01-06 23:31:41306FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32307 if (safety_state_ == DownloadItem::SAFE)
308 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16309 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41310 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16311 AppendNumberToPath(&name, path_uniquifier_);
312 return name;
313 }
[email protected]9ccbb372008-10-10 18:50:32314 return original_name_;
315}
316
initial.commit09911bf2008-07-26 23:55:29317// DownloadManager implementation ----------------------------------------------
318
319// static
320void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
321 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
322 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32323 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
324
325 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41326 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12327 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
328 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32329 NOTREACHED();
330 }
[email protected]b9636002009-03-04 00:05:25331 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
332 default_download_path);
[email protected]f052118e2008-09-05 02:25:32333
334 // If the download path is dangerous we forcefully reset it. But if we do
335 // so we set a flag to make sure we only do it once, to avoid fighting
336 // the user if he really wants it on an unsafe place such as the desktop.
337
338 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41339 FilePath current_download_dir = FilePath::FromWStringHack(
340 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32341 if (DownloadPathIsDangerous(current_download_dir)) {
342 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41343 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32344 }
345 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
346 }
initial.commit09911bf2008-07-26 23:55:29347}
348
349DownloadManager::DownloadManager()
350 : shutdown_needed_(false),
351 profile_(NULL),
[email protected]d83d03aa2009-11-02 21:44:37352 file_manager_(NULL) {
initial.commit09911bf2008-07-26 23:55:29353}
354
355DownloadManager::~DownloadManager() {
356 if (shutdown_needed_)
357 Shutdown();
358}
359
360void DownloadManager::Shutdown() {
361 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
362
363 // Stop receiving download updates
364 file_manager_->RemoveDownloadManager(this);
365
366 // Stop making history service requests
367 cancelable_consumer_.CancelAllRequests();
368
369 // 'in_progress_' may contain DownloadItems that have not finished the start
370 // complete (from the history service) and thus aren't in downloads_.
371 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32372 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29373 for (; it != in_progress_.end(); ++it) {
374 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32375 if (download->safety_state() == DownloadItem::DANGEROUS) {
376 // Forget about any download that the user did not approve.
377 // Note that we cannot call download->Remove() this would invalidate our
378 // iterator.
379 to_remove.insert(download);
380 continue;
initial.commit09911bf2008-07-26 23:55:29381 }
[email protected]9ccbb372008-10-10 18:50:32382 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
383 download->Cancel(false);
384 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29385 if (download->db_handle() == kUninitializedHandle) {
386 // An invalid handle means that 'download' does not yet exist in
387 // 'downloads_', so we have to delete it here.
388 delete download;
389 }
390 }
391
[email protected]9ccbb372008-10-10 18:50:32392 // 'dangerous_finished_' contains all complete downloads that have not been
393 // approved. They should be removed.
394 it = dangerous_finished_.begin();
395 for (; it != dangerous_finished_.end(); ++it)
396 to_remove.insert(it->second);
397
398 // Remove the dangerous download that are not approved.
399 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
400 rm_it != to_remove.end(); ++rm_it) {
401 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32402 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32403 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32404 // Same as above, delete the download if it is not in 'downloads_' (as the
405 // Remove() call above won't have deleted it).
406 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32407 delete download;
408 }
409 to_remove.clear();
410
initial.commit09911bf2008-07-26 23:55:29411 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32412 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29413 STLDeleteValues(&downloads_);
414
415 file_manager_ = NULL;
416
417 // Save our file extensions to auto open.
418 SaveAutoOpens();
419
420 // Make sure the save as dialog doesn't notify us back if we're gone before
421 // it returns.
422 if (select_file_dialog_.get())
423 select_file_dialog_->ListenerDestroyed();
424
425 shutdown_needed_ = false;
426}
427
428// Issue a history query for downloads matching 'search_text'. If 'search_text'
429// is empty, return all downloads that we know about.
430void DownloadManager::GetDownloads(Observer* observer,
431 const std::wstring& search_text) {
432 DCHECK(observer);
433
434 // Return a empty list if we've not yet received the set of downloads from the
435 // history system (we'll update all observers once we get that list in
436 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
437 std::vector<DownloadItem*> download_copy;
438 if (downloads_.empty()) {
439 observer->SetDownloads(download_copy);
440 return;
441 }
442
443 // We already know all the downloads and there is no filter, so just return a
444 // copy to the observer.
445 if (search_text.empty()) {
446 download_copy.reserve(downloads_.size());
447 for (DownloadMap::iterator it = downloads_.begin();
448 it != downloads_.end(); ++it) {
[email protected]67f373a2009-09-22 02:44:51449 if (it->second->db_handle() > kUninitializedHandle)
450 download_copy.push_back(it->second);
initial.commit09911bf2008-07-26 23:55:29451 }
452
453 // We retain ownership of the DownloadItems.
454 observer->SetDownloads(download_copy);
455 return;
456 }
457
458 // Issue a request to the history service for a list of downloads matching
459 // our search text.
460 HistoryService* hs =
461 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
462 if (hs) {
463 HistoryService::Handle h =
464 hs->SearchDownloads(search_text,
465 &cancelable_consumer_,
466 NewCallback(this,
467 &DownloadManager::OnSearchComplete));
468 cancelable_consumer_.SetClientData(hs, h, observer);
469 }
470}
471
472// Query the history service for information about all persisted downloads.
473bool DownloadManager::Init(Profile* profile) {
474 DCHECK(profile);
475 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
476 shutdown_needed_ = true;
477
478 profile_ = profile;
[email protected]be180c802009-10-23 06:33:31479 request_context_getter_ = profile_->GetRequestContext();
initial.commit09911bf2008-07-26 23:55:29480
481 // 'incognito mode' will have access to past downloads, but we won't store
482 // information about new downloads while in that mode.
483 QueryHistoryForDownloads();
484
485 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
486 if (!rdh) {
487 NOTREACHED();
488 return false;
489 }
490
491 file_manager_ = rdh->download_file_manager();
492 if (!file_manager_) {
493 NOTREACHED();
494 return false;
495 }
496
initial.commit09911bf2008-07-26 23:55:29497 // Get our user preference state.
498 PrefService* prefs = profile_->GetPrefs();
499 DCHECK(prefs);
500 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
501
initial.commit09911bf2008-07-26 23:55:29502 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
503
[email protected]7ae7c2cb2009-01-06 23:31:41504 // This variable is needed to resolve which CreateDirectory we want to point
505 // to. Without it, the NewRunnableFunction cannot resolve the ambiguity.
506 // TODO(estade): when file_util::CreateDirectory(wstring) is removed,
507 // get rid of |CreateDirectoryPtr|.
508 bool (*CreateDirectoryPtr)(const FilePath&) = &file_util::CreateDirectory;
[email protected]bb69e9b32008-08-14 23:08:14509 // Ensure that the download directory specified in the preferences exists.
[email protected]d83d03aa2009-11-02 21:44:37510 ChromeThread::PostTask(
511 ChromeThread::FILE, FROM_HERE,
512 NewRunnableFunction(CreateDirectoryPtr, download_path()));
initial.commit09911bf2008-07-26 23:55:29513
[email protected]a0a9577b2009-05-27 23:52:32514 // We use this to determine possibly dangerous downloads.
[email protected]2b2f8f72009-02-24 22:42:05515 download_util::InitializeExeTypes(&exe_types_);
[email protected]2b2f8f72009-02-24 22:42:05516
517 // We store any file extension that should be opened automatically at
518 // download completion in this pref.
initial.commit09911bf2008-07-26 23:55:29519 std::wstring extensions_to_open =
520 prefs->GetString(prefs::kDownloadExtensionsToOpen);
521 std::vector<std::wstring> extensions;
522 SplitString(extensions_to_open, L':', &extensions);
523 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]eccb9d12009-10-28 05:40:09524 if (!extensions[i].empty() && !IsExecutableFile(
525 FilePath::FromWStringHack(extensions[i])))
[email protected]b7f05882009-02-22 01:21:56526 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29527 }
528
529 return true;
530}
531
532void DownloadManager::QueryHistoryForDownloads() {
533 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
534 if (hs) {
535 hs->QueryDownloads(
536 &cancelable_consumer_,
537 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
538 }
539}
540
541// We have received a message from DownloadFileManager about a new download. We
542// create a download item and store it in our download map, and inform the
543// history system of a new download. Since this method can be called while the
544// history service thread is still reading the persistent state, we do not
545// insert the new DownloadItem into 'downloads_' or inform our observers at this
546// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
547// download creation as a callback from the history thread.
548void DownloadManager::StartDownload(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37549 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29550 DCHECK(info);
551
[email protected]7d3851d82008-12-12 03:26:07552 // Freeze the user's preference for showing a Save As dialog. We're going to
553 // bounce around a bunch of threads and we don't want to worry about race
554 // conditions where the user changes this pref out from under us.
[email protected]7bc4f702009-09-25 22:12:38555 if (*prompt_for_download_) {
556 // But never obey the preference for extension installation. Note that we
557 // only care here about the case where an extension is installed, not when
558 // one is downloaded with "save as...".
559 if (!IsExtensionInstall(info))
560 info->save_as = true;
561 }
[email protected]7d3851d82008-12-12 03:26:07562
initial.commit09911bf2008-07-26 23:55:29563 // Determine the proper path for a download, by choosing either the default
564 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41565 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29566 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07567 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29568 info->suggested_path = last_download_path_;
569 else
[email protected]7ae7c2cb2009-01-06 23:31:41570 info->suggested_path = download_path();
571 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29572
[email protected]7d3851d82008-12-12 03:26:07573 if (!info->save_as) {
[email protected]4289d9b2009-07-25 21:17:34574 // Downloads can be marked as dangerous for two reasons:
575 // a) They have a dangerous-looking filename
576 // b) They are an extension that is not from the gallery
577 if (IsDangerous(info->suggested_path.BaseName()))
578 info->is_dangerous = true;
[email protected]67f373a2009-09-22 02:44:51579 else if (IsExtensionInstall(info) &&
[email protected]4289d9b2009-07-25 21:17:34580 !ExtensionsService::IsDownloadFromGallery(info->url,
581 info->referrer_url)) {
582 info->is_dangerous = true;
583 }
[email protected]e9ebf3fc2008-10-17 22:06:58584 }
585
initial.commit09911bf2008-07-26 23:55:29586 // We need to move over to the download thread because we don't want to stat
587 // the suggested path on the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37588 ChromeThread::PostTask(
589 ChromeThread::FILE, FROM_HERE,
590 NewRunnableMethod(
591 this, &DownloadManager::CheckIfSuggestedPathExists, info));
initial.commit09911bf2008-07-26 23:55:29592}
593
594void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
595 DCHECK(info);
596
597 // Check writability of the suggested path. If we can't write to it, default
598 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41599 FilePath dir = info->suggested_path.DirName();
600 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32601 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29602 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29603 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41604 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29605 }
606
[email protected]7a256ea2008-10-17 17:34:16607 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29608
[email protected]6cade212008-12-03 00:32:22609 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58610 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41611 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32612 // Create a temporary file to hold the file until the user approves its
613 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41614 FilePath::StringType file_name;
615 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32616 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41617 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32618 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41619 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07620 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41621 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32622 }
623 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16624 } else {
625 // We know the final path, build it if necessary.
626 if (info->path_uniquifier > 0) {
627 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
628 // Setting path_uniquifier to 0 to make sure we don't try to unique it
629 // later on.
630 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07631 } else if (info->path_uniquifier == -1) {
632 // We failed to find a unique path. We have to prompt the user.
633 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16634 }
[email protected]9ccbb372008-10-10 18:50:32635 }
636
[email protected]7d3851d82008-12-12 03:26:07637 if (!info->save_as) {
638 // Create an empty file at the suggested path so that we don't allocate the
639 // same "non-existant" path to multiple downloads.
640 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ff3f632009-10-13 18:43:35641 file_util::WriteFile(info->suggested_path, "", 0);
[email protected]7d3851d82008-12-12 03:26:07642 }
643
initial.commit09911bf2008-07-26 23:55:29644 // Now we return to the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37645 ChromeThread::PostTask(
646 ChromeThread::UI, FROM_HERE,
initial.commit09911bf2008-07-26 23:55:29647 NewRunnableMethod(this,
648 &DownloadManager::OnPathExistenceAvailable,
649 info));
650}
651
652void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37653 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29654 DCHECK(info);
655
[email protected]7d3851d82008-12-12 03:26:07656 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29657 // We must ask the user for the place to put the download.
658 if (!select_file_dialog_.get())
659 select_file_dialog_ = SelectFileDialog::Create(this);
660
[email protected]76543b92009-08-31 17:27:45661 TabContents* contents = tab_util::GetTabContentsByID(info->child_id,
662 info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08663 SelectFileDialog::FileTypeInfo file_type_info;
664 file_type_info.extensions.resize(1);
665 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24666 if (!file_type_info.extensions[0][0].empty())
667 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08668 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23669 gfx::NativeWindow owning_window =
670 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29671 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34672 string16(),
673 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08674 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30675 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29676 } else {
677 // No prompting for download, just continue with the suggested name.
678 ContinueStartDownload(info, info->suggested_path);
679 }
680}
681
682void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41683 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29684 scoped_ptr<DownloadCreateInfo> infop(info);
685 info->path = target_path;
686
687 DownloadItem* download = NULL;
688 DownloadMap::iterator it = in_progress_.find(info->download_id);
689 if (it == in_progress_.end()) {
690 download = new DownloadItem(info->download_id,
691 info->path,
[email protected]7a256ea2008-10-17 17:34:16692 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29693 info->url,
[email protected]494c06e2009-07-25 01:06:42694 info->referrer_url,
[email protected]e435d6b72009-07-25 03:15:58695 info->mime_type,
[email protected]9ccbb372008-10-10 18:50:32696 info->original_name,
initial.commit09911bf2008-07-26 23:55:29697 info->start_time,
698 info->total_bytes,
[email protected]76543b92009-08-31 17:27:45699 info->child_id,
[email protected]9ccbb372008-10-10 18:50:32700 info->request_id,
[email protected]67f373a2009-09-22 02:44:51701 info->is_dangerous,
702 info->save_as);
initial.commit09911bf2008-07-26 23:55:29703 download->set_manager(this);
704 in_progress_[info->download_id] = download;
705 } else {
706 NOTREACHED(); // Should not exist!
707 return;
708 }
709
[email protected]6b323782009-03-27 18:43:08710 // Called before DownloadFinished in order to avoid a race condition where we
711 // attempt to open a completed download before it has been renamed.
[email protected]d83d03aa2009-11-02 21:44:37712 ChromeThread::PostTask(
713 ChromeThread::FILE, FROM_HERE,
714 NewRunnableMethod(
715 file_manager_, &DownloadFileManager::OnFinalDownloadName,
716 download->id(), target_path, this));
[email protected]6b323782009-03-27 18:43:08717
initial.commit09911bf2008-07-26 23:55:29718 // If the download already completed by the time we reached this point, then
719 // notify observers that it did.
720 PendingFinishedMap::iterator pending_it =
721 pending_finished_downloads_.find(info->download_id);
722 if (pending_it != pending_finished_downloads_.end())
723 DownloadFinished(pending_it->first, pending_it->second);
724
725 download->Rename(target_path);
726
[email protected]67f373a2009-09-22 02:44:51727 // Do not store the download in the history database for a few special cases:
728 // - incognito mode (that is the point of this mode)
729 // - extensions (users don't think of extension installation as 'downloading')
730 // We have to make sure that these handles don't collide with normal db
731 // handles, so we use a negative value. Eventually, they could overlap, but
732 // you'd have to do enough downloading that your ISP would likely stab you in
733 // the neck first. YMMV.
734 if (profile_->IsOffTheRecord() || IsExtensionInstall(download)) {
initial.commit09911bf2008-07-26 23:55:29735 static int64 fake_db_handle = kUninitializedHandle - 1;
736 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
737 } else {
738 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22739 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29740 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
741 if (hs) {
742 hs->CreateDownload(
743 *info, &cancelable_consumer_,
744 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
745 }
746 }
747}
748
749// Convenience function for updating the history service for a download.
750void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
751 DCHECK(download);
752
753 // Don't store info in the database if the download was initiated while in
754 // incognito mode or if it hasn't been initialized in our database table.
755 if (download->db_handle() <= kUninitializedHandle)
756 return;
757
[email protected]6cade212008-12-03 00:32:22758 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29759 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
760 if (hs) {
761 hs->UpdateDownload(download->received_bytes(),
762 download->state(),
763 download->db_handle());
764 }
765}
766
767void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
768 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22769 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29770 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
771 if (download->db_handle() > kUninitializedHandle && hs)
772 hs->RemoveDownload(download->db_handle());
773}
774
[email protected]e93d2822009-01-30 05:59:59775void DownloadManager::RemoveDownloadsFromHistoryBetween(
776 const base::Time remove_begin,
777 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22778 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29779 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
780 if (hs)
781 hs->RemoveDownloadsBetween(remove_begin, remove_end);
782}
783
784void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
785 DownloadMap::iterator it = in_progress_.find(download_id);
786 if (it != in_progress_.end()) {
787 DownloadItem* download = it->second;
788 download->Update(size);
789 UpdateHistoryForDownload(download);
790 }
791}
792
793void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
794 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32795 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29796 // The download is done, but the user hasn't selected a final location for
797 // it yet (the Save As dialog box is probably still showing), so just keep
798 // track of the fact that this download id is complete, when the
799 // DownloadItem is constructed later we'll notify its completion then.
800 PendingFinishedMap::iterator erase_it =
801 pending_finished_downloads_.find(download_id);
802 DCHECK(erase_it == pending_finished_downloads_.end());
803 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32804 return;
initial.commit09911bf2008-07-26 23:55:29805 }
[email protected]9ccbb372008-10-10 18:50:32806
807 // Remove the id from the list of pending ids.
808 PendingFinishedMap::iterator erase_it =
809 pending_finished_downloads_.find(download_id);
810 if (erase_it != pending_finished_downloads_.end())
811 pending_finished_downloads_.erase(erase_it);
812
813 DownloadItem* download = it->second;
814 download->Finished(size);
815
816 // Clean up will happen when the history system create callback runs if we
817 // don't have a valid db_handle yet.
818 if (download->db_handle() != kUninitializedHandle) {
819 in_progress_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32820 UpdateHistoryForDownload(download);
821 }
822
823 // If this a dangerous download not yet validated by the user, don't do
824 // anything. When the user notifies us, it will trigger a call to
825 // ProceedWithFinishedDangerousDownload.
826 if (download->safety_state() == DownloadItem::DANGEROUS) {
827 dangerous_finished_[download_id] = download;
828 return;
829 }
830
831 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22832 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32833 // its final name before we can continue.
[email protected]d83d03aa2009-11-02 21:44:37834 ChromeThread::PostTask(
835 ChromeThread::FILE, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32836 NewRunnableMethod(
837 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
838 download->db_handle(),
839 download->full_path(), download->original_name()));
840 return;
841 }
842 ContinueDownloadFinished(download);
843}
844
[email protected]8f783752009-04-01 23:33:45845void DownloadManager::DownloadRenamedToFinalName(int download_id,
846 const FilePath& full_path) {
[email protected]8f783752009-04-01 23:33:45847}
848
[email protected]9ccbb372008-10-10 18:50:32849void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
850 // If this was a dangerous download, it has now been approved and must be
851 // removed from dangerous_finished_ so it does not get deleted on shutdown.
852 DownloadMap::iterator it = dangerous_finished_.find(download->id());
853 if (it != dangerous_finished_.end())
854 dangerous_finished_.erase(it);
855
[email protected]0aad67b2009-07-15 20:34:28856 // Handle chrome extensions explicitly and skip the shell execute.
[email protected]67f373a2009-09-22 02:44:51857 if (IsExtensionInstall(download)) {
[email protected]494c06e2009-07-25 01:06:42858 OpenChromeExtension(download->full_path(), download->url(),
859 download->referrer_url());
[email protected]0aad67b2009-07-15 20:34:28860 download->set_auto_opened(true);
861 } else if (download->open_when_complete() ||
[email protected]eccb9d12009-10-28 05:40:09862 ShouldOpenFileBasedOnExtension(download->full_path())) {
[email protected]9ccbb372008-10-10 18:50:32863 OpenDownloadInShell(download, NULL);
[email protected]0aad67b2009-07-15 20:34:28864 download->set_auto_opened(true);
865 }
[email protected]9ccbb372008-10-10 18:50:32866
[email protected]0aad67b2009-07-15 20:34:28867 // Notify our observers that we are complete (the call to Finished() set the
868 // state to complete but did not notify).
869 download->UpdateObservers();
870}
[email protected]eccb9d12009-10-28 05:40:09871
[email protected]9ccbb372008-10-10 18:50:32872// Called on the file thread. Renames the downloaded file to its original name.
873void DownloadManager::ProceedWithFinishedDangerousDownload(
874 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41875 const FilePath& path,
876 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32877 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41878 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16879 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32880 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24881 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16882 // Make our name unique at this point, as if a dangerous file is downloading
883 // and a 2nd download is started for a file with the same name, they would
884 // have the same path. This is because we uniquify the name on download
885 // start, and at that time the first file does not exists yet, so the second
886 // file gets the same name.
887 uniquifier = GetUniquePathNumber(new_path);
888 if (uniquifier > 0)
889 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32890 success = file_util::Move(path, new_path);
891 } else {
892 NOTREACHED();
893 }
[email protected]6cade212008-12-03 00:32:22894
[email protected]d83d03aa2009-11-02 21:44:37895 ChromeThread::PostTask(
896 ChromeThread::UI, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32897 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16898 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32899}
900
901// Call from the file thread when the finished dangerous download was renamed.
902void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
903 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41904 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16905 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32906 DownloadMap::iterator it = downloads_.find(download_handle);
907 if (it == downloads_.end()) {
908 NOTREACHED();
909 return;
910 }
911
912 DownloadItem* download = it->second;
913 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16914 if (success) {
915 // We need to update the path uniquifier so that the UI shows the right
916 // name when calling GetFileName().
917 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32918 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16919 }
[email protected]9ccbb372008-10-10 18:50:32920
921 // Continue the download finished sequence.
922 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29923}
924
925// static
initial.commit09911bf2008-07-26 23:55:29926void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
927 int render_process_id,
928 int request_id) {
[email protected]d85cf072009-10-27 03:59:31929 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
initial.commit09911bf2008-07-26 23:55:29930 rdh->CancelRequest(render_process_id, request_id, false);
931}
932
933void DownloadManager::DownloadCancelled(int32 download_id) {
934 DownloadMap::iterator it = in_progress_.find(download_id);
935 if (it == in_progress_.end())
936 return;
937 DownloadItem* download = it->second;
938
initial.commit09911bf2008-07-26 23:55:29939 // Clean up will happen when the history system create callback runs if we
940 // don't have a valid db_handle yet.
941 if (download->db_handle() != kUninitializedHandle) {
942 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:29943 UpdateHistoryForDownload(download);
944 }
945
[email protected]d7d1c5c2009-08-05 23:52:50946 DownloadCancelledInternal(download_id,
947 download->render_process_id(),
948 download->request_id());
949}
950
951void DownloadManager::DownloadCancelledInternal(int download_id,
952 int render_process_id,
953 int request_id) {
[email protected]d85cf072009-10-27 03:59:31954 // Cancel the network request. RDH is guaranteed to outlive the IO thread.
955 ChromeThread::PostTask(
956 ChromeThread::IO, FROM_HERE,
957 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
958 g_browser_process->resource_dispatcher_host(),
959 render_process_id,
960 request_id));
[email protected]d7d1c5c2009-08-05 23:52:50961
initial.commit09911bf2008-07-26 23:55:29962 // Tell the file manager to cancel the download.
[email protected]d7d1c5c2009-08-05 23:52:50963 file_manager_->RemoveDownload(download_id, this); // On the UI thread
[email protected]d83d03aa2009-11-02 21:44:37964 ChromeThread::PostTask(
965 ChromeThread::FILE, FROM_HERE,
966 NewRunnableMethod(
967 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:29968}
969
970void DownloadManager::PauseDownload(int32 download_id, bool pause) {
971 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]d85cf072009-10-27 03:59:31972 if (it == in_progress_.end())
973 return;
initial.commit09911bf2008-07-26 23:55:29974
[email protected]d85cf072009-10-27 03:59:31975 DownloadItem* download = it->second;
976 if (pause == download->is_paused())
977 return;
initial.commit09911bf2008-07-26 23:55:29978
[email protected]d85cf072009-10-27 03:59:31979 // Inform the ResourceDispatcherHost of the new pause state.
980 ChromeThread::PostTask(
981 ChromeThread::IO, FROM_HERE,
982 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
983 g_browser_process->resource_dispatcher_host(),
984 download->render_process_id(),
985 download->request_id(),
986 pause));
initial.commit09911bf2008-07-26 23:55:29987}
988
989// static
990void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
991 int render_process_id,
992 int request_id,
993 bool pause) {
994 rdh->PauseRequest(render_process_id, request_id, pause);
995}
996
[email protected]7ae7c2cb2009-01-06 23:31:41997bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:32998 // TODO(jcampan): Improve me.
[email protected]eccb9d12009-10-28 05:40:09999 return IsExecutableFile(file_name);
[email protected]9ccbb372008-10-10 18:50:321000}
1001
1002void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:411003 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:321004 download->Rename(new_path);
1005
1006 // Update the history.
1007
1008 // No update necessary if the download was initiated while in incognito mode.
1009 if (download->db_handle() <= kUninitializedHandle)
1010 return;
1011
[email protected]6cade212008-12-03 00:32:221012 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:321013 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1014 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:411015 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:321016}
1017
initial.commit09911bf2008-07-26 23:55:291018void DownloadManager::RemoveDownload(int64 download_handle) {
1019 DownloadMap::iterator it = downloads_.find(download_handle);
1020 if (it == downloads_.end())
1021 return;
1022
1023 // Make history update.
1024 DownloadItem* download = it->second;
1025 RemoveDownloadFromHistory(download);
1026
1027 // Remove from our tables and delete.
1028 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321029 it = dangerous_finished_.find(download->id());
1030 if (it != dangerous_finished_.end())
1031 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291032
1033 // Tell observers to refresh their views.
1034 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:361035
1036 delete download;
initial.commit09911bf2008-07-26 23:55:291037}
1038
[email protected]e93d2822009-01-30 05:59:591039int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1040 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291041 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1042
initial.commit09911bf2008-07-26 23:55:291043 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:281044 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:291045 while (it != downloads_.end()) {
1046 DownloadItem* download = it->second;
1047 DownloadItem::DownloadState state = download->state();
1048 if (download->start_time() >= remove_begin &&
1049 (remove_end.is_null() || download->start_time() < remove_end) &&
1050 (state == DownloadItem::COMPLETE ||
1051 state == DownloadItem::CANCELLED)) {
1052 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561053 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581054
1055 // Also remove it from any completed dangerous downloads.
1056 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1057 if (dit != dangerous_finished_.end())
1058 dangerous_finished_.erase(dit);
1059
[email protected]78b8fcc92009-03-31 17:36:281060 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:291061
initial.commit09911bf2008-07-26 23:55:291062 continue;
1063 }
1064
1065 ++it;
1066 }
1067
1068 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281069 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291070 if (num_deleted > 0)
1071 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1072
[email protected]78b8fcc92009-03-31 17:36:281073 // Delete the download items after updating the observers.
1074 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1075 pending_deletes.clear();
1076
initial.commit09911bf2008-07-26 23:55:291077 return num_deleted;
1078}
1079
[email protected]e93d2822009-01-30 05:59:591080int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1081 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291082}
1083
[email protected]d41355e6f2009-04-07 21:21:121084int DownloadManager::RemoveAllDownloads() {
1085 // The null times make the date range unbounded.
1086 return RemoveDownloadsBetween(base::Time(), base::Time());
1087}
1088
initial.commit09911bf2008-07-26 23:55:291089// Initiate a download of a specific URL. We send the request to the
1090// ResourceDispatcherHost, and let it send us responses like a regular
1091// download.
1092void DownloadManager::DownloadUrl(const GURL& url,
1093 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:501094 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:341095 TabContents* tab_contents) {
1096 DCHECK(tab_contents);
initial.commit09911bf2008-07-26 23:55:291097 file_manager_->DownloadUrl(url,
1098 referrer,
[email protected]be180c802009-10-23 06:33:311099 referrer_charset,
[email protected]76543b92009-08-31 17:27:451100 tab_contents->process()->id(),
[email protected]57c6a652009-05-04 07:58:341101 tab_contents->render_view_host()->routing_id(),
[email protected]be180c802009-10-23 06:33:311102 request_context_getter_);
initial.commit09911bf2008-07-26 23:55:291103}
1104
[email protected]7ae7c2cb2009-01-06 23:31:411105void DownloadManager::GenerateExtension(
1106 const FilePath& file_name,
1107 const std::string& mime_type,
1108 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291109 // We're worried about three things here:
1110 //
1111 // 1) Security. Many sites let users upload content, such as buddy icons, to
1112 // their web sites. We want to mitigate the case where an attacker
1113 // supplies a malicious executable with an executable file extension but an
1114 // honest site serves the content with a benign content type, such as
1115 // image/jpeg.
1116 //
1117 // 2) Usability. If the site fails to provide a file extension, we want to
1118 // guess a reasonable file extension based on the content type.
1119 //
1120 // 3) Shell integration. Some file extensions automatically integrate with
1121 // the shell. We block these extensions to prevent a malicious web site
1122 // from integrating with the user's shell.
1123
[email protected]7ae7c2cb2009-01-06 23:31:411124 static const FilePath::CharType default_extension[] =
1125 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291126
1127 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411128 FilePath::StringType extension(
1129 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291130
[email protected]b7f05882009-02-22 01:21:561131#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291132 // Rename shell-integrated extensions.
1133 if (win_util::IsShellIntegratedExtension(extension))
1134 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561135#endif
initial.commit09911bf2008-07-26 23:55:291136
1137 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411138 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411139 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291140 if (mime_type == mime_type_from_extension) {
1141 // The hinted extension matches the mime type. It looks like a winner.
1142 generated_extension->swap(extension);
1143 return;
1144 }
1145
[email protected]eccb9d12009-10-28 05:40:091146 if (IsExecutableExtension(extension) && !IsExecutableMimeType(mime_type)) {
initial.commit09911bf2008-07-26 23:55:291147 // We want to be careful about executable extensions. The worry here is
1148 // that a trusted web site could be tricked into dropping an executable file
1149 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101150 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291151 // We couldn't find a good extension for this content type. Use a dummy
1152 // extension instead.
1153 extension.assign(default_extension);
1154 }
1155 }
1156
1157 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101158 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291159 } else {
[email protected]6cade212008-12-03 00:32:221160 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291161 // 1. New extension is not ".txt"
1162 // 2. New extension is not the same as the already existing extension.
1163 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411164 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291165 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1166 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371167 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1168 // servers, i.e. bug 5772.
[email protected]e32642f62009-09-11 21:58:291169 // 5. The original extension is not ".tgz" & the new extension is not "gz".
[email protected]7ae7c2cb2009-01-06 23:31:411170 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101171 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171172 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411173 append_extension != extension &&
[email protected]eccb9d12009-10-28 05:40:091174 !IsExecutableExtension(append_extension) &&
[email protected]e32642f62009-09-11 21:58:291175 !(append_extension == FILE_PATH_LITERAL("gz") &&
1176 extension == FILE_PATH_LITERAL("tgz")) &&
[email protected]e106457b2009-03-25 22:43:371177 (append_extension != FILE_PATH_LITERAL("tar") ||
1178 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171179 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291180 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171181 }
initial.commit09911bf2008-07-26 23:55:291182 }
1183 }
1184
1185 generated_extension->swap(extension);
1186}
1187
1188void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411189 FilePath* generated_name) {
[email protected]630947c2009-11-04 18:37:311190 std::wstring default_name =
1191 l10n_util::GetString(IDS_DEFAULT_DOWNLOAD_FILENAME);
1192#if defined(OS_WIN)
1193 FilePath default_file_path(default_name);
1194#elif defined(OS_POSIX)
1195 FilePath default_file_path(base::SysWideToNativeMB(default_name));
1196#endif
1197
[email protected]de2943352009-10-22 23:06:121198 *generated_name = net::GetSuggestedFilename(GURL(info->url),
1199 info->content_disposition,
1200 info->referrer_charset,
[email protected]630947c2009-11-04 18:37:311201 default_file_path);
1202
[email protected]7ae7c2cb2009-01-06 23:31:411203 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291204
[email protected]7ae7c2cb2009-01-06 23:31:411205 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291206}
1207
1208void DownloadManager::AddObserver(Observer* observer) {
1209 observers_.AddObserver(observer);
1210 observer->ModelChanged();
1211}
1212
1213void DownloadManager::RemoveObserver(Observer* observer) {
1214 observers_.RemoveObserver(observer);
1215}
1216
1217// Post Windows Shell operations to the Download thread, to avoid blocking the
1218// user interface.
1219void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1220 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:371221 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:581222#if defined(OS_MACOSX)
1223 // Mac needs to run this operation on the UI thread.
1224 platform_util::ShowItemInFolder(download->full_path());
1225#else
[email protected]d83d03aa2009-11-02 21:44:371226 ChromeThread::PostTask(
1227 ChromeThread::FILE, FROM_HERE,
1228 NewRunnableMethod(
1229 file_manager_, &DownloadFileManager::OnShowDownloadInShell,
1230 FilePath(download->full_path())));
[email protected]8b6ff012009-08-18 22:29:581231#endif
initial.commit09911bf2008-07-26 23:55:291232}
1233
[email protected]8f783752009-04-01 23:33:451234void DownloadManager::OpenDownload(const DownloadItem* download,
1235 gfx::NativeView parent_window) {
[email protected]0e34d7892009-06-05 19:17:401236 // Open Chrome extensions with ExtensionsService. For everything else do shell
[email protected]8f783752009-04-01 23:33:451237 // execute.
[email protected]67f373a2009-09-22 02:44:511238 if (IsExtensionInstall(download)) {
[email protected]494c06e2009-07-25 01:06:421239 OpenChromeExtension(download->full_path(), download->url(),
1240 download->referrer_url());
[email protected]8f783752009-04-01 23:33:451241 } else {
1242 OpenDownloadInShell(download, parent_window);
1243 }
1244}
1245
[email protected]c1e432a2009-07-22 21:21:481246void DownloadManager::OpenChromeExtension(const FilePath& full_path,
[email protected]494c06e2009-07-25 01:06:421247 const GURL& download_url,
1248 const GURL& referrer_url) {
[email protected]6ef635e42009-07-26 06:16:121249 // We don't support extensions in OTR mode.
[email protected]2a464a92009-08-01 17:58:351250 ExtensionsService* service = profile_->GetExtensionsService();
1251 if (service) {
[email protected]91e1bd82009-09-03 22:04:401252 NotificationService* nservice = NotificationService::current();
1253 nservice->Notify(NotificationType::EXTENSION_READY_FOR_INSTALL,
1254 Source<DownloadManager>(this),
1255 NotificationService::NoDetails());
[email protected]6657afa62009-11-04 02:15:201256 if (UserScript::HasUserScriptFileExtension(full_path)) {
1257 CrxInstaller::InstallUserScript(
1258 full_path,
1259 download_url,
1260 service->install_directory(),
1261 true, // please delete crx on completion
1262 service,
1263 new ExtensionInstallUI(profile_));
1264 } else {
1265 CrxInstaller::Start(
1266 full_path,
1267 service->install_directory(),
1268 Extension::INTERNAL,
1269 "", // no expected id
1270 true, // please delete crx on completion
1271 true, // privilege increase allowed
1272 service,
1273 new ExtensionInstallUI(profile_));
1274 }
[email protected]2a464a92009-08-01 17:58:351275 }
[email protected]8f783752009-04-01 23:33:451276}
1277
initial.commit09911bf2008-07-26 23:55:291278void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591279 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291280 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:371281 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:581282#if defined(OS_MACOSX)
1283 // Mac OS X requires opening downloads on the UI thread.
1284 platform_util::OpenItem(download->full_path());
1285#else
[email protected]d83d03aa2009-11-02 21:44:371286 ChromeThread::PostTask(
1287 ChromeThread::FILE, FROM_HERE,
1288 NewRunnableMethod(
1289 file_manager_, &DownloadFileManager::OnOpenDownloadInShell,
1290 download->full_path(), download->url(), parent_window));
[email protected]8b6ff012009-08-18 22:29:581291#endif
initial.commit09911bf2008-07-26 23:55:291292}
1293
[email protected]eccb9d12009-10-28 05:40:091294void DownloadManager::OpenFilesBasedOnExtension(
1295 const FilePath& path, bool open) {
1296 FilePath::StringType extension = path.Extension();
1297 if (extension.empty())
1298 return;
1299 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1300 extension.erase(0, 1);
1301 if (open && !IsExecutableExtension(extension))
initial.commit09911bf2008-07-26 23:55:291302 auto_open_.insert(extension);
1303 else
1304 auto_open_.erase(extension);
1305 SaveAutoOpens();
1306}
1307
[email protected]eccb9d12009-10-28 05:40:091308bool DownloadManager::ShouldOpenFileBasedOnExtension(
1309 const FilePath& path) const {
[email protected]8c756ac2009-01-30 23:36:411310 // Special-case Chrome extensions as always-open.
[email protected]eccb9d12009-10-28 05:40:091311 FilePath::StringType extension = path.Extension();
1312 if (extension.empty())
1313 return false;
1314 if (IsExecutableExtension(extension))
1315 return false;
1316 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1317 extension.erase(0, 1);
1318 if (auto_open_.find(extension) != auto_open_.end() ||
1319 Extension::IsExtension(path))
[email protected]8c756ac2009-01-30 23:36:411320 return true;
initial.commit09911bf2008-07-26 23:55:291321 return false;
1322}
1323
[email protected]7b73d992008-12-15 20:56:461324static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291325 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461326 "text/javascript",
1327 "text/javascript;version=*",
[email protected]54d8d452009-04-08 17:29:241328 // Registry files can cause critical changes to the MS OS behavior.
1329 // Addition of this mimetype also addresses bug 7337.
1330 "text/x-registry",
[email protected]60ff8f912008-12-05 07:58:391331 // Some sites use binary/octet-stream to mean application/octet-stream.
1332 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461333 "binary/octet-stream"
1334};
initial.commit09911bf2008-07-26 23:55:291335
[email protected]7b73d992008-12-15 20:56:461336static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291337 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461338 "application/*+xml",
1339 "application/xml"
1340};
initial.commit09911bf2008-07-26 23:55:291341
[email protected]7b73d992008-12-15 20:56:461342// static
1343bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411344 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461345 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1346 return true;
1347 }
[email protected]bae0ea12009-02-14 01:20:411348 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461349 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1350 return false;
1351 }
1352 // We consider only other application types to be executable.
1353 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291354}
1355
[email protected]eccb9d12009-10-28 05:40:091356bool DownloadManager::IsExecutableFile(const FilePath& path) const {
1357 return IsExecutableExtension(path.Extension());
1358}
1359
1360bool DownloadManager::IsExecutableExtension(
1361 const FilePath::StringType& extension) const {
1362 if (extension.empty())
1363 return false;
[email protected]64da0b932009-02-24 02:30:041364 if (!IsStringASCII(extension))
1365 return false;
[email protected]a0a9577b2009-05-27 23:52:321366#if defined(OS_WIN)
[email protected]64da0b932009-02-24 02:30:041367 std::string ascii_extension = WideToASCII(extension);
[email protected]e9ef0a62009-08-11 22:50:131368#elif defined(OS_POSIX)
[email protected]a0a9577b2009-05-27 23:52:321369 std::string ascii_extension = extension;
1370#endif
[email protected]64da0b932009-02-24 02:30:041371 StringToLowerASCII(&ascii_extension);
1372
[email protected]eccb9d12009-10-28 05:40:091373 // Strip out leading dot if it's still there
1374 if (ascii_extension[0] == FilePath::kExtensionSeparator)
1375 ascii_extension.erase(0, 1);
1376
[email protected]64da0b932009-02-24 02:30:041377 return exe_types_.find(ascii_extension) != exe_types_.end();
initial.commit09911bf2008-07-26 23:55:291378}
1379
1380void DownloadManager::ResetAutoOpenFiles() {
1381 auto_open_.clear();
1382 SaveAutoOpens();
1383}
1384
1385bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1386 return !auto_open_.empty();
1387}
1388
1389void DownloadManager::SaveAutoOpens() {
1390 PrefService* prefs = profile_->GetPrefs();
1391 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411392 FilePath::StringType extensions;
[email protected]eccb9d12009-10-28 05:40:091393 for (AutoOpenSet::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291394 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411395 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291396 }
1397 if (!extensions.empty())
1398 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561399
1400 std::wstring extensions_w;
1401#if defined(OS_WIN)
1402 extensions_w = extensions;
1403#elif defined(OS_POSIX)
[email protected]1b5044d2009-02-24 00:04:141404 extensions_w = base::SysNativeMBToWide(extensions);
[email protected]b7f05882009-02-22 01:21:561405#endif
1406
1407 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291408 }
1409}
1410
[email protected]561abe62009-04-06 18:08:341411void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361412 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291413 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071414 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411415 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291416 ContinueStartDownload(info, path);
1417}
1418
1419void DownloadManager::FileSelectionCanceled(void* params) {
1420 // The user didn't pick a place to save the file, so need to cancel the
1421 // download that's already in progress to the temporary location.
1422 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]d7d1c5c2009-08-05 23:52:501423 DownloadCancelledInternal(info->download_id,
[email protected]76543b92009-08-31 17:27:451424 info->child_id,
[email protected]d7d1c5c2009-08-05 23:52:501425 info->request_id);
initial.commit09911bf2008-07-26 23:55:291426}
1427
[email protected]7ae7c2cb2009-01-06 23:31:411428void DownloadManager::DeleteDownload(const FilePath& path) {
[email protected]d83d03aa2009-11-02 21:44:371429 ChromeThread::PostTask(
1430 ChromeThread::FILE, FROM_HERE,
1431 NewRunnableFunction(&DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321432}
1433
1434
1435void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1436 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1437 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1438 download->UpdateObservers();
1439
1440 // If the download is not complete, nothing to do. The required
1441 // post-processing will be performed when it does complete.
1442 if (download->state() != DownloadItem::COMPLETE)
1443 return;
1444
[email protected]d83d03aa2009-11-02 21:44:371445 ChromeThread::PostTask(
1446 ChromeThread::FILE, FROM_HERE,
1447 NewRunnableMethod(
1448 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
1449 download->db_handle(), download->full_path(),
1450 download->original_name()));
[email protected]9ccbb372008-10-10 18:50:321451}
1452
[email protected]763f946a2009-01-06 19:04:391453void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411454 FilePath* file_name) {
1455 // Make sure we get the right file extension
1456 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391457 GenerateExtension(*file_name, mime_type, &extension);
1458 file_util::ReplaceExtension(file_name, extension);
1459
[email protected]2b2f8f72009-02-24 22:42:051460#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391461 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411462 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391463 DCHECK(!leaf_name.empty());
1464 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411465 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1466 *file_name = file_name->DirName();
1467 if (file_name->value() == FilePath::kCurrentDirectory) {
1468 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391469 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411470 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391471 }
1472 }
[email protected]b7f05882009-02-22 01:21:561473#endif
[email protected]763f946a2009-01-06 19:04:391474}
1475
[email protected]f1b11d32009-10-09 22:51:391476bool DownloadManager::IsExtensionInstall(const DownloadItem* item) {
[email protected]6657afa62009-11-04 02:15:201477 if (item->save_as())
1478 return false;
1479
1480 if (UserScript::HasUserScriptFileExtension(item->original_name()))
1481 return true;
1482
1483 return item->mime_type() == Extension::kMimeType;
[email protected]f1b11d32009-10-09 22:51:391484}
1485
1486bool DownloadManager::IsExtensionInstall(const DownloadCreateInfo* info) {
[email protected]6657afa62009-11-04 02:15:201487 if (info->save_as)
1488 return false;
1489
1490 if (UserScript::HasUserScriptFileExtension(info->path))
1491 return true;
1492
1493 return info->mime_type == Extension::kMimeType;
[email protected]f1b11d32009-10-09 22:51:391494}
1495
initial.commit09911bf2008-07-26 23:55:291496// Operations posted to us from the history service ----------------------------
1497
1498// The history service has retrieved all download entries. 'entries' contains
1499// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1500void DownloadManager::OnQueryDownloadEntriesComplete(
1501 std::vector<DownloadCreateInfo>* entries) {
1502 for (size_t i = 0; i < entries->size(); ++i) {
1503 DownloadItem* download = new DownloadItem(entries->at(i));
1504 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1505 downloads_[download->db_handle()] = download;
1506 download->set_manager(this);
1507 }
1508 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1509}
1510
initial.commit09911bf2008-07-26 23:55:291511// Once the new DownloadItem's creation info has been committed to the history
1512// service, we associate the DownloadItem with the db handle, update our
1513// 'downloads_' map and inform observers.
1514void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1515 int64 db_handle) {
1516 DownloadMap::iterator it = in_progress_.find(info.download_id);
1517 DCHECK(it != in_progress_.end());
1518
1519 DownloadItem* download = it->second;
1520 DCHECK(download->db_handle() == kUninitializedHandle);
1521 download->set_db_handle(db_handle);
1522
1523 // Insert into our full map.
1524 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1525 downloads_[download->db_handle()] = download;
1526
[email protected]5e595482009-05-06 20:16:531527 // Show in the appropropriate browser UI.
1528 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291529
1530 // Inform interested objects about the new download.
1531 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
initial.commit09911bf2008-07-26 23:55:291532
1533 // If this download has been completed before we've received the db handle,
1534 // post one final message to the history service so that it can be properly
1535 // in sync with the DownloadItem's completion status, and also inform any
1536 // observers so that they get more than just the start notification.
1537 if (download->state() != DownloadItem::IN_PROGRESS) {
1538 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291539 UpdateHistoryForDownload(download);
1540 download->UpdateObservers();
1541 }
1542}
1543
1544// Called when the history service has retrieved the list of downloads that
1545// match the search text.
1546void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1547 std::vector<int64>* results) {
1548 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1549 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1550 if (!requestor)
1551 return;
1552
1553 std::vector<DownloadItem*> searched_downloads;
1554 for (std::vector<int64>::iterator it = results->begin();
1555 it != results->end(); ++it) {
1556 DownloadMap::iterator dit = downloads_.find(*it);
1557 if (dit != downloads_.end())
1558 searched_downloads.push_back(dit->second);
1559 }
1560
1561 requestor->SetDownloads(searched_downloads);
1562}
[email protected]905a08d2008-11-19 07:24:121563
[email protected]5e595482009-05-06 20:16:531564void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1565 DownloadItem* download) {
[email protected]5e595482009-05-06 20:16:531566 // The 'contents' may no longer exist if the user closed the tab before we get
1567 // this start completion event. If it does, tell the origin TabContents to
1568 // display its download shelf.
[email protected]76543b92009-08-31 17:27:451569 TabContents* contents = tab_util::GetTabContentsByID(info.child_id,
1570 info.render_view_id);
[email protected]5e595482009-05-06 20:16:531571
1572 // If the contents no longer exists, we start the download in the last active
1573 // browser. This is not ideal but better than fully hiding the download from
1574 // the user.
1575 if (!contents) {
1576 Browser* last_active = BrowserList::GetLastActive();
1577 if (last_active)
1578 contents = last_active->GetSelectedTabContents();
1579 }
1580
1581 if (contents)
1582 contents->OnStartDownload(download);
1583}
1584
[email protected]6cade212008-12-03 00:32:221585// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121586void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411587 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381588}
1589