blob: 92a9885e0174db3e5e30e630abed877d06da23e4 [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]076700e62009-04-01 18:41:2335#include "chrome/common/platform_util.h"
initial.commit09911bf2008-07-26 23:55:2936#include "chrome/common/pref_names.h"
37#include "chrome/common/pref_service.h"
[email protected]46072d42008-07-28 14:49:3538#include "googleurl/src/gurl.h"
[email protected]d81706b82009-04-03 20:28:4439#include "grit/chromium_strings.h"
[email protected]34ac8f32009-02-22 23:03:2740#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2941#include "net/base/mime_util.h"
42#include "net/base/net_util.h"
43#include "net/url_request/url_request_context.h"
44
[email protected]b7f05882009-02-22 01:21:5645#if defined(OS_WIN)
[email protected]4a0765a2009-05-08 23:12:2546#include "app/win_util.h"
[email protected]b7f05882009-02-22 01:21:5647#include "base/registry.h"
48#include "base/win_util.h"
[email protected]a0a9577b2009-05-27 23:52:3249#endif
50
[email protected]b7f05882009-02-22 01:21:5651
[email protected]0f44d3e2009-03-12 23:36:3052#if defined(OS_LINUX)
53#include <gtk/gtk.h>
54#endif
55
initial.commit09911bf2008-07-26 23:55:2956// Periodically update our observers.
57class DownloadItemUpdateTask : public Task {
58 public:
59 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
60 void Run() { if (item_) item_->UpdateObservers(); }
61
62 private:
63 DownloadItem* item_;
64};
65
66// Update frequency (milliseconds).
67static const int kUpdateTimeMs = 1000;
68
69// Our download table ID starts at 1, so we use 0 to represent a download that
70// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2271// database handles in incognito mode starting at -1 and progressively getting
72// more negative.
initial.commit09911bf2008-07-26 23:55:2973static const int kUninitializedHandle = 0;
74
[email protected]7a256ea2008-10-17 17:34:1675// Appends the passed the number between parenthesis the path before the
76// extension.
[email protected]7ae7c2cb2009-01-06 23:31:4177static void AppendNumberToPath(FilePath* path, int number) {
78 file_util::InsertBeforeExtension(path,
79 StringPrintf(FILE_PATH_LITERAL(" (%d)"), number));
[email protected]7a256ea2008-10-17 17:34:1680}
81
82// Attempts to find a number that can be appended to that path to make it
83// unique. If |path| does not exist, 0 is returned. If it fails to find such
84// a number, -1 is returned.
[email protected]7ae7c2cb2009-01-06 23:31:4185static int GetUniquePathNumber(const FilePath& path) {
initial.commit09911bf2008-07-26 23:55:2986 const int kMaxAttempts = 100;
87
[email protected]7a256ea2008-10-17 17:34:1688 if (!file_util::PathExists(path))
89 return 0;
initial.commit09911bf2008-07-26 23:55:2990
[email protected]7ae7c2cb2009-01-06 23:31:4191 FilePath new_path;
initial.commit09911bf2008-07-26 23:55:2992 for (int count = 1; count <= kMaxAttempts; ++count) {
[email protected]7ae7c2cb2009-01-06 23:31:4193 new_path = FilePath(path);
[email protected]7a256ea2008-10-17 17:34:1694 AppendNumberToPath(&new_path, count);
initial.commit09911bf2008-07-26 23:55:2995
[email protected]7a256ea2008-10-17 17:34:1696 if (!file_util::PathExists(new_path))
97 return count;
initial.commit09911bf2008-07-26 23:55:2998 }
99
[email protected]7a256ea2008-10-17 17:34:16100 return -1;
initial.commit09911bf2008-07-26 23:55:29101}
102
[email protected]7ae7c2cb2009-01-06 23:31:41103static bool DownloadPathIsDangerous(const FilePath& download_path) {
104 FilePath desktop_dir;
[email protected]f052118e2008-09-05 02:25:32105 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
106 NOTREACHED();
107 return false;
108 }
109 return (download_path == desktop_dir);
110}
111
[email protected]1e7e93402009-08-13 20:55:17112// Helper to determine if a download is a Chrome extension. We should be able to
113// just use the mime type, but even our own servers are not setup to serve the
114// right headers yet, so we have a short-term file extension heuristic, too.
115static bool IsChromeExtension(const FilePath& path,
116 const std::string& mime_type) {
117 // If the server says it is an extension, it is definitely an extension.
118 if (mime_type == Extension::kMimeType)
119 return true;
120
121 // Otherwise, it is an extension if it has the right, err, extension.
122 return path.Extension().size() > 1 &&
123 path.Extension().substr(1) == chrome::kExtensionFileExtension;
124}
125
initial.commit09911bf2008-07-26 23:55:29126// DownloadItem implementation -------------------------------------------------
127
128// Constructor for reading from the history service.
129DownloadItem::DownloadItem(const DownloadCreateInfo& info)
130 : id_(-1),
131 full_path_(info.path),
132 url_(info.url),
[email protected]e435d6b72009-07-25 03:15:58133 referrer_url_(info.referrer_url),
134 mime_type_(info.mime_type),
initial.commit09911bf2008-07-26 23:55:29135 total_bytes_(info.total_bytes),
136 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56137 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29138 state_(static_cast<DownloadState>(info.state)),
139 start_time_(info.start_time),
140 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29141 manager_(NULL),
142 is_paused_(false),
143 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56144 safety_state_(SAFE),
[email protected]0aad67b2009-07-15 20:34:28145 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56146 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29147 render_process_id_(-1),
148 request_id_(-1) {
149 if (state_ == IN_PROGRESS)
150 state_ = CANCELLED;
151 Init(false /* don't start progress timer */);
152}
153
154// Constructor for DownloadItem created via user action in the main thread.
155DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41156 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16157 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32158 const GURL& url,
[email protected]494c06e2009-07-25 01:06:42159 const GURL& referrer_url,
[email protected]e435d6b72009-07-25 03:15:58160 const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:41161 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59162 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29163 int64 download_size,
164 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32165 int request_id,
166 bool is_dangerous)
initial.commit09911bf2008-07-26 23:55:29167 : id_(download_id),
168 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16169 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29170 url_(url),
[email protected]494c06e2009-07-25 01:06:42171 referrer_url_(referrer_url),
[email protected]e435d6b72009-07-25 03:15:58172 mime_type_(mime_type),
initial.commit09911bf2008-07-26 23:55:29173 total_bytes_(download_size),
174 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56175 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29176 state_(IN_PROGRESS),
177 start_time_(start_time),
178 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29179 manager_(NULL),
180 is_paused_(false),
181 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56182 safety_state_(is_dangerous ? DANGEROUS : SAFE),
[email protected]0aad67b2009-07-15 20:34:28183 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56184 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29185 render_process_id_(render_process_id),
186 request_id_(request_id) {
187 Init(true /* start progress timer */);
188}
189
190void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41191 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29192 if (start_timer)
193 StartProgressTimer();
194}
195
196DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29197 state_ = REMOVING;
198 UpdateObservers();
199}
200
201void DownloadItem::AddObserver(Observer* observer) {
202 observers_.AddObserver(observer);
203}
204
205void DownloadItem::RemoveObserver(Observer* observer) {
206 observers_.RemoveObserver(observer);
207}
208
209void DownloadItem::UpdateObservers() {
210 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
211}
212
[email protected]45e3c122009-04-07 19:58:03213void DownloadItem::NotifyObserversDownloadOpened() {
214 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadOpened(this));
215}
216
initial.commit09911bf2008-07-26 23:55:29217// If we've received more data than we were expecting (bad server info?), revert
218// to 'unknown size mode'.
219void DownloadItem::UpdateSize(int64 bytes_so_far) {
220 received_bytes_ = bytes_so_far;
221 if (received_bytes_ > total_bytes_)
222 total_bytes_ = 0;
223}
224
225// Updates from the download thread may have been posted while this download
226// was being cancelled in the UI thread, so we'll accept them unless we're
227// complete.
228void DownloadItem::Update(int64 bytes_so_far) {
229 if (state_ == COMPLETE) {
230 NOTREACHED();
231 return;
232 }
233 UpdateSize(bytes_so_far);
234 UpdateObservers();
235}
236
[email protected]6cade212008-12-03 00:32:22237// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29238void DownloadItem::Cancel(bool update_history) {
239 if (state_ != IN_PROGRESS) {
240 // Small downloads might be complete before this method has a chance to run.
241 return;
242 }
243 state_ = CANCELLED;
244 UpdateObservers();
245 StopProgressTimer();
246 if (update_history)
247 manager_->DownloadCancelled(id_);
248}
249
250void DownloadItem::Finished(int64 size) {
251 state_ = COMPLETE;
252 UpdateSize(size);
[email protected]22fbe5a2008-10-29 22:20:40253 UpdateObservers();
initial.commit09911bf2008-07-26 23:55:29254 StopProgressTimer();
255}
256
[email protected]9ccbb372008-10-10 18:50:32257void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29258 Cancel(true);
259 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32260 if (delete_on_disk)
261 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29262 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22263 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29264}
265
266void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59267 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14268 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29269}
270
271void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14272 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29273}
274
[email protected]e93d2822009-01-30 05:59:59275bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29276 if (total_bytes_ <= 0)
277 return false; // We never received the content_length for this download.
278
279 int64 speed = CurrentSpeed();
280 if (speed == 0)
281 return false;
282
283 *remaining =
[email protected]e93d2822009-01-30 05:59:59284 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29285 return true;
286}
287
288int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56289 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
290 int64 diff_ms = diff.InMilliseconds();
291 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29292}
293
294int DownloadItem::PercentComplete() const {
295 int percent = -1;
296 if (total_bytes_ > 0)
297 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
298 return percent;
299}
300
[email protected]7ae7c2cb2009-01-06 23:31:41301void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29302 DCHECK(!full_path.empty());
303 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41304 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29305}
306
307void DownloadItem::TogglePause() {
308 DCHECK(state_ == IN_PROGRESS);
309 manager_->PauseDownload(id_, !is_paused_);
310 is_paused_ = !is_paused_;
311 UpdateObservers();
312}
313
[email protected]7ae7c2cb2009-01-06 23:31:41314FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32315 if (safety_state_ == DownloadItem::SAFE)
316 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16317 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41318 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16319 AppendNumberToPath(&name, path_uniquifier_);
320 return name;
321 }
[email protected]9ccbb372008-10-10 18:50:32322 return original_name_;
323}
324
initial.commit09911bf2008-07-26 23:55:29325// DownloadManager implementation ----------------------------------------------
326
327// static
328void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
329 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
330 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32331 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
332
333 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41334 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12335 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
336 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32337 NOTREACHED();
338 }
[email protected]b9636002009-03-04 00:05:25339 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
340 default_download_path);
[email protected]f052118e2008-09-05 02:25:32341
342 // If the download path is dangerous we forcefully reset it. But if we do
343 // so we set a flag to make sure we only do it once, to avoid fighting
344 // the user if he really wants it on an unsafe place such as the desktop.
345
346 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41347 FilePath current_download_dir = FilePath::FromWStringHack(
348 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32349 if (DownloadPathIsDangerous(current_download_dir)) {
350 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41351 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32352 }
353 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
354 }
initial.commit09911bf2008-07-26 23:55:29355}
356
357DownloadManager::DownloadManager()
358 : shutdown_needed_(false),
359 profile_(NULL),
360 file_manager_(NULL),
361 ui_loop_(MessageLoop::current()),
362 file_loop_(NULL) {
363}
364
365DownloadManager::~DownloadManager() {
366 if (shutdown_needed_)
367 Shutdown();
368}
369
370void DownloadManager::Shutdown() {
371 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
372
373 // Stop receiving download updates
374 file_manager_->RemoveDownloadManager(this);
375
376 // Stop making history service requests
377 cancelable_consumer_.CancelAllRequests();
378
379 // 'in_progress_' may contain DownloadItems that have not finished the start
380 // complete (from the history service) and thus aren't in downloads_.
381 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32382 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29383 for (; it != in_progress_.end(); ++it) {
384 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32385 if (download->safety_state() == DownloadItem::DANGEROUS) {
386 // Forget about any download that the user did not approve.
387 // Note that we cannot call download->Remove() this would invalidate our
388 // iterator.
389 to_remove.insert(download);
390 continue;
initial.commit09911bf2008-07-26 23:55:29391 }
[email protected]9ccbb372008-10-10 18:50:32392 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
393 download->Cancel(false);
394 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29395 if (download->db_handle() == kUninitializedHandle) {
396 // An invalid handle means that 'download' does not yet exist in
397 // 'downloads_', so we have to delete it here.
398 delete download;
399 }
400 }
401
[email protected]9ccbb372008-10-10 18:50:32402 // 'dangerous_finished_' contains all complete downloads that have not been
403 // approved. They should be removed.
404 it = dangerous_finished_.begin();
405 for (; it != dangerous_finished_.end(); ++it)
406 to_remove.insert(it->second);
407
408 // Remove the dangerous download that are not approved.
409 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
410 rm_it != to_remove.end(); ++rm_it) {
411 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32412 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32413 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32414 // Same as above, delete the download if it is not in 'downloads_' (as the
415 // Remove() call above won't have deleted it).
416 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32417 delete download;
418 }
419 to_remove.clear();
420
initial.commit09911bf2008-07-26 23:55:29421 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32422 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29423 STLDeleteValues(&downloads_);
424
425 file_manager_ = NULL;
426
427 // Save our file extensions to auto open.
428 SaveAutoOpens();
429
430 // Make sure the save as dialog doesn't notify us back if we're gone before
431 // it returns.
432 if (select_file_dialog_.get())
433 select_file_dialog_->ListenerDestroyed();
434
435 shutdown_needed_ = false;
436}
437
438// Issue a history query for downloads matching 'search_text'. If 'search_text'
439// is empty, return all downloads that we know about.
440void DownloadManager::GetDownloads(Observer* observer,
441 const std::wstring& search_text) {
442 DCHECK(observer);
443
444 // Return a empty list if we've not yet received the set of downloads from the
445 // history system (we'll update all observers once we get that list in
446 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
447 std::vector<DownloadItem*> download_copy;
448 if (downloads_.empty()) {
449 observer->SetDownloads(download_copy);
450 return;
451 }
452
453 // We already know all the downloads and there is no filter, so just return a
454 // copy to the observer.
455 if (search_text.empty()) {
456 download_copy.reserve(downloads_.size());
457 for (DownloadMap::iterator it = downloads_.begin();
458 it != downloads_.end(); ++it) {
459 download_copy.push_back(it->second);
460 }
461
462 // We retain ownership of the DownloadItems.
463 observer->SetDownloads(download_copy);
464 return;
465 }
466
467 // Issue a request to the history service for a list of downloads matching
468 // our search text.
469 HistoryService* hs =
470 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
471 if (hs) {
472 HistoryService::Handle h =
473 hs->SearchDownloads(search_text,
474 &cancelable_consumer_,
475 NewCallback(this,
476 &DownloadManager::OnSearchComplete));
477 cancelable_consumer_.SetClientData(hs, h, observer);
478 }
479}
480
481// Query the history service for information about all persisted downloads.
482bool DownloadManager::Init(Profile* profile) {
483 DCHECK(profile);
484 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
485 shutdown_needed_ = true;
486
487 profile_ = profile;
488 request_context_ = profile_->GetRequestContext();
489
490 // 'incognito mode' will have access to past downloads, but we won't store
491 // information about new downloads while in that mode.
492 QueryHistoryForDownloads();
493
494 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
495 if (!rdh) {
496 NOTREACHED();
497 return false;
498 }
499
500 file_manager_ = rdh->download_file_manager();
501 if (!file_manager_) {
502 NOTREACHED();
503 return false;
504 }
505
506 file_loop_ = g_browser_process->file_thread()->message_loop();
507 if (!file_loop_) {
508 NOTREACHED();
509 return false;
510 }
511
512 // Get our user preference state.
513 PrefService* prefs = profile_->GetPrefs();
514 DCHECK(prefs);
515 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
516
initial.commit09911bf2008-07-26 23:55:29517 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
518
[email protected]7ae7c2cb2009-01-06 23:31:41519 // This variable is needed to resolve which CreateDirectory we want to point
520 // to. Without it, the NewRunnableFunction cannot resolve the ambiguity.
521 // TODO(estade): when file_util::CreateDirectory(wstring) is removed,
522 // get rid of |CreateDirectoryPtr|.
523 bool (*CreateDirectoryPtr)(const FilePath&) = &file_util::CreateDirectory;
[email protected]bb69e9b32008-08-14 23:08:14524 // Ensure that the download directory specified in the preferences exists.
[email protected]7ae7c2cb2009-01-06 23:31:41525 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
526 CreateDirectoryPtr, download_path()));
initial.commit09911bf2008-07-26 23:55:29527
[email protected]a0a9577b2009-05-27 23:52:32528 // We use this to determine possibly dangerous downloads.
[email protected]2b2f8f72009-02-24 22:42:05529 download_util::InitializeExeTypes(&exe_types_);
[email protected]2b2f8f72009-02-24 22:42:05530
531 // We store any file extension that should be opened automatically at
532 // download completion in this pref.
initial.commit09911bf2008-07-26 23:55:29533 std::wstring extensions_to_open =
534 prefs->GetString(prefs::kDownloadExtensionsToOpen);
535 std::vector<std::wstring> extensions;
536 SplitString(extensions_to_open, L':', &extensions);
537 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]b7f05882009-02-22 01:21:56538 if (!extensions[i].empty() && !IsExecutable(
539 FilePath::FromWStringHack(extensions[i]).value()))
540 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29541 }
542
543 return true;
544}
545
546void DownloadManager::QueryHistoryForDownloads() {
547 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
548 if (hs) {
549 hs->QueryDownloads(
550 &cancelable_consumer_,
551 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
552 }
553}
554
555// We have received a message from DownloadFileManager about a new download. We
556// create a download item and store it in our download map, and inform the
557// history system of a new download. Since this method can be called while the
558// history service thread is still reading the persistent state, we do not
559// insert the new DownloadItem into 'downloads_' or inform our observers at this
560// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
561// download creation as a callback from the history thread.
562void DownloadManager::StartDownload(DownloadCreateInfo* info) {
563 DCHECK(MessageLoop::current() == ui_loop_);
564 DCHECK(info);
565
[email protected]7d3851d82008-12-12 03:26:07566 // Freeze the user's preference for showing a Save As dialog. We're going to
567 // bounce around a bunch of threads and we don't want to worry about race
568 // conditions where the user changes this pref out from under us.
569 if (*prompt_for_download_)
570 info->save_as = true;
571
initial.commit09911bf2008-07-26 23:55:29572 // Determine the proper path for a download, by choosing either the default
573 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41574 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29575 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07576 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29577 info->suggested_path = last_download_path_;
578 else
[email protected]7ae7c2cb2009-01-06 23:31:41579 info->suggested_path = download_path();
580 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29581
[email protected]7d3851d82008-12-12 03:26:07582 if (!info->save_as) {
[email protected]4289d9b2009-07-25 21:17:34583 // Downloads can be marked as dangerous for two reasons:
584 // a) They have a dangerous-looking filename
585 // b) They are an extension that is not from the gallery
586 if (IsDangerous(info->suggested_path.BaseName()))
587 info->is_dangerous = true;
[email protected]336e0c32009-08-14 22:22:08588 else if (IsChromeExtension(info->suggested_path, info->mime_type) &&
[email protected]4289d9b2009-07-25 21:17:34589 !ExtensionsService::IsDownloadFromGallery(info->url,
590 info->referrer_url)) {
591 info->is_dangerous = true;
592 }
[email protected]e9ebf3fc2008-10-17 22:06:58593 }
594
initial.commit09911bf2008-07-26 23:55:29595 // We need to move over to the download thread because we don't want to stat
596 // the suggested path on the UI thread.
597 file_loop_->PostTask(FROM_HERE,
598 NewRunnableMethod(this,
599 &DownloadManager::CheckIfSuggestedPathExists,
600 info));
601}
602
603void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
604 DCHECK(info);
605
606 // Check writability of the suggested path. If we can't write to it, default
607 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41608 FilePath dir = info->suggested_path.DirName();
609 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32610 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29611 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29612 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41613 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29614 }
615
[email protected]7a256ea2008-10-17 17:34:16616 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29617
[email protected]6cade212008-12-03 00:32:22618 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58619 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41620 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32621 // Create a temporary file to hold the file until the user approves its
622 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41623 FilePath::StringType file_name;
624 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32625 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41626 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32627 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41628 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07629 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41630 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32631 }
632 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16633 } else {
634 // We know the final path, build it if necessary.
635 if (info->path_uniquifier > 0) {
636 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
637 // Setting path_uniquifier to 0 to make sure we don't try to unique it
638 // later on.
639 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07640 } else if (info->path_uniquifier == -1) {
641 // We failed to find a unique path. We have to prompt the user.
642 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16643 }
[email protected]9ccbb372008-10-10 18:50:32644 }
645
[email protected]7d3851d82008-12-12 03:26:07646 if (!info->save_as) {
647 // Create an empty file at the suggested path so that we don't allocate the
648 // same "non-existant" path to multiple downloads.
649 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ae7c2cb2009-01-06 23:31:41650 file_util::WriteFile(info->suggested_path.ToWStringHack(), "", 0);
[email protected]7d3851d82008-12-12 03:26:07651 }
652
initial.commit09911bf2008-07-26 23:55:29653 // Now we return to the UI thread.
654 ui_loop_->PostTask(FROM_HERE,
655 NewRunnableMethod(this,
656 &DownloadManager::OnPathExistenceAvailable,
657 info));
658}
659
660void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
661 DCHECK(MessageLoop::current() == ui_loop_);
662 DCHECK(info);
663
[email protected]7d3851d82008-12-12 03:26:07664 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29665 // We must ask the user for the place to put the download.
666 if (!select_file_dialog_.get())
667 select_file_dialog_ = SelectFileDialog::Create(this);
668
[email protected]57c6a652009-05-04 07:58:34669 TabContents* contents = tab_util::GetTabContentsByID(
initial.commit09911bf2008-07-26 23:55:29670 info->render_process_id, info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08671 SelectFileDialog::FileTypeInfo file_type_info;
672 file_type_info.extensions.resize(1);
673 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24674 if (!file_type_info.extensions[0][0].empty())
675 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08676 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23677 gfx::NativeWindow owning_window =
678 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29679 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34680 string16(),
681 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08682 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30683 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29684 } else {
685 // No prompting for download, just continue with the suggested name.
686 ContinueStartDownload(info, info->suggested_path);
687 }
688}
689
690void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41691 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29692 scoped_ptr<DownloadCreateInfo> infop(info);
693 info->path = target_path;
694
695 DownloadItem* download = NULL;
696 DownloadMap::iterator it = in_progress_.find(info->download_id);
697 if (it == in_progress_.end()) {
698 download = new DownloadItem(info->download_id,
699 info->path,
[email protected]7a256ea2008-10-17 17:34:16700 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29701 info->url,
[email protected]494c06e2009-07-25 01:06:42702 info->referrer_url,
[email protected]e435d6b72009-07-25 03:15:58703 info->mime_type,
[email protected]9ccbb372008-10-10 18:50:32704 info->original_name,
initial.commit09911bf2008-07-26 23:55:29705 info->start_time,
706 info->total_bytes,
707 info->render_process_id,
[email protected]9ccbb372008-10-10 18:50:32708 info->request_id,
709 info->is_dangerous);
initial.commit09911bf2008-07-26 23:55:29710 download->set_manager(this);
711 in_progress_[info->download_id] = download;
712 } else {
713 NOTREACHED(); // Should not exist!
714 return;
715 }
716
[email protected]6b323782009-03-27 18:43:08717 // Called before DownloadFinished in order to avoid a race condition where we
718 // attempt to open a completed download before it has been renamed.
719 file_loop_->PostTask(FROM_HERE,
720 NewRunnableMethod(file_manager_,
721 &DownloadFileManager::OnFinalDownloadName,
722 download->id(),
[email protected]8f783752009-04-01 23:33:45723 target_path,
724 this));
[email protected]6b323782009-03-27 18:43:08725
initial.commit09911bf2008-07-26 23:55:29726 // If the download already completed by the time we reached this point, then
727 // notify observers that it did.
728 PendingFinishedMap::iterator pending_it =
729 pending_finished_downloads_.find(info->download_id);
730 if (pending_it != pending_finished_downloads_.end())
731 DownloadFinished(pending_it->first, pending_it->second);
732
733 download->Rename(target_path);
734
initial.commit09911bf2008-07-26 23:55:29735 if (profile_->IsOffTheRecord()) {
736 // Fake a db handle for incognito mode, since nothing is actually stored in
737 // the database in this mode. We have to make sure that these handles don't
738 // collide with normal db handles, so we use a negative value. Eventually,
739 // they could overlap, but you'd have to do enough downloading that your ISP
740 // would likely stab you in the neck first. YMMV.
741 static int64 fake_db_handle = kUninitializedHandle - 1;
742 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
743 } else {
744 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22745 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29746 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
747 if (hs) {
748 hs->CreateDownload(
749 *info, &cancelable_consumer_,
750 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
751 }
752 }
753}
754
755// Convenience function for updating the history service for a download.
756void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
757 DCHECK(download);
758
759 // Don't store info in the database if the download was initiated while in
760 // incognito mode or if it hasn't been initialized in our database table.
761 if (download->db_handle() <= kUninitializedHandle)
762 return;
763
[email protected]6cade212008-12-03 00:32:22764 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29765 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
766 if (hs) {
767 hs->UpdateDownload(download->received_bytes(),
768 download->state(),
769 download->db_handle());
770 }
771}
772
773void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
774 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22775 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29776 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
777 if (download->db_handle() > kUninitializedHandle && hs)
778 hs->RemoveDownload(download->db_handle());
779}
780
[email protected]e93d2822009-01-30 05:59:59781void DownloadManager::RemoveDownloadsFromHistoryBetween(
782 const base::Time remove_begin,
783 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22784 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29785 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
786 if (hs)
787 hs->RemoveDownloadsBetween(remove_begin, remove_end);
788}
789
790void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
791 DownloadMap::iterator it = in_progress_.find(download_id);
792 if (it != in_progress_.end()) {
793 DownloadItem* download = it->second;
794 download->Update(size);
795 UpdateHistoryForDownload(download);
796 }
797}
798
799void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
800 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32801 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29802 // The download is done, but the user hasn't selected a final location for
803 // it yet (the Save As dialog box is probably still showing), so just keep
804 // track of the fact that this download id is complete, when the
805 // DownloadItem is constructed later we'll notify its completion then.
806 PendingFinishedMap::iterator erase_it =
807 pending_finished_downloads_.find(download_id);
808 DCHECK(erase_it == pending_finished_downloads_.end());
809 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32810 return;
initial.commit09911bf2008-07-26 23:55:29811 }
[email protected]9ccbb372008-10-10 18:50:32812
813 // Remove the id from the list of pending ids.
814 PendingFinishedMap::iterator erase_it =
815 pending_finished_downloads_.find(download_id);
816 if (erase_it != pending_finished_downloads_.end())
817 pending_finished_downloads_.erase(erase_it);
818
819 DownloadItem* download = it->second;
820 download->Finished(size);
821
822 // Clean up will happen when the history system create callback runs if we
823 // don't have a valid db_handle yet.
824 if (download->db_handle() != kUninitializedHandle) {
825 in_progress_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32826 UpdateHistoryForDownload(download);
827 }
828
829 // If this a dangerous download not yet validated by the user, don't do
830 // anything. When the user notifies us, it will trigger a call to
831 // ProceedWithFinishedDangerousDownload.
832 if (download->safety_state() == DownloadItem::DANGEROUS) {
833 dangerous_finished_[download_id] = download;
834 return;
835 }
836
837 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22838 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32839 // its final name before we can continue.
840 file_loop_->PostTask(FROM_HERE,
841 NewRunnableMethod(
842 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
843 download->db_handle(),
844 download->full_path(), download->original_name()));
845 return;
846 }
847 ContinueDownloadFinished(download);
848}
849
[email protected]8f783752009-04-01 23:33:45850void DownloadManager::DownloadRenamedToFinalName(int download_id,
851 const FilePath& full_path) {
[email protected]8f783752009-04-01 23:33:45852}
853
[email protected]9ccbb372008-10-10 18:50:32854void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
855 // If this was a dangerous download, it has now been approved and must be
856 // removed from dangerous_finished_ so it does not get deleted on shutdown.
857 DownloadMap::iterator it = dangerous_finished_.find(download->id());
858 if (it != dangerous_finished_.end())
859 dangerous_finished_.erase(it);
860
[email protected]5a102892009-07-15 19:59:30861 // Open the download if the user or user prefs indicate it should be.
862 FilePath::StringType extension = download->full_path().Extension();
863 // Drop the leading period. (The auto-open list is period-less.)
864 if (extension.size() > 0)
865 extension = extension.substr(1);
866
[email protected]0aad67b2009-07-15 20:34:28867 // Handle chrome extensions explicitly and skip the shell execute.
[email protected]1e7e93402009-08-13 20:55:17868 if (IsChromeExtension(download->full_path(), download->mime_type())) {
[email protected]494c06e2009-07-25 01:06:42869 OpenChromeExtension(download->full_path(), download->url(),
870 download->referrer_url());
[email protected]0aad67b2009-07-15 20:34:28871 download->set_auto_opened(true);
872 } else if (download->open_when_complete() ||
873 ShouldOpenFileExtension(extension)) {
[email protected]9ccbb372008-10-10 18:50:32874 OpenDownloadInShell(download, NULL);
[email protected]0aad67b2009-07-15 20:34:28875 download->set_auto_opened(true);
876 }
[email protected]9ccbb372008-10-10 18:50:32877
[email protected]0aad67b2009-07-15 20:34:28878 // Notify our observers that we are complete (the call to Finished() set the
879 // state to complete but did not notify).
880 download->UpdateObservers();
881}
[email protected]9ccbb372008-10-10 18:50:32882// Called on the file thread. Renames the downloaded file to its original name.
883void DownloadManager::ProceedWithFinishedDangerousDownload(
884 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41885 const FilePath& path,
886 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32887 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41888 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16889 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32890 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24891 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16892 // Make our name unique at this point, as if a dangerous file is downloading
893 // and a 2nd download is started for a file with the same name, they would
894 // have the same path. This is because we uniquify the name on download
895 // start, and at that time the first file does not exists yet, so the second
896 // file gets the same name.
897 uniquifier = GetUniquePathNumber(new_path);
898 if (uniquifier > 0)
899 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32900 success = file_util::Move(path, new_path);
901 } else {
902 NOTREACHED();
903 }
[email protected]6cade212008-12-03 00:32:22904
[email protected]9ccbb372008-10-10 18:50:32905 ui_loop_->PostTask(FROM_HERE,
906 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16907 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32908}
909
910// Call from the file thread when the finished dangerous download was renamed.
911void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
912 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41913 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16914 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32915 DownloadMap::iterator it = downloads_.find(download_handle);
916 if (it == downloads_.end()) {
917 NOTREACHED();
918 return;
919 }
920
921 DownloadItem* download = it->second;
922 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16923 if (success) {
924 // We need to update the path uniquifier so that the UI shows the right
925 // name when calling GetFileName().
926 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32927 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16928 }
[email protected]9ccbb372008-10-10 18:50:32929
930 // Continue the download finished sequence.
931 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29932}
933
934// static
935// We have to tell the ResourceDispatcherHost to cancel the download from this
[email protected]6cade212008-12-03 00:32:22936// thread, since we can't forward tasks from the file thread to the IO thread
initial.commit09911bf2008-07-26 23:55:29937// reliably (crash on shutdown race condition).
938void DownloadManager::CancelDownloadRequest(int render_process_id,
939 int request_id) {
940 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]ab820df2008-08-26 05:55:10941 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29942 if (!io_thread || !rdh)
943 return;
944 io_thread->message_loop()->PostTask(FROM_HERE,
945 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
946 rdh,
947 render_process_id,
948 request_id));
949}
950
951// static
952void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
953 int render_process_id,
954 int request_id) {
955 rdh->CancelRequest(render_process_id, request_id, false);
956}
957
958void DownloadManager::DownloadCancelled(int32 download_id) {
959 DownloadMap::iterator it = in_progress_.find(download_id);
960 if (it == in_progress_.end())
961 return;
962 DownloadItem* download = it->second;
963
initial.commit09911bf2008-07-26 23:55:29964 // Clean up will happen when the history system create callback runs if we
965 // don't have a valid db_handle yet.
966 if (download->db_handle() != kUninitializedHandle) {
967 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:29968 UpdateHistoryForDownload(download);
969 }
970
[email protected]d7d1c5c2009-08-05 23:52:50971 DownloadCancelledInternal(download_id,
972 download->render_process_id(),
973 download->request_id());
974}
975
976void DownloadManager::DownloadCancelledInternal(int download_id,
977 int render_process_id,
978 int request_id) {
979 // Cancel the network request.
980 CancelDownloadRequest(render_process_id, request_id);
981
initial.commit09911bf2008-07-26 23:55:29982 // Tell the file manager to cancel the download.
[email protected]d7d1c5c2009-08-05 23:52:50983 file_manager_->RemoveDownload(download_id, this); // On the UI thread
initial.commit09911bf2008-07-26 23:55:29984 file_loop_->PostTask(FROM_HERE,
985 NewRunnableMethod(file_manager_,
986 &DownloadFileManager::CancelDownload,
[email protected]d7d1c5c2009-08-05 23:52:50987 download_id));
initial.commit09911bf2008-07-26 23:55:29988}
989
990void DownloadManager::PauseDownload(int32 download_id, bool pause) {
991 DownloadMap::iterator it = in_progress_.find(download_id);
992 if (it != in_progress_.end()) {
993 DownloadItem* download = it->second;
994 if (pause == download->is_paused())
995 return;
996
997 // Inform the ResourceDispatcherHost of the new pause state.
[email protected]ab820df2008-08-26 05:55:10998 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29999 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
1000 if (!io_thread || !rdh)
1001 return;
1002
1003 io_thread->message_loop()->PostTask(FROM_HERE,
1004 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
1005 rdh,
1006 download->render_process_id(),
1007 download->request_id(),
1008 pause));
1009 }
1010}
1011
1012// static
1013void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
1014 int render_process_id,
1015 int request_id,
1016 bool pause) {
1017 rdh->PauseRequest(render_process_id, request_id, pause);
1018}
1019
[email protected]7ae7c2cb2009-01-06 23:31:411020bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:321021 // TODO(jcampan): Improve me.
[email protected]2001fe82009-02-23 23:53:141022 FilePath::StringType extension = file_name.Extension();
1023 // Drop the leading period.
1024 if (extension.size() > 0)
1025 extension = extension.substr(1);
1026 return IsExecutable(extension);
[email protected]9ccbb372008-10-10 18:50:321027}
1028
1029void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:411030 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:321031 download->Rename(new_path);
1032
1033 // Update the history.
1034
1035 // No update necessary if the download was initiated while in incognito mode.
1036 if (download->db_handle() <= kUninitializedHandle)
1037 return;
1038
[email protected]6cade212008-12-03 00:32:221039 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:321040 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1041 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:411042 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:321043}
1044
initial.commit09911bf2008-07-26 23:55:291045void DownloadManager::RemoveDownload(int64 download_handle) {
1046 DownloadMap::iterator it = downloads_.find(download_handle);
1047 if (it == downloads_.end())
1048 return;
1049
1050 // Make history update.
1051 DownloadItem* download = it->second;
1052 RemoveDownloadFromHistory(download);
1053
1054 // Remove from our tables and delete.
1055 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321056 it = dangerous_finished_.find(download->id());
1057 if (it != dangerous_finished_.end())
1058 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291059
1060 // Tell observers to refresh their views.
1061 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:361062
1063 delete download;
initial.commit09911bf2008-07-26 23:55:291064}
1065
[email protected]e93d2822009-01-30 05:59:591066int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1067 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291068 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1069
initial.commit09911bf2008-07-26 23:55:291070 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:281071 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:291072 while (it != downloads_.end()) {
1073 DownloadItem* download = it->second;
1074 DownloadItem::DownloadState state = download->state();
1075 if (download->start_time() >= remove_begin &&
1076 (remove_end.is_null() || download->start_time() < remove_end) &&
1077 (state == DownloadItem::COMPLETE ||
1078 state == DownloadItem::CANCELLED)) {
1079 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561080 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581081
1082 // Also remove it from any completed dangerous downloads.
1083 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1084 if (dit != dangerous_finished_.end())
1085 dangerous_finished_.erase(dit);
1086
[email protected]78b8fcc92009-03-31 17:36:281087 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:291088
initial.commit09911bf2008-07-26 23:55:291089 continue;
1090 }
1091
1092 ++it;
1093 }
1094
1095 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281096 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291097 if (num_deleted > 0)
1098 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1099
[email protected]78b8fcc92009-03-31 17:36:281100 // Delete the download items after updating the observers.
1101 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1102 pending_deletes.clear();
1103
initial.commit09911bf2008-07-26 23:55:291104 return num_deleted;
1105}
1106
[email protected]e93d2822009-01-30 05:59:591107int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1108 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291109}
1110
[email protected]d41355e6f2009-04-07 21:21:121111int DownloadManager::RemoveAllDownloads() {
1112 // The null times make the date range unbounded.
1113 return RemoveDownloadsBetween(base::Time(), base::Time());
1114}
1115
initial.commit09911bf2008-07-26 23:55:291116// Initiate a download of a specific URL. We send the request to the
1117// ResourceDispatcherHost, and let it send us responses like a regular
1118// download.
1119void DownloadManager::DownloadUrl(const GURL& url,
1120 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:501121 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:341122 TabContents* tab_contents) {
1123 DCHECK(tab_contents);
[email protected]c9825a42009-05-01 22:51:501124 request_context_->set_referrer_charset(referrer_charset);
initial.commit09911bf2008-07-26 23:55:291125 file_manager_->DownloadUrl(url,
1126 referrer,
[email protected]57c6a652009-05-04 07:58:341127 tab_contents->process()->pid(),
1128 tab_contents->render_view_host()->routing_id(),
initial.commit09911bf2008-07-26 23:55:291129 request_context_.get());
1130}
1131
[email protected]7ae7c2cb2009-01-06 23:31:411132void DownloadManager::GenerateExtension(
1133 const FilePath& file_name,
1134 const std::string& mime_type,
1135 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291136 // We're worried about three things here:
1137 //
1138 // 1) Security. Many sites let users upload content, such as buddy icons, to
1139 // their web sites. We want to mitigate the case where an attacker
1140 // supplies a malicious executable with an executable file extension but an
1141 // honest site serves the content with a benign content type, such as
1142 // image/jpeg.
1143 //
1144 // 2) Usability. If the site fails to provide a file extension, we want to
1145 // guess a reasonable file extension based on the content type.
1146 //
1147 // 3) Shell integration. Some file extensions automatically integrate with
1148 // the shell. We block these extensions to prevent a malicious web site
1149 // from integrating with the user's shell.
1150
[email protected]7ae7c2cb2009-01-06 23:31:411151 static const FilePath::CharType default_extension[] =
1152 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291153
1154 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411155 FilePath::StringType extension(
1156 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291157
[email protected]b7f05882009-02-22 01:21:561158#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291159 // Rename shell-integrated extensions.
1160 if (win_util::IsShellIntegratedExtension(extension))
1161 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561162#endif
initial.commit09911bf2008-07-26 23:55:291163
1164 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411165 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411166 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291167 if (mime_type == mime_type_from_extension) {
1168 // The hinted extension matches the mime type. It looks like a winner.
1169 generated_extension->swap(extension);
1170 return;
1171 }
1172
1173 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1174 // We want to be careful about executable extensions. The worry here is
1175 // that a trusted web site could be tricked into dropping an executable file
1176 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101177 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291178 // We couldn't find a good extension for this content type. Use a dummy
1179 // extension instead.
1180 extension.assign(default_extension);
1181 }
1182 }
1183
1184 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101185 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291186 } else {
[email protected]6cade212008-12-03 00:32:221187 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291188 // 1. New extension is not ".txt"
1189 // 2. New extension is not the same as the already existing extension.
1190 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411191 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291192 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1193 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371194 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1195 // servers, i.e. bug 5772.
[email protected]7ae7c2cb2009-01-06 23:31:411196 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101197 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171198 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411199 append_extension != extension &&
[email protected]e106457b2009-03-25 22:43:371200 !IsExecutable(append_extension) &&
1201 (append_extension != FILE_PATH_LITERAL("tar") ||
1202 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171203 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291204 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171205 }
initial.commit09911bf2008-07-26 23:55:291206 }
1207 }
1208
1209 generated_extension->swap(extension);
1210}
1211
1212void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411213 FilePath* generated_name) {
1214 *generated_name = FilePath::FromWStringHack(
[email protected]8ac1a752008-07-31 19:40:371215 net::GetSuggestedFilename(GURL(info->url),
1216 info->content_disposition,
[email protected]c9825a42009-05-01 22:51:501217 info->referrer_charset,
[email protected]7ae7c2cb2009-01-06 23:31:411218 L"download"));
1219 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291220
[email protected]7ae7c2cb2009-01-06 23:31:411221 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291222}
1223
1224void DownloadManager::AddObserver(Observer* observer) {
1225 observers_.AddObserver(observer);
1226 observer->ModelChanged();
1227}
1228
1229void DownloadManager::RemoveObserver(Observer* observer) {
1230 observers_.RemoveObserver(observer);
1231}
1232
1233// Post Windows Shell operations to the Download thread, to avoid blocking the
1234// user interface.
1235void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1236 DCHECK(file_manager_);
[email protected]8b6ff012009-08-18 22:29:581237 DCHECK(MessageLoop::current() == ui_loop_);
1238#if defined(OS_MACOSX)
1239 // Mac needs to run this operation on the UI thread.
1240 platform_util::ShowItemInFolder(download->full_path());
1241#else
initial.commit09911bf2008-07-26 23:55:291242 file_loop_->PostTask(FROM_HERE,
1243 NewRunnableMethod(file_manager_,
1244 &DownloadFileManager::OnShowDownloadInShell,
[email protected]7ae7c2cb2009-01-06 23:31:411245 FilePath(download->full_path())));
[email protected]8b6ff012009-08-18 22:29:581246#endif
initial.commit09911bf2008-07-26 23:55:291247}
1248
[email protected]8f783752009-04-01 23:33:451249void DownloadManager::OpenDownload(const DownloadItem* download,
1250 gfx::NativeView parent_window) {
[email protected]0e34d7892009-06-05 19:17:401251 // Open Chrome extensions with ExtensionsService. For everything else do shell
[email protected]8f783752009-04-01 23:33:451252 // execute.
[email protected]1e7e93402009-08-13 20:55:171253 if (IsChromeExtension(download->full_path(), download->mime_type())) {
[email protected]494c06e2009-07-25 01:06:421254 OpenChromeExtension(download->full_path(), download->url(),
1255 download->referrer_url());
[email protected]8f783752009-04-01 23:33:451256 } else {
1257 OpenDownloadInShell(download, parent_window);
1258 }
1259}
1260
[email protected]c1e432a2009-07-22 21:21:481261void DownloadManager::OpenChromeExtension(const FilePath& full_path,
[email protected]494c06e2009-07-25 01:06:421262 const GURL& download_url,
1263 const GURL& referrer_url) {
[email protected]6ef635e42009-07-26 06:16:121264 // We don't support extensions in OTR mode.
[email protected]2a464a92009-08-01 17:58:351265 ExtensionsService* service = profile_->GetExtensionsService();
1266 if (service) {
1267 CrxInstaller::Start(full_path,
1268 service->install_directory(),
1269 Extension::INTERNAL,
1270 "", // no expected id
1271 true, // please delete crx on completion
1272 g_browser_process->file_thread()->message_loop(),
1273 service,
1274 new ExtensionInstallUI(profile_));
1275 }
[email protected]8f783752009-04-01 23:33:451276}
1277
initial.commit09911bf2008-07-26 23:55:291278void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591279 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291280 DCHECK(file_manager_);
[email protected]8b6ff012009-08-18 22:29:581281 DCHECK(MessageLoop::current() == ui_loop_);
1282#if defined(OS_MACOSX)
1283 // Mac OS X requires opening downloads on the UI thread.
1284 platform_util::OpenItem(download->full_path());
1285#else
initial.commit09911bf2008-07-26 23:55:291286 file_loop_->PostTask(FROM_HERE,
1287 NewRunnableMethod(file_manager_,
1288 &DownloadFileManager::OnOpenDownloadInShell,
1289 download->full_path(), download->url(), parent_window));
[email protected]8b6ff012009-08-18 22:29:581290#endif
initial.commit09911bf2008-07-26 23:55:291291}
1292
[email protected]7ae7c2cb2009-01-06 23:31:411293void DownloadManager::OpenFilesOfExtension(
1294 const FilePath::StringType& extension, bool open) {
initial.commit09911bf2008-07-26 23:55:291295 if (open && !IsExecutable(extension))
1296 auto_open_.insert(extension);
1297 else
1298 auto_open_.erase(extension);
1299 SaveAutoOpens();
1300}
1301
[email protected]7ae7c2cb2009-01-06 23:31:411302bool DownloadManager::ShouldOpenFileExtension(
1303 const FilePath::StringType& extension) {
[email protected]8c756ac2009-01-30 23:36:411304 // Special-case Chrome extensions as always-open.
initial.commit09911bf2008-07-26 23:55:291305 if (!IsExecutable(extension) &&
[email protected]8c756ac2009-01-30 23:36:411306 (auto_open_.find(extension) != auto_open_.end() ||
[email protected]f1ce6e62009-06-29 20:31:291307 Extension::IsExtension(FilePath(extension))))
[email protected]8c756ac2009-01-30 23:36:411308 return true;
initial.commit09911bf2008-07-26 23:55:291309 return false;
1310}
1311
[email protected]7b73d992008-12-15 20:56:461312static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291313 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461314 "text/javascript",
1315 "text/javascript;version=*",
[email protected]54d8d452009-04-08 17:29:241316 // Registry files can cause critical changes to the MS OS behavior.
1317 // Addition of this mimetype also addresses bug 7337.
1318 "text/x-registry",
[email protected]60ff8f912008-12-05 07:58:391319 // Some sites use binary/octet-stream to mean application/octet-stream.
1320 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461321 "binary/octet-stream"
1322};
initial.commit09911bf2008-07-26 23:55:291323
[email protected]7b73d992008-12-15 20:56:461324static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291325 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461326 "application/*+xml",
1327 "application/xml"
1328};
initial.commit09911bf2008-07-26 23:55:291329
[email protected]7b73d992008-12-15 20:56:461330// static
1331bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411332 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461333 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1334 return true;
1335 }
[email protected]bae0ea12009-02-14 01:20:411336 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461337 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1338 return false;
1339 }
1340 // We consider only other application types to be executable.
1341 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291342}
1343
[email protected]7ae7c2cb2009-01-06 23:31:411344bool DownloadManager::IsExecutable(const FilePath::StringType& extension) {
[email protected]64da0b932009-02-24 02:30:041345 if (!IsStringASCII(extension))
1346 return false;
[email protected]a0a9577b2009-05-27 23:52:321347#if defined(OS_WIN)
[email protected]64da0b932009-02-24 02:30:041348 std::string ascii_extension = WideToASCII(extension);
[email protected]e9ef0a62009-08-11 22:50:131349#elif defined(OS_POSIX)
[email protected]a0a9577b2009-05-27 23:52:321350 std::string ascii_extension = extension;
1351#endif
[email protected]64da0b932009-02-24 02:30:041352 StringToLowerASCII(&ascii_extension);
1353
1354 return exe_types_.find(ascii_extension) != exe_types_.end();
initial.commit09911bf2008-07-26 23:55:291355}
1356
1357void DownloadManager::ResetAutoOpenFiles() {
1358 auto_open_.clear();
1359 SaveAutoOpens();
1360}
1361
1362bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1363 return !auto_open_.empty();
1364}
1365
1366void DownloadManager::SaveAutoOpens() {
1367 PrefService* prefs = profile_->GetPrefs();
1368 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411369 FilePath::StringType extensions;
1370 for (std::set<FilePath::StringType>::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291371 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411372 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291373 }
1374 if (!extensions.empty())
1375 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561376
1377 std::wstring extensions_w;
1378#if defined(OS_WIN)
1379 extensions_w = extensions;
1380#elif defined(OS_POSIX)
[email protected]1b5044d2009-02-24 00:04:141381 extensions_w = base::SysNativeMBToWide(extensions);
[email protected]b7f05882009-02-22 01:21:561382#endif
1383
1384 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291385 }
1386}
1387
[email protected]561abe62009-04-06 18:08:341388void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361389 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291390 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071391 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411392 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291393 ContinueStartDownload(info, path);
1394}
1395
1396void DownloadManager::FileSelectionCanceled(void* params) {
1397 // The user didn't pick a place to save the file, so need to cancel the
1398 // download that's already in progress to the temporary location.
1399 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]d7d1c5c2009-08-05 23:52:501400 DownloadCancelledInternal(info->download_id,
1401 info->render_process_id,
1402 info->request_id);
initial.commit09911bf2008-07-26 23:55:291403}
1404
[email protected]7ae7c2cb2009-01-06 23:31:411405void DownloadManager::DeleteDownload(const FilePath& path) {
1406 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
1407 &DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321408}
1409
1410
1411void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1412 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1413 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1414 download->UpdateObservers();
1415
1416 // If the download is not complete, nothing to do. The required
1417 // post-processing will be performed when it does complete.
1418 if (download->state() != DownloadItem::COMPLETE)
1419 return;
1420
1421 file_loop_->PostTask(FROM_HERE,
1422 NewRunnableMethod(this,
1423 &DownloadManager::ProceedWithFinishedDangerousDownload,
1424 download->db_handle(), download->full_path(),
1425 download->original_name()));
1426}
1427
[email protected]763f946a2009-01-06 19:04:391428void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411429 FilePath* file_name) {
1430 // Make sure we get the right file extension
1431 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391432 GenerateExtension(*file_name, mime_type, &extension);
1433 file_util::ReplaceExtension(file_name, extension);
1434
[email protected]2b2f8f72009-02-24 22:42:051435#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391436 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411437 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391438 DCHECK(!leaf_name.empty());
1439 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411440 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1441 *file_name = file_name->DirName();
1442 if (file_name->value() == FilePath::kCurrentDirectory) {
1443 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391444 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411445 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391446 }
1447 }
[email protected]b7f05882009-02-22 01:21:561448#elif defined(OS_POSIX)
1449 NOTIMPLEMENTED();
1450#endif
[email protected]763f946a2009-01-06 19:04:391451}
1452
initial.commit09911bf2008-07-26 23:55:291453// Operations posted to us from the history service ----------------------------
1454
1455// The history service has retrieved all download entries. 'entries' contains
1456// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1457void DownloadManager::OnQueryDownloadEntriesComplete(
1458 std::vector<DownloadCreateInfo>* entries) {
1459 for (size_t i = 0; i < entries->size(); ++i) {
1460 DownloadItem* download = new DownloadItem(entries->at(i));
1461 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1462 downloads_[download->db_handle()] = download;
1463 download->set_manager(this);
1464 }
1465 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1466}
1467
initial.commit09911bf2008-07-26 23:55:291468// Once the new DownloadItem's creation info has been committed to the history
1469// service, we associate the DownloadItem with the db handle, update our
1470// 'downloads_' map and inform observers.
1471void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1472 int64 db_handle) {
1473 DownloadMap::iterator it = in_progress_.find(info.download_id);
1474 DCHECK(it != in_progress_.end());
1475
1476 DownloadItem* download = it->second;
1477 DCHECK(download->db_handle() == kUninitializedHandle);
1478 download->set_db_handle(db_handle);
1479
1480 // Insert into our full map.
1481 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1482 downloads_[download->db_handle()] = download;
1483
[email protected]5e595482009-05-06 20:16:531484 // Show in the appropropriate browser UI.
1485 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291486
1487 // Inform interested objects about the new download.
1488 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
initial.commit09911bf2008-07-26 23:55:291489
1490 // If this download has been completed before we've received the db handle,
1491 // post one final message to the history service so that it can be properly
1492 // in sync with the DownloadItem's completion status, and also inform any
1493 // observers so that they get more than just the start notification.
1494 if (download->state() != DownloadItem::IN_PROGRESS) {
1495 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291496 UpdateHistoryForDownload(download);
1497 download->UpdateObservers();
1498 }
1499}
1500
1501// Called when the history service has retrieved the list of downloads that
1502// match the search text.
1503void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1504 std::vector<int64>* results) {
1505 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1506 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1507 if (!requestor)
1508 return;
1509
1510 std::vector<DownloadItem*> searched_downloads;
1511 for (std::vector<int64>::iterator it = results->begin();
1512 it != results->end(); ++it) {
1513 DownloadMap::iterator dit = downloads_.find(*it);
1514 if (dit != downloads_.end())
1515 searched_downloads.push_back(dit->second);
1516 }
1517
1518 requestor->SetDownloads(searched_downloads);
1519}
[email protected]905a08d2008-11-19 07:24:121520
[email protected]5e595482009-05-06 20:16:531521void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1522 DownloadItem* download) {
[email protected]5e595482009-05-06 20:16:531523 // The 'contents' may no longer exist if the user closed the tab before we get
1524 // this start completion event. If it does, tell the origin TabContents to
1525 // display its download shelf.
1526 TabContents* contents =
1527 tab_util::GetTabContentsByID(info.render_process_id, info.render_view_id);
1528
1529 // If the contents no longer exists, we start the download in the last active
1530 // browser. This is not ideal but better than fully hiding the download from
1531 // the user.
1532 if (!contents) {
1533 Browser* last_active = BrowserList::GetLastActive();
1534 if (last_active)
1535 contents = last_active->GetSelectedTabContents();
1536 }
1537
1538 if (contents)
1539 contents->OnStartDownload(download);
1540}
1541
[email protected]6cade212008-12-03 00:32:221542// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121543void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411544 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381545}
1546