blob: 9ac30999d3527e5a8e62499731c15e8b2f6daaf3 [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"
11#include "base/registry.h"
12#include "base/string_util.h"
13#include "base/task.h"
14#include "base/thread.h"
15#include "base/timer.h"
[email protected]9ccbb372008-10-10 18:50:3216#include "base/rand_util.h"
initial.commit09911bf2008-07-26 23:55:2917#include "base/win_util.h"
18#include "chrome/browser/browser_list.h"
19#include "chrome/browser/browser_process.h"
[email protected]cdaa8652008-09-13 02:48:5920#include "chrome/browser/download/download_file.h"
21#include "chrome/browser/download/download_util.h"
initial.commit09911bf2008-07-26 23:55:2922#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:2623#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2524#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]e3c404b2008-12-23 01:07:3225#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
[email protected]f3ec7742009-01-15 00:59:1626#include "chrome/browser/tab_contents/tab_util.h"
27#include "chrome/browser/tab_contents/web_contents.h"
initial.commit09911bf2008-07-26 23:55:2928#include "chrome/common/chrome_paths.h"
29#include "chrome/common/l10n_util.h"
30#include "chrome/common/notification_service.h"
31#include "chrome/common/pref_names.h"
32#include "chrome/common/pref_service.h"
33#include "chrome/common/stl_util-inl.h"
34#include "chrome/common/win_util.h"
[email protected]46072d42008-07-28 14:49:3535#include "googleurl/src/gurl.h"
initial.commit09911bf2008-07-26 23:55:2936#include "net/base/mime_util.h"
37#include "net/base/net_util.h"
38#include "net/url_request/url_request_context.h"
39
40#include "generated_resources.h"
41
42// Periodically update our observers.
43class DownloadItemUpdateTask : public Task {
44 public:
45 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
46 void Run() { if (item_) item_->UpdateObservers(); }
47
48 private:
49 DownloadItem* item_;
50};
51
52// Update frequency (milliseconds).
53static const int kUpdateTimeMs = 1000;
54
55// Our download table ID starts at 1, so we use 0 to represent a download that
56// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2257// database handles in incognito mode starting at -1 and progressively getting
58// more negative.
initial.commit09911bf2008-07-26 23:55:2959static const int kUninitializedHandle = 0;
60
[email protected]7a256ea2008-10-17 17:34:1661// Appends the passed the number between parenthesis the path before the
62// extension.
[email protected]7ae7c2cb2009-01-06 23:31:4163static void AppendNumberToPath(FilePath* path, int number) {
64 file_util::InsertBeforeExtension(path,
65 StringPrintf(FILE_PATH_LITERAL(" (%d)"), number));
[email protected]7a256ea2008-10-17 17:34:1666}
67
68// Attempts to find a number that can be appended to that path to make it
69// unique. If |path| does not exist, 0 is returned. If it fails to find such
70// a number, -1 is returned.
[email protected]7ae7c2cb2009-01-06 23:31:4171static int GetUniquePathNumber(const FilePath& path) {
initial.commit09911bf2008-07-26 23:55:2972 const int kMaxAttempts = 100;
73
[email protected]7a256ea2008-10-17 17:34:1674 if (!file_util::PathExists(path))
75 return 0;
initial.commit09911bf2008-07-26 23:55:2976
[email protected]7ae7c2cb2009-01-06 23:31:4177 FilePath new_path;
initial.commit09911bf2008-07-26 23:55:2978 for (int count = 1; count <= kMaxAttempts; ++count) {
[email protected]7ae7c2cb2009-01-06 23:31:4179 new_path = FilePath(path);
[email protected]7a256ea2008-10-17 17:34:1680 AppendNumberToPath(&new_path, count);
initial.commit09911bf2008-07-26 23:55:2981
[email protected]7a256ea2008-10-17 17:34:1682 if (!file_util::PathExists(new_path))
83 return count;
initial.commit09911bf2008-07-26 23:55:2984 }
85
[email protected]7a256ea2008-10-17 17:34:1686 return -1;
initial.commit09911bf2008-07-26 23:55:2987}
88
[email protected]7ae7c2cb2009-01-06 23:31:4189static bool DownloadPathIsDangerous(const FilePath& download_path) {
90 FilePath desktop_dir;
[email protected]f052118e2008-09-05 02:25:3291 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
92 NOTREACHED();
93 return false;
94 }
95 return (download_path == desktop_dir);
96}
97
initial.commit09911bf2008-07-26 23:55:2998// DownloadItem implementation -------------------------------------------------
99
100// Constructor for reading from the history service.
101DownloadItem::DownloadItem(const DownloadCreateInfo& info)
102 : id_(-1),
103 full_path_(info.path),
[email protected]9ccbb372008-10-10 18:50:32104 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29105 url_(info.url),
106 total_bytes_(info.total_bytes),
107 received_bytes_(info.received_bytes),
108 start_tick_(0),
109 state_(static_cast<DownloadState>(info.state)),
110 start_time_(info.start_time),
111 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29112 manager_(NULL),
[email protected]9ccbb372008-10-10 18:50:32113 safety_state_(SAFE),
initial.commit09911bf2008-07-26 23:55:29114 is_paused_(false),
115 open_when_complete_(false),
116 render_process_id_(-1),
117 request_id_(-1) {
118 if (state_ == IN_PROGRESS)
119 state_ = CANCELLED;
120 Init(false /* don't start progress timer */);
121}
122
123// Constructor for DownloadItem created via user action in the main thread.
124DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41125 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16126 int path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29127 const std::wstring& url,
[email protected]7ae7c2cb2009-01-06 23:31:41128 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59129 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29130 int64 download_size,
131 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32132 int request_id,
133 bool is_dangerous)
initial.commit09911bf2008-07-26 23:55:29134 : id_(download_id),
135 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16136 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29137 url_(url),
[email protected]9ccbb372008-10-10 18:50:32138 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29139 total_bytes_(download_size),
140 received_bytes_(0),
141 start_tick_(GetTickCount()),
142 state_(IN_PROGRESS),
143 start_time_(start_time),
144 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29145 manager_(NULL),
[email protected]9ccbb372008-10-10 18:50:32146 safety_state_(is_dangerous ? DANGEROUS : SAFE),
initial.commit09911bf2008-07-26 23:55:29147 is_paused_(false),
148 open_when_complete_(false),
149 render_process_id_(render_process_id),
150 request_id_(request_id) {
151 Init(true /* start progress timer */);
152}
153
154void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41155 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29156 if (start_timer)
157 StartProgressTimer();
158}
159
160DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29161 state_ = REMOVING;
162 UpdateObservers();
163}
164
165void DownloadItem::AddObserver(Observer* observer) {
166 observers_.AddObserver(observer);
167}
168
169void DownloadItem::RemoveObserver(Observer* observer) {
170 observers_.RemoveObserver(observer);
171}
172
173void DownloadItem::UpdateObservers() {
174 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
175}
176
177// If we've received more data than we were expecting (bad server info?), revert
178// to 'unknown size mode'.
179void DownloadItem::UpdateSize(int64 bytes_so_far) {
180 received_bytes_ = bytes_so_far;
181 if (received_bytes_ > total_bytes_)
182 total_bytes_ = 0;
183}
184
185// Updates from the download thread may have been posted while this download
186// was being cancelled in the UI thread, so we'll accept them unless we're
187// complete.
188void DownloadItem::Update(int64 bytes_so_far) {
189 if (state_ == COMPLETE) {
190 NOTREACHED();
191 return;
192 }
193 UpdateSize(bytes_so_far);
194 UpdateObservers();
195}
196
[email protected]6cade212008-12-03 00:32:22197// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29198void DownloadItem::Cancel(bool update_history) {
199 if (state_ != IN_PROGRESS) {
200 // Small downloads might be complete before this method has a chance to run.
201 return;
202 }
203 state_ = CANCELLED;
204 UpdateObservers();
205 StopProgressTimer();
206 if (update_history)
207 manager_->DownloadCancelled(id_);
208}
209
210void DownloadItem::Finished(int64 size) {
211 state_ = COMPLETE;
212 UpdateSize(size);
[email protected]22fbe5a2008-10-29 22:20:40213 UpdateObservers();
initial.commit09911bf2008-07-26 23:55:29214 StopProgressTimer();
215}
216
[email protected]9ccbb372008-10-10 18:50:32217void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29218 Cancel(true);
219 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32220 if (delete_on_disk)
221 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29222 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22223 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29224}
225
226void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59227 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14228 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29229}
230
231void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14232 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29233}
234
[email protected]e93d2822009-01-30 05:59:59235bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29236 if (total_bytes_ <= 0)
237 return false; // We never received the content_length for this download.
238
239 int64 speed = CurrentSpeed();
240 if (speed == 0)
241 return false;
242
243 *remaining =
[email protected]e93d2822009-01-30 05:59:59244 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29245 return true;
246}
247
248int64 DownloadItem::CurrentSpeed() const {
249 uintptr_t diff = GetTickCount() - start_tick_;
250 return diff == 0 ? 0 : received_bytes_ * 1000 / diff;
251}
252
253int DownloadItem::PercentComplete() const {
254 int percent = -1;
255 if (total_bytes_ > 0)
256 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
257 return percent;
258}
259
[email protected]7ae7c2cb2009-01-06 23:31:41260void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29261 DCHECK(!full_path.empty());
262 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41263 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29264}
265
266void DownloadItem::TogglePause() {
267 DCHECK(state_ == IN_PROGRESS);
268 manager_->PauseDownload(id_, !is_paused_);
269 is_paused_ = !is_paused_;
270 UpdateObservers();
271}
272
[email protected]7ae7c2cb2009-01-06 23:31:41273FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32274 if (safety_state_ == DownloadItem::SAFE)
275 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16276 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41277 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16278 AppendNumberToPath(&name, path_uniquifier_);
279 return name;
280 }
[email protected]9ccbb372008-10-10 18:50:32281 return original_name_;
282}
283
initial.commit09911bf2008-07-26 23:55:29284// DownloadManager implementation ----------------------------------------------
285
286// static
287void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
288 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
289 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32290 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
291
292 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41293 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12294 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
295 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32296 NOTREACHED();
297 }
[email protected]f052118e2008-09-05 02:25:32298 prefs->RegisterStringPref(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41299 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32300
301 // If the download path is dangerous we forcefully reset it. But if we do
302 // so we set a flag to make sure we only do it once, to avoid fighting
303 // the user if he really wants it on an unsafe place such as the desktop.
304
305 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41306 FilePath current_download_dir = FilePath::FromWStringHack(
307 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32308 if (DownloadPathIsDangerous(current_download_dir)) {
309 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41310 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32311 }
312 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
313 }
initial.commit09911bf2008-07-26 23:55:29314}
315
316DownloadManager::DownloadManager()
317 : shutdown_needed_(false),
318 profile_(NULL),
319 file_manager_(NULL),
320 ui_loop_(MessageLoop::current()),
321 file_loop_(NULL) {
322}
323
324DownloadManager::~DownloadManager() {
325 if (shutdown_needed_)
326 Shutdown();
327}
328
329void DownloadManager::Shutdown() {
330 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
331
332 // Stop receiving download updates
333 file_manager_->RemoveDownloadManager(this);
334
335 // Stop making history service requests
336 cancelable_consumer_.CancelAllRequests();
337
338 // 'in_progress_' may contain DownloadItems that have not finished the start
339 // complete (from the history service) and thus aren't in downloads_.
340 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32341 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29342 for (; it != in_progress_.end(); ++it) {
343 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32344 if (download->safety_state() == DownloadItem::DANGEROUS) {
345 // Forget about any download that the user did not approve.
346 // Note that we cannot call download->Remove() this would invalidate our
347 // iterator.
348 to_remove.insert(download);
349 continue;
initial.commit09911bf2008-07-26 23:55:29350 }
[email protected]9ccbb372008-10-10 18:50:32351 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
352 download->Cancel(false);
353 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29354 if (download->db_handle() == kUninitializedHandle) {
355 // An invalid handle means that 'download' does not yet exist in
356 // 'downloads_', so we have to delete it here.
357 delete download;
358 }
359 }
360
[email protected]9ccbb372008-10-10 18:50:32361 // 'dangerous_finished_' contains all complete downloads that have not been
362 // approved. They should be removed.
363 it = dangerous_finished_.begin();
364 for (; it != dangerous_finished_.end(); ++it)
365 to_remove.insert(it->second);
366
367 // Remove the dangerous download that are not approved.
368 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
369 rm_it != to_remove.end(); ++rm_it) {
370 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32371 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32372 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32373 // Same as above, delete the download if it is not in 'downloads_' (as the
374 // Remove() call above won't have deleted it).
375 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32376 delete download;
377 }
378 to_remove.clear();
379
initial.commit09911bf2008-07-26 23:55:29380 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32381 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29382 STLDeleteValues(&downloads_);
383
384 file_manager_ = NULL;
385
386 // Save our file extensions to auto open.
387 SaveAutoOpens();
388
389 // Make sure the save as dialog doesn't notify us back if we're gone before
390 // it returns.
391 if (select_file_dialog_.get())
392 select_file_dialog_->ListenerDestroyed();
393
394 shutdown_needed_ = false;
395}
396
397// Issue a history query for downloads matching 'search_text'. If 'search_text'
398// is empty, return all downloads that we know about.
399void DownloadManager::GetDownloads(Observer* observer,
400 const std::wstring& search_text) {
401 DCHECK(observer);
402
403 // Return a empty list if we've not yet received the set of downloads from the
404 // history system (we'll update all observers once we get that list in
405 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
406 std::vector<DownloadItem*> download_copy;
407 if (downloads_.empty()) {
408 observer->SetDownloads(download_copy);
409 return;
410 }
411
412 // We already know all the downloads and there is no filter, so just return a
413 // copy to the observer.
414 if (search_text.empty()) {
415 download_copy.reserve(downloads_.size());
416 for (DownloadMap::iterator it = downloads_.begin();
417 it != downloads_.end(); ++it) {
418 download_copy.push_back(it->second);
419 }
420
421 // We retain ownership of the DownloadItems.
422 observer->SetDownloads(download_copy);
423 return;
424 }
425
426 // Issue a request to the history service for a list of downloads matching
427 // our search text.
428 HistoryService* hs =
429 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
430 if (hs) {
431 HistoryService::Handle h =
432 hs->SearchDownloads(search_text,
433 &cancelable_consumer_,
434 NewCallback(this,
435 &DownloadManager::OnSearchComplete));
436 cancelable_consumer_.SetClientData(hs, h, observer);
437 }
438}
439
440// Query the history service for information about all persisted downloads.
441bool DownloadManager::Init(Profile* profile) {
442 DCHECK(profile);
443 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
444 shutdown_needed_ = true;
445
446 profile_ = profile;
447 request_context_ = profile_->GetRequestContext();
448
449 // 'incognito mode' will have access to past downloads, but we won't store
450 // information about new downloads while in that mode.
451 QueryHistoryForDownloads();
452
453 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
454 if (!rdh) {
455 NOTREACHED();
456 return false;
457 }
458
459 file_manager_ = rdh->download_file_manager();
460 if (!file_manager_) {
461 NOTREACHED();
462 return false;
463 }
464
465 file_loop_ = g_browser_process->file_thread()->message_loop();
466 if (!file_loop_) {
467 NOTREACHED();
468 return false;
469 }
470
471 // Get our user preference state.
472 PrefService* prefs = profile_->GetPrefs();
473 DCHECK(prefs);
474 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
475
initial.commit09911bf2008-07-26 23:55:29476 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
477
[email protected]7ae7c2cb2009-01-06 23:31:41478 // This variable is needed to resolve which CreateDirectory we want to point
479 // to. Without it, the NewRunnableFunction cannot resolve the ambiguity.
480 // TODO(estade): when file_util::CreateDirectory(wstring) is removed,
481 // get rid of |CreateDirectoryPtr|.
482 bool (*CreateDirectoryPtr)(const FilePath&) = &file_util::CreateDirectory;
[email protected]bb69e9b32008-08-14 23:08:14483 // Ensure that the download directory specified in the preferences exists.
[email protected]7ae7c2cb2009-01-06 23:31:41484 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
485 CreateDirectoryPtr, download_path()));
[email protected]bb69e9b32008-08-14 23:08:14486
initial.commit09911bf2008-07-26 23:55:29487 // We store any file extension that should be opened automatically at
488 // download completion in this pref.
489 download_util::InitializeExeTypes(&exe_types_);
490
491 std::wstring extensions_to_open =
492 prefs->GetString(prefs::kDownloadExtensionsToOpen);
493 std::vector<std::wstring> extensions;
494 SplitString(extensions_to_open, L':', &extensions);
495 for (size_t i = 0; i < extensions.size(); ++i) {
496 if (!extensions[i].empty() && !IsExecutable(extensions[i]))
497 auto_open_.insert(extensions[i]);
498 }
499
500 return true;
501}
502
503void DownloadManager::QueryHistoryForDownloads() {
504 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
505 if (hs) {
506 hs->QueryDownloads(
507 &cancelable_consumer_,
508 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
509 }
510}
511
512// We have received a message from DownloadFileManager about a new download. We
513// create a download item and store it in our download map, and inform the
514// history system of a new download. Since this method can be called while the
515// history service thread is still reading the persistent state, we do not
516// insert the new DownloadItem into 'downloads_' or inform our observers at this
517// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
518// download creation as a callback from the history thread.
519void DownloadManager::StartDownload(DownloadCreateInfo* info) {
520 DCHECK(MessageLoop::current() == ui_loop_);
521 DCHECK(info);
522
[email protected]7d3851d82008-12-12 03:26:07523 // Freeze the user's preference for showing a Save As dialog. We're going to
524 // bounce around a bunch of threads and we don't want to worry about race
525 // conditions where the user changes this pref out from under us.
526 if (*prompt_for_download_)
527 info->save_as = true;
528
initial.commit09911bf2008-07-26 23:55:29529 // Determine the proper path for a download, by choosing either the default
530 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41531 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29532 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07533 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29534 info->suggested_path = last_download_path_;
535 else
[email protected]7ae7c2cb2009-01-06 23:31:41536 info->suggested_path = download_path();
537 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29538
[email protected]7d3851d82008-12-12 03:26:07539 if (!info->save_as) {
540 // Let's check if this download is dangerous, based on its name.
[email protected]7ae7c2cb2009-01-06 23:31:41541 info->is_dangerous = IsDangerous(info->suggested_path.BaseName());
[email protected]e9ebf3fc2008-10-17 22:06:58542 }
543
initial.commit09911bf2008-07-26 23:55:29544 // We need to move over to the download thread because we don't want to stat
545 // the suggested path on the UI thread.
546 file_loop_->PostTask(FROM_HERE,
547 NewRunnableMethod(this,
548 &DownloadManager::CheckIfSuggestedPathExists,
549 info));
550}
551
552void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
553 DCHECK(info);
554
555 // Check writability of the suggested path. If we can't write to it, default
556 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41557 FilePath dir = info->suggested_path.DirName();
558 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32559 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29560 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29561 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41562 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29563 }
564
[email protected]7a256ea2008-10-17 17:34:16565 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29566
[email protected]6cade212008-12-03 00:32:22567 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58568 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41569 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32570 // Create a temporary file to hold the file until the user approves its
571 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41572 FilePath::StringType file_name;
573 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32574 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41575 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32576 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41577 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07578 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41579 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32580 }
581 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16582 } else {
583 // We know the final path, build it if necessary.
584 if (info->path_uniquifier > 0) {
585 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
586 // Setting path_uniquifier to 0 to make sure we don't try to unique it
587 // later on.
588 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07589 } else if (info->path_uniquifier == -1) {
590 // We failed to find a unique path. We have to prompt the user.
591 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16592 }
[email protected]9ccbb372008-10-10 18:50:32593 }
594
[email protected]7d3851d82008-12-12 03:26:07595 if (!info->save_as) {
596 // Create an empty file at the suggested path so that we don't allocate the
597 // same "non-existant" path to multiple downloads.
598 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ae7c2cb2009-01-06 23:31:41599 file_util::WriteFile(info->suggested_path.ToWStringHack(), "", 0);
[email protected]7d3851d82008-12-12 03:26:07600 }
601
initial.commit09911bf2008-07-26 23:55:29602 // Now we return to the UI thread.
603 ui_loop_->PostTask(FROM_HERE,
604 NewRunnableMethod(this,
605 &DownloadManager::OnPathExistenceAvailable,
606 info));
607}
608
609void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
610 DCHECK(MessageLoop::current() == ui_loop_);
611 DCHECK(info);
612
[email protected]7d3851d82008-12-12 03:26:07613 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29614 // We must ask the user for the place to put the download.
615 if (!select_file_dialog_.get())
616 select_file_dialog_ = SelectFileDialog::Create(this);
617
[email protected]a3a1d142008-12-19 00:42:30618 WebContents* contents = tab_util::GetWebContentsByID(
initial.commit09911bf2008-07-26 23:55:29619 info->render_process_id, info->render_view_id);
[email protected]7ae7c2cb2009-01-06 23:31:41620 std::wstring filter =
621 win_util::GetFileFilterFromPath(info->suggested_path.value());
initial.commit09911bf2008-07-26 23:55:29622 HWND owning_hwnd =
623 contents ? GetAncestor(contents->GetContainerHWND(), GA_ROOT) : NULL;
624 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]7ae7c2cb2009-01-06 23:31:41625 std::wstring(),
626 info->suggested_path.ToWStringHack(),
[email protected]6cade212008-12-03 00:32:22627 filter, std::wstring(),
initial.commit09911bf2008-07-26 23:55:29628 owning_hwnd, info);
629 } else {
630 // No prompting for download, just continue with the suggested name.
631 ContinueStartDownload(info, info->suggested_path);
632 }
633}
634
635void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41636 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29637 scoped_ptr<DownloadCreateInfo> infop(info);
638 info->path = target_path;
639
640 DownloadItem* download = NULL;
641 DownloadMap::iterator it = in_progress_.find(info->download_id);
642 if (it == in_progress_.end()) {
643 download = new DownloadItem(info->download_id,
644 info->path,
[email protected]7a256ea2008-10-17 17:34:16645 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29646 info->url,
[email protected]9ccbb372008-10-10 18:50:32647 info->original_name,
initial.commit09911bf2008-07-26 23:55:29648 info->start_time,
649 info->total_bytes,
650 info->render_process_id,
[email protected]9ccbb372008-10-10 18:50:32651 info->request_id,
652 info->is_dangerous);
initial.commit09911bf2008-07-26 23:55:29653 download->set_manager(this);
654 in_progress_[info->download_id] = download;
655 } else {
656 NOTREACHED(); // Should not exist!
657 return;
658 }
659
660 // If the download already completed by the time we reached this point, then
661 // notify observers that it did.
662 PendingFinishedMap::iterator pending_it =
663 pending_finished_downloads_.find(info->download_id);
664 if (pending_it != pending_finished_downloads_.end())
665 DownloadFinished(pending_it->first, pending_it->second);
666
667 download->Rename(target_path);
668
669 file_loop_->PostTask(FROM_HERE,
670 NewRunnableMethod(file_manager_,
671 &DownloadFileManager::OnFinalDownloadName,
672 download->id(),
673 target_path));
674
675 if (profile_->IsOffTheRecord()) {
676 // Fake a db handle for incognito mode, since nothing is actually stored in
677 // the database in this mode. We have to make sure that these handles don't
678 // collide with normal db handles, so we use a negative value. Eventually,
679 // they could overlap, but you'd have to do enough downloading that your ISP
680 // would likely stab you in the neck first. YMMV.
681 static int64 fake_db_handle = kUninitializedHandle - 1;
682 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
683 } else {
684 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22685 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29686 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
687 if (hs) {
688 hs->CreateDownload(
689 *info, &cancelable_consumer_,
690 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
691 }
692 }
693}
694
695// Convenience function for updating the history service for a download.
696void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
697 DCHECK(download);
698
699 // Don't store info in the database if the download was initiated while in
700 // incognito mode or if it hasn't been initialized in our database table.
701 if (download->db_handle() <= kUninitializedHandle)
702 return;
703
[email protected]6cade212008-12-03 00:32:22704 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29705 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
706 if (hs) {
707 hs->UpdateDownload(download->received_bytes(),
708 download->state(),
709 download->db_handle());
710 }
711}
712
713void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
714 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22715 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29716 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
717 if (download->db_handle() > kUninitializedHandle && hs)
718 hs->RemoveDownload(download->db_handle());
719}
720
[email protected]e93d2822009-01-30 05:59:59721void DownloadManager::RemoveDownloadsFromHistoryBetween(
722 const base::Time remove_begin,
723 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22724 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29725 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
726 if (hs)
727 hs->RemoveDownloadsBetween(remove_begin, remove_end);
728}
729
730void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
731 DownloadMap::iterator it = in_progress_.find(download_id);
732 if (it != in_progress_.end()) {
733 DownloadItem* download = it->second;
734 download->Update(size);
735 UpdateHistoryForDownload(download);
736 }
737}
738
739void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
740 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32741 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29742 // The download is done, but the user hasn't selected a final location for
743 // it yet (the Save As dialog box is probably still showing), so just keep
744 // track of the fact that this download id is complete, when the
745 // DownloadItem is constructed later we'll notify its completion then.
746 PendingFinishedMap::iterator erase_it =
747 pending_finished_downloads_.find(download_id);
748 DCHECK(erase_it == pending_finished_downloads_.end());
749 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32750 return;
initial.commit09911bf2008-07-26 23:55:29751 }
[email protected]9ccbb372008-10-10 18:50:32752
753 // Remove the id from the list of pending ids.
754 PendingFinishedMap::iterator erase_it =
755 pending_finished_downloads_.find(download_id);
756 if (erase_it != pending_finished_downloads_.end())
757 pending_finished_downloads_.erase(erase_it);
758
759 DownloadItem* download = it->second;
760 download->Finished(size);
761
762 // Clean up will happen when the history system create callback runs if we
763 // don't have a valid db_handle yet.
764 if (download->db_handle() != kUninitializedHandle) {
765 in_progress_.erase(it);
766 NotifyAboutDownloadStop();
767 UpdateHistoryForDownload(download);
768 }
769
770 // If this a dangerous download not yet validated by the user, don't do
771 // anything. When the user notifies us, it will trigger a call to
772 // ProceedWithFinishedDangerousDownload.
773 if (download->safety_state() == DownloadItem::DANGEROUS) {
774 dangerous_finished_[download_id] = download;
775 return;
776 }
777
778 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22779 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32780 // its final name before we can continue.
781 file_loop_->PostTask(FROM_HERE,
782 NewRunnableMethod(
783 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
784 download->db_handle(),
785 download->full_path(), download->original_name()));
786 return;
787 }
788 ContinueDownloadFinished(download);
789}
790
791void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
792 // If this was a dangerous download, it has now been approved and must be
793 // removed from dangerous_finished_ so it does not get deleted on shutdown.
794 DownloadMap::iterator it = dangerous_finished_.find(download->id());
795 if (it != dangerous_finished_.end())
796 dangerous_finished_.erase(it);
797
798 // Notify our observers that we are complete (the call to Finished() set the
799 // state to complete but did not notify).
800 download->UpdateObservers();
801
802 // Open the download if the user or user prefs indicate it should be.
803 const std::wstring extension =
804 file_util::GetFileExtensionFromPath(download->full_path());
805 if (download->open_when_complete() || ShouldOpenFileExtension(extension))
806 OpenDownloadInShell(download, NULL);
807}
808
809// Called on the file thread. Renames the downloaded file to its original name.
810void DownloadManager::ProceedWithFinishedDangerousDownload(
811 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41812 const FilePath& path,
813 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32814 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41815 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16816 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32817 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24818 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16819 // Make our name unique at this point, as if a dangerous file is downloading
820 // and a 2nd download is started for a file with the same name, they would
821 // have the same path. This is because we uniquify the name on download
822 // start, and at that time the first file does not exists yet, so the second
823 // file gets the same name.
824 uniquifier = GetUniquePathNumber(new_path);
825 if (uniquifier > 0)
826 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32827 success = file_util::Move(path, new_path);
828 } else {
829 NOTREACHED();
830 }
[email protected]6cade212008-12-03 00:32:22831
[email protected]9ccbb372008-10-10 18:50:32832 ui_loop_->PostTask(FROM_HERE,
833 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16834 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32835}
836
837// Call from the file thread when the finished dangerous download was renamed.
838void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
839 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41840 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16841 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32842 DownloadMap::iterator it = downloads_.find(download_handle);
843 if (it == downloads_.end()) {
844 NOTREACHED();
845 return;
846 }
847
848 DownloadItem* download = it->second;
849 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16850 if (success) {
851 // We need to update the path uniquifier so that the UI shows the right
852 // name when calling GetFileName().
853 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32854 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16855 }
[email protected]9ccbb372008-10-10 18:50:32856
857 // Continue the download finished sequence.
858 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29859}
860
861// static
862// We have to tell the ResourceDispatcherHost to cancel the download from this
[email protected]6cade212008-12-03 00:32:22863// thread, since we can't forward tasks from the file thread to the IO thread
initial.commit09911bf2008-07-26 23:55:29864// reliably (crash on shutdown race condition).
865void DownloadManager::CancelDownloadRequest(int render_process_id,
866 int request_id) {
867 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]ab820df2008-08-26 05:55:10868 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29869 if (!io_thread || !rdh)
870 return;
871 io_thread->message_loop()->PostTask(FROM_HERE,
872 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
873 rdh,
874 render_process_id,
875 request_id));
876}
877
878// static
879void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
880 int render_process_id,
881 int request_id) {
882 rdh->CancelRequest(render_process_id, request_id, false);
883}
884
885void DownloadManager::DownloadCancelled(int32 download_id) {
886 DownloadMap::iterator it = in_progress_.find(download_id);
887 if (it == in_progress_.end())
888 return;
889 DownloadItem* download = it->second;
890
891 CancelDownloadRequest(download->render_process_id(), download->request_id());
892
893 // Clean up will happen when the history system create callback runs if we
894 // don't have a valid db_handle yet.
895 if (download->db_handle() != kUninitializedHandle) {
896 in_progress_.erase(it);
897 NotifyAboutDownloadStop();
898 UpdateHistoryForDownload(download);
899 }
900
901 // Tell the file manager to cancel the download.
902 file_manager_->RemoveDownload(download->id(), this); // On the UI thread
903 file_loop_->PostTask(FROM_HERE,
904 NewRunnableMethod(file_manager_,
905 &DownloadFileManager::CancelDownload,
906 download->id()));
907}
908
909void DownloadManager::PauseDownload(int32 download_id, bool pause) {
910 DownloadMap::iterator it = in_progress_.find(download_id);
911 if (it != in_progress_.end()) {
912 DownloadItem* download = it->second;
913 if (pause == download->is_paused())
914 return;
915
916 // Inform the ResourceDispatcherHost of the new pause state.
[email protected]ab820df2008-08-26 05:55:10917 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29918 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
919 if (!io_thread || !rdh)
920 return;
921
922 io_thread->message_loop()->PostTask(FROM_HERE,
923 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
924 rdh,
925 download->render_process_id(),
926 download->request_id(),
927 pause));
928 }
929}
930
931// static
932void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
933 int render_process_id,
934 int request_id,
935 bool pause) {
936 rdh->PauseRequest(render_process_id, request_id, pause);
937}
938
[email protected]7ae7c2cb2009-01-06 23:31:41939bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:32940 // TODO(jcampan): Improve me.
941 return IsExecutable(file_util::GetFileExtensionFromPath(file_name));
942}
943
944void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:41945 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:32946 download->Rename(new_path);
947
948 // Update the history.
949
950 // No update necessary if the download was initiated while in incognito mode.
951 if (download->db_handle() <= kUninitializedHandle)
952 return;
953
[email protected]6cade212008-12-03 00:32:22954 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:32955 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
956 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:41957 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:32958}
959
initial.commit09911bf2008-07-26 23:55:29960void DownloadManager::RemoveDownload(int64 download_handle) {
961 DownloadMap::iterator it = downloads_.find(download_handle);
962 if (it == downloads_.end())
963 return;
964
965 // Make history update.
966 DownloadItem* download = it->second;
967 RemoveDownloadFromHistory(download);
968
969 // Remove from our tables and delete.
970 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32971 it = dangerous_finished_.find(download->id());
972 if (it != dangerous_finished_.end())
973 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:29974
975 // Tell observers to refresh their views.
976 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:36977
978 delete download;
initial.commit09911bf2008-07-26 23:55:29979}
980
[email protected]e93d2822009-01-30 05:59:59981int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
982 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:29983 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
984
985 int num_deleted = 0;
986 DownloadMap::iterator it = downloads_.begin();
987 while (it != downloads_.end()) {
988 DownloadItem* download = it->second;
989 DownloadItem::DownloadState state = download->state();
990 if (download->start_time() >= remove_begin &&
991 (remove_end.is_null() || download->start_time() < remove_end) &&
992 (state == DownloadItem::COMPLETE ||
993 state == DownloadItem::CANCELLED)) {
994 // Remove from the map and move to the next in the list.
995 it = downloads_.erase(it);
[email protected]a6604d92008-10-30 00:58:58996
997 // Also remove it from any completed dangerous downloads.
998 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
999 if (dit != dangerous_finished_.end())
1000 dangerous_finished_.erase(dit);
1001
initial.commit09911bf2008-07-26 23:55:291002 delete download;
1003
1004 ++num_deleted;
1005 continue;
1006 }
1007
1008 ++it;
1009 }
1010
1011 // Tell observers to refresh their views.
1012 if (num_deleted > 0)
1013 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1014
1015 return num_deleted;
1016}
1017
[email protected]e93d2822009-01-30 05:59:591018int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1019 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291020}
1021
1022// Initiate a download of a specific URL. We send the request to the
1023// ResourceDispatcherHost, and let it send us responses like a regular
1024// download.
1025void DownloadManager::DownloadUrl(const GURL& url,
1026 const GURL& referrer,
1027 WebContents* web_contents) {
1028 DCHECK(web_contents);
1029 file_manager_->DownloadUrl(url,
1030 referrer,
1031 web_contents->process()->host_id(),
1032 web_contents->render_view_host()->routing_id(),
1033 request_context_.get());
1034}
1035
1036void DownloadManager::NotifyAboutDownloadStart() {
1037 NotificationService::current()->
1038 Notify(NOTIFY_DOWNLOAD_START, NotificationService::AllSources(),
1039 NotificationService::NoDetails());
1040}
1041
1042void DownloadManager::NotifyAboutDownloadStop() {
1043 NotificationService::current()->
1044 Notify(NOTIFY_DOWNLOAD_STOP, NotificationService::AllSources(),
1045 NotificationService::NoDetails());
1046}
1047
[email protected]7ae7c2cb2009-01-06 23:31:411048void DownloadManager::GenerateExtension(
1049 const FilePath& file_name,
1050 const std::string& mime_type,
1051 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291052 // We're worried about three things here:
1053 //
1054 // 1) Security. Many sites let users upload content, such as buddy icons, to
1055 // their web sites. We want to mitigate the case where an attacker
1056 // supplies a malicious executable with an executable file extension but an
1057 // honest site serves the content with a benign content type, such as
1058 // image/jpeg.
1059 //
1060 // 2) Usability. If the site fails to provide a file extension, we want to
1061 // guess a reasonable file extension based on the content type.
1062 //
1063 // 3) Shell integration. Some file extensions automatically integrate with
1064 // the shell. We block these extensions to prevent a malicious web site
1065 // from integrating with the user's shell.
1066
[email protected]7ae7c2cb2009-01-06 23:31:411067 static const FilePath::CharType default_extension[] =
1068 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291069
1070 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411071 FilePath::StringType extension(
1072 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291073
1074 // Rename shell-integrated extensions.
1075 if (win_util::IsShellIntegratedExtension(extension))
1076 extension.assign(default_extension);
1077
1078 std::string mime_type_from_extension;
[email protected]7ae7c2cb2009-01-06 23:31:411079 net::GetMimeTypeFromFile(file_name.ToWStringHack(),
1080 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291081 if (mime_type == mime_type_from_extension) {
1082 // The hinted extension matches the mime type. It looks like a winner.
1083 generated_extension->swap(extension);
1084 return;
1085 }
1086
1087 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1088 // We want to be careful about executable extensions. The worry here is
1089 // that a trusted web site could be tricked into dropping an executable file
1090 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101091 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291092 // We couldn't find a good extension for this content type. Use a dummy
1093 // extension instead.
1094 extension.assign(default_extension);
1095 }
1096 }
1097
1098 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101099 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291100 } else {
[email protected]6cade212008-12-03 00:32:221101 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291102 // 1. New extension is not ".txt"
1103 // 2. New extension is not the same as the already existing extension.
1104 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411105 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291106 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1107 // application/x-javascript.
[email protected]7ae7c2cb2009-01-06 23:31:411108 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101109 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]7ae7c2cb2009-01-06 23:31:411110 if (append_extension != FILE_PATH_LITERAL(".txt") &&
1111 append_extension != extension &&
initial.commit09911bf2008-07-26 23:55:291112 !IsExecutable(append_extension))
1113 extension += append_extension;
1114 }
1115 }
1116
1117 generated_extension->swap(extension);
1118}
1119
1120void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411121 FilePath* generated_name) {
1122 *generated_name = FilePath::FromWStringHack(
[email protected]8ac1a752008-07-31 19:40:371123 net::GetSuggestedFilename(GURL(info->url),
1124 info->content_disposition,
[email protected]7ae7c2cb2009-01-06 23:31:411125 L"download"));
1126 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291127
[email protected]7ae7c2cb2009-01-06 23:31:411128 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291129}
1130
1131void DownloadManager::AddObserver(Observer* observer) {
1132 observers_.AddObserver(observer);
1133 observer->ModelChanged();
1134}
1135
1136void DownloadManager::RemoveObserver(Observer* observer) {
1137 observers_.RemoveObserver(observer);
1138}
1139
1140// Post Windows Shell operations to the Download thread, to avoid blocking the
1141// user interface.
1142void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1143 DCHECK(file_manager_);
1144 file_loop_->PostTask(FROM_HERE,
1145 NewRunnableMethod(file_manager_,
1146 &DownloadFileManager::OnShowDownloadInShell,
[email protected]7ae7c2cb2009-01-06 23:31:411147 FilePath(download->full_path())));
initial.commit09911bf2008-07-26 23:55:291148}
1149
1150void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591151 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291152 DCHECK(file_manager_);
1153 file_loop_->PostTask(FROM_HERE,
1154 NewRunnableMethod(file_manager_,
1155 &DownloadFileManager::OnOpenDownloadInShell,
1156 download->full_path(), download->url(), parent_window));
1157}
1158
[email protected]7ae7c2cb2009-01-06 23:31:411159void DownloadManager::OpenFilesOfExtension(
1160 const FilePath::StringType& extension, bool open) {
initial.commit09911bf2008-07-26 23:55:291161 if (open && !IsExecutable(extension))
1162 auto_open_.insert(extension);
1163 else
1164 auto_open_.erase(extension);
1165 SaveAutoOpens();
1166}
1167
[email protected]7ae7c2cb2009-01-06 23:31:411168bool DownloadManager::ShouldOpenFileExtension(
1169 const FilePath::StringType& extension) {
initial.commit09911bf2008-07-26 23:55:291170 if (!IsExecutable(extension) &&
1171 auto_open_.find(extension) != auto_open_.end())
1172 return true;
1173 return false;
1174}
1175
[email protected]7b73d992008-12-15 20:56:461176static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291177 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461178 "text/javascript",
1179 "text/javascript;version=*",
[email protected]60ff8f912008-12-05 07:58:391180 // Some sites use binary/octet-stream to mean application/octet-stream.
1181 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461182 "binary/octet-stream"
1183};
initial.commit09911bf2008-07-26 23:55:291184
[email protected]7b73d992008-12-15 20:56:461185static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291186 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461187 "application/*+xml",
1188 "application/xml"
1189};
initial.commit09911bf2008-07-26 23:55:291190
[email protected]7b73d992008-12-15 20:56:461191// static
1192bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
1193 for (int i=0; i < arraysize(kExecutableWhiteList); ++i) {
1194 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1195 return true;
1196 }
1197 for (int i=0; i < arraysize(kExecutableBlackList); ++i) {
1198 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1199 return false;
1200 }
1201 // We consider only other application types to be executable.
1202 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291203}
1204
[email protected]7ae7c2cb2009-01-06 23:31:411205bool DownloadManager::IsExecutable(const FilePath::StringType& extension) {
initial.commit09911bf2008-07-26 23:55:291206 return exe_types_.find(extension) != exe_types_.end();
1207}
1208
1209void DownloadManager::ResetAutoOpenFiles() {
1210 auto_open_.clear();
1211 SaveAutoOpens();
1212}
1213
1214bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1215 return !auto_open_.empty();
1216}
1217
1218void DownloadManager::SaveAutoOpens() {
1219 PrefService* prefs = profile_->GetPrefs();
1220 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411221 FilePath::StringType extensions;
1222 for (std::set<FilePath::StringType>::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291223 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411224 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291225 }
1226 if (!extensions.empty())
1227 extensions.erase(extensions.size() - 1);
1228 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions);
1229 }
1230}
1231
[email protected]7ae7c2cb2009-01-06 23:31:411232void DownloadManager::FileSelected(const std::wstring& path_string,
1233 void* params) {
1234 FilePath path = FilePath::FromWStringHack(path_string);
initial.commit09911bf2008-07-26 23:55:291235 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071236 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411237 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291238 ContinueStartDownload(info, path);
1239}
1240
1241void DownloadManager::FileSelectionCanceled(void* params) {
1242 // The user didn't pick a place to save the file, so need to cancel the
1243 // download that's already in progress to the temporary location.
1244 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
1245 file_loop_->PostTask(FROM_HERE,
1246 NewRunnableMethod(file_manager_, &DownloadFileManager::CancelDownload,
1247 info->download_id));
1248}
1249
[email protected]7ae7c2cb2009-01-06 23:31:411250void DownloadManager::DeleteDownload(const FilePath& path) {
1251 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
1252 &DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321253}
1254
1255
1256void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1257 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1258 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1259 download->UpdateObservers();
1260
1261 // If the download is not complete, nothing to do. The required
1262 // post-processing will be performed when it does complete.
1263 if (download->state() != DownloadItem::COMPLETE)
1264 return;
1265
1266 file_loop_->PostTask(FROM_HERE,
1267 NewRunnableMethod(this,
1268 &DownloadManager::ProceedWithFinishedDangerousDownload,
1269 download->db_handle(), download->full_path(),
1270 download->original_name()));
1271}
1272
[email protected]763f946a2009-01-06 19:04:391273void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411274 FilePath* file_name) {
1275 // Make sure we get the right file extension
1276 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391277 GenerateExtension(*file_name, mime_type, &extension);
1278 file_util::ReplaceExtension(file_name, extension);
1279
1280 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411281 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391282 DCHECK(!leaf_name.empty());
1283 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411284 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1285 *file_name = file_name->DirName();
1286 if (file_name->value() == FilePath::kCurrentDirectory) {
1287 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391288 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411289 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391290 }
1291 }
1292}
1293
initial.commit09911bf2008-07-26 23:55:291294// Operations posted to us from the history service ----------------------------
1295
1296// The history service has retrieved all download entries. 'entries' contains
1297// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1298void DownloadManager::OnQueryDownloadEntriesComplete(
1299 std::vector<DownloadCreateInfo>* entries) {
1300 for (size_t i = 0; i < entries->size(); ++i) {
1301 DownloadItem* download = new DownloadItem(entries->at(i));
1302 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1303 downloads_[download->db_handle()] = download;
1304 download->set_manager(this);
1305 }
1306 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1307}
1308
1309
1310// Once the new DownloadItem's creation info has been committed to the history
1311// service, we associate the DownloadItem with the db handle, update our
1312// 'downloads_' map and inform observers.
1313void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1314 int64 db_handle) {
1315 DownloadMap::iterator it = in_progress_.find(info.download_id);
1316 DCHECK(it != in_progress_.end());
1317
1318 DownloadItem* download = it->second;
1319 DCHECK(download->db_handle() == kUninitializedHandle);
1320 download->set_db_handle(db_handle);
1321
1322 // Insert into our full map.
1323 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1324 downloads_[download->db_handle()] = download;
1325
1326 // The 'contents' may no longer exist if the user closed the tab before we get
1327 // this start completion event. If it does, tell the origin WebContents to
1328 // display its download shelf.
1329 TabContents* contents =
[email protected]a3a1d142008-12-19 00:42:301330 tab_util::GetWebContentsByID(info.render_process_id, info.render_view_id);
initial.commit09911bf2008-07-26 23:55:291331
1332 // If the contents no longer exists or is no longer active, we start the
1333 // download in the last active browser. This is not ideal but better than
1334 // fully hiding the download from the user. Note: non active means that the
1335 // user navigated away from the tab contents. This has nothing to do with
1336 // tab selection.
1337 if (!contents || !contents->is_active()) {
1338 Browser* last_active = BrowserList::GetLastActive();
1339 if (last_active)
1340 contents = last_active->GetSelectedTabContents();
1341 }
1342
1343 if (contents)
1344 contents->OnStartDownload(download);
1345
1346 // Inform interested objects about the new download.
1347 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1348 NotifyAboutDownloadStart();
1349
1350 // If this download has been completed before we've received the db handle,
1351 // post one final message to the history service so that it can be properly
1352 // in sync with the DownloadItem's completion status, and also inform any
1353 // observers so that they get more than just the start notification.
1354 if (download->state() != DownloadItem::IN_PROGRESS) {
1355 in_progress_.erase(it);
1356 NotifyAboutDownloadStop();
1357 UpdateHistoryForDownload(download);
1358 download->UpdateObservers();
1359 }
1360}
1361
1362// Called when the history service has retrieved the list of downloads that
1363// match the search text.
1364void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1365 std::vector<int64>* results) {
1366 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1367 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1368 if (!requestor)
1369 return;
1370
1371 std::vector<DownloadItem*> searched_downloads;
1372 for (std::vector<int64>::iterator it = results->begin();
1373 it != results->end(); ++it) {
1374 DownloadMap::iterator dit = downloads_.find(*it);
1375 if (dit != downloads_.end())
1376 searched_downloads.push_back(dit->second);
1377 }
1378
1379 requestor->SetDownloads(searched_downloads);
1380}
[email protected]905a08d2008-11-19 07:24:121381
[email protected]6cade212008-12-03 00:32:221382// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121383void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411384 last_download_path_ = FilePath();
[email protected]905a08d2008-11-19 07:24:121385}