blob: f0cdb973c4e94bfcbb2d2819adf261be81794195 [file] [log] [blame]
[email protected]d41355e6f2009-04-07 21:21:121// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]cdaa8652008-09-13 02:48:595#include "chrome/browser/download/download_manager.h"
initial.commit09911bf2008-07-26 23:55:296
[email protected]a92b8642009-05-05 23:38:567#include "app/l10n_util.h"
initial.commit09911bf2008-07-26 23:55:298#include "base/file_util.h"
9#include "base/logging.h"
10#include "base/message_loop.h"
11#include "base/path_service.h"
[email protected]1b5044d2009-02-24 00:04:1412#include "base/rand_util.h"
[email protected]807204142009-05-05 03:31:4413#include "base/stl_util-inl.h"
initial.commit09911bf2008-07-26 23:55:2914#include "base/string_util.h"
[email protected]1b5044d2009-02-24 00:04:1415#include "base/sys_string_conversions.h"
initial.commit09911bf2008-07-26 23:55:2916#include "base/task.h"
17#include "base/thread.h"
18#include "base/timer.h"
initial.commit09911bf2008-07-26 23:55:2919#include "chrome/browser/browser_list.h"
20#include "chrome/browser/browser_process.h"
[email protected]cdaa8652008-09-13 02:48:5921#include "chrome/browser/download/download_file.h"
[email protected]e9ef0a62009-08-11 22:50:1322#include "chrome/browser/download/download_util.h"
[email protected]866930682009-08-18 22:53:4723#include "chrome/browser/extensions/crx_installer.h"
[email protected]2a464a92009-08-01 17:58:3524#include "chrome/browser/extensions/extension_install_ui.h"
[email protected]8f783752009-04-01 23:33:4525#include "chrome/browser/extensions/extensions_service.h"
initial.commit09911bf2008-07-26 23:55:2926#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:2627#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2528#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]e3c404b2008-12-23 01:07:3229#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
[email protected]f3ec7742009-01-15 00:59:1630#include "chrome/browser/tab_contents/tab_util.h"
[email protected]57c6a652009-05-04 07:58:3431#include "chrome/browser/tab_contents/tab_contents.h"
[email protected]4a0380c2009-07-26 07:25:3232#include "chrome/common/chrome_constants.h"
initial.commit09911bf2008-07-26 23:55:2933#include "chrome/common/chrome_paths.h"
[email protected]5b1a0e22009-05-26 19:00:5834#include "chrome/common/extensions/extension.h"
[email protected]91e1bd82009-09-03 22:04:4035#include "chrome/common/notification_service.h"
36#include "chrome/common/notification_type.h"
[email protected]076700e62009-04-01 18:41:2337#include "chrome/common/platform_util.h"
initial.commit09911bf2008-07-26 23:55:2938#include "chrome/common/pref_names.h"
39#include "chrome/common/pref_service.h"
[email protected]46072d42008-07-28 14:49:3540#include "googleurl/src/gurl.h"
[email protected]d81706b82009-04-03 20:28:4441#include "grit/chromium_strings.h"
[email protected]34ac8f32009-02-22 23:03:2742#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2943#include "net/base/mime_util.h"
44#include "net/base/net_util.h"
45#include "net/url_request/url_request_context.h"
46
[email protected]b7f05882009-02-22 01:21:5647#if defined(OS_WIN)
[email protected]4a0765a2009-05-08 23:12:2548#include "app/win_util.h"
[email protected]b7f05882009-02-22 01:21:5649#include "base/registry.h"
50#include "base/win_util.h"
[email protected]a0a9577b2009-05-27 23:52:3251#endif
52
[email protected]0f44d3e2009-03-12 23:36:3053#if defined(OS_LINUX)
54#include <gtk/gtk.h>
55#endif
56
initial.commit09911bf2008-07-26 23:55:2957// Periodically update our observers.
58class DownloadItemUpdateTask : public Task {
59 public:
60 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
61 void Run() { if (item_) item_->UpdateObservers(); }
62
63 private:
64 DownloadItem* item_;
65};
66
67// Update frequency (milliseconds).
68static const int kUpdateTimeMs = 1000;
69
70// Our download table ID starts at 1, so we use 0 to represent a download that
71// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2272// database handles in incognito mode starting at -1 and progressively getting
73// more negative.
initial.commit09911bf2008-07-26 23:55:2974static const int kUninitializedHandle = 0;
75
[email protected]7a256ea2008-10-17 17:34:1676// Appends the passed the number between parenthesis the path before the
77// extension.
[email protected]7ae7c2cb2009-01-06 23:31:4178static void AppendNumberToPath(FilePath* path, int number) {
79 file_util::InsertBeforeExtension(path,
80 StringPrintf(FILE_PATH_LITERAL(" (%d)"), number));
[email protected]7a256ea2008-10-17 17:34:1681}
82
83// Attempts to find a number that can be appended to that path to make it
84// unique. If |path| does not exist, 0 is returned. If it fails to find such
85// a number, -1 is returned.
[email protected]7ae7c2cb2009-01-06 23:31:4186static int GetUniquePathNumber(const FilePath& path) {
initial.commit09911bf2008-07-26 23:55:2987 const int kMaxAttempts = 100;
88
[email protected]7a256ea2008-10-17 17:34:1689 if (!file_util::PathExists(path))
90 return 0;
initial.commit09911bf2008-07-26 23:55:2991
[email protected]7ae7c2cb2009-01-06 23:31:4192 FilePath new_path;
initial.commit09911bf2008-07-26 23:55:2993 for (int count = 1; count <= kMaxAttempts; ++count) {
[email protected]7ae7c2cb2009-01-06 23:31:4194 new_path = FilePath(path);
[email protected]7a256ea2008-10-17 17:34:1695 AppendNumberToPath(&new_path, count);
initial.commit09911bf2008-07-26 23:55:2996
[email protected]7a256ea2008-10-17 17:34:1697 if (!file_util::PathExists(new_path))
98 return count;
initial.commit09911bf2008-07-26 23:55:2999 }
100
[email protected]7a256ea2008-10-17 17:34:16101 return -1;
initial.commit09911bf2008-07-26 23:55:29102}
103
[email protected]7ae7c2cb2009-01-06 23:31:41104static bool DownloadPathIsDangerous(const FilePath& download_path) {
105 FilePath desktop_dir;
[email protected]f052118e2008-09-05 02:25:32106 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
107 NOTREACHED();
108 return false;
109 }
110 return (download_path == desktop_dir);
111}
112
initial.commit09911bf2008-07-26 23:55:29113// DownloadItem implementation -------------------------------------------------
114
115// Constructor for reading from the history service.
116DownloadItem::DownloadItem(const DownloadCreateInfo& info)
117 : id_(-1),
118 full_path_(info.path),
119 url_(info.url),
[email protected]e435d6b72009-07-25 03:15:58120 referrer_url_(info.referrer_url),
121 mime_type_(info.mime_type),
initial.commit09911bf2008-07-26 23:55:29122 total_bytes_(info.total_bytes),
123 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56124 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29125 state_(static_cast<DownloadState>(info.state)),
126 start_time_(info.start_time),
127 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29128 manager_(NULL),
129 is_paused_(false),
130 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56131 safety_state_(SAFE),
[email protected]0aad67b2009-07-15 20:34:28132 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56133 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29134 render_process_id_(-1),
135 request_id_(-1) {
136 if (state_ == IN_PROGRESS)
137 state_ = CANCELLED;
138 Init(false /* don't start progress timer */);
139}
140
141// Constructor for DownloadItem created via user action in the main thread.
142DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41143 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16144 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32145 const GURL& url,
[email protected]494c06e2009-07-25 01:06:42146 const GURL& referrer_url,
[email protected]e435d6b72009-07-25 03:15:58147 const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:41148 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59149 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29150 int64 download_size,
151 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32152 int request_id,
[email protected]67f373a2009-09-22 02:44:51153 bool is_dangerous,
154 bool save_as)
initial.commit09911bf2008-07-26 23:55:29155 : id_(download_id),
156 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16157 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29158 url_(url),
[email protected]494c06e2009-07-25 01:06:42159 referrer_url_(referrer_url),
[email protected]e435d6b72009-07-25 03:15:58160 mime_type_(mime_type),
initial.commit09911bf2008-07-26 23:55:29161 total_bytes_(download_size),
162 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56163 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29164 state_(IN_PROGRESS),
165 start_time_(start_time),
166 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29167 manager_(NULL),
168 is_paused_(false),
169 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56170 safety_state_(is_dangerous ? DANGEROUS : SAFE),
[email protected]0aad67b2009-07-15 20:34:28171 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56172 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29173 render_process_id_(render_process_id),
[email protected]67f373a2009-09-22 02:44:51174 request_id_(request_id),
175 save_as_(save_as) {
initial.commit09911bf2008-07-26 23:55:29176 Init(true /* start progress timer */);
177}
178
179void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41180 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29181 if (start_timer)
182 StartProgressTimer();
183}
184
185DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29186 state_ = REMOVING;
187 UpdateObservers();
188}
189
190void DownloadItem::AddObserver(Observer* observer) {
191 observers_.AddObserver(observer);
192}
193
194void DownloadItem::RemoveObserver(Observer* observer) {
195 observers_.RemoveObserver(observer);
196}
197
198void DownloadItem::UpdateObservers() {
199 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
200}
201
[email protected]45e3c122009-04-07 19:58:03202void DownloadItem::NotifyObserversDownloadOpened() {
203 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadOpened(this));
204}
205
initial.commit09911bf2008-07-26 23:55:29206// If we've received more data than we were expecting (bad server info?), revert
207// to 'unknown size mode'.
208void DownloadItem::UpdateSize(int64 bytes_so_far) {
209 received_bytes_ = bytes_so_far;
210 if (received_bytes_ > total_bytes_)
211 total_bytes_ = 0;
212}
213
214// Updates from the download thread may have been posted while this download
215// was being cancelled in the UI thread, so we'll accept them unless we're
216// complete.
217void DownloadItem::Update(int64 bytes_so_far) {
218 if (state_ == COMPLETE) {
219 NOTREACHED();
220 return;
221 }
222 UpdateSize(bytes_so_far);
223 UpdateObservers();
224}
225
[email protected]6cade212008-12-03 00:32:22226// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29227void DownloadItem::Cancel(bool update_history) {
228 if (state_ != IN_PROGRESS) {
229 // Small downloads might be complete before this method has a chance to run.
230 return;
231 }
232 state_ = CANCELLED;
233 UpdateObservers();
234 StopProgressTimer();
235 if (update_history)
236 manager_->DownloadCancelled(id_);
237}
238
239void DownloadItem::Finished(int64 size) {
240 state_ = COMPLETE;
241 UpdateSize(size);
[email protected]22fbe5a2008-10-29 22:20:40242 UpdateObservers();
initial.commit09911bf2008-07-26 23:55:29243 StopProgressTimer();
244}
245
[email protected]9ccbb372008-10-10 18:50:32246void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29247 Cancel(true);
248 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32249 if (delete_on_disk)
250 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29251 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22252 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29253}
254
255void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59256 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14257 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29258}
259
260void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14261 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29262}
263
[email protected]e93d2822009-01-30 05:59:59264bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29265 if (total_bytes_ <= 0)
266 return false; // We never received the content_length for this download.
267
268 int64 speed = CurrentSpeed();
269 if (speed == 0)
270 return false;
271
272 *remaining =
[email protected]e93d2822009-01-30 05:59:59273 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29274 return true;
275}
276
277int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56278 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
279 int64 diff_ms = diff.InMilliseconds();
280 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29281}
282
283int DownloadItem::PercentComplete() const {
284 int percent = -1;
285 if (total_bytes_ > 0)
286 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
287 return percent;
288}
289
[email protected]7ae7c2cb2009-01-06 23:31:41290void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29291 DCHECK(!full_path.empty());
292 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41293 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29294}
295
296void DownloadItem::TogglePause() {
297 DCHECK(state_ == IN_PROGRESS);
298 manager_->PauseDownload(id_, !is_paused_);
299 is_paused_ = !is_paused_;
300 UpdateObservers();
301}
302
[email protected]7ae7c2cb2009-01-06 23:31:41303FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32304 if (safety_state_ == DownloadItem::SAFE)
305 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16306 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41307 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16308 AppendNumberToPath(&name, path_uniquifier_);
309 return name;
310 }
[email protected]9ccbb372008-10-10 18:50:32311 return original_name_;
312}
313
initial.commit09911bf2008-07-26 23:55:29314// DownloadManager implementation ----------------------------------------------
315
316// static
317void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
318 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
319 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32320 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
321
322 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41323 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12324 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
325 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32326 NOTREACHED();
327 }
[email protected]b9636002009-03-04 00:05:25328 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
329 default_download_path);
[email protected]f052118e2008-09-05 02:25:32330
331 // If the download path is dangerous we forcefully reset it. But if we do
332 // so we set a flag to make sure we only do it once, to avoid fighting
333 // the user if he really wants it on an unsafe place such as the desktop.
334
335 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41336 FilePath current_download_dir = FilePath::FromWStringHack(
337 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32338 if (DownloadPathIsDangerous(current_download_dir)) {
339 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41340 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32341 }
342 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
343 }
initial.commit09911bf2008-07-26 23:55:29344}
345
346DownloadManager::DownloadManager()
347 : shutdown_needed_(false),
348 profile_(NULL),
349 file_manager_(NULL),
350 ui_loop_(MessageLoop::current()),
351 file_loop_(NULL) {
352}
353
354DownloadManager::~DownloadManager() {
355 if (shutdown_needed_)
356 Shutdown();
357}
358
359void DownloadManager::Shutdown() {
360 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
361
362 // Stop receiving download updates
363 file_manager_->RemoveDownloadManager(this);
364
365 // Stop making history service requests
366 cancelable_consumer_.CancelAllRequests();
367
368 // 'in_progress_' may contain DownloadItems that have not finished the start
369 // complete (from the history service) and thus aren't in downloads_.
370 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32371 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29372 for (; it != in_progress_.end(); ++it) {
373 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32374 if (download->safety_state() == DownloadItem::DANGEROUS) {
375 // Forget about any download that the user did not approve.
376 // Note that we cannot call download->Remove() this would invalidate our
377 // iterator.
378 to_remove.insert(download);
379 continue;
initial.commit09911bf2008-07-26 23:55:29380 }
[email protected]9ccbb372008-10-10 18:50:32381 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
382 download->Cancel(false);
383 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29384 if (download->db_handle() == kUninitializedHandle) {
385 // An invalid handle means that 'download' does not yet exist in
386 // 'downloads_', so we have to delete it here.
387 delete download;
388 }
389 }
390
[email protected]9ccbb372008-10-10 18:50:32391 // 'dangerous_finished_' contains all complete downloads that have not been
392 // approved. They should be removed.
393 it = dangerous_finished_.begin();
394 for (; it != dangerous_finished_.end(); ++it)
395 to_remove.insert(it->second);
396
397 // Remove the dangerous download that are not approved.
398 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
399 rm_it != to_remove.end(); ++rm_it) {
400 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32401 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32402 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32403 // Same as above, delete the download if it is not in 'downloads_' (as the
404 // Remove() call above won't have deleted it).
405 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32406 delete download;
407 }
408 to_remove.clear();
409
initial.commit09911bf2008-07-26 23:55:29410 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32411 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29412 STLDeleteValues(&downloads_);
413
414 file_manager_ = NULL;
415
416 // Save our file extensions to auto open.
417 SaveAutoOpens();
418
419 // Make sure the save as dialog doesn't notify us back if we're gone before
420 // it returns.
421 if (select_file_dialog_.get())
422 select_file_dialog_->ListenerDestroyed();
423
424 shutdown_needed_ = false;
425}
426
427// Issue a history query for downloads matching 'search_text'. If 'search_text'
428// is empty, return all downloads that we know about.
429void DownloadManager::GetDownloads(Observer* observer,
430 const std::wstring& search_text) {
431 DCHECK(observer);
432
433 // Return a empty list if we've not yet received the set of downloads from the
434 // history system (we'll update all observers once we get that list in
435 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
436 std::vector<DownloadItem*> download_copy;
437 if (downloads_.empty()) {
438 observer->SetDownloads(download_copy);
439 return;
440 }
441
442 // We already know all the downloads and there is no filter, so just return a
443 // copy to the observer.
444 if (search_text.empty()) {
445 download_copy.reserve(downloads_.size());
446 for (DownloadMap::iterator it = downloads_.begin();
447 it != downloads_.end(); ++it) {
[email protected]67f373a2009-09-22 02:44:51448 if (it->second->db_handle() > kUninitializedHandle)
449 download_copy.push_back(it->second);
initial.commit09911bf2008-07-26 23:55:29450 }
451
452 // We retain ownership of the DownloadItems.
453 observer->SetDownloads(download_copy);
454 return;
455 }
456
457 // Issue a request to the history service for a list of downloads matching
458 // our search text.
459 HistoryService* hs =
460 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
461 if (hs) {
462 HistoryService::Handle h =
463 hs->SearchDownloads(search_text,
464 &cancelable_consumer_,
465 NewCallback(this,
466 &DownloadManager::OnSearchComplete));
467 cancelable_consumer_.SetClientData(hs, h, observer);
468 }
469}
470
471// Query the history service for information about all persisted downloads.
472bool DownloadManager::Init(Profile* profile) {
473 DCHECK(profile);
474 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
475 shutdown_needed_ = true;
476
477 profile_ = profile;
478 request_context_ = profile_->GetRequestContext();
479
480 // 'incognito mode' will have access to past downloads, but we won't store
481 // information about new downloads while in that mode.
482 QueryHistoryForDownloads();
483
484 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
485 if (!rdh) {
486 NOTREACHED();
487 return false;
488 }
489
490 file_manager_ = rdh->download_file_manager();
491 if (!file_manager_) {
492 NOTREACHED();
493 return false;
494 }
495
496 file_loop_ = g_browser_process->file_thread()->message_loop();
497 if (!file_loop_) {
498 NOTREACHED();
499 return false;
500 }
501
502 // Get our user preference state.
503 PrefService* prefs = profile_->GetPrefs();
504 DCHECK(prefs);
505 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
506
initial.commit09911bf2008-07-26 23:55:29507 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
508
[email protected]7ae7c2cb2009-01-06 23:31:41509 // This variable is needed to resolve which CreateDirectory we want to point
510 // to. Without it, the NewRunnableFunction cannot resolve the ambiguity.
511 // TODO(estade): when file_util::CreateDirectory(wstring) is removed,
512 // get rid of |CreateDirectoryPtr|.
513 bool (*CreateDirectoryPtr)(const FilePath&) = &file_util::CreateDirectory;
[email protected]bb69e9b32008-08-14 23:08:14514 // Ensure that the download directory specified in the preferences exists.
[email protected]7ae7c2cb2009-01-06 23:31:41515 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
516 CreateDirectoryPtr, download_path()));
initial.commit09911bf2008-07-26 23:55:29517
[email protected]a0a9577b2009-05-27 23:52:32518 // We use this to determine possibly dangerous downloads.
[email protected]2b2f8f72009-02-24 22:42:05519 download_util::InitializeExeTypes(&exe_types_);
[email protected]2b2f8f72009-02-24 22:42:05520
521 // We store any file extension that should be opened automatically at
522 // download completion in this pref.
initial.commit09911bf2008-07-26 23:55:29523 std::wstring extensions_to_open =
524 prefs->GetString(prefs::kDownloadExtensionsToOpen);
525 std::vector<std::wstring> extensions;
526 SplitString(extensions_to_open, L':', &extensions);
527 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]b7f05882009-02-22 01:21:56528 if (!extensions[i].empty() && !IsExecutable(
529 FilePath::FromWStringHack(extensions[i]).value()))
530 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29531 }
532
533 return true;
534}
535
536void DownloadManager::QueryHistoryForDownloads() {
537 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
538 if (hs) {
539 hs->QueryDownloads(
540 &cancelable_consumer_,
541 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
542 }
543}
544
545// We have received a message from DownloadFileManager about a new download. We
546// create a download item and store it in our download map, and inform the
547// history system of a new download. Since this method can be called while the
548// history service thread is still reading the persistent state, we do not
549// insert the new DownloadItem into 'downloads_' or inform our observers at this
550// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
551// download creation as a callback from the history thread.
552void DownloadManager::StartDownload(DownloadCreateInfo* info) {
553 DCHECK(MessageLoop::current() == ui_loop_);
554 DCHECK(info);
555
[email protected]7d3851d82008-12-12 03:26:07556 // Freeze the user's preference for showing a Save As dialog. We're going to
557 // bounce around a bunch of threads and we don't want to worry about race
558 // conditions where the user changes this pref out from under us.
[email protected]7bc4f702009-09-25 22:12:38559 if (*prompt_for_download_) {
560 // But never obey the preference for extension installation. Note that we
561 // only care here about the case where an extension is installed, not when
562 // one is downloaded with "save as...".
563 if (!IsExtensionInstall(info))
564 info->save_as = true;
565 }
[email protected]7d3851d82008-12-12 03:26:07566
initial.commit09911bf2008-07-26 23:55:29567 // Determine the proper path for a download, by choosing either the default
568 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41569 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29570 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07571 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29572 info->suggested_path = last_download_path_;
573 else
[email protected]7ae7c2cb2009-01-06 23:31:41574 info->suggested_path = download_path();
575 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29576
[email protected]7d3851d82008-12-12 03:26:07577 if (!info->save_as) {
[email protected]4289d9b2009-07-25 21:17:34578 // Downloads can be marked as dangerous for two reasons:
579 // a) They have a dangerous-looking filename
580 // b) They are an extension that is not from the gallery
581 if (IsDangerous(info->suggested_path.BaseName()))
582 info->is_dangerous = true;
[email protected]67f373a2009-09-22 02:44:51583 else if (IsExtensionInstall(info) &&
[email protected]4289d9b2009-07-25 21:17:34584 !ExtensionsService::IsDownloadFromGallery(info->url,
585 info->referrer_url)) {
586 info->is_dangerous = true;
587 }
[email protected]e9ebf3fc2008-10-17 22:06:58588 }
589
initial.commit09911bf2008-07-26 23:55:29590 // We need to move over to the download thread because we don't want to stat
591 // the suggested path on the UI thread.
592 file_loop_->PostTask(FROM_HERE,
593 NewRunnableMethod(this,
594 &DownloadManager::CheckIfSuggestedPathExists,
595 info));
596}
597
598void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
599 DCHECK(info);
600
601 // Check writability of the suggested path. If we can't write to it, default
602 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41603 FilePath dir = info->suggested_path.DirName();
604 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32605 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29606 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29607 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41608 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29609 }
610
[email protected]7a256ea2008-10-17 17:34:16611 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29612
[email protected]6cade212008-12-03 00:32:22613 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58614 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41615 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32616 // Create a temporary file to hold the file until the user approves its
617 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41618 FilePath::StringType file_name;
619 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32620 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41621 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32622 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41623 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07624 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41625 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32626 }
627 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16628 } else {
629 // We know the final path, build it if necessary.
630 if (info->path_uniquifier > 0) {
631 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
632 // Setting path_uniquifier to 0 to make sure we don't try to unique it
633 // later on.
634 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07635 } else if (info->path_uniquifier == -1) {
636 // We failed to find a unique path. We have to prompt the user.
637 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16638 }
[email protected]9ccbb372008-10-10 18:50:32639 }
640
[email protected]7d3851d82008-12-12 03:26:07641 if (!info->save_as) {
642 // Create an empty file at the suggested path so that we don't allocate the
643 // same "non-existant" path to multiple downloads.
644 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ae7c2cb2009-01-06 23:31:41645 file_util::WriteFile(info->suggested_path.ToWStringHack(), "", 0);
[email protected]7d3851d82008-12-12 03:26:07646 }
647
initial.commit09911bf2008-07-26 23:55:29648 // Now we return to the UI thread.
649 ui_loop_->PostTask(FROM_HERE,
650 NewRunnableMethod(this,
651 &DownloadManager::OnPathExistenceAvailable,
652 info));
653}
654
655void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
656 DCHECK(MessageLoop::current() == ui_loop_);
657 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,
705 info->save_as);
initial.commit09911bf2008-07-26 23:55:29706 download->set_manager(this);
707 in_progress_[info->download_id] = download;
708 } else {
709 NOTREACHED(); // Should not exist!
710 return;
711 }
712
[email protected]6b323782009-03-27 18:43:08713 // Called before DownloadFinished in order to avoid a race condition where we
714 // attempt to open a completed download before it has been renamed.
715 file_loop_->PostTask(FROM_HERE,
716 NewRunnableMethod(file_manager_,
717 &DownloadFileManager::OnFinalDownloadName,
718 download->id(),
[email protected]8f783752009-04-01 23:33:45719 target_path,
720 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.
738 if (profile_->IsOffTheRecord() || IsExtensionInstall(download)) {
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.
838 file_loop_->PostTask(FROM_HERE,
839 NewRunnableMethod(
840 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
841 download->db_handle(),
842 download->full_path(), download->original_name()));
843 return;
844 }
845 ContinueDownloadFinished(download);
846}
847
[email protected]8f783752009-04-01 23:33:45848void DownloadManager::DownloadRenamedToFinalName(int download_id,
849 const FilePath& full_path) {
[email protected]8f783752009-04-01 23:33:45850}
851
[email protected]9ccbb372008-10-10 18:50:32852void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
853 // If this was a dangerous download, it has now been approved and must be
854 // removed from dangerous_finished_ so it does not get deleted on shutdown.
855 DownloadMap::iterator it = dangerous_finished_.find(download->id());
856 if (it != dangerous_finished_.end())
857 dangerous_finished_.erase(it);
858
[email protected]5a102892009-07-15 19:59:30859 // Open the download if the user or user prefs indicate it should be.
860 FilePath::StringType extension = download->full_path().Extension();
861 // Drop the leading period. (The auto-open list is period-less.)
862 if (extension.size() > 0)
863 extension = extension.substr(1);
864
[email protected]0aad67b2009-07-15 20:34:28865 // Handle chrome extensions explicitly and skip the shell execute.
[email protected]67f373a2009-09-22 02:44:51866 if (IsExtensionInstall(download)) {
[email protected]494c06e2009-07-25 01:06:42867 OpenChromeExtension(download->full_path(), download->url(),
868 download->referrer_url());
[email protected]0aad67b2009-07-15 20:34:28869 download->set_auto_opened(true);
870 } else if (download->open_when_complete() ||
871 ShouldOpenFileExtension(extension)) {
[email protected]9ccbb372008-10-10 18:50:32872 OpenDownloadInShell(download, NULL);
[email protected]0aad67b2009-07-15 20:34:28873 download->set_auto_opened(true);
874 }
[email protected]9ccbb372008-10-10 18:50:32875
[email protected]0aad67b2009-07-15 20:34:28876 // Notify our observers that we are complete (the call to Finished() set the
877 // state to complete but did not notify).
878 download->UpdateObservers();
879}
[email protected]9ccbb372008-10-10 18:50:32880// Called on the file thread. Renames the downloaded file to its original name.
881void DownloadManager::ProceedWithFinishedDangerousDownload(
882 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41883 const FilePath& path,
884 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32885 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41886 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16887 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32888 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24889 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16890 // Make our name unique at this point, as if a dangerous file is downloading
891 // and a 2nd download is started for a file with the same name, they would
892 // have the same path. This is because we uniquify the name on download
893 // start, and at that time the first file does not exists yet, so the second
894 // file gets the same name.
895 uniquifier = GetUniquePathNumber(new_path);
896 if (uniquifier > 0)
897 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32898 success = file_util::Move(path, new_path);
899 } else {
900 NOTREACHED();
901 }
[email protected]6cade212008-12-03 00:32:22902
[email protected]9ccbb372008-10-10 18:50:32903 ui_loop_->PostTask(FROM_HERE,
904 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16905 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32906}
907
908// Call from the file thread when the finished dangerous download was renamed.
909void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
910 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41911 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16912 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32913 DownloadMap::iterator it = downloads_.find(download_handle);
914 if (it == downloads_.end()) {
915 NOTREACHED();
916 return;
917 }
918
919 DownloadItem* download = it->second;
920 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16921 if (success) {
922 // We need to update the path uniquifier so that the UI shows the right
923 // name when calling GetFileName().
924 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32925 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16926 }
[email protected]9ccbb372008-10-10 18:50:32927
928 // Continue the download finished sequence.
929 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29930}
931
932// static
933// We have to tell the ResourceDispatcherHost to cancel the download from this
[email protected]6cade212008-12-03 00:32:22934// thread, since we can't forward tasks from the file thread to the IO thread
initial.commit09911bf2008-07-26 23:55:29935// reliably (crash on shutdown race condition).
936void DownloadManager::CancelDownloadRequest(int render_process_id,
937 int request_id) {
938 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]ab820df2008-08-26 05:55:10939 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29940 if (!io_thread || !rdh)
941 return;
942 io_thread->message_loop()->PostTask(FROM_HERE,
943 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
944 rdh,
945 render_process_id,
946 request_id));
947}
948
949// static
950void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
951 int render_process_id,
952 int request_id) {
953 rdh->CancelRequest(render_process_id, request_id, false);
954}
955
956void DownloadManager::DownloadCancelled(int32 download_id) {
957 DownloadMap::iterator it = in_progress_.find(download_id);
958 if (it == in_progress_.end())
959 return;
960 DownloadItem* download = it->second;
961
initial.commit09911bf2008-07-26 23:55:29962 // Clean up will happen when the history system create callback runs if we
963 // don't have a valid db_handle yet.
964 if (download->db_handle() != kUninitializedHandle) {
965 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:29966 UpdateHistoryForDownload(download);
967 }
968
[email protected]d7d1c5c2009-08-05 23:52:50969 DownloadCancelledInternal(download_id,
970 download->render_process_id(),
971 download->request_id());
972}
973
974void DownloadManager::DownloadCancelledInternal(int download_id,
975 int render_process_id,
976 int request_id) {
977 // Cancel the network request.
978 CancelDownloadRequest(render_process_id, request_id);
979
initial.commit09911bf2008-07-26 23:55:29980 // Tell the file manager to cancel the download.
[email protected]d7d1c5c2009-08-05 23:52:50981 file_manager_->RemoveDownload(download_id, this); // On the UI thread
initial.commit09911bf2008-07-26 23:55:29982 file_loop_->PostTask(FROM_HERE,
983 NewRunnableMethod(file_manager_,
984 &DownloadFileManager::CancelDownload,
[email protected]d7d1c5c2009-08-05 23:52:50985 download_id));
initial.commit09911bf2008-07-26 23:55:29986}
987
988void DownloadManager::PauseDownload(int32 download_id, bool pause) {
989 DownloadMap::iterator it = in_progress_.find(download_id);
990 if (it != in_progress_.end()) {
991 DownloadItem* download = it->second;
992 if (pause == download->is_paused())
993 return;
994
995 // Inform the ResourceDispatcherHost of the new pause state.
[email protected]ab820df2008-08-26 05:55:10996 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29997 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
998 if (!io_thread || !rdh)
999 return;
1000
1001 io_thread->message_loop()->PostTask(FROM_HERE,
1002 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
1003 rdh,
1004 download->render_process_id(),
1005 download->request_id(),
1006 pause));
1007 }
1008}
1009
1010// static
1011void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
1012 int render_process_id,
1013 int request_id,
1014 bool pause) {
1015 rdh->PauseRequest(render_process_id, request_id, pause);
1016}
1017
[email protected]7ae7c2cb2009-01-06 23:31:411018bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:321019 // TODO(jcampan): Improve me.
[email protected]2001fe82009-02-23 23:53:141020 FilePath::StringType extension = file_name.Extension();
1021 // Drop the leading period.
1022 if (extension.size() > 0)
1023 extension = extension.substr(1);
1024 return IsExecutable(extension);
[email protected]9ccbb372008-10-10 18:50:321025}
1026
1027void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:411028 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:321029 download->Rename(new_path);
1030
1031 // Update the history.
1032
1033 // No update necessary if the download was initiated while in incognito mode.
1034 if (download->db_handle() <= kUninitializedHandle)
1035 return;
1036
[email protected]6cade212008-12-03 00:32:221037 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:321038 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1039 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:411040 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:321041}
1042
initial.commit09911bf2008-07-26 23:55:291043void DownloadManager::RemoveDownload(int64 download_handle) {
1044 DownloadMap::iterator it = downloads_.find(download_handle);
1045 if (it == downloads_.end())
1046 return;
1047
1048 // Make history update.
1049 DownloadItem* download = it->second;
1050 RemoveDownloadFromHistory(download);
1051
1052 // Remove from our tables and delete.
1053 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321054 it = dangerous_finished_.find(download->id());
1055 if (it != dangerous_finished_.end())
1056 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291057
1058 // Tell observers to refresh their views.
1059 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:361060
1061 delete download;
initial.commit09911bf2008-07-26 23:55:291062}
1063
[email protected]e93d2822009-01-30 05:59:591064int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1065 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291066 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1067
initial.commit09911bf2008-07-26 23:55:291068 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:281069 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:291070 while (it != downloads_.end()) {
1071 DownloadItem* download = it->second;
1072 DownloadItem::DownloadState state = download->state();
1073 if (download->start_time() >= remove_begin &&
1074 (remove_end.is_null() || download->start_time() < remove_end) &&
1075 (state == DownloadItem::COMPLETE ||
1076 state == DownloadItem::CANCELLED)) {
1077 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561078 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581079
1080 // Also remove it from any completed dangerous downloads.
1081 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1082 if (dit != dangerous_finished_.end())
1083 dangerous_finished_.erase(dit);
1084
[email protected]78b8fcc92009-03-31 17:36:281085 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:291086
initial.commit09911bf2008-07-26 23:55:291087 continue;
1088 }
1089
1090 ++it;
1091 }
1092
1093 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281094 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291095 if (num_deleted > 0)
1096 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1097
[email protected]78b8fcc92009-03-31 17:36:281098 // Delete the download items after updating the observers.
1099 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1100 pending_deletes.clear();
1101
initial.commit09911bf2008-07-26 23:55:291102 return num_deleted;
1103}
1104
[email protected]e93d2822009-01-30 05:59:591105int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1106 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291107}
1108
[email protected]d41355e6f2009-04-07 21:21:121109int DownloadManager::RemoveAllDownloads() {
1110 // The null times make the date range unbounded.
1111 return RemoveDownloadsBetween(base::Time(), base::Time());
1112}
1113
initial.commit09911bf2008-07-26 23:55:291114// Initiate a download of a specific URL. We send the request to the
1115// ResourceDispatcherHost, and let it send us responses like a regular
1116// download.
1117void DownloadManager::DownloadUrl(const GURL& url,
1118 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:501119 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:341120 TabContents* tab_contents) {
1121 DCHECK(tab_contents);
[email protected]c9825a42009-05-01 22:51:501122 request_context_->set_referrer_charset(referrer_charset);
initial.commit09911bf2008-07-26 23:55:291123 file_manager_->DownloadUrl(url,
1124 referrer,
[email protected]76543b92009-08-31 17:27:451125 tab_contents->process()->id(),
[email protected]57c6a652009-05-04 07:58:341126 tab_contents->render_view_host()->routing_id(),
initial.commit09911bf2008-07-26 23:55:291127 request_context_.get());
1128}
1129
[email protected]7ae7c2cb2009-01-06 23:31:411130void DownloadManager::GenerateExtension(
1131 const FilePath& file_name,
1132 const std::string& mime_type,
1133 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291134 // We're worried about three things here:
1135 //
1136 // 1) Security. Many sites let users upload content, such as buddy icons, to
1137 // their web sites. We want to mitigate the case where an attacker
1138 // supplies a malicious executable with an executable file extension but an
1139 // honest site serves the content with a benign content type, such as
1140 // image/jpeg.
1141 //
1142 // 2) Usability. If the site fails to provide a file extension, we want to
1143 // guess a reasonable file extension based on the content type.
1144 //
1145 // 3) Shell integration. Some file extensions automatically integrate with
1146 // the shell. We block these extensions to prevent a malicious web site
1147 // from integrating with the user's shell.
1148
[email protected]7ae7c2cb2009-01-06 23:31:411149 static const FilePath::CharType default_extension[] =
1150 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291151
1152 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411153 FilePath::StringType extension(
1154 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291155
[email protected]b7f05882009-02-22 01:21:561156#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291157 // Rename shell-integrated extensions.
1158 if (win_util::IsShellIntegratedExtension(extension))
1159 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561160#endif
initial.commit09911bf2008-07-26 23:55:291161
1162 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411163 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411164 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291165 if (mime_type == mime_type_from_extension) {
1166 // The hinted extension matches the mime type. It looks like a winner.
1167 generated_extension->swap(extension);
1168 return;
1169 }
1170
1171 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1172 // We want to be careful about executable extensions. The worry here is
1173 // that a trusted web site could be tricked into dropping an executable file
1174 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101175 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291176 // We couldn't find a good extension for this content type. Use a dummy
1177 // extension instead.
1178 extension.assign(default_extension);
1179 }
1180 }
1181
1182 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101183 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291184 } else {
[email protected]6cade212008-12-03 00:32:221185 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291186 // 1. New extension is not ".txt"
1187 // 2. New extension is not the same as the already existing extension.
1188 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411189 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291190 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1191 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371192 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1193 // servers, i.e. bug 5772.
[email protected]e32642f62009-09-11 21:58:291194 // 5. The original extension is not ".tgz" & the new extension is not "gz".
[email protected]7ae7c2cb2009-01-06 23:31:411195 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101196 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171197 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411198 append_extension != extension &&
[email protected]e106457b2009-03-25 22:43:371199 !IsExecutable(append_extension) &&
[email protected]e32642f62009-09-11 21:58:291200 !(append_extension == FILE_PATH_LITERAL("gz") &&
1201 extension == FILE_PATH_LITERAL("tgz")) &&
[email protected]e106457b2009-03-25 22:43:371202 (append_extension != FILE_PATH_LITERAL("tar") ||
1203 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171204 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291205 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171206 }
initial.commit09911bf2008-07-26 23:55:291207 }
1208 }
1209
1210 generated_extension->swap(extension);
1211}
1212
1213void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411214 FilePath* generated_name) {
1215 *generated_name = FilePath::FromWStringHack(
[email protected]8ac1a752008-07-31 19:40:371216 net::GetSuggestedFilename(GURL(info->url),
1217 info->content_disposition,
[email protected]c9825a42009-05-01 22:51:501218 info->referrer_charset,
[email protected]7ae7c2cb2009-01-06 23:31:411219 L"download"));
1220 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291221
[email protected]7ae7c2cb2009-01-06 23:31:411222 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291223}
1224
1225void DownloadManager::AddObserver(Observer* observer) {
1226 observers_.AddObserver(observer);
1227 observer->ModelChanged();
1228}
1229
1230void DownloadManager::RemoveObserver(Observer* observer) {
1231 observers_.RemoveObserver(observer);
1232}
1233
1234// Post Windows Shell operations to the Download thread, to avoid blocking the
1235// user interface.
1236void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1237 DCHECK(file_manager_);
[email protected]8b6ff012009-08-18 22:29:581238 DCHECK(MessageLoop::current() == ui_loop_);
1239#if defined(OS_MACOSX)
1240 // Mac needs to run this operation on the UI thread.
1241 platform_util::ShowItemInFolder(download->full_path());
1242#else
initial.commit09911bf2008-07-26 23:55:291243 file_loop_->PostTask(FROM_HERE,
1244 NewRunnableMethod(file_manager_,
1245 &DownloadFileManager::OnShowDownloadInShell,
[email protected]7ae7c2cb2009-01-06 23:31:411246 FilePath(download->full_path())));
[email protected]8b6ff012009-08-18 22:29:581247#endif
initial.commit09911bf2008-07-26 23:55:291248}
1249
[email protected]8f783752009-04-01 23:33:451250void DownloadManager::OpenDownload(const DownloadItem* download,
1251 gfx::NativeView parent_window) {
[email protected]0e34d7892009-06-05 19:17:401252 // Open Chrome extensions with ExtensionsService. For everything else do shell
[email protected]8f783752009-04-01 23:33:451253 // execute.
[email protected]67f373a2009-09-22 02:44:511254 if (IsExtensionInstall(download)) {
[email protected]494c06e2009-07-25 01:06:421255 OpenChromeExtension(download->full_path(), download->url(),
1256 download->referrer_url());
[email protected]8f783752009-04-01 23:33:451257 } else {
1258 OpenDownloadInShell(download, parent_window);
1259 }
1260}
1261
[email protected]c1e432a2009-07-22 21:21:481262void DownloadManager::OpenChromeExtension(const FilePath& full_path,
[email protected]494c06e2009-07-25 01:06:421263 const GURL& download_url,
1264 const GURL& referrer_url) {
[email protected]6ef635e42009-07-26 06:16:121265 // We don't support extensions in OTR mode.
[email protected]2a464a92009-08-01 17:58:351266 ExtensionsService* service = profile_->GetExtensionsService();
1267 if (service) {
[email protected]91e1bd82009-09-03 22:04:401268 NotificationService* nservice = NotificationService::current();
1269 nservice->Notify(NotificationType::EXTENSION_READY_FOR_INSTALL,
1270 Source<DownloadManager>(this),
1271 NotificationService::NoDetails());
[email protected]2a464a92009-08-01 17:58:351272 CrxInstaller::Start(full_path,
1273 service->install_directory(),
1274 Extension::INTERNAL,
1275 "", // no expected id
1276 true, // please delete crx on completion
[email protected]2a409532009-08-28 19:39:441277 true, // privilege increase allowed
[email protected]2a464a92009-08-01 17:58:351278 g_browser_process->file_thread()->message_loop(),
1279 service,
1280 new ExtensionInstallUI(profile_));
1281 }
[email protected]8f783752009-04-01 23:33:451282}
1283
initial.commit09911bf2008-07-26 23:55:291284void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591285 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291286 DCHECK(file_manager_);
[email protected]8b6ff012009-08-18 22:29:581287 DCHECK(MessageLoop::current() == ui_loop_);
1288#if defined(OS_MACOSX)
1289 // Mac OS X requires opening downloads on the UI thread.
1290 platform_util::OpenItem(download->full_path());
1291#else
initial.commit09911bf2008-07-26 23:55:291292 file_loop_->PostTask(FROM_HERE,
1293 NewRunnableMethod(file_manager_,
1294 &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]7ae7c2cb2009-01-06 23:31:411299void DownloadManager::OpenFilesOfExtension(
1300 const FilePath::StringType& extension, bool open) {
initial.commit09911bf2008-07-26 23:55:291301 if (open && !IsExecutable(extension))
1302 auto_open_.insert(extension);
1303 else
1304 auto_open_.erase(extension);
1305 SaveAutoOpens();
1306}
1307
[email protected]7ae7c2cb2009-01-06 23:31:411308bool DownloadManager::ShouldOpenFileExtension(
1309 const FilePath::StringType& extension) {
[email protected]8c756ac2009-01-30 23:36:411310 // Special-case Chrome extensions as always-open.
initial.commit09911bf2008-07-26 23:55:291311 if (!IsExecutable(extension) &&
[email protected]8c756ac2009-01-30 23:36:411312 (auto_open_.find(extension) != auto_open_.end() ||
[email protected]f1ce6e62009-06-29 20:31:291313 Extension::IsExtension(FilePath(extension))))
[email protected]8c756ac2009-01-30 23:36:411314 return true;
initial.commit09911bf2008-07-26 23:55:291315 return false;
1316}
1317
[email protected]7b73d992008-12-15 20:56:461318static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291319 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461320 "text/javascript",
1321 "text/javascript;version=*",
[email protected]54d8d452009-04-08 17:29:241322 // Registry files can cause critical changes to the MS OS behavior.
1323 // Addition of this mimetype also addresses bug 7337.
1324 "text/x-registry",
[email protected]60ff8f912008-12-05 07:58:391325 // Some sites use binary/octet-stream to mean application/octet-stream.
1326 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461327 "binary/octet-stream"
1328};
initial.commit09911bf2008-07-26 23:55:291329
[email protected]7b73d992008-12-15 20:56:461330static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291331 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461332 "application/*+xml",
1333 "application/xml"
1334};
initial.commit09911bf2008-07-26 23:55:291335
[email protected]7b73d992008-12-15 20:56:461336// static
1337bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411338 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461339 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1340 return true;
1341 }
[email protected]bae0ea12009-02-14 01:20:411342 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461343 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1344 return false;
1345 }
1346 // We consider only other application types to be executable.
1347 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291348}
1349
[email protected]7ae7c2cb2009-01-06 23:31:411350bool DownloadManager::IsExecutable(const FilePath::StringType& extension) {
[email protected]64da0b932009-02-24 02:30:041351 if (!IsStringASCII(extension))
1352 return false;
[email protected]a0a9577b2009-05-27 23:52:321353#if defined(OS_WIN)
[email protected]64da0b932009-02-24 02:30:041354 std::string ascii_extension = WideToASCII(extension);
[email protected]e9ef0a62009-08-11 22:50:131355#elif defined(OS_POSIX)
[email protected]a0a9577b2009-05-27 23:52:321356 std::string ascii_extension = extension;
1357#endif
[email protected]64da0b932009-02-24 02:30:041358 StringToLowerASCII(&ascii_extension);
1359
1360 return exe_types_.find(ascii_extension) != exe_types_.end();
initial.commit09911bf2008-07-26 23:55:291361}
1362
1363void DownloadManager::ResetAutoOpenFiles() {
1364 auto_open_.clear();
1365 SaveAutoOpens();
1366}
1367
1368bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1369 return !auto_open_.empty();
1370}
1371
1372void DownloadManager::SaveAutoOpens() {
1373 PrefService* prefs = profile_->GetPrefs();
1374 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411375 FilePath::StringType extensions;
1376 for (std::set<FilePath::StringType>::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291377 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411378 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291379 }
1380 if (!extensions.empty())
1381 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561382
1383 std::wstring extensions_w;
1384#if defined(OS_WIN)
1385 extensions_w = extensions;
1386#elif defined(OS_POSIX)
[email protected]1b5044d2009-02-24 00:04:141387 extensions_w = base::SysNativeMBToWide(extensions);
[email protected]b7f05882009-02-22 01:21:561388#endif
1389
1390 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291391 }
1392}
1393
[email protected]561abe62009-04-06 18:08:341394void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361395 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291396 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071397 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411398 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291399 ContinueStartDownload(info, path);
1400}
1401
1402void DownloadManager::FileSelectionCanceled(void* params) {
1403 // The user didn't pick a place to save the file, so need to cancel the
1404 // download that's already in progress to the temporary location.
1405 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]d7d1c5c2009-08-05 23:52:501406 DownloadCancelledInternal(info->download_id,
[email protected]76543b92009-08-31 17:27:451407 info->child_id,
[email protected]d7d1c5c2009-08-05 23:52:501408 info->request_id);
initial.commit09911bf2008-07-26 23:55:291409}
1410
[email protected]7ae7c2cb2009-01-06 23:31:411411void DownloadManager::DeleteDownload(const FilePath& path) {
1412 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
1413 &DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321414}
1415
1416
1417void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1418 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1419 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1420 download->UpdateObservers();
1421
1422 // If the download is not complete, nothing to do. The required
1423 // post-processing will be performed when it does complete.
1424 if (download->state() != DownloadItem::COMPLETE)
1425 return;
1426
1427 file_loop_->PostTask(FROM_HERE,
1428 NewRunnableMethod(this,
1429 &DownloadManager::ProceedWithFinishedDangerousDownload,
1430 download->db_handle(), download->full_path(),
1431 download->original_name()));
1432}
1433
[email protected]763f946a2009-01-06 19:04:391434void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411435 FilePath* file_name) {
1436 // Make sure we get the right file extension
1437 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391438 GenerateExtension(*file_name, mime_type, &extension);
1439 file_util::ReplaceExtension(file_name, extension);
1440
[email protected]2b2f8f72009-02-24 22:42:051441#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391442 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411443 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391444 DCHECK(!leaf_name.empty());
1445 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411446 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1447 *file_name = file_name->DirName();
1448 if (file_name->value() == FilePath::kCurrentDirectory) {
1449 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391450 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411451 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391452 }
1453 }
[email protected]b7f05882009-02-22 01:21:561454#endif
[email protected]763f946a2009-01-06 19:04:391455}
1456
[email protected]f1b11d32009-10-09 22:51:391457bool DownloadManager::IsExtensionInstall(const DownloadItem* item) {
1458 return item->mime_type() == Extension::kMimeType && !item->save_as();
1459}
1460
1461bool DownloadManager::IsExtensionInstall(const DownloadCreateInfo* info) {
1462 return info->mime_type == Extension::kMimeType && !info->save_as;
1463}
1464
initial.commit09911bf2008-07-26 23:55:291465// Operations posted to us from the history service ----------------------------
1466
1467// The history service has retrieved all download entries. 'entries' contains
1468// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1469void DownloadManager::OnQueryDownloadEntriesComplete(
1470 std::vector<DownloadCreateInfo>* entries) {
1471 for (size_t i = 0; i < entries->size(); ++i) {
1472 DownloadItem* download = new DownloadItem(entries->at(i));
1473 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1474 downloads_[download->db_handle()] = download;
1475 download->set_manager(this);
1476 }
1477 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1478}
1479
initial.commit09911bf2008-07-26 23:55:291480// Once the new DownloadItem's creation info has been committed to the history
1481// service, we associate the DownloadItem with the db handle, update our
1482// 'downloads_' map and inform observers.
1483void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1484 int64 db_handle) {
1485 DownloadMap::iterator it = in_progress_.find(info.download_id);
1486 DCHECK(it != in_progress_.end());
1487
1488 DownloadItem* download = it->second;
1489 DCHECK(download->db_handle() == kUninitializedHandle);
1490 download->set_db_handle(db_handle);
1491
1492 // Insert into our full map.
1493 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1494 downloads_[download->db_handle()] = download;
1495
[email protected]5e595482009-05-06 20:16:531496 // Show in the appropropriate browser UI.
1497 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291498
1499 // Inform interested objects about the new download.
1500 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
initial.commit09911bf2008-07-26 23:55:291501
1502 // If this download has been completed before we've received the db handle,
1503 // post one final message to the history service so that it can be properly
1504 // in sync with the DownloadItem's completion status, and also inform any
1505 // observers so that they get more than just the start notification.
1506 if (download->state() != DownloadItem::IN_PROGRESS) {
1507 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291508 UpdateHistoryForDownload(download);
1509 download->UpdateObservers();
1510 }
1511}
1512
1513// Called when the history service has retrieved the list of downloads that
1514// match the search text.
1515void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1516 std::vector<int64>* results) {
1517 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1518 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1519 if (!requestor)
1520 return;
1521
1522 std::vector<DownloadItem*> searched_downloads;
1523 for (std::vector<int64>::iterator it = results->begin();
1524 it != results->end(); ++it) {
1525 DownloadMap::iterator dit = downloads_.find(*it);
1526 if (dit != downloads_.end())
1527 searched_downloads.push_back(dit->second);
1528 }
1529
1530 requestor->SetDownloads(searched_downloads);
1531}
[email protected]905a08d2008-11-19 07:24:121532
[email protected]5e595482009-05-06 20:16:531533void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1534 DownloadItem* download) {
[email protected]5e595482009-05-06 20:16:531535 // The 'contents' may no longer exist if the user closed the tab before we get
1536 // this start completion event. If it does, tell the origin TabContents to
1537 // display its download shelf.
[email protected]76543b92009-08-31 17:27:451538 TabContents* contents = tab_util::GetTabContentsByID(info.child_id,
1539 info.render_view_id);
[email protected]5e595482009-05-06 20:16:531540
1541 // If the contents no longer exists, we start the download in the last active
1542 // browser. This is not ideal but better than fully hiding the download from
1543 // the user.
1544 if (!contents) {
1545 Browser* last_active = BrowserList::GetLastActive();
1546 if (last_active)
1547 contents = last_active->GetSelectedTabContents();
1548 }
1549
1550 if (contents)
1551 contents->OnStartDownload(download);
1552}
1553
[email protected]6cade212008-12-03 00:32:221554// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121555void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411556 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381557}
1558