blob: da4ccd8caffa919cb2b5582d4dfe32909a809ca0 [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]2a464a92009-08-01 17:58:3523#include "chrome/browser/extensions/extension_install_ui.h"
[email protected]8f783752009-04-01 23:33:4524#include "chrome/browser/extensions/extensions_service.h"
initial.commit09911bf2008-07-26 23:55:2925#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:2626#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2527#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]e3c404b2008-12-23 01:07:3228#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
[email protected]f3ec7742009-01-15 00:59:1629#include "chrome/browser/tab_contents/tab_util.h"
[email protected]57c6a652009-05-04 07:58:3430#include "chrome/browser/tab_contents/tab_contents.h"
[email protected]4a0380c2009-07-26 07:25:3231#include "chrome/common/chrome_constants.h"
initial.commit09911bf2008-07-26 23:55:2932#include "chrome/common/chrome_paths.h"
[email protected]5b1a0e22009-05-26 19:00:5833#include "chrome/common/extensions/extension.h"
[email protected]076700e62009-04-01 18:41:2334#include "chrome/common/platform_util.h"
initial.commit09911bf2008-07-26 23:55:2935#include "chrome/common/pref_names.h"
36#include "chrome/common/pref_service.h"
[email protected]46072d42008-07-28 14:49:3537#include "googleurl/src/gurl.h"
[email protected]d81706b82009-04-03 20:28:4438#include "grit/chromium_strings.h"
[email protected]34ac8f32009-02-22 23:03:2739#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2940#include "net/base/mime_util.h"
41#include "net/base/net_util.h"
42#include "net/url_request/url_request_context.h"
43
[email protected]b7f05882009-02-22 01:21:5644#if defined(OS_WIN)
[email protected]4a0765a2009-05-08 23:12:2545#include "app/win_util.h"
[email protected]b7f05882009-02-22 01:21:5646#include "base/registry.h"
47#include "base/win_util.h"
[email protected]a0a9577b2009-05-27 23:52:3248#endif
49
[email protected]b7f05882009-02-22 01:21:5650
[email protected]0f44d3e2009-03-12 23:36:3051#if defined(OS_LINUX)
52#include <gtk/gtk.h>
53#endif
54
initial.commit09911bf2008-07-26 23:55:2955// Periodically update our observers.
56class DownloadItemUpdateTask : public Task {
57 public:
58 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
59 void Run() { if (item_) item_->UpdateObservers(); }
60
61 private:
62 DownloadItem* item_;
63};
64
65// Update frequency (milliseconds).
66static const int kUpdateTimeMs = 1000;
67
68// Our download table ID starts at 1, so we use 0 to represent a download that
69// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2270// database handles in incognito mode starting at -1 and progressively getting
71// more negative.
initial.commit09911bf2008-07-26 23:55:2972static const int kUninitializedHandle = 0;
73
[email protected]7a256ea2008-10-17 17:34:1674// Appends the passed the number between parenthesis the path before the
75// extension.
[email protected]7ae7c2cb2009-01-06 23:31:4176static void AppendNumberToPath(FilePath* path, int number) {
77 file_util::InsertBeforeExtension(path,
78 StringPrintf(FILE_PATH_LITERAL(" (%d)"), number));
[email protected]7a256ea2008-10-17 17:34:1679}
80
81// Attempts to find a number that can be appended to that path to make it
82// unique. If |path| does not exist, 0 is returned. If it fails to find such
83// a number, -1 is returned.
[email protected]7ae7c2cb2009-01-06 23:31:4184static int GetUniquePathNumber(const FilePath& path) {
initial.commit09911bf2008-07-26 23:55:2985 const int kMaxAttempts = 100;
86
[email protected]7a256ea2008-10-17 17:34:1687 if (!file_util::PathExists(path))
88 return 0;
initial.commit09911bf2008-07-26 23:55:2989
[email protected]7ae7c2cb2009-01-06 23:31:4190 FilePath new_path;
initial.commit09911bf2008-07-26 23:55:2991 for (int count = 1; count <= kMaxAttempts; ++count) {
[email protected]7ae7c2cb2009-01-06 23:31:4192 new_path = FilePath(path);
[email protected]7a256ea2008-10-17 17:34:1693 AppendNumberToPath(&new_path, count);
initial.commit09911bf2008-07-26 23:55:2994
[email protected]7a256ea2008-10-17 17:34:1695 if (!file_util::PathExists(new_path))
96 return count;
initial.commit09911bf2008-07-26 23:55:2997 }
98
[email protected]7a256ea2008-10-17 17:34:1699 return -1;
initial.commit09911bf2008-07-26 23:55:29100}
101
[email protected]7ae7c2cb2009-01-06 23:31:41102static bool DownloadPathIsDangerous(const FilePath& download_path) {
103 FilePath desktop_dir;
[email protected]f052118e2008-09-05 02:25:32104 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
105 NOTREACHED();
106 return false;
107 }
108 return (download_path == desktop_dir);
109}
110
[email protected]1e7e93402009-08-13 20:55:17111// Helper to determine if a download is a Chrome extension. We should be able to
112// just use the mime type, but even our own servers are not setup to serve the
113// right headers yet, so we have a short-term file extension heuristic, too.
114static bool IsChromeExtension(const FilePath& path,
115 const std::string& mime_type) {
116 // If the server says it is an extension, it is definitely an extension.
117 if (mime_type == Extension::kMimeType)
118 return true;
119
120 // Otherwise, it is an extension if it has the right, err, extension.
121 return path.Extension().size() > 1 &&
122 path.Extension().substr(1) == chrome::kExtensionFileExtension;
123}
124
initial.commit09911bf2008-07-26 23:55:29125// DownloadItem implementation -------------------------------------------------
126
127// Constructor for reading from the history service.
128DownloadItem::DownloadItem(const DownloadCreateInfo& info)
129 : id_(-1),
130 full_path_(info.path),
131 url_(info.url),
[email protected]e435d6b72009-07-25 03:15:58132 referrer_url_(info.referrer_url),
133 mime_type_(info.mime_type),
initial.commit09911bf2008-07-26 23:55:29134 total_bytes_(info.total_bytes),
135 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56136 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29137 state_(static_cast<DownloadState>(info.state)),
138 start_time_(info.start_time),
139 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29140 manager_(NULL),
141 is_paused_(false),
142 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56143 safety_state_(SAFE),
[email protected]0aad67b2009-07-15 20:34:28144 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56145 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29146 render_process_id_(-1),
147 request_id_(-1) {
148 if (state_ == IN_PROGRESS)
149 state_ = CANCELLED;
150 Init(false /* don't start progress timer */);
151}
152
153// Constructor for DownloadItem created via user action in the main thread.
154DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41155 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16156 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32157 const GURL& url,
[email protected]494c06e2009-07-25 01:06:42158 const GURL& referrer_url,
[email protected]e435d6b72009-07-25 03:15:58159 const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:41160 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59161 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29162 int64 download_size,
163 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32164 int request_id,
165 bool is_dangerous)
initial.commit09911bf2008-07-26 23:55:29166 : id_(download_id),
167 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16168 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29169 url_(url),
[email protected]494c06e2009-07-25 01:06:42170 referrer_url_(referrer_url),
[email protected]e435d6b72009-07-25 03:15:58171 mime_type_(mime_type),
initial.commit09911bf2008-07-26 23:55:29172 total_bytes_(download_size),
173 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56174 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29175 state_(IN_PROGRESS),
176 start_time_(start_time),
177 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29178 manager_(NULL),
179 is_paused_(false),
180 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56181 safety_state_(is_dangerous ? DANGEROUS : SAFE),
[email protected]0aad67b2009-07-15 20:34:28182 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56183 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29184 render_process_id_(render_process_id),
185 request_id_(request_id) {
186 Init(true /* start progress timer */);
187}
188
189void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41190 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29191 if (start_timer)
192 StartProgressTimer();
193}
194
195DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29196 state_ = REMOVING;
197 UpdateObservers();
198}
199
200void DownloadItem::AddObserver(Observer* observer) {
201 observers_.AddObserver(observer);
202}
203
204void DownloadItem::RemoveObserver(Observer* observer) {
205 observers_.RemoveObserver(observer);
206}
207
208void DownloadItem::UpdateObservers() {
209 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
210}
211
[email protected]45e3c122009-04-07 19:58:03212void DownloadItem::NotifyObserversDownloadOpened() {
213 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadOpened(this));
214}
215
initial.commit09911bf2008-07-26 23:55:29216// If we've received more data than we were expecting (bad server info?), revert
217// to 'unknown size mode'.
218void DownloadItem::UpdateSize(int64 bytes_so_far) {
219 received_bytes_ = bytes_so_far;
220 if (received_bytes_ > total_bytes_)
221 total_bytes_ = 0;
222}
223
224// Updates from the download thread may have been posted while this download
225// was being cancelled in the UI thread, so we'll accept them unless we're
226// complete.
227void DownloadItem::Update(int64 bytes_so_far) {
228 if (state_ == COMPLETE) {
229 NOTREACHED();
230 return;
231 }
232 UpdateSize(bytes_so_far);
233 UpdateObservers();
234}
235
[email protected]6cade212008-12-03 00:32:22236// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29237void DownloadItem::Cancel(bool update_history) {
238 if (state_ != IN_PROGRESS) {
239 // Small downloads might be complete before this method has a chance to run.
240 return;
241 }
242 state_ = CANCELLED;
243 UpdateObservers();
244 StopProgressTimer();
245 if (update_history)
246 manager_->DownloadCancelled(id_);
247}
248
249void DownloadItem::Finished(int64 size) {
250 state_ = COMPLETE;
251 UpdateSize(size);
[email protected]22fbe5a2008-10-29 22:20:40252 UpdateObservers();
initial.commit09911bf2008-07-26 23:55:29253 StopProgressTimer();
254}
255
[email protected]9ccbb372008-10-10 18:50:32256void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29257 Cancel(true);
258 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32259 if (delete_on_disk)
260 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29261 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22262 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29263}
264
265void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59266 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14267 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29268}
269
270void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14271 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29272}
273
[email protected]e93d2822009-01-30 05:59:59274bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29275 if (total_bytes_ <= 0)
276 return false; // We never received the content_length for this download.
277
278 int64 speed = CurrentSpeed();
279 if (speed == 0)
280 return false;
281
282 *remaining =
[email protected]e93d2822009-01-30 05:59:59283 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29284 return true;
285}
286
287int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56288 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
289 int64 diff_ms = diff.InMilliseconds();
290 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29291}
292
293int DownloadItem::PercentComplete() const {
294 int percent = -1;
295 if (total_bytes_ > 0)
296 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
297 return percent;
298}
299
[email protected]7ae7c2cb2009-01-06 23:31:41300void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29301 DCHECK(!full_path.empty());
302 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41303 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29304}
305
306void DownloadItem::TogglePause() {
307 DCHECK(state_ == IN_PROGRESS);
308 manager_->PauseDownload(id_, !is_paused_);
309 is_paused_ = !is_paused_;
310 UpdateObservers();
311}
312
[email protected]7ae7c2cb2009-01-06 23:31:41313FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32314 if (safety_state_ == DownloadItem::SAFE)
315 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16316 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41317 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16318 AppendNumberToPath(&name, path_uniquifier_);
319 return name;
320 }
[email protected]9ccbb372008-10-10 18:50:32321 return original_name_;
322}
323
initial.commit09911bf2008-07-26 23:55:29324// DownloadManager implementation ----------------------------------------------
325
326// static
327void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
328 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
329 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32330 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
331
332 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41333 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12334 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
335 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32336 NOTREACHED();
337 }
[email protected]b9636002009-03-04 00:05:25338 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
339 default_download_path);
[email protected]f052118e2008-09-05 02:25:32340
341 // If the download path is dangerous we forcefully reset it. But if we do
342 // so we set a flag to make sure we only do it once, to avoid fighting
343 // the user if he really wants it on an unsafe place such as the desktop.
344
345 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41346 FilePath current_download_dir = FilePath::FromWStringHack(
347 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32348 if (DownloadPathIsDangerous(current_download_dir)) {
349 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41350 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32351 }
352 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
353 }
initial.commit09911bf2008-07-26 23:55:29354}
355
356DownloadManager::DownloadManager()
357 : shutdown_needed_(false),
358 profile_(NULL),
359 file_manager_(NULL),
360 ui_loop_(MessageLoop::current()),
361 file_loop_(NULL) {
362}
363
364DownloadManager::~DownloadManager() {
365 if (shutdown_needed_)
366 Shutdown();
367}
368
369void DownloadManager::Shutdown() {
370 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
371
372 // Stop receiving download updates
373 file_manager_->RemoveDownloadManager(this);
374
375 // Stop making history service requests
376 cancelable_consumer_.CancelAllRequests();
377
378 // 'in_progress_' may contain DownloadItems that have not finished the start
379 // complete (from the history service) and thus aren't in downloads_.
380 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32381 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29382 for (; it != in_progress_.end(); ++it) {
383 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32384 if (download->safety_state() == DownloadItem::DANGEROUS) {
385 // Forget about any download that the user did not approve.
386 // Note that we cannot call download->Remove() this would invalidate our
387 // iterator.
388 to_remove.insert(download);
389 continue;
initial.commit09911bf2008-07-26 23:55:29390 }
[email protected]9ccbb372008-10-10 18:50:32391 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
392 download->Cancel(false);
393 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29394 if (download->db_handle() == kUninitializedHandle) {
395 // An invalid handle means that 'download' does not yet exist in
396 // 'downloads_', so we have to delete it here.
397 delete download;
398 }
399 }
400
[email protected]9ccbb372008-10-10 18:50:32401 // 'dangerous_finished_' contains all complete downloads that have not been
402 // approved. They should be removed.
403 it = dangerous_finished_.begin();
404 for (; it != dangerous_finished_.end(); ++it)
405 to_remove.insert(it->second);
406
407 // Remove the dangerous download that are not approved.
408 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
409 rm_it != to_remove.end(); ++rm_it) {
410 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32411 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32412 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32413 // Same as above, delete the download if it is not in 'downloads_' (as the
414 // Remove() call above won't have deleted it).
415 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32416 delete download;
417 }
418 to_remove.clear();
419
initial.commit09911bf2008-07-26 23:55:29420 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32421 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29422 STLDeleteValues(&downloads_);
423
424 file_manager_ = NULL;
425
426 // Save our file extensions to auto open.
427 SaveAutoOpens();
428
429 // Make sure the save as dialog doesn't notify us back if we're gone before
430 // it returns.
431 if (select_file_dialog_.get())
432 select_file_dialog_->ListenerDestroyed();
433
434 shutdown_needed_ = false;
435}
436
437// Issue a history query for downloads matching 'search_text'. If 'search_text'
438// is empty, return all downloads that we know about.
439void DownloadManager::GetDownloads(Observer* observer,
440 const std::wstring& search_text) {
441 DCHECK(observer);
442
443 // Return a empty list if we've not yet received the set of downloads from the
444 // history system (we'll update all observers once we get that list in
445 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
446 std::vector<DownloadItem*> download_copy;
447 if (downloads_.empty()) {
448 observer->SetDownloads(download_copy);
449 return;
450 }
451
452 // We already know all the downloads and there is no filter, so just return a
453 // copy to the observer.
454 if (search_text.empty()) {
455 download_copy.reserve(downloads_.size());
456 for (DownloadMap::iterator it = downloads_.begin();
457 it != downloads_.end(); ++it) {
458 download_copy.push_back(it->second);
459 }
460
461 // We retain ownership of the DownloadItems.
462 observer->SetDownloads(download_copy);
463 return;
464 }
465
466 // Issue a request to the history service for a list of downloads matching
467 // our search text.
468 HistoryService* hs =
469 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
470 if (hs) {
471 HistoryService::Handle h =
472 hs->SearchDownloads(search_text,
473 &cancelable_consumer_,
474 NewCallback(this,
475 &DownloadManager::OnSearchComplete));
476 cancelable_consumer_.SetClientData(hs, h, observer);
477 }
478}
479
480// Query the history service for information about all persisted downloads.
481bool DownloadManager::Init(Profile* profile) {
482 DCHECK(profile);
483 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
484 shutdown_needed_ = true;
485
486 profile_ = profile;
487 request_context_ = profile_->GetRequestContext();
488
489 // 'incognito mode' will have access to past downloads, but we won't store
490 // information about new downloads while in that mode.
491 QueryHistoryForDownloads();
492
493 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
494 if (!rdh) {
495 NOTREACHED();
496 return false;
497 }
498
499 file_manager_ = rdh->download_file_manager();
500 if (!file_manager_) {
501 NOTREACHED();
502 return false;
503 }
504
505 file_loop_ = g_browser_process->file_thread()->message_loop();
506 if (!file_loop_) {
507 NOTREACHED();
508 return false;
509 }
510
511 // Get our user preference state.
512 PrefService* prefs = profile_->GetPrefs();
513 DCHECK(prefs);
514 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
515
initial.commit09911bf2008-07-26 23:55:29516 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
517
[email protected]7ae7c2cb2009-01-06 23:31:41518 // This variable is needed to resolve which CreateDirectory we want to point
519 // to. Without it, the NewRunnableFunction cannot resolve the ambiguity.
520 // TODO(estade): when file_util::CreateDirectory(wstring) is removed,
521 // get rid of |CreateDirectoryPtr|.
522 bool (*CreateDirectoryPtr)(const FilePath&) = &file_util::CreateDirectory;
[email protected]bb69e9b32008-08-14 23:08:14523 // Ensure that the download directory specified in the preferences exists.
[email protected]7ae7c2cb2009-01-06 23:31:41524 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
525 CreateDirectoryPtr, download_path()));
initial.commit09911bf2008-07-26 23:55:29526
[email protected]a0a9577b2009-05-27 23:52:32527 // We use this to determine possibly dangerous downloads.
[email protected]2b2f8f72009-02-24 22:42:05528 download_util::InitializeExeTypes(&exe_types_);
[email protected]2b2f8f72009-02-24 22:42:05529
530 // We store any file extension that should be opened automatically at
531 // download completion in this pref.
initial.commit09911bf2008-07-26 23:55:29532 std::wstring extensions_to_open =
533 prefs->GetString(prefs::kDownloadExtensionsToOpen);
534 std::vector<std::wstring> extensions;
535 SplitString(extensions_to_open, L':', &extensions);
536 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]b7f05882009-02-22 01:21:56537 if (!extensions[i].empty() && !IsExecutable(
538 FilePath::FromWStringHack(extensions[i]).value()))
539 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29540 }
541
542 return true;
543}
544
545void DownloadManager::QueryHistoryForDownloads() {
546 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
547 if (hs) {
548 hs->QueryDownloads(
549 &cancelable_consumer_,
550 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
551 }
552}
553
554// We have received a message from DownloadFileManager about a new download. We
555// create a download item and store it in our download map, and inform the
556// history system of a new download. Since this method can be called while the
557// history service thread is still reading the persistent state, we do not
558// insert the new DownloadItem into 'downloads_' or inform our observers at this
559// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
560// download creation as a callback from the history thread.
561void DownloadManager::StartDownload(DownloadCreateInfo* info) {
562 DCHECK(MessageLoop::current() == ui_loop_);
563 DCHECK(info);
564
[email protected]7d3851d82008-12-12 03:26:07565 // Freeze the user's preference for showing a Save As dialog. We're going to
566 // bounce around a bunch of threads and we don't want to worry about race
567 // conditions where the user changes this pref out from under us.
568 if (*prompt_for_download_)
569 info->save_as = true;
570
initial.commit09911bf2008-07-26 23:55:29571 // Determine the proper path for a download, by choosing either the default
572 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41573 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29574 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07575 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29576 info->suggested_path = last_download_path_;
577 else
[email protected]7ae7c2cb2009-01-06 23:31:41578 info->suggested_path = download_path();
579 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29580
[email protected]7d3851d82008-12-12 03:26:07581 if (!info->save_as) {
[email protected]4289d9b2009-07-25 21:17:34582 // Downloads can be marked as dangerous for two reasons:
583 // a) They have a dangerous-looking filename
584 // b) They are an extension that is not from the gallery
585 if (IsDangerous(info->suggested_path.BaseName()))
586 info->is_dangerous = true;
[email protected]336e0c32009-08-14 22:22:08587 else if (IsChromeExtension(info->suggested_path, info->mime_type) &&
[email protected]4289d9b2009-07-25 21:17:34588 !ExtensionsService::IsDownloadFromGallery(info->url,
589 info->referrer_url)) {
590 info->is_dangerous = true;
591 }
[email protected]e9ebf3fc2008-10-17 22:06:58592 }
593
initial.commit09911bf2008-07-26 23:55:29594 // We need to move over to the download thread because we don't want to stat
595 // the suggested path on the UI thread.
596 file_loop_->PostTask(FROM_HERE,
597 NewRunnableMethod(this,
598 &DownloadManager::CheckIfSuggestedPathExists,
599 info));
600}
601
602void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
603 DCHECK(info);
604
605 // Check writability of the suggested path. If we can't write to it, default
606 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41607 FilePath dir = info->suggested_path.DirName();
608 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32609 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29610 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29611 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41612 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29613 }
614
[email protected]7a256ea2008-10-17 17:34:16615 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29616
[email protected]6cade212008-12-03 00:32:22617 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58618 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41619 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32620 // Create a temporary file to hold the file until the user approves its
621 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41622 FilePath::StringType file_name;
623 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32624 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41625 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32626 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41627 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07628 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41629 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32630 }
631 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16632 } else {
633 // We know the final path, build it if necessary.
634 if (info->path_uniquifier > 0) {
635 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
636 // Setting path_uniquifier to 0 to make sure we don't try to unique it
637 // later on.
638 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07639 } else if (info->path_uniquifier == -1) {
640 // We failed to find a unique path. We have to prompt the user.
641 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16642 }
[email protected]9ccbb372008-10-10 18:50:32643 }
644
[email protected]7d3851d82008-12-12 03:26:07645 if (!info->save_as) {
646 // Create an empty file at the suggested path so that we don't allocate the
647 // same "non-existant" path to multiple downloads.
648 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ae7c2cb2009-01-06 23:31:41649 file_util::WriteFile(info->suggested_path.ToWStringHack(), "", 0);
[email protected]7d3851d82008-12-12 03:26:07650 }
651
initial.commit09911bf2008-07-26 23:55:29652 // Now we return to the UI thread.
653 ui_loop_->PostTask(FROM_HERE,
654 NewRunnableMethod(this,
655 &DownloadManager::OnPathExistenceAvailable,
656 info));
657}
658
659void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
660 DCHECK(MessageLoop::current() == ui_loop_);
661 DCHECK(info);
662
[email protected]7d3851d82008-12-12 03:26:07663 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29664 // We must ask the user for the place to put the download.
665 if (!select_file_dialog_.get())
666 select_file_dialog_ = SelectFileDialog::Create(this);
667
[email protected]57c6a652009-05-04 07:58:34668 TabContents* contents = tab_util::GetTabContentsByID(
initial.commit09911bf2008-07-26 23:55:29669 info->render_process_id, info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08670 SelectFileDialog::FileTypeInfo file_type_info;
671 file_type_info.extensions.resize(1);
672 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24673 if (!file_type_info.extensions[0][0].empty())
674 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08675 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23676 gfx::NativeWindow owning_window =
677 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29678 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34679 string16(),
680 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08681 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30682 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29683 } else {
684 // No prompting for download, just continue with the suggested name.
685 ContinueStartDownload(info, info->suggested_path);
686 }
687}
688
689void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41690 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29691 scoped_ptr<DownloadCreateInfo> infop(info);
692 info->path = target_path;
693
694 DownloadItem* download = NULL;
695 DownloadMap::iterator it = in_progress_.find(info->download_id);
696 if (it == in_progress_.end()) {
697 download = new DownloadItem(info->download_id,
698 info->path,
[email protected]7a256ea2008-10-17 17:34:16699 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29700 info->url,
[email protected]494c06e2009-07-25 01:06:42701 info->referrer_url,
[email protected]e435d6b72009-07-25 03:15:58702 info->mime_type,
[email protected]9ccbb372008-10-10 18:50:32703 info->original_name,
initial.commit09911bf2008-07-26 23:55:29704 info->start_time,
705 info->total_bytes,
706 info->render_process_id,
[email protected]9ccbb372008-10-10 18:50:32707 info->request_id,
708 info->is_dangerous);
initial.commit09911bf2008-07-26 23:55:29709 download->set_manager(this);
710 in_progress_[info->download_id] = download;
711 } else {
712 NOTREACHED(); // Should not exist!
713 return;
714 }
715
[email protected]6b323782009-03-27 18:43:08716 // Called before DownloadFinished in order to avoid a race condition where we
717 // attempt to open a completed download before it has been renamed.
718 file_loop_->PostTask(FROM_HERE,
719 NewRunnableMethod(file_manager_,
720 &DownloadFileManager::OnFinalDownloadName,
721 download->id(),
[email protected]8f783752009-04-01 23:33:45722 target_path,
723 this));
[email protected]6b323782009-03-27 18:43:08724
initial.commit09911bf2008-07-26 23:55:29725 // If the download already completed by the time we reached this point, then
726 // notify observers that it did.
727 PendingFinishedMap::iterator pending_it =
728 pending_finished_downloads_.find(info->download_id);
729 if (pending_it != pending_finished_downloads_.end())
730 DownloadFinished(pending_it->first, pending_it->second);
731
732 download->Rename(target_path);
733
initial.commit09911bf2008-07-26 23:55:29734 if (profile_->IsOffTheRecord()) {
735 // Fake a db handle for incognito mode, since nothing is actually stored in
736 // the database in this mode. We have to make sure that these handles don't
737 // collide with normal db handles, so we use a negative value. Eventually,
738 // they could overlap, but you'd have to do enough downloading that your ISP
739 // would likely stab you in the neck first. YMMV.
740 static int64 fake_db_handle = kUninitializedHandle - 1;
741 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
742 } else {
743 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22744 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29745 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
746 if (hs) {
747 hs->CreateDownload(
748 *info, &cancelable_consumer_,
749 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
750 }
751 }
752}
753
754// Convenience function for updating the history service for a download.
755void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
756 DCHECK(download);
757
758 // Don't store info in the database if the download was initiated while in
759 // incognito mode or if it hasn't been initialized in our database table.
760 if (download->db_handle() <= kUninitializedHandle)
761 return;
762
[email protected]6cade212008-12-03 00:32:22763 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29764 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
765 if (hs) {
766 hs->UpdateDownload(download->received_bytes(),
767 download->state(),
768 download->db_handle());
769 }
770}
771
772void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
773 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22774 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29775 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
776 if (download->db_handle() > kUninitializedHandle && hs)
777 hs->RemoveDownload(download->db_handle());
778}
779
[email protected]e93d2822009-01-30 05:59:59780void DownloadManager::RemoveDownloadsFromHistoryBetween(
781 const base::Time remove_begin,
782 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22783 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29784 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
785 if (hs)
786 hs->RemoveDownloadsBetween(remove_begin, remove_end);
787}
788
789void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
790 DownloadMap::iterator it = in_progress_.find(download_id);
791 if (it != in_progress_.end()) {
792 DownloadItem* download = it->second;
793 download->Update(size);
794 UpdateHistoryForDownload(download);
795 }
796}
797
798void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
799 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32800 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29801 // The download is done, but the user hasn't selected a final location for
802 // it yet (the Save As dialog box is probably still showing), so just keep
803 // track of the fact that this download id is complete, when the
804 // DownloadItem is constructed later we'll notify its completion then.
805 PendingFinishedMap::iterator erase_it =
806 pending_finished_downloads_.find(download_id);
807 DCHECK(erase_it == pending_finished_downloads_.end());
808 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32809 return;
initial.commit09911bf2008-07-26 23:55:29810 }
[email protected]9ccbb372008-10-10 18:50:32811
812 // Remove the id from the list of pending ids.
813 PendingFinishedMap::iterator erase_it =
814 pending_finished_downloads_.find(download_id);
815 if (erase_it != pending_finished_downloads_.end())
816 pending_finished_downloads_.erase(erase_it);
817
818 DownloadItem* download = it->second;
819 download->Finished(size);
820
821 // Clean up will happen when the history system create callback runs if we
822 // don't have a valid db_handle yet.
823 if (download->db_handle() != kUninitializedHandle) {
824 in_progress_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32825 UpdateHistoryForDownload(download);
826 }
827
828 // If this a dangerous download not yet validated by the user, don't do
829 // anything. When the user notifies us, it will trigger a call to
830 // ProceedWithFinishedDangerousDownload.
831 if (download->safety_state() == DownloadItem::DANGEROUS) {
832 dangerous_finished_[download_id] = download;
833 return;
834 }
835
836 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22837 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32838 // its final name before we can continue.
839 file_loop_->PostTask(FROM_HERE,
840 NewRunnableMethod(
841 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
842 download->db_handle(),
843 download->full_path(), download->original_name()));
844 return;
845 }
846 ContinueDownloadFinished(download);
847}
848
[email protected]8f783752009-04-01 23:33:45849void DownloadManager::DownloadRenamedToFinalName(int download_id,
850 const FilePath& full_path) {
[email protected]8f783752009-04-01 23:33:45851}
852
[email protected]9ccbb372008-10-10 18:50:32853void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
854 // If this was a dangerous download, it has now been approved and must be
855 // removed from dangerous_finished_ so it does not get deleted on shutdown.
856 DownloadMap::iterator it = dangerous_finished_.find(download->id());
857 if (it != dangerous_finished_.end())
858 dangerous_finished_.erase(it);
859
[email protected]5a102892009-07-15 19:59:30860 // Open the download if the user or user prefs indicate it should be.
861 FilePath::StringType extension = download->full_path().Extension();
862 // Drop the leading period. (The auto-open list is period-less.)
863 if (extension.size() > 0)
864 extension = extension.substr(1);
865
[email protected]0aad67b2009-07-15 20:34:28866 // Handle chrome extensions explicitly and skip the shell execute.
[email protected]1e7e93402009-08-13 20:55:17867 if (IsChromeExtension(download->full_path(), download->mime_type())) {
[email protected]494c06e2009-07-25 01:06:42868 OpenChromeExtension(download->full_path(), download->url(),
869 download->referrer_url());
[email protected]0aad67b2009-07-15 20:34:28870 download->set_auto_opened(true);
871 } else if (download->open_when_complete() ||
872 ShouldOpenFileExtension(extension)) {
[email protected]9ccbb372008-10-10 18:50:32873 OpenDownloadInShell(download, NULL);
[email protected]0aad67b2009-07-15 20:34:28874 download->set_auto_opened(true);
875 }
[email protected]9ccbb372008-10-10 18:50:32876
[email protected]0aad67b2009-07-15 20:34:28877 // Notify our observers that we are complete (the call to Finished() set the
878 // state to complete but did not notify).
879 download->UpdateObservers();
880}
[email protected]9ccbb372008-10-10 18:50:32881// Called on the file thread. Renames the downloaded file to its original name.
882void DownloadManager::ProceedWithFinishedDangerousDownload(
883 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41884 const FilePath& path,
885 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32886 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41887 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16888 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32889 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24890 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16891 // Make our name unique at this point, as if a dangerous file is downloading
892 // and a 2nd download is started for a file with the same name, they would
893 // have the same path. This is because we uniquify the name on download
894 // start, and at that time the first file does not exists yet, so the second
895 // file gets the same name.
896 uniquifier = GetUniquePathNumber(new_path);
897 if (uniquifier > 0)
898 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32899 success = file_util::Move(path, new_path);
900 } else {
901 NOTREACHED();
902 }
[email protected]6cade212008-12-03 00:32:22903
[email protected]9ccbb372008-10-10 18:50:32904 ui_loop_->PostTask(FROM_HERE,
905 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16906 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32907}
908
909// Call from the file thread when the finished dangerous download was renamed.
910void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
911 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41912 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16913 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32914 DownloadMap::iterator it = downloads_.find(download_handle);
915 if (it == downloads_.end()) {
916 NOTREACHED();
917 return;
918 }
919
920 DownloadItem* download = it->second;
921 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16922 if (success) {
923 // We need to update the path uniquifier so that the UI shows the right
924 // name when calling GetFileName().
925 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32926 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16927 }
[email protected]9ccbb372008-10-10 18:50:32928
929 // Continue the download finished sequence.
930 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29931}
932
933// static
934// We have to tell the ResourceDispatcherHost to cancel the download from this
[email protected]6cade212008-12-03 00:32:22935// thread, since we can't forward tasks from the file thread to the IO thread
initial.commit09911bf2008-07-26 23:55:29936// reliably (crash on shutdown race condition).
937void DownloadManager::CancelDownloadRequest(int render_process_id,
938 int request_id) {
939 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]ab820df2008-08-26 05:55:10940 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29941 if (!io_thread || !rdh)
942 return;
943 io_thread->message_loop()->PostTask(FROM_HERE,
944 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
945 rdh,
946 render_process_id,
947 request_id));
948}
949
950// static
951void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
952 int render_process_id,
953 int request_id) {
954 rdh->CancelRequest(render_process_id, request_id, false);
955}
956
957void DownloadManager::DownloadCancelled(int32 download_id) {
958 DownloadMap::iterator it = in_progress_.find(download_id);
959 if (it == in_progress_.end())
960 return;
961 DownloadItem* download = it->second;
962
initial.commit09911bf2008-07-26 23:55:29963 // Clean up will happen when the history system create callback runs if we
964 // don't have a valid db_handle yet.
965 if (download->db_handle() != kUninitializedHandle) {
966 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:29967 UpdateHistoryForDownload(download);
968 }
969
[email protected]d7d1c5c2009-08-05 23:52:50970 DownloadCancelledInternal(download_id,
971 download->render_process_id(),
972 download->request_id());
973}
974
975void DownloadManager::DownloadCancelledInternal(int download_id,
976 int render_process_id,
977 int request_id) {
978 // Cancel the network request.
979 CancelDownloadRequest(render_process_id, request_id);
980
initial.commit09911bf2008-07-26 23:55:29981 // Tell the file manager to cancel the download.
[email protected]d7d1c5c2009-08-05 23:52:50982 file_manager_->RemoveDownload(download_id, this); // On the UI thread
initial.commit09911bf2008-07-26 23:55:29983 file_loop_->PostTask(FROM_HERE,
984 NewRunnableMethod(file_manager_,
985 &DownloadFileManager::CancelDownload,
[email protected]d7d1c5c2009-08-05 23:52:50986 download_id));
initial.commit09911bf2008-07-26 23:55:29987}
988
989void DownloadManager::PauseDownload(int32 download_id, bool pause) {
990 DownloadMap::iterator it = in_progress_.find(download_id);
991 if (it != in_progress_.end()) {
992 DownloadItem* download = it->second;
993 if (pause == download->is_paused())
994 return;
995
996 // Inform the ResourceDispatcherHost of the new pause state.
[email protected]ab820df2008-08-26 05:55:10997 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29998 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
999 if (!io_thread || !rdh)
1000 return;
1001
1002 io_thread->message_loop()->PostTask(FROM_HERE,
1003 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
1004 rdh,
1005 download->render_process_id(),
1006 download->request_id(),
1007 pause));
1008 }
1009}
1010
1011// static
1012void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
1013 int render_process_id,
1014 int request_id,
1015 bool pause) {
1016 rdh->PauseRequest(render_process_id, request_id, pause);
1017}
1018
[email protected]7ae7c2cb2009-01-06 23:31:411019bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:321020 // TODO(jcampan): Improve me.
[email protected]2001fe82009-02-23 23:53:141021 FilePath::StringType extension = file_name.Extension();
1022 // Drop the leading period.
1023 if (extension.size() > 0)
1024 extension = extension.substr(1);
1025 return IsExecutable(extension);
[email protected]9ccbb372008-10-10 18:50:321026}
1027
1028void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:411029 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:321030 download->Rename(new_path);
1031
1032 // Update the history.
1033
1034 // No update necessary if the download was initiated while in incognito mode.
1035 if (download->db_handle() <= kUninitializedHandle)
1036 return;
1037
[email protected]6cade212008-12-03 00:32:221038 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:321039 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1040 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:411041 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:321042}
1043
initial.commit09911bf2008-07-26 23:55:291044void DownloadManager::RemoveDownload(int64 download_handle) {
1045 DownloadMap::iterator it = downloads_.find(download_handle);
1046 if (it == downloads_.end())
1047 return;
1048
1049 // Make history update.
1050 DownloadItem* download = it->second;
1051 RemoveDownloadFromHistory(download);
1052
1053 // Remove from our tables and delete.
1054 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321055 it = dangerous_finished_.find(download->id());
1056 if (it != dangerous_finished_.end())
1057 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291058
1059 // Tell observers to refresh their views.
1060 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:361061
1062 delete download;
initial.commit09911bf2008-07-26 23:55:291063}
1064
[email protected]e93d2822009-01-30 05:59:591065int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1066 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291067 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1068
initial.commit09911bf2008-07-26 23:55:291069 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:281070 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:291071 while (it != downloads_.end()) {
1072 DownloadItem* download = it->second;
1073 DownloadItem::DownloadState state = download->state();
1074 if (download->start_time() >= remove_begin &&
1075 (remove_end.is_null() || download->start_time() < remove_end) &&
1076 (state == DownloadItem::COMPLETE ||
1077 state == DownloadItem::CANCELLED)) {
1078 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561079 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581080
1081 // Also remove it from any completed dangerous downloads.
1082 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1083 if (dit != dangerous_finished_.end())
1084 dangerous_finished_.erase(dit);
1085
[email protected]78b8fcc92009-03-31 17:36:281086 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:291087
initial.commit09911bf2008-07-26 23:55:291088 continue;
1089 }
1090
1091 ++it;
1092 }
1093
1094 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281095 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291096 if (num_deleted > 0)
1097 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1098
[email protected]78b8fcc92009-03-31 17:36:281099 // Delete the download items after updating the observers.
1100 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1101 pending_deletes.clear();
1102
initial.commit09911bf2008-07-26 23:55:291103 return num_deleted;
1104}
1105
[email protected]e93d2822009-01-30 05:59:591106int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1107 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291108}
1109
[email protected]d41355e6f2009-04-07 21:21:121110int DownloadManager::RemoveAllDownloads() {
1111 // The null times make the date range unbounded.
1112 return RemoveDownloadsBetween(base::Time(), base::Time());
1113}
1114
initial.commit09911bf2008-07-26 23:55:291115// Initiate a download of a specific URL. We send the request to the
1116// ResourceDispatcherHost, and let it send us responses like a regular
1117// download.
1118void DownloadManager::DownloadUrl(const GURL& url,
1119 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:501120 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:341121 TabContents* tab_contents) {
1122 DCHECK(tab_contents);
[email protected]c9825a42009-05-01 22:51:501123 request_context_->set_referrer_charset(referrer_charset);
initial.commit09911bf2008-07-26 23:55:291124 file_manager_->DownloadUrl(url,
1125 referrer,
[email protected]57c6a652009-05-04 07:58:341126 tab_contents->process()->pid(),
1127 tab_contents->render_view_host()->routing_id(),
initial.commit09911bf2008-07-26 23:55:291128 request_context_.get());
1129}
1130
[email protected]7ae7c2cb2009-01-06 23:31:411131void DownloadManager::GenerateExtension(
1132 const FilePath& file_name,
1133 const std::string& mime_type,
1134 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291135 // We're worried about three things here:
1136 //
1137 // 1) Security. Many sites let users upload content, such as buddy icons, to
1138 // their web sites. We want to mitigate the case where an attacker
1139 // supplies a malicious executable with an executable file extension but an
1140 // honest site serves the content with a benign content type, such as
1141 // image/jpeg.
1142 //
1143 // 2) Usability. If the site fails to provide a file extension, we want to
1144 // guess a reasonable file extension based on the content type.
1145 //
1146 // 3) Shell integration. Some file extensions automatically integrate with
1147 // the shell. We block these extensions to prevent a malicious web site
1148 // from integrating with the user's shell.
1149
[email protected]7ae7c2cb2009-01-06 23:31:411150 static const FilePath::CharType default_extension[] =
1151 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291152
1153 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411154 FilePath::StringType extension(
1155 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291156
[email protected]b7f05882009-02-22 01:21:561157#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291158 // Rename shell-integrated extensions.
1159 if (win_util::IsShellIntegratedExtension(extension))
1160 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561161#endif
initial.commit09911bf2008-07-26 23:55:291162
1163 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411164 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411165 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291166 if (mime_type == mime_type_from_extension) {
1167 // The hinted extension matches the mime type. It looks like a winner.
1168 generated_extension->swap(extension);
1169 return;
1170 }
1171
1172 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1173 // We want to be careful about executable extensions. The worry here is
1174 // that a trusted web site could be tricked into dropping an executable file
1175 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101176 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291177 // We couldn't find a good extension for this content type. Use a dummy
1178 // extension instead.
1179 extension.assign(default_extension);
1180 }
1181 }
1182
1183 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101184 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291185 } else {
[email protected]6cade212008-12-03 00:32:221186 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291187 // 1. New extension is not ".txt"
1188 // 2. New extension is not the same as the already existing extension.
1189 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411190 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291191 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1192 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371193 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1194 // servers, i.e. bug 5772.
[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) &&
1200 (append_extension != FILE_PATH_LITERAL("tar") ||
1201 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171202 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291203 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171204 }
initial.commit09911bf2008-07-26 23:55:291205 }
1206 }
1207
1208 generated_extension->swap(extension);
1209}
1210
1211void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411212 FilePath* generated_name) {
1213 *generated_name = FilePath::FromWStringHack(
[email protected]8ac1a752008-07-31 19:40:371214 net::GetSuggestedFilename(GURL(info->url),
1215 info->content_disposition,
[email protected]c9825a42009-05-01 22:51:501216 info->referrer_charset,
[email protected]7ae7c2cb2009-01-06 23:31:411217 L"download"));
1218 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291219
[email protected]7ae7c2cb2009-01-06 23:31:411220 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291221}
1222
1223void DownloadManager::AddObserver(Observer* observer) {
1224 observers_.AddObserver(observer);
1225 observer->ModelChanged();
1226}
1227
1228void DownloadManager::RemoveObserver(Observer* observer) {
1229 observers_.RemoveObserver(observer);
1230}
1231
1232// Post Windows Shell operations to the Download thread, to avoid blocking the
1233// user interface.
1234void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1235 DCHECK(file_manager_);
[email protected]8b6ff012009-08-18 22:29:581236 DCHECK(MessageLoop::current() == ui_loop_);
1237#if defined(OS_MACOSX)
1238 // Mac needs to run this operation on the UI thread.
1239 platform_util::ShowItemInFolder(download->full_path());
1240#else
initial.commit09911bf2008-07-26 23:55:291241 file_loop_->PostTask(FROM_HERE,
1242 NewRunnableMethod(file_manager_,
1243 &DownloadFileManager::OnShowDownloadInShell,
[email protected]7ae7c2cb2009-01-06 23:31:411244 FilePath(download->full_path())));
[email protected]8b6ff012009-08-18 22:29:581245#endif
initial.commit09911bf2008-07-26 23:55:291246}
1247
[email protected]8f783752009-04-01 23:33:451248void DownloadManager::OpenDownload(const DownloadItem* download,
1249 gfx::NativeView parent_window) {
[email protected]0e34d7892009-06-05 19:17:401250 // Open Chrome extensions with ExtensionsService. For everything else do shell
[email protected]8f783752009-04-01 23:33:451251 // execute.
[email protected]1e7e93402009-08-13 20:55:171252 if (IsChromeExtension(download->full_path(), download->mime_type())) {
[email protected]494c06e2009-07-25 01:06:421253 OpenChromeExtension(download->full_path(), download->url(),
1254 download->referrer_url());
[email protected]8f783752009-04-01 23:33:451255 } else {
1256 OpenDownloadInShell(download, parent_window);
1257 }
1258}
1259
[email protected]c1e432a2009-07-22 21:21:481260void DownloadManager::OpenChromeExtension(const FilePath& full_path,
[email protected]494c06e2009-07-25 01:06:421261 const GURL& download_url,
1262 const GURL& referrer_url) {
[email protected]6ef635e42009-07-26 06:16:121263 // We don't support extensions in OTR mode.
[email protected]2a464a92009-08-01 17:58:351264 ExtensionsService* service = profile_->GetExtensionsService();
1265 if (service) {
1266 CrxInstaller::Start(full_path,
1267 service->install_directory(),
1268 Extension::INTERNAL,
1269 "", // no expected id
1270 true, // please delete crx on completion
1271 g_browser_process->file_thread()->message_loop(),
1272 service,
1273 new ExtensionInstallUI(profile_));
1274 }
[email protected]8f783752009-04-01 23:33:451275}
1276
initial.commit09911bf2008-07-26 23:55:291277void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591278 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291279 DCHECK(file_manager_);
[email protected]8b6ff012009-08-18 22:29:581280 DCHECK(MessageLoop::current() == ui_loop_);
1281#if defined(OS_MACOSX)
1282 // Mac OS X requires opening downloads on the UI thread.
1283 platform_util::OpenItem(download->full_path());
1284#else
initial.commit09911bf2008-07-26 23:55:291285 file_loop_->PostTask(FROM_HERE,
1286 NewRunnableMethod(file_manager_,
1287 &DownloadFileManager::OnOpenDownloadInShell,
1288 download->full_path(), download->url(), parent_window));
[email protected]8b6ff012009-08-18 22:29:581289#endif
initial.commit09911bf2008-07-26 23:55:291290}
1291
[email protected]7ae7c2cb2009-01-06 23:31:411292void DownloadManager::OpenFilesOfExtension(
1293 const FilePath::StringType& extension, bool open) {
initial.commit09911bf2008-07-26 23:55:291294 if (open && !IsExecutable(extension))
1295 auto_open_.insert(extension);
1296 else
1297 auto_open_.erase(extension);
1298 SaveAutoOpens();
1299}
1300
[email protected]7ae7c2cb2009-01-06 23:31:411301bool DownloadManager::ShouldOpenFileExtension(
1302 const FilePath::StringType& extension) {
[email protected]8c756ac2009-01-30 23:36:411303 // Special-case Chrome extensions as always-open.
initial.commit09911bf2008-07-26 23:55:291304 if (!IsExecutable(extension) &&
[email protected]8c756ac2009-01-30 23:36:411305 (auto_open_.find(extension) != auto_open_.end() ||
[email protected]f1ce6e62009-06-29 20:31:291306 Extension::IsExtension(FilePath(extension))))
[email protected]8c756ac2009-01-30 23:36:411307 return true;
initial.commit09911bf2008-07-26 23:55:291308 return false;
1309}
1310
[email protected]7b73d992008-12-15 20:56:461311static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291312 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461313 "text/javascript",
1314 "text/javascript;version=*",
[email protected]54d8d452009-04-08 17:29:241315 // Registry files can cause critical changes to the MS OS behavior.
1316 // Addition of this mimetype also addresses bug 7337.
1317 "text/x-registry",
[email protected]60ff8f912008-12-05 07:58:391318 // Some sites use binary/octet-stream to mean application/octet-stream.
1319 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461320 "binary/octet-stream"
1321};
initial.commit09911bf2008-07-26 23:55:291322
[email protected]7b73d992008-12-15 20:56:461323static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291324 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461325 "application/*+xml",
1326 "application/xml"
1327};
initial.commit09911bf2008-07-26 23:55:291328
[email protected]7b73d992008-12-15 20:56:461329// static
1330bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411331 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461332 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1333 return true;
1334 }
[email protected]bae0ea12009-02-14 01:20:411335 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461336 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1337 return false;
1338 }
1339 // We consider only other application types to be executable.
1340 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291341}
1342
[email protected]7ae7c2cb2009-01-06 23:31:411343bool DownloadManager::IsExecutable(const FilePath::StringType& extension) {
[email protected]64da0b932009-02-24 02:30:041344 if (!IsStringASCII(extension))
1345 return false;
[email protected]a0a9577b2009-05-27 23:52:321346#if defined(OS_WIN)
[email protected]64da0b932009-02-24 02:30:041347 std::string ascii_extension = WideToASCII(extension);
[email protected]e9ef0a62009-08-11 22:50:131348#elif defined(OS_POSIX)
[email protected]a0a9577b2009-05-27 23:52:321349 std::string ascii_extension = extension;
1350#endif
[email protected]64da0b932009-02-24 02:30:041351 StringToLowerASCII(&ascii_extension);
1352
1353 return exe_types_.find(ascii_extension) != exe_types_.end();
initial.commit09911bf2008-07-26 23:55:291354}
1355
1356void DownloadManager::ResetAutoOpenFiles() {
1357 auto_open_.clear();
1358 SaveAutoOpens();
1359}
1360
1361bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1362 return !auto_open_.empty();
1363}
1364
1365void DownloadManager::SaveAutoOpens() {
1366 PrefService* prefs = profile_->GetPrefs();
1367 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411368 FilePath::StringType extensions;
1369 for (std::set<FilePath::StringType>::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291370 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411371 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291372 }
1373 if (!extensions.empty())
1374 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561375
1376 std::wstring extensions_w;
1377#if defined(OS_WIN)
1378 extensions_w = extensions;
1379#elif defined(OS_POSIX)
[email protected]1b5044d2009-02-24 00:04:141380 extensions_w = base::SysNativeMBToWide(extensions);
[email protected]b7f05882009-02-22 01:21:561381#endif
1382
1383 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291384 }
1385}
1386
[email protected]561abe62009-04-06 18:08:341387void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361388 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291389 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071390 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411391 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291392 ContinueStartDownload(info, path);
1393}
1394
1395void DownloadManager::FileSelectionCanceled(void* params) {
1396 // The user didn't pick a place to save the file, so need to cancel the
1397 // download that's already in progress to the temporary location.
1398 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]d7d1c5c2009-08-05 23:52:501399 DownloadCancelledInternal(info->download_id,
1400 info->render_process_id,
1401 info->request_id);
initial.commit09911bf2008-07-26 23:55:291402}
1403
[email protected]7ae7c2cb2009-01-06 23:31:411404void DownloadManager::DeleteDownload(const FilePath& path) {
1405 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
1406 &DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321407}
1408
1409
1410void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1411 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1412 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1413 download->UpdateObservers();
1414
1415 // If the download is not complete, nothing to do. The required
1416 // post-processing will be performed when it does complete.
1417 if (download->state() != DownloadItem::COMPLETE)
1418 return;
1419
1420 file_loop_->PostTask(FROM_HERE,
1421 NewRunnableMethod(this,
1422 &DownloadManager::ProceedWithFinishedDangerousDownload,
1423 download->db_handle(), download->full_path(),
1424 download->original_name()));
1425}
1426
[email protected]763f946a2009-01-06 19:04:391427void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411428 FilePath* file_name) {
1429 // Make sure we get the right file extension
1430 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391431 GenerateExtension(*file_name, mime_type, &extension);
1432 file_util::ReplaceExtension(file_name, extension);
1433
[email protected]2b2f8f72009-02-24 22:42:051434#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391435 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411436 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391437 DCHECK(!leaf_name.empty());
1438 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411439 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1440 *file_name = file_name->DirName();
1441 if (file_name->value() == FilePath::kCurrentDirectory) {
1442 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391443 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411444 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391445 }
1446 }
[email protected]b7f05882009-02-22 01:21:561447#elif defined(OS_POSIX)
1448 NOTIMPLEMENTED();
1449#endif
[email protected]763f946a2009-01-06 19:04:391450}
1451
initial.commit09911bf2008-07-26 23:55:291452// Operations posted to us from the history service ----------------------------
1453
1454// The history service has retrieved all download entries. 'entries' contains
1455// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1456void DownloadManager::OnQueryDownloadEntriesComplete(
1457 std::vector<DownloadCreateInfo>* entries) {
1458 for (size_t i = 0; i < entries->size(); ++i) {
1459 DownloadItem* download = new DownloadItem(entries->at(i));
1460 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1461 downloads_[download->db_handle()] = download;
1462 download->set_manager(this);
1463 }
1464 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1465}
1466
initial.commit09911bf2008-07-26 23:55:291467// Once the new DownloadItem's creation info has been committed to the history
1468// service, we associate the DownloadItem with the db handle, update our
1469// 'downloads_' map and inform observers.
1470void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1471 int64 db_handle) {
1472 DownloadMap::iterator it = in_progress_.find(info.download_id);
1473 DCHECK(it != in_progress_.end());
1474
1475 DownloadItem* download = it->second;
1476 DCHECK(download->db_handle() == kUninitializedHandle);
1477 download->set_db_handle(db_handle);
1478
1479 // Insert into our full map.
1480 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1481 downloads_[download->db_handle()] = download;
1482
[email protected]5e595482009-05-06 20:16:531483 // Show in the appropropriate browser UI.
1484 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291485
1486 // Inform interested objects about the new download.
1487 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
initial.commit09911bf2008-07-26 23:55:291488
1489 // If this download has been completed before we've received the db handle,
1490 // post one final message to the history service so that it can be properly
1491 // in sync with the DownloadItem's completion status, and also inform any
1492 // observers so that they get more than just the start notification.
1493 if (download->state() != DownloadItem::IN_PROGRESS) {
1494 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291495 UpdateHistoryForDownload(download);
1496 download->UpdateObservers();
1497 }
1498}
1499
1500// Called when the history service has retrieved the list of downloads that
1501// match the search text.
1502void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1503 std::vector<int64>* results) {
1504 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1505 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1506 if (!requestor)
1507 return;
1508
1509 std::vector<DownloadItem*> searched_downloads;
1510 for (std::vector<int64>::iterator it = results->begin();
1511 it != results->end(); ++it) {
1512 DownloadMap::iterator dit = downloads_.find(*it);
1513 if (dit != downloads_.end())
1514 searched_downloads.push_back(dit->second);
1515 }
1516
1517 requestor->SetDownloads(searched_downloads);
1518}
[email protected]905a08d2008-11-19 07:24:121519
[email protected]5e595482009-05-06 20:16:531520void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1521 DownloadItem* download) {
[email protected]5e595482009-05-06 20:16:531522 // The 'contents' may no longer exist if the user closed the tab before we get
1523 // this start completion event. If it does, tell the origin TabContents to
1524 // display its download shelf.
1525 TabContents* contents =
1526 tab_util::GetTabContentsByID(info.render_process_id, info.render_view_id);
1527
1528 // If the contents no longer exists, we start the download in the last active
1529 // browser. This is not ideal but better than fully hiding the download from
1530 // the user.
1531 if (!contents) {
1532 Browser* last_active = BrowserList::GetLastActive();
1533 if (last_active)
1534 contents = last_active->GetSelectedTabContents();
1535 }
1536
1537 if (contents)
1538 contents->OnStartDownload(download);
1539}
1540
[email protected]6cade212008-12-03 00:32:221541// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121542void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411543 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381544}
1545