blob: 275b3851353cf5edcd01069fd7d46d108bb53375 [file] [log] [blame]
license.botbf09a502008-08-24 00:55:551// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
2// 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
7#include "base/file_util.h"
8#include "base/logging.h"
9#include "base/message_loop.h"
10#include "base/path_service.h"
initial.commit09911bf2008-07-26 23:55:2911#include "base/string_util.h"
12#include "base/task.h"
13#include "base/thread.h"
14#include "base/timer.h"
[email protected]9ccbb372008-10-10 18:50:3215#include "base/rand_util.h"
initial.commit09911bf2008-07-26 23:55:2916#include "chrome/browser/browser_list.h"
17#include "chrome/browser/browser_process.h"
[email protected]cdaa8652008-09-13 02:48:5918#include "chrome/browser/download/download_file.h"
[email protected]8c756ac2009-01-30 23:36:4119#include "chrome/browser/extensions/extension.h"
initial.commit09911bf2008-07-26 23:55:2920#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:2621#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2522#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]e3c404b2008-12-23 01:07:3223#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
[email protected]f3ec7742009-01-15 00:59:1624#include "chrome/browser/tab_contents/tab_util.h"
25#include "chrome/browser/tab_contents/web_contents.h"
[email protected]8c756ac2009-01-30 23:36:4126#include "chrome/common/chrome_constants.h"
initial.commit09911bf2008-07-26 23:55:2927#include "chrome/common/chrome_paths.h"
28#include "chrome/common/l10n_util.h"
29#include "chrome/common/notification_service.h"
30#include "chrome/common/pref_names.h"
31#include "chrome/common/pref_service.h"
32#include "chrome/common/stl_util-inl.h"
[email protected]46072d42008-07-28 14:49:3533#include "googleurl/src/gurl.h"
[email protected]34ac8f32009-02-22 23:03:2734#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2935#include "net/base/mime_util.h"
36#include "net/base/net_util.h"
37#include "net/url_request/url_request_context.h"
38
[email protected]b7f05882009-02-22 01:21:5639#if defined(OS_WIN)
40// TODO(port): some of these need porting.
41#include "base/registry.h"
42#include "base/win_util.h"
43#include "chrome/browser/download/download_util.h"
44#include "chrome/common/win_util.h"
45#endif
46
initial.commit09911bf2008-07-26 23:55:2947// Periodically update our observers.
48class DownloadItemUpdateTask : public Task {
49 public:
50 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
51 void Run() { if (item_) item_->UpdateObservers(); }
52
53 private:
54 DownloadItem* item_;
55};
56
57// Update frequency (milliseconds).
58static const int kUpdateTimeMs = 1000;
59
60// Our download table ID starts at 1, so we use 0 to represent a download that
61// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2262// database handles in incognito mode starting at -1 and progressively getting
63// more negative.
initial.commit09911bf2008-07-26 23:55:2964static const int kUninitializedHandle = 0;
65
[email protected]7a256ea2008-10-17 17:34:1666// Appends the passed the number between parenthesis the path before the
67// extension.
[email protected]7ae7c2cb2009-01-06 23:31:4168static void AppendNumberToPath(FilePath* path, int number) {
69 file_util::InsertBeforeExtension(path,
70 StringPrintf(FILE_PATH_LITERAL(" (%d)"), number));
[email protected]7a256ea2008-10-17 17:34:1671}
72
73// Attempts to find a number that can be appended to that path to make it
74// unique. If |path| does not exist, 0 is returned. If it fails to find such
75// a number, -1 is returned.
[email protected]7ae7c2cb2009-01-06 23:31:4176static int GetUniquePathNumber(const FilePath& path) {
initial.commit09911bf2008-07-26 23:55:2977 const int kMaxAttempts = 100;
78
[email protected]7a256ea2008-10-17 17:34:1679 if (!file_util::PathExists(path))
80 return 0;
initial.commit09911bf2008-07-26 23:55:2981
[email protected]7ae7c2cb2009-01-06 23:31:4182 FilePath new_path;
initial.commit09911bf2008-07-26 23:55:2983 for (int count = 1; count <= kMaxAttempts; ++count) {
[email protected]7ae7c2cb2009-01-06 23:31:4184 new_path = FilePath(path);
[email protected]7a256ea2008-10-17 17:34:1685 AppendNumberToPath(&new_path, count);
initial.commit09911bf2008-07-26 23:55:2986
[email protected]7a256ea2008-10-17 17:34:1687 if (!file_util::PathExists(new_path))
88 return count;
initial.commit09911bf2008-07-26 23:55:2989 }
90
[email protected]7a256ea2008-10-17 17:34:1691 return -1;
initial.commit09911bf2008-07-26 23:55:2992}
93
[email protected]b7f05882009-02-22 01:21:5694#if defined(OS_WIN)
[email protected]7ae7c2cb2009-01-06 23:31:4195static bool DownloadPathIsDangerous(const FilePath& download_path) {
96 FilePath desktop_dir;
[email protected]f052118e2008-09-05 02:25:3297 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
98 NOTREACHED();
99 return false;
100 }
101 return (download_path == desktop_dir);
102}
[email protected]b7f05882009-02-22 01:21:56103#endif
[email protected]f052118e2008-09-05 02:25:32104
initial.commit09911bf2008-07-26 23:55:29105// DownloadItem implementation -------------------------------------------------
106
107// Constructor for reading from the history service.
108DownloadItem::DownloadItem(const DownloadCreateInfo& info)
109 : id_(-1),
110 full_path_(info.path),
initial.commit09911bf2008-07-26 23:55:29111 url_(info.url),
112 total_bytes_(info.total_bytes),
113 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56114 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29115 state_(static_cast<DownloadState>(info.state)),
116 start_time_(info.start_time),
117 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29118 manager_(NULL),
initial.commit09911bf2008-07-26 23:55:29119 is_paused_(false),
120 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56121 safety_state_(SAFE),
122 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29123 render_process_id_(-1),
124 request_id_(-1) {
125 if (state_ == IN_PROGRESS)
126 state_ = CANCELLED;
127 Init(false /* don't start progress timer */);
128}
129
130// Constructor for DownloadItem created via user action in the main thread.
131DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41132 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16133 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32134 const GURL& url,
[email protected]7ae7c2cb2009-01-06 23:31:41135 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59136 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29137 int64 download_size,
138 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32139 int request_id,
140 bool is_dangerous)
initial.commit09911bf2008-07-26 23:55:29141 : id_(download_id),
142 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16143 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29144 url_(url),
initial.commit09911bf2008-07-26 23:55:29145 total_bytes_(download_size),
146 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56147 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29148 state_(IN_PROGRESS),
149 start_time_(start_time),
150 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29151 manager_(NULL),
initial.commit09911bf2008-07-26 23:55:29152 is_paused_(false),
153 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56154 safety_state_(is_dangerous ? DANGEROUS : SAFE),
155 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29156 render_process_id_(render_process_id),
157 request_id_(request_id) {
158 Init(true /* start progress timer */);
159}
160
161void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41162 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29163 if (start_timer)
164 StartProgressTimer();
165}
166
167DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29168 state_ = REMOVING;
169 UpdateObservers();
170}
171
172void DownloadItem::AddObserver(Observer* observer) {
173 observers_.AddObserver(observer);
174}
175
176void DownloadItem::RemoveObserver(Observer* observer) {
177 observers_.RemoveObserver(observer);
178}
179
180void DownloadItem::UpdateObservers() {
181 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
182}
183
184// If we've received more data than we were expecting (bad server info?), revert
185// to 'unknown size mode'.
186void DownloadItem::UpdateSize(int64 bytes_so_far) {
187 received_bytes_ = bytes_so_far;
188 if (received_bytes_ > total_bytes_)
189 total_bytes_ = 0;
190}
191
192// Updates from the download thread may have been posted while this download
193// was being cancelled in the UI thread, so we'll accept them unless we're
194// complete.
195void DownloadItem::Update(int64 bytes_so_far) {
196 if (state_ == COMPLETE) {
197 NOTREACHED();
198 return;
199 }
200 UpdateSize(bytes_so_far);
201 UpdateObservers();
202}
203
[email protected]6cade212008-12-03 00:32:22204// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29205void DownloadItem::Cancel(bool update_history) {
206 if (state_ != IN_PROGRESS) {
207 // Small downloads might be complete before this method has a chance to run.
208 return;
209 }
210 state_ = CANCELLED;
211 UpdateObservers();
212 StopProgressTimer();
213 if (update_history)
214 manager_->DownloadCancelled(id_);
215}
216
217void DownloadItem::Finished(int64 size) {
218 state_ = COMPLETE;
219 UpdateSize(size);
[email protected]22fbe5a2008-10-29 22:20:40220 UpdateObservers();
initial.commit09911bf2008-07-26 23:55:29221 StopProgressTimer();
222}
223
[email protected]9ccbb372008-10-10 18:50:32224void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29225 Cancel(true);
226 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32227 if (delete_on_disk)
228 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29229 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22230 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29231}
232
233void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59234 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14235 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29236}
237
238void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14239 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29240}
241
[email protected]e93d2822009-01-30 05:59:59242bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29243 if (total_bytes_ <= 0)
244 return false; // We never received the content_length for this download.
245
246 int64 speed = CurrentSpeed();
247 if (speed == 0)
248 return false;
249
250 *remaining =
[email protected]e93d2822009-01-30 05:59:59251 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29252 return true;
253}
254
255int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56256 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
257 int64 diff_ms = diff.InMilliseconds();
258 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29259}
260
261int DownloadItem::PercentComplete() const {
262 int percent = -1;
263 if (total_bytes_ > 0)
264 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
265 return percent;
266}
267
[email protected]7ae7c2cb2009-01-06 23:31:41268void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29269 DCHECK(!full_path.empty());
270 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41271 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29272}
273
274void DownloadItem::TogglePause() {
275 DCHECK(state_ == IN_PROGRESS);
276 manager_->PauseDownload(id_, !is_paused_);
277 is_paused_ = !is_paused_;
278 UpdateObservers();
279}
280
[email protected]7ae7c2cb2009-01-06 23:31:41281FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32282 if (safety_state_ == DownloadItem::SAFE)
283 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16284 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41285 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16286 AppendNumberToPath(&name, path_uniquifier_);
287 return name;
288 }
[email protected]9ccbb372008-10-10 18:50:32289 return original_name_;
290}
291
initial.commit09911bf2008-07-26 23:55:29292// DownloadManager implementation ----------------------------------------------
293
294// static
295void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
296 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
297 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32298 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
299
[email protected]b7f05882009-02-22 01:21:56300// TODO(port): port the necessary bits of chrome_paths.
301#if defined(OS_WIN)
[email protected]f052118e2008-09-05 02:25:32302 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41303 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12304 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
305 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32306 NOTREACHED();
307 }
[email protected]f052118e2008-09-05 02:25:32308 prefs->RegisterStringPref(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41309 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32310
311 // If the download path is dangerous we forcefully reset it. But if we do
312 // so we set a flag to make sure we only do it once, to avoid fighting
313 // the user if he really wants it on an unsafe place such as the desktop.
314
315 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41316 FilePath current_download_dir = FilePath::FromWStringHack(
317 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32318 if (DownloadPathIsDangerous(current_download_dir)) {
319 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41320 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32321 }
322 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
323 }
[email protected]b7f05882009-02-22 01:21:56324#endif
initial.commit09911bf2008-07-26 23:55:29325}
326
327DownloadManager::DownloadManager()
328 : shutdown_needed_(false),
329 profile_(NULL),
330 file_manager_(NULL),
331 ui_loop_(MessageLoop::current()),
332 file_loop_(NULL) {
333}
334
335DownloadManager::~DownloadManager() {
336 if (shutdown_needed_)
337 Shutdown();
338}
339
340void DownloadManager::Shutdown() {
341 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
342
343 // Stop receiving download updates
344 file_manager_->RemoveDownloadManager(this);
345
346 // Stop making history service requests
347 cancelable_consumer_.CancelAllRequests();
348
349 // 'in_progress_' may contain DownloadItems that have not finished the start
350 // complete (from the history service) and thus aren't in downloads_.
351 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32352 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29353 for (; it != in_progress_.end(); ++it) {
354 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32355 if (download->safety_state() == DownloadItem::DANGEROUS) {
356 // Forget about any download that the user did not approve.
357 // Note that we cannot call download->Remove() this would invalidate our
358 // iterator.
359 to_remove.insert(download);
360 continue;
initial.commit09911bf2008-07-26 23:55:29361 }
[email protected]9ccbb372008-10-10 18:50:32362 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
363 download->Cancel(false);
364 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29365 if (download->db_handle() == kUninitializedHandle) {
366 // An invalid handle means that 'download' does not yet exist in
367 // 'downloads_', so we have to delete it here.
368 delete download;
369 }
370 }
371
[email protected]9ccbb372008-10-10 18:50:32372 // 'dangerous_finished_' contains all complete downloads that have not been
373 // approved. They should be removed.
374 it = dangerous_finished_.begin();
375 for (; it != dangerous_finished_.end(); ++it)
376 to_remove.insert(it->second);
377
378 // Remove the dangerous download that are not approved.
379 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
380 rm_it != to_remove.end(); ++rm_it) {
381 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32382 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32383 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32384 // Same as above, delete the download if it is not in 'downloads_' (as the
385 // Remove() call above won't have deleted it).
386 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32387 delete download;
388 }
389 to_remove.clear();
390
initial.commit09911bf2008-07-26 23:55:29391 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32392 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29393 STLDeleteValues(&downloads_);
394
395 file_manager_ = NULL;
396
397 // Save our file extensions to auto open.
398 SaveAutoOpens();
399
400 // Make sure the save as dialog doesn't notify us back if we're gone before
401 // it returns.
402 if (select_file_dialog_.get())
403 select_file_dialog_->ListenerDestroyed();
404
405 shutdown_needed_ = false;
406}
407
408// Issue a history query for downloads matching 'search_text'. If 'search_text'
409// is empty, return all downloads that we know about.
410void DownloadManager::GetDownloads(Observer* observer,
411 const std::wstring& search_text) {
412 DCHECK(observer);
413
414 // Return a empty list if we've not yet received the set of downloads from the
415 // history system (we'll update all observers once we get that list in
416 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
417 std::vector<DownloadItem*> download_copy;
418 if (downloads_.empty()) {
419 observer->SetDownloads(download_copy);
420 return;
421 }
422
423 // We already know all the downloads and there is no filter, so just return a
424 // copy to the observer.
425 if (search_text.empty()) {
426 download_copy.reserve(downloads_.size());
427 for (DownloadMap::iterator it = downloads_.begin();
428 it != downloads_.end(); ++it) {
429 download_copy.push_back(it->second);
430 }
431
432 // We retain ownership of the DownloadItems.
433 observer->SetDownloads(download_copy);
434 return;
435 }
436
437 // Issue a request to the history service for a list of downloads matching
438 // our search text.
439 HistoryService* hs =
440 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
441 if (hs) {
442 HistoryService::Handle h =
443 hs->SearchDownloads(search_text,
444 &cancelable_consumer_,
445 NewCallback(this,
446 &DownloadManager::OnSearchComplete));
447 cancelable_consumer_.SetClientData(hs, h, observer);
448 }
449}
450
451// Query the history service for information about all persisted downloads.
452bool DownloadManager::Init(Profile* profile) {
453 DCHECK(profile);
454 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
455 shutdown_needed_ = true;
456
457 profile_ = profile;
458 request_context_ = profile_->GetRequestContext();
459
460 // 'incognito mode' will have access to past downloads, but we won't store
461 // information about new downloads while in that mode.
462 QueryHistoryForDownloads();
463
464 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
465 if (!rdh) {
466 NOTREACHED();
467 return false;
468 }
469
470 file_manager_ = rdh->download_file_manager();
471 if (!file_manager_) {
472 NOTREACHED();
473 return false;
474 }
475
476 file_loop_ = g_browser_process->file_thread()->message_loop();
477 if (!file_loop_) {
478 NOTREACHED();
479 return false;
480 }
481
482 // Get our user preference state.
483 PrefService* prefs = profile_->GetPrefs();
484 DCHECK(prefs);
485 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
486
[email protected]b7f05882009-02-22 01:21:56487// TODO(port): enable this after implementing chrome_paths for posix.
488#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29489 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
490
[email protected]7ae7c2cb2009-01-06 23:31:41491 // This variable is needed to resolve which CreateDirectory we want to point
492 // to. Without it, the NewRunnableFunction cannot resolve the ambiguity.
493 // TODO(estade): when file_util::CreateDirectory(wstring) is removed,
494 // get rid of |CreateDirectoryPtr|.
495 bool (*CreateDirectoryPtr)(const FilePath&) = &file_util::CreateDirectory;
[email protected]bb69e9b32008-08-14 23:08:14496 // Ensure that the download directory specified in the preferences exists.
[email protected]7ae7c2cb2009-01-06 23:31:41497 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
498 CreateDirectoryPtr, download_path()));
[email protected]bb69e9b32008-08-14 23:08:14499
initial.commit09911bf2008-07-26 23:55:29500 // We store any file extension that should be opened automatically at
501 // download completion in this pref.
502 download_util::InitializeExeTypes(&exe_types_);
[email protected]b7f05882009-02-22 01:21:56503#elif defined(OS_POSIX)
504 NOTIMPLEMENTED();
505#endif
initial.commit09911bf2008-07-26 23:55:29506
507 std::wstring extensions_to_open =
508 prefs->GetString(prefs::kDownloadExtensionsToOpen);
509 std::vector<std::wstring> extensions;
510 SplitString(extensions_to_open, L':', &extensions);
511 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]b7f05882009-02-22 01:21:56512 if (!extensions[i].empty() && !IsExecutable(
513 FilePath::FromWStringHack(extensions[i]).value()))
514 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29515 }
516
517 return true;
518}
519
520void DownloadManager::QueryHistoryForDownloads() {
521 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
522 if (hs) {
523 hs->QueryDownloads(
524 &cancelable_consumer_,
525 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
526 }
527}
528
529// We have received a message from DownloadFileManager about a new download. We
530// create a download item and store it in our download map, and inform the
531// history system of a new download. Since this method can be called while the
532// history service thread is still reading the persistent state, we do not
533// insert the new DownloadItem into 'downloads_' or inform our observers at this
534// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
535// download creation as a callback from the history thread.
536void DownloadManager::StartDownload(DownloadCreateInfo* info) {
537 DCHECK(MessageLoop::current() == ui_loop_);
538 DCHECK(info);
539
[email protected]7d3851d82008-12-12 03:26:07540 // Freeze the user's preference for showing a Save As dialog. We're going to
541 // bounce around a bunch of threads and we don't want to worry about race
542 // conditions where the user changes this pref out from under us.
543 if (*prompt_for_download_)
544 info->save_as = true;
545
initial.commit09911bf2008-07-26 23:55:29546 // Determine the proper path for a download, by choosing either the default
547 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41548 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29549 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07550 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29551 info->suggested_path = last_download_path_;
552 else
[email protected]7ae7c2cb2009-01-06 23:31:41553 info->suggested_path = download_path();
554 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29555
[email protected]7d3851d82008-12-12 03:26:07556 if (!info->save_as) {
557 // Let's check if this download is dangerous, based on its name.
[email protected]7ae7c2cb2009-01-06 23:31:41558 info->is_dangerous = IsDangerous(info->suggested_path.BaseName());
[email protected]e9ebf3fc2008-10-17 22:06:58559 }
560
initial.commit09911bf2008-07-26 23:55:29561 // We need to move over to the download thread because we don't want to stat
562 // the suggested path on the UI thread.
563 file_loop_->PostTask(FROM_HERE,
564 NewRunnableMethod(this,
565 &DownloadManager::CheckIfSuggestedPathExists,
566 info));
567}
568
569void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
570 DCHECK(info);
571
572 // Check writability of the suggested path. If we can't write to it, default
573 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41574 FilePath dir = info->suggested_path.DirName();
575 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32576 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29577 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29578 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41579 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29580 }
581
[email protected]7a256ea2008-10-17 17:34:16582 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29583
[email protected]6cade212008-12-03 00:32:22584 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58585 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41586 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32587 // Create a temporary file to hold the file until the user approves its
588 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41589 FilePath::StringType file_name;
590 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32591 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41592 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32593 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41594 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07595 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41596 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32597 }
598 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16599 } else {
600 // We know the final path, build it if necessary.
601 if (info->path_uniquifier > 0) {
602 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
603 // Setting path_uniquifier to 0 to make sure we don't try to unique it
604 // later on.
605 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07606 } else if (info->path_uniquifier == -1) {
607 // We failed to find a unique path. We have to prompt the user.
608 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16609 }
[email protected]9ccbb372008-10-10 18:50:32610 }
611
[email protected]7d3851d82008-12-12 03:26:07612 if (!info->save_as) {
613 // Create an empty file at the suggested path so that we don't allocate the
614 // same "non-existant" path to multiple downloads.
615 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ae7c2cb2009-01-06 23:31:41616 file_util::WriteFile(info->suggested_path.ToWStringHack(), "", 0);
[email protected]7d3851d82008-12-12 03:26:07617 }
618
initial.commit09911bf2008-07-26 23:55:29619 // Now we return to the UI thread.
620 ui_loop_->PostTask(FROM_HERE,
621 NewRunnableMethod(this,
622 &DownloadManager::OnPathExistenceAvailable,
623 info));
624}
625
626void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]b7f05882009-02-22 01:21:56627#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29628 DCHECK(MessageLoop::current() == ui_loop_);
629 DCHECK(info);
630
[email protected]7d3851d82008-12-12 03:26:07631 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29632 // We must ask the user for the place to put the download.
633 if (!select_file_dialog_.get())
634 select_file_dialog_ = SelectFileDialog::Create(this);
635
[email protected]a3a1d142008-12-19 00:42:30636 WebContents* contents = tab_util::GetWebContentsByID(
initial.commit09911bf2008-07-26 23:55:29637 info->render_process_id, info->render_view_id);
[email protected]7ae7c2cb2009-01-06 23:31:41638 std::wstring filter =
639 win_util::GetFileFilterFromPath(info->suggested_path.value());
initial.commit09911bf2008-07-26 23:55:29640 HWND owning_hwnd =
[email protected]92edc472009-02-10 20:32:06641 contents ? GetAncestor(contents->GetNativeView(), GA_ROOT) : NULL;
initial.commit09911bf2008-07-26 23:55:29642 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]7ae7c2cb2009-01-06 23:31:41643 std::wstring(),
644 info->suggested_path.ToWStringHack(),
[email protected]6cade212008-12-03 00:32:22645 filter, std::wstring(),
initial.commit09911bf2008-07-26 23:55:29646 owning_hwnd, info);
647 } else {
648 // No prompting for download, just continue with the suggested name.
649 ContinueStartDownload(info, info->suggested_path);
650 }
[email protected]b7f05882009-02-22 01:21:56651#elif defined(OS_POSIX)
652 // TODO(port): port this file -- need dialogs.
653 NOTIMPLEMENTED();
654#endif
initial.commit09911bf2008-07-26 23:55:29655}
656
657void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41658 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29659 scoped_ptr<DownloadCreateInfo> infop(info);
660 info->path = target_path;
661
662 DownloadItem* download = NULL;
663 DownloadMap::iterator it = in_progress_.find(info->download_id);
664 if (it == in_progress_.end()) {
665 download = new DownloadItem(info->download_id,
666 info->path,
[email protected]7a256ea2008-10-17 17:34:16667 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29668 info->url,
[email protected]9ccbb372008-10-10 18:50:32669 info->original_name,
initial.commit09911bf2008-07-26 23:55:29670 info->start_time,
671 info->total_bytes,
672 info->render_process_id,
[email protected]9ccbb372008-10-10 18:50:32673 info->request_id,
674 info->is_dangerous);
initial.commit09911bf2008-07-26 23:55:29675 download->set_manager(this);
676 in_progress_[info->download_id] = download;
677 } else {
678 NOTREACHED(); // Should not exist!
679 return;
680 }
681
682 // If the download already completed by the time we reached this point, then
683 // notify observers that it did.
684 PendingFinishedMap::iterator pending_it =
685 pending_finished_downloads_.find(info->download_id);
686 if (pending_it != pending_finished_downloads_.end())
687 DownloadFinished(pending_it->first, pending_it->second);
688
689 download->Rename(target_path);
690
691 file_loop_->PostTask(FROM_HERE,
692 NewRunnableMethod(file_manager_,
693 &DownloadFileManager::OnFinalDownloadName,
694 download->id(),
695 target_path));
696
697 if (profile_->IsOffTheRecord()) {
698 // Fake a db handle for incognito mode, since nothing is actually stored in
699 // the database in this mode. We have to make sure that these handles don't
700 // collide with normal db handles, so we use a negative value. Eventually,
701 // they could overlap, but you'd have to do enough downloading that your ISP
702 // would likely stab you in the neck first. YMMV.
703 static int64 fake_db_handle = kUninitializedHandle - 1;
704 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
705 } else {
706 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22707 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29708 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
709 if (hs) {
710 hs->CreateDownload(
711 *info, &cancelable_consumer_,
712 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
713 }
714 }
715}
716
717// Convenience function for updating the history service for a download.
718void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
719 DCHECK(download);
720
721 // Don't store info in the database if the download was initiated while in
722 // incognito mode or if it hasn't been initialized in our database table.
723 if (download->db_handle() <= kUninitializedHandle)
724 return;
725
[email protected]6cade212008-12-03 00:32:22726 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29727 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
728 if (hs) {
729 hs->UpdateDownload(download->received_bytes(),
730 download->state(),
731 download->db_handle());
732 }
733}
734
735void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
736 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22737 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29738 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
739 if (download->db_handle() > kUninitializedHandle && hs)
740 hs->RemoveDownload(download->db_handle());
741}
742
[email protected]e93d2822009-01-30 05:59:59743void DownloadManager::RemoveDownloadsFromHistoryBetween(
744 const base::Time remove_begin,
745 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22746 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29747 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
748 if (hs)
749 hs->RemoveDownloadsBetween(remove_begin, remove_end);
750}
751
752void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
753 DownloadMap::iterator it = in_progress_.find(download_id);
754 if (it != in_progress_.end()) {
755 DownloadItem* download = it->second;
756 download->Update(size);
757 UpdateHistoryForDownload(download);
758 }
759}
760
761void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
762 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32763 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29764 // The download is done, but the user hasn't selected a final location for
765 // it yet (the Save As dialog box is probably still showing), so just keep
766 // track of the fact that this download id is complete, when the
767 // DownloadItem is constructed later we'll notify its completion then.
768 PendingFinishedMap::iterator erase_it =
769 pending_finished_downloads_.find(download_id);
770 DCHECK(erase_it == pending_finished_downloads_.end());
771 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32772 return;
initial.commit09911bf2008-07-26 23:55:29773 }
[email protected]9ccbb372008-10-10 18:50:32774
775 // Remove the id from the list of pending ids.
776 PendingFinishedMap::iterator erase_it =
777 pending_finished_downloads_.find(download_id);
778 if (erase_it != pending_finished_downloads_.end())
779 pending_finished_downloads_.erase(erase_it);
780
781 DownloadItem* download = it->second;
782 download->Finished(size);
783
784 // Clean up will happen when the history system create callback runs if we
785 // don't have a valid db_handle yet.
786 if (download->db_handle() != kUninitializedHandle) {
787 in_progress_.erase(it);
788 NotifyAboutDownloadStop();
789 UpdateHistoryForDownload(download);
790 }
791
792 // If this a dangerous download not yet validated by the user, don't do
793 // anything. When the user notifies us, it will trigger a call to
794 // ProceedWithFinishedDangerousDownload.
795 if (download->safety_state() == DownloadItem::DANGEROUS) {
796 dangerous_finished_[download_id] = download;
797 return;
798 }
799
800 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22801 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32802 // its final name before we can continue.
803 file_loop_->PostTask(FROM_HERE,
804 NewRunnableMethod(
805 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
806 download->db_handle(),
807 download->full_path(), download->original_name()));
808 return;
809 }
810 ContinueDownloadFinished(download);
811}
812
813void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
814 // If this was a dangerous download, it has now been approved and must be
815 // removed from dangerous_finished_ so it does not get deleted on shutdown.
816 DownloadMap::iterator it = dangerous_finished_.find(download->id());
817 if (it != dangerous_finished_.end())
818 dangerous_finished_.erase(it);
819
820 // Notify our observers that we are complete (the call to Finished() set the
821 // state to complete but did not notify).
822 download->UpdateObservers();
823
824 // Open the download if the user or user prefs indicate it should be.
[email protected]b7f05882009-02-22 01:21:56825 const FilePath::StringType extension = download->full_path().Extension();
[email protected]9ccbb372008-10-10 18:50:32826 if (download->open_when_complete() || ShouldOpenFileExtension(extension))
827 OpenDownloadInShell(download, NULL);
828}
829
830// Called on the file thread. Renames the downloaded file to its original name.
831void DownloadManager::ProceedWithFinishedDangerousDownload(
832 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41833 const FilePath& path,
834 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32835 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41836 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16837 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32838 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24839 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16840 // Make our name unique at this point, as if a dangerous file is downloading
841 // and a 2nd download is started for a file with the same name, they would
842 // have the same path. This is because we uniquify the name on download
843 // start, and at that time the first file does not exists yet, so the second
844 // file gets the same name.
845 uniquifier = GetUniquePathNumber(new_path);
846 if (uniquifier > 0)
847 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32848 success = file_util::Move(path, new_path);
849 } else {
850 NOTREACHED();
851 }
[email protected]6cade212008-12-03 00:32:22852
[email protected]9ccbb372008-10-10 18:50:32853 ui_loop_->PostTask(FROM_HERE,
854 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16855 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32856}
857
858// Call from the file thread when the finished dangerous download was renamed.
859void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
860 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41861 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16862 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32863 DownloadMap::iterator it = downloads_.find(download_handle);
864 if (it == downloads_.end()) {
865 NOTREACHED();
866 return;
867 }
868
869 DownloadItem* download = it->second;
870 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16871 if (success) {
872 // We need to update the path uniquifier so that the UI shows the right
873 // name when calling GetFileName().
874 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32875 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16876 }
[email protected]9ccbb372008-10-10 18:50:32877
878 // Continue the download finished sequence.
879 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29880}
881
882// static
883// We have to tell the ResourceDispatcherHost to cancel the download from this
[email protected]6cade212008-12-03 00:32:22884// thread, since we can't forward tasks from the file thread to the IO thread
initial.commit09911bf2008-07-26 23:55:29885// reliably (crash on shutdown race condition).
886void DownloadManager::CancelDownloadRequest(int render_process_id,
887 int request_id) {
888 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]ab820df2008-08-26 05:55:10889 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29890 if (!io_thread || !rdh)
891 return;
892 io_thread->message_loop()->PostTask(FROM_HERE,
893 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
894 rdh,
895 render_process_id,
896 request_id));
897}
898
899// static
900void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
901 int render_process_id,
902 int request_id) {
903 rdh->CancelRequest(render_process_id, request_id, false);
904}
905
906void DownloadManager::DownloadCancelled(int32 download_id) {
907 DownloadMap::iterator it = in_progress_.find(download_id);
908 if (it == in_progress_.end())
909 return;
910 DownloadItem* download = it->second;
911
912 CancelDownloadRequest(download->render_process_id(), download->request_id());
913
914 // Clean up will happen when the history system create callback runs if we
915 // don't have a valid db_handle yet.
916 if (download->db_handle() != kUninitializedHandle) {
917 in_progress_.erase(it);
918 NotifyAboutDownloadStop();
919 UpdateHistoryForDownload(download);
920 }
921
922 // Tell the file manager to cancel the download.
923 file_manager_->RemoveDownload(download->id(), this); // On the UI thread
924 file_loop_->PostTask(FROM_HERE,
925 NewRunnableMethod(file_manager_,
926 &DownloadFileManager::CancelDownload,
927 download->id()));
928}
929
930void DownloadManager::PauseDownload(int32 download_id, bool pause) {
931 DownloadMap::iterator it = in_progress_.find(download_id);
932 if (it != in_progress_.end()) {
933 DownloadItem* download = it->second;
934 if (pause == download->is_paused())
935 return;
936
937 // Inform the ResourceDispatcherHost of the new pause state.
[email protected]ab820df2008-08-26 05:55:10938 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29939 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
940 if (!io_thread || !rdh)
941 return;
942
943 io_thread->message_loop()->PostTask(FROM_HERE,
944 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
945 rdh,
946 download->render_process_id(),
947 download->request_id(),
948 pause));
949 }
950}
951
952// static
953void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
954 int render_process_id,
955 int request_id,
956 bool pause) {
957 rdh->PauseRequest(render_process_id, request_id, pause);
958}
959
[email protected]7ae7c2cb2009-01-06 23:31:41960bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:32961 // TODO(jcampan): Improve me.
[email protected]b7f05882009-02-22 01:21:56962 return IsExecutable(file_name.Extension());
[email protected]9ccbb372008-10-10 18:50:32963}
964
965void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:41966 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:32967 download->Rename(new_path);
968
969 // Update the history.
970
971 // No update necessary if the download was initiated while in incognito mode.
972 if (download->db_handle() <= kUninitializedHandle)
973 return;
974
[email protected]6cade212008-12-03 00:32:22975 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:32976 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
977 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:41978 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:32979}
980
initial.commit09911bf2008-07-26 23:55:29981void DownloadManager::RemoveDownload(int64 download_handle) {
982 DownloadMap::iterator it = downloads_.find(download_handle);
983 if (it == downloads_.end())
984 return;
985
986 // Make history update.
987 DownloadItem* download = it->second;
988 RemoveDownloadFromHistory(download);
989
990 // Remove from our tables and delete.
991 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32992 it = dangerous_finished_.find(download->id());
993 if (it != dangerous_finished_.end())
994 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:29995
996 // Tell observers to refresh their views.
997 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:36998
999 delete download;
initial.commit09911bf2008-07-26 23:55:291000}
1001
[email protected]e93d2822009-01-30 05:59:591002int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1003 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291004 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1005
1006 int num_deleted = 0;
1007 DownloadMap::iterator it = downloads_.begin();
1008 while (it != downloads_.end()) {
1009 DownloadItem* download = it->second;
1010 DownloadItem::DownloadState state = download->state();
1011 if (download->start_time() >= remove_begin &&
1012 (remove_end.is_null() || download->start_time() < remove_end) &&
1013 (state == DownloadItem::COMPLETE ||
1014 state == DownloadItem::CANCELLED)) {
1015 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561016 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581017
1018 // Also remove it from any completed dangerous downloads.
1019 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1020 if (dit != dangerous_finished_.end())
1021 dangerous_finished_.erase(dit);
1022
initial.commit09911bf2008-07-26 23:55:291023 delete download;
1024
1025 ++num_deleted;
1026 continue;
1027 }
1028
1029 ++it;
1030 }
1031
1032 // Tell observers to refresh their views.
1033 if (num_deleted > 0)
1034 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1035
1036 return num_deleted;
1037}
1038
[email protected]e93d2822009-01-30 05:59:591039int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1040 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291041}
1042
1043// Initiate a download of a specific URL. We send the request to the
1044// ResourceDispatcherHost, and let it send us responses like a regular
1045// download.
1046void DownloadManager::DownloadUrl(const GURL& url,
1047 const GURL& referrer,
1048 WebContents* web_contents) {
1049 DCHECK(web_contents);
1050 file_manager_->DownloadUrl(url,
1051 referrer,
1052 web_contents->process()->host_id(),
1053 web_contents->render_view_host()->routing_id(),
1054 request_context_.get());
1055}
1056
1057void DownloadManager::NotifyAboutDownloadStart() {
[email protected]bfd04a62009-02-01 18:16:561058 NotificationService::current()->Notify(
1059 NotificationType::DOWNLOAD_START,
1060 NotificationService::AllSources(),
1061 NotificationService::NoDetails());
initial.commit09911bf2008-07-26 23:55:291062}
1063
1064void DownloadManager::NotifyAboutDownloadStop() {
[email protected]bfd04a62009-02-01 18:16:561065 NotificationService::current()->Notify(
1066 NotificationType::DOWNLOAD_STOP,
1067 NotificationService::AllSources(),
1068 NotificationService::NoDetails());
initial.commit09911bf2008-07-26 23:55:291069}
1070
[email protected]7ae7c2cb2009-01-06 23:31:411071void DownloadManager::GenerateExtension(
1072 const FilePath& file_name,
1073 const std::string& mime_type,
1074 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291075 // We're worried about three things here:
1076 //
1077 // 1) Security. Many sites let users upload content, such as buddy icons, to
1078 // their web sites. We want to mitigate the case where an attacker
1079 // supplies a malicious executable with an executable file extension but an
1080 // honest site serves the content with a benign content type, such as
1081 // image/jpeg.
1082 //
1083 // 2) Usability. If the site fails to provide a file extension, we want to
1084 // guess a reasonable file extension based on the content type.
1085 //
1086 // 3) Shell integration. Some file extensions automatically integrate with
1087 // the shell. We block these extensions to prevent a malicious web site
1088 // from integrating with the user's shell.
1089
[email protected]7ae7c2cb2009-01-06 23:31:411090 static const FilePath::CharType default_extension[] =
1091 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291092
1093 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411094 FilePath::StringType extension(
1095 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291096
[email protected]b7f05882009-02-22 01:21:561097#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291098 // Rename shell-integrated extensions.
1099 if (win_util::IsShellIntegratedExtension(extension))
1100 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561101#endif
initial.commit09911bf2008-07-26 23:55:291102
1103 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411104 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411105 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291106 if (mime_type == mime_type_from_extension) {
1107 // The hinted extension matches the mime type. It looks like a winner.
1108 generated_extension->swap(extension);
1109 return;
1110 }
1111
1112 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1113 // We want to be careful about executable extensions. The worry here is
1114 // that a trusted web site could be tricked into dropping an executable file
1115 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101116 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291117 // We couldn't find a good extension for this content type. Use a dummy
1118 // extension instead.
1119 extension.assign(default_extension);
1120 }
1121 }
1122
1123 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101124 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291125 } else {
[email protected]6cade212008-12-03 00:32:221126 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291127 // 1. New extension is not ".txt"
1128 // 2. New extension is not the same as the already existing extension.
1129 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411130 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291131 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1132 // application/x-javascript.
[email protected]7ae7c2cb2009-01-06 23:31:411133 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101134 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171135 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411136 append_extension != extension &&
[email protected]3f156552009-02-09 19:44:171137 !IsExecutable(append_extension)) {
1138 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291139 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171140 }
initial.commit09911bf2008-07-26 23:55:291141 }
1142 }
1143
1144 generated_extension->swap(extension);
1145}
1146
1147void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411148 FilePath* generated_name) {
1149 *generated_name = FilePath::FromWStringHack(
[email protected]8ac1a752008-07-31 19:40:371150 net::GetSuggestedFilename(GURL(info->url),
1151 info->content_disposition,
[email protected]7ae7c2cb2009-01-06 23:31:411152 L"download"));
1153 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291154
[email protected]7ae7c2cb2009-01-06 23:31:411155 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291156}
1157
1158void DownloadManager::AddObserver(Observer* observer) {
1159 observers_.AddObserver(observer);
1160 observer->ModelChanged();
1161}
1162
1163void DownloadManager::RemoveObserver(Observer* observer) {
1164 observers_.RemoveObserver(observer);
1165}
1166
1167// Post Windows Shell operations to the Download thread, to avoid blocking the
1168// user interface.
1169void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1170 DCHECK(file_manager_);
1171 file_loop_->PostTask(FROM_HERE,
1172 NewRunnableMethod(file_manager_,
1173 &DownloadFileManager::OnShowDownloadInShell,
[email protected]7ae7c2cb2009-01-06 23:31:411174 FilePath(download->full_path())));
initial.commit09911bf2008-07-26 23:55:291175}
1176
1177void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591178 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291179 DCHECK(file_manager_);
1180 file_loop_->PostTask(FROM_HERE,
1181 NewRunnableMethod(file_manager_,
1182 &DownloadFileManager::OnOpenDownloadInShell,
1183 download->full_path(), download->url(), parent_window));
1184}
1185
[email protected]7ae7c2cb2009-01-06 23:31:411186void DownloadManager::OpenFilesOfExtension(
1187 const FilePath::StringType& extension, bool open) {
initial.commit09911bf2008-07-26 23:55:291188 if (open && !IsExecutable(extension))
1189 auto_open_.insert(extension);
1190 else
1191 auto_open_.erase(extension);
1192 SaveAutoOpens();
1193}
1194
[email protected]7ae7c2cb2009-01-06 23:31:411195bool DownloadManager::ShouldOpenFileExtension(
1196 const FilePath::StringType& extension) {
[email protected]8c756ac2009-01-30 23:36:411197 // Special-case Chrome extensions as always-open.
initial.commit09911bf2008-07-26 23:55:291198 if (!IsExecutable(extension) &&
[email protected]8c756ac2009-01-30 23:36:411199 (auto_open_.find(extension) != auto_open_.end() ||
1200 extension == chrome::kExtensionFileExtension))
1201 return true;
initial.commit09911bf2008-07-26 23:55:291202 return false;
1203}
1204
[email protected]7b73d992008-12-15 20:56:461205static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291206 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461207 "text/javascript",
1208 "text/javascript;version=*",
[email protected]60ff8f912008-12-05 07:58:391209 // Some sites use binary/octet-stream to mean application/octet-stream.
1210 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461211 "binary/octet-stream"
1212};
initial.commit09911bf2008-07-26 23:55:291213
[email protected]7b73d992008-12-15 20:56:461214static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291215 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461216 "application/*+xml",
1217 "application/xml"
1218};
initial.commit09911bf2008-07-26 23:55:291219
[email protected]7b73d992008-12-15 20:56:461220// static
1221bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411222 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461223 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1224 return true;
1225 }
[email protected]bae0ea12009-02-14 01:20:411226 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461227 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1228 return false;
1229 }
1230 // We consider only other application types to be executable.
1231 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291232}
1233
[email protected]7ae7c2cb2009-01-06 23:31:411234bool DownloadManager::IsExecutable(const FilePath::StringType& extension) {
initial.commit09911bf2008-07-26 23:55:291235 return exe_types_.find(extension) != exe_types_.end();
1236}
1237
1238void DownloadManager::ResetAutoOpenFiles() {
1239 auto_open_.clear();
1240 SaveAutoOpens();
1241}
1242
1243bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1244 return !auto_open_.empty();
1245}
1246
1247void DownloadManager::SaveAutoOpens() {
1248 PrefService* prefs = profile_->GetPrefs();
1249 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411250 FilePath::StringType extensions;
1251 for (std::set<FilePath::StringType>::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291252 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411253 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291254 }
1255 if (!extensions.empty())
1256 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561257
1258 std::wstring extensions_w;
1259#if defined(OS_WIN)
1260 extensions_w = extensions;
1261#elif defined(OS_POSIX)
1262 // TODO(port): this is not correct since FilePath::StringType is not
1263 // necessarily UTF8.
1264 extensions_w = UTF8ToWide(extensions);
1265#endif
1266
1267 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291268 }
1269}
1270
[email protected]7ae7c2cb2009-01-06 23:31:411271void DownloadManager::FileSelected(const std::wstring& path_string,
1272 void* params) {
1273 FilePath path = FilePath::FromWStringHack(path_string);
initial.commit09911bf2008-07-26 23:55:291274 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071275 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411276 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291277 ContinueStartDownload(info, path);
1278}
1279
1280void DownloadManager::FileSelectionCanceled(void* params) {
1281 // The user didn't pick a place to save the file, so need to cancel the
1282 // download that's already in progress to the temporary location.
1283 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
1284 file_loop_->PostTask(FROM_HERE,
1285 NewRunnableMethod(file_manager_, &DownloadFileManager::CancelDownload,
1286 info->download_id));
1287}
1288
[email protected]7ae7c2cb2009-01-06 23:31:411289void DownloadManager::DeleteDownload(const FilePath& path) {
1290 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
1291 &DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321292}
1293
1294
1295void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1296 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1297 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1298 download->UpdateObservers();
1299
1300 // If the download is not complete, nothing to do. The required
1301 // post-processing will be performed when it does complete.
1302 if (download->state() != DownloadItem::COMPLETE)
1303 return;
1304
1305 file_loop_->PostTask(FROM_HERE,
1306 NewRunnableMethod(this,
1307 &DownloadManager::ProceedWithFinishedDangerousDownload,
1308 download->db_handle(), download->full_path(),
1309 download->original_name()));
1310}
1311
[email protected]763f946a2009-01-06 19:04:391312void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411313 FilePath* file_name) {
1314 // Make sure we get the right file extension
1315 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391316 GenerateExtension(*file_name, mime_type, &extension);
1317 file_util::ReplaceExtension(file_name, extension);
1318
1319 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411320 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391321 DCHECK(!leaf_name.empty());
[email protected]b7f05882009-02-22 01:21:561322#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391323 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411324 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1325 *file_name = file_name->DirName();
1326 if (file_name->value() == FilePath::kCurrentDirectory) {
1327 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391328 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411329 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391330 }
1331 }
[email protected]b7f05882009-02-22 01:21:561332#elif defined(OS_POSIX)
1333 NOTIMPLEMENTED();
1334#endif
[email protected]763f946a2009-01-06 19:04:391335}
1336
initial.commit09911bf2008-07-26 23:55:291337// Operations posted to us from the history service ----------------------------
1338
1339// The history service has retrieved all download entries. 'entries' contains
1340// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1341void DownloadManager::OnQueryDownloadEntriesComplete(
1342 std::vector<DownloadCreateInfo>* entries) {
1343 for (size_t i = 0; i < entries->size(); ++i) {
1344 DownloadItem* download = new DownloadItem(entries->at(i));
1345 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1346 downloads_[download->db_handle()] = download;
1347 download->set_manager(this);
1348 }
1349 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1350}
1351
1352
1353// Once the new DownloadItem's creation info has been committed to the history
1354// service, we associate the DownloadItem with the db handle, update our
1355// 'downloads_' map and inform observers.
1356void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1357 int64 db_handle) {
1358 DownloadMap::iterator it = in_progress_.find(info.download_id);
1359 DCHECK(it != in_progress_.end());
1360
1361 DownloadItem* download = it->second;
1362 DCHECK(download->db_handle() == kUninitializedHandle);
1363 download->set_db_handle(db_handle);
1364
1365 // Insert into our full map.
1366 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1367 downloads_[download->db_handle()] = download;
1368
1369 // The 'contents' may no longer exist if the user closed the tab before we get
1370 // this start completion event. If it does, tell the origin WebContents to
1371 // display its download shelf.
1372 TabContents* contents =
[email protected]a3a1d142008-12-19 00:42:301373 tab_util::GetWebContentsByID(info.render_process_id, info.render_view_id);
initial.commit09911bf2008-07-26 23:55:291374
1375 // If the contents no longer exists or is no longer active, we start the
1376 // download in the last active browser. This is not ideal but better than
1377 // fully hiding the download from the user. Note: non active means that the
1378 // user navigated away from the tab contents. This has nothing to do with
1379 // tab selection.
1380 if (!contents || !contents->is_active()) {
1381 Browser* last_active = BrowserList::GetLastActive();
1382 if (last_active)
1383 contents = last_active->GetSelectedTabContents();
1384 }
1385
1386 if (contents)
1387 contents->OnStartDownload(download);
1388
1389 // Inform interested objects about the new download.
1390 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1391 NotifyAboutDownloadStart();
1392
1393 // If this download has been completed before we've received the db handle,
1394 // post one final message to the history service so that it can be properly
1395 // in sync with the DownloadItem's completion status, and also inform any
1396 // observers so that they get more than just the start notification.
1397 if (download->state() != DownloadItem::IN_PROGRESS) {
1398 in_progress_.erase(it);
1399 NotifyAboutDownloadStop();
1400 UpdateHistoryForDownload(download);
1401 download->UpdateObservers();
1402 }
1403}
1404
1405// Called when the history service has retrieved the list of downloads that
1406// match the search text.
1407void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1408 std::vector<int64>* results) {
1409 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1410 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1411 if (!requestor)
1412 return;
1413
1414 std::vector<DownloadItem*> searched_downloads;
1415 for (std::vector<int64>::iterator it = results->begin();
1416 it != results->end(); ++it) {
1417 DownloadMap::iterator dit = downloads_.find(*it);
1418 if (dit != downloads_.end())
1419 searched_downloads.push_back(dit->second);
1420 }
1421
1422 requestor->SetDownloads(searched_downloads);
1423}
[email protected]905a08d2008-11-19 07:24:121424
[email protected]6cade212008-12-03 00:32:221425// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121426void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411427 last_download_path_ = FilePath();
[email protected]905a08d2008-11-19 07:24:121428}