blob: 44038b40647ac98d8e29f4bd2cf140d0fcf3d862 [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"
[email protected]8c756ac2009-01-30 23:36:4122#include "chrome/browser/extensions/extension.h"
initial.commit09911bf2008-07-26 23:55:2923#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:2624#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2525#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]e3c404b2008-12-23 01:07:3226#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
[email protected]f3ec7742009-01-15 00:59:1627#include "chrome/browser/tab_contents/tab_util.h"
28#include "chrome/browser/tab_contents/web_contents.h"
[email protected]8c756ac2009-01-30 23:36:4129#include "chrome/common/chrome_constants.h"
initial.commit09911bf2008-07-26 23:55:2930#include "chrome/common/chrome_paths.h"
31#include "chrome/common/l10n_util.h"
32#include "chrome/common/notification_service.h"
33#include "chrome/common/pref_names.h"
34#include "chrome/common/pref_service.h"
35#include "chrome/common/stl_util-inl.h"
36#include "chrome/common/win_util.h"
[email protected]46072d42008-07-28 14:49:3537#include "googleurl/src/gurl.h"
initial.commit09911bf2008-07-26 23:55:2938#include "net/base/mime_util.h"
39#include "net/base/net_util.h"
40#include "net/url_request/url_request_context.h"
41
42#include "generated_resources.h"
43
44// Periodically update our observers.
45class DownloadItemUpdateTask : public Task {
46 public:
47 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
48 void Run() { if (item_) item_->UpdateObservers(); }
49
50 private:
51 DownloadItem* item_;
52};
53
54// Update frequency (milliseconds).
55static const int kUpdateTimeMs = 1000;
56
57// Our download table ID starts at 1, so we use 0 to represent a download that
58// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2259// database handles in incognito mode starting at -1 and progressively getting
60// more negative.
initial.commit09911bf2008-07-26 23:55:2961static const int kUninitializedHandle = 0;
62
[email protected]7a256ea2008-10-17 17:34:1663// Appends the passed the number between parenthesis the path before the
64// extension.
[email protected]7ae7c2cb2009-01-06 23:31:4165static void AppendNumberToPath(FilePath* path, int number) {
66 file_util::InsertBeforeExtension(path,
67 StringPrintf(FILE_PATH_LITERAL(" (%d)"), number));
[email protected]7a256ea2008-10-17 17:34:1668}
69
70// Attempts to find a number that can be appended to that path to make it
71// unique. If |path| does not exist, 0 is returned. If it fails to find such
72// a number, -1 is returned.
[email protected]7ae7c2cb2009-01-06 23:31:4173static int GetUniquePathNumber(const FilePath& path) {
initial.commit09911bf2008-07-26 23:55:2974 const int kMaxAttempts = 100;
75
[email protected]7a256ea2008-10-17 17:34:1676 if (!file_util::PathExists(path))
77 return 0;
initial.commit09911bf2008-07-26 23:55:2978
[email protected]7ae7c2cb2009-01-06 23:31:4179 FilePath new_path;
initial.commit09911bf2008-07-26 23:55:2980 for (int count = 1; count <= kMaxAttempts; ++count) {
[email protected]7ae7c2cb2009-01-06 23:31:4181 new_path = FilePath(path);
[email protected]7a256ea2008-10-17 17:34:1682 AppendNumberToPath(&new_path, count);
initial.commit09911bf2008-07-26 23:55:2983
[email protected]7a256ea2008-10-17 17:34:1684 if (!file_util::PathExists(new_path))
85 return count;
initial.commit09911bf2008-07-26 23:55:2986 }
87
[email protected]7a256ea2008-10-17 17:34:1688 return -1;
initial.commit09911bf2008-07-26 23:55:2989}
90
[email protected]7ae7c2cb2009-01-06 23:31:4191static bool DownloadPathIsDangerous(const FilePath& download_path) {
92 FilePath desktop_dir;
[email protected]f052118e2008-09-05 02:25:3293 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
94 NOTREACHED();
95 return false;
96 }
97 return (download_path == desktop_dir);
98}
99
initial.commit09911bf2008-07-26 23:55:29100// DownloadItem implementation -------------------------------------------------
101
102// Constructor for reading from the history service.
103DownloadItem::DownloadItem(const DownloadCreateInfo& info)
104 : id_(-1),
105 full_path_(info.path),
[email protected]9ccbb372008-10-10 18:50:32106 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29107 url_(info.url),
108 total_bytes_(info.total_bytes),
109 received_bytes_(info.received_bytes),
110 start_tick_(0),
111 state_(static_cast<DownloadState>(info.state)),
112 start_time_(info.start_time),
113 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29114 manager_(NULL),
[email protected]9ccbb372008-10-10 18:50:32115 safety_state_(SAFE),
initial.commit09911bf2008-07-26 23:55:29116 is_paused_(false),
117 open_when_complete_(false),
118 render_process_id_(-1),
119 request_id_(-1) {
120 if (state_ == IN_PROGRESS)
121 state_ = CANCELLED;
122 Init(false /* don't start progress timer */);
123}
124
125// Constructor for DownloadItem created via user action in the main thread.
126DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41127 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16128 int path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29129 const std::wstring& url,
[email protected]7ae7c2cb2009-01-06 23:31:41130 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59131 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29132 int64 download_size,
133 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32134 int request_id,
135 bool is_dangerous)
initial.commit09911bf2008-07-26 23:55:29136 : id_(download_id),
137 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16138 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29139 url_(url),
[email protected]9ccbb372008-10-10 18:50:32140 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29141 total_bytes_(download_size),
142 received_bytes_(0),
143 start_tick_(GetTickCount()),
144 state_(IN_PROGRESS),
145 start_time_(start_time),
146 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29147 manager_(NULL),
[email protected]9ccbb372008-10-10 18:50:32148 safety_state_(is_dangerous ? DANGEROUS : SAFE),
initial.commit09911bf2008-07-26 23:55:29149 is_paused_(false),
150 open_when_complete_(false),
151 render_process_id_(render_process_id),
152 request_id_(request_id) {
153 Init(true /* start progress timer */);
154}
155
156void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41157 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29158 if (start_timer)
159 StartProgressTimer();
160}
161
162DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29163 state_ = REMOVING;
164 UpdateObservers();
165}
166
167void DownloadItem::AddObserver(Observer* observer) {
168 observers_.AddObserver(observer);
169}
170
171void DownloadItem::RemoveObserver(Observer* observer) {
172 observers_.RemoveObserver(observer);
173}
174
175void DownloadItem::UpdateObservers() {
176 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
177}
178
179// If we've received more data than we were expecting (bad server info?), revert
180// to 'unknown size mode'.
181void DownloadItem::UpdateSize(int64 bytes_so_far) {
182 received_bytes_ = bytes_so_far;
183 if (received_bytes_ > total_bytes_)
184 total_bytes_ = 0;
185}
186
187// Updates from the download thread may have been posted while this download
188// was being cancelled in the UI thread, so we'll accept them unless we're
189// complete.
190void DownloadItem::Update(int64 bytes_so_far) {
191 if (state_ == COMPLETE) {
192 NOTREACHED();
193 return;
194 }
195 UpdateSize(bytes_so_far);
196 UpdateObservers();
197}
198
[email protected]6cade212008-12-03 00:32:22199// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29200void DownloadItem::Cancel(bool update_history) {
201 if (state_ != IN_PROGRESS) {
202 // Small downloads might be complete before this method has a chance to run.
203 return;
204 }
205 state_ = CANCELLED;
206 UpdateObservers();
207 StopProgressTimer();
208 if (update_history)
209 manager_->DownloadCancelled(id_);
210}
211
212void DownloadItem::Finished(int64 size) {
213 state_ = COMPLETE;
214 UpdateSize(size);
[email protected]22fbe5a2008-10-29 22:20:40215 UpdateObservers();
initial.commit09911bf2008-07-26 23:55:29216 StopProgressTimer();
217}
218
[email protected]9ccbb372008-10-10 18:50:32219void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29220 Cancel(true);
221 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32222 if (delete_on_disk)
223 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29224 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22225 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29226}
227
228void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59229 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14230 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29231}
232
233void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14234 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29235}
236
[email protected]e93d2822009-01-30 05:59:59237bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29238 if (total_bytes_ <= 0)
239 return false; // We never received the content_length for this download.
240
241 int64 speed = CurrentSpeed();
242 if (speed == 0)
243 return false;
244
245 *remaining =
[email protected]e93d2822009-01-30 05:59:59246 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29247 return true;
248}
249
250int64 DownloadItem::CurrentSpeed() const {
251 uintptr_t diff = GetTickCount() - start_tick_;
252 return diff == 0 ? 0 : received_bytes_ * 1000 / diff;
253}
254
255int DownloadItem::PercentComplete() const {
256 int percent = -1;
257 if (total_bytes_ > 0)
258 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
259 return percent;
260}
261
[email protected]7ae7c2cb2009-01-06 23:31:41262void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29263 DCHECK(!full_path.empty());
264 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41265 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29266}
267
268void DownloadItem::TogglePause() {
269 DCHECK(state_ == IN_PROGRESS);
270 manager_->PauseDownload(id_, !is_paused_);
271 is_paused_ = !is_paused_;
272 UpdateObservers();
273}
274
[email protected]7ae7c2cb2009-01-06 23:31:41275FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32276 if (safety_state_ == DownloadItem::SAFE)
277 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16278 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41279 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16280 AppendNumberToPath(&name, path_uniquifier_);
281 return name;
282 }
[email protected]9ccbb372008-10-10 18:50:32283 return original_name_;
284}
285
initial.commit09911bf2008-07-26 23:55:29286// DownloadManager implementation ----------------------------------------------
287
288// static
289void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
290 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
291 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32292 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
293
294 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41295 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12296 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
297 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32298 NOTREACHED();
299 }
[email protected]f052118e2008-09-05 02:25:32300 prefs->RegisterStringPref(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41301 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32302
303 // If the download path is dangerous we forcefully reset it. But if we do
304 // so we set a flag to make sure we only do it once, to avoid fighting
305 // the user if he really wants it on an unsafe place such as the desktop.
306
307 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41308 FilePath current_download_dir = FilePath::FromWStringHack(
309 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32310 if (DownloadPathIsDangerous(current_download_dir)) {
311 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41312 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32313 }
314 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
315 }
initial.commit09911bf2008-07-26 23:55:29316}
317
318DownloadManager::DownloadManager()
319 : shutdown_needed_(false),
320 profile_(NULL),
321 file_manager_(NULL),
322 ui_loop_(MessageLoop::current()),
323 file_loop_(NULL) {
324}
325
326DownloadManager::~DownloadManager() {
327 if (shutdown_needed_)
328 Shutdown();
329}
330
331void DownloadManager::Shutdown() {
332 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
333
334 // Stop receiving download updates
335 file_manager_->RemoveDownloadManager(this);
336
337 // Stop making history service requests
338 cancelable_consumer_.CancelAllRequests();
339
340 // 'in_progress_' may contain DownloadItems that have not finished the start
341 // complete (from the history service) and thus aren't in downloads_.
342 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32343 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29344 for (; it != in_progress_.end(); ++it) {
345 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32346 if (download->safety_state() == DownloadItem::DANGEROUS) {
347 // Forget about any download that the user did not approve.
348 // Note that we cannot call download->Remove() this would invalidate our
349 // iterator.
350 to_remove.insert(download);
351 continue;
initial.commit09911bf2008-07-26 23:55:29352 }
[email protected]9ccbb372008-10-10 18:50:32353 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
354 download->Cancel(false);
355 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29356 if (download->db_handle() == kUninitializedHandle) {
357 // An invalid handle means that 'download' does not yet exist in
358 // 'downloads_', so we have to delete it here.
359 delete download;
360 }
361 }
362
[email protected]9ccbb372008-10-10 18:50:32363 // 'dangerous_finished_' contains all complete downloads that have not been
364 // approved. They should be removed.
365 it = dangerous_finished_.begin();
366 for (; it != dangerous_finished_.end(); ++it)
367 to_remove.insert(it->second);
368
369 // Remove the dangerous download that are not approved.
370 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
371 rm_it != to_remove.end(); ++rm_it) {
372 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32373 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32374 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32375 // Same as above, delete the download if it is not in 'downloads_' (as the
376 // Remove() call above won't have deleted it).
377 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32378 delete download;
379 }
380 to_remove.clear();
381
initial.commit09911bf2008-07-26 23:55:29382 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32383 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29384 STLDeleteValues(&downloads_);
385
386 file_manager_ = NULL;
387
388 // Save our file extensions to auto open.
389 SaveAutoOpens();
390
391 // Make sure the save as dialog doesn't notify us back if we're gone before
392 // it returns.
393 if (select_file_dialog_.get())
394 select_file_dialog_->ListenerDestroyed();
395
396 shutdown_needed_ = false;
397}
398
399// Issue a history query for downloads matching 'search_text'. If 'search_text'
400// is empty, return all downloads that we know about.
401void DownloadManager::GetDownloads(Observer* observer,
402 const std::wstring& search_text) {
403 DCHECK(observer);
404
405 // Return a empty list if we've not yet received the set of downloads from the
406 // history system (we'll update all observers once we get that list in
407 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
408 std::vector<DownloadItem*> download_copy;
409 if (downloads_.empty()) {
410 observer->SetDownloads(download_copy);
411 return;
412 }
413
414 // We already know all the downloads and there is no filter, so just return a
415 // copy to the observer.
416 if (search_text.empty()) {
417 download_copy.reserve(downloads_.size());
418 for (DownloadMap::iterator it = downloads_.begin();
419 it != downloads_.end(); ++it) {
420 download_copy.push_back(it->second);
421 }
422
423 // We retain ownership of the DownloadItems.
424 observer->SetDownloads(download_copy);
425 return;
426 }
427
428 // Issue a request to the history service for a list of downloads matching
429 // our search text.
430 HistoryService* hs =
431 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
432 if (hs) {
433 HistoryService::Handle h =
434 hs->SearchDownloads(search_text,
435 &cancelable_consumer_,
436 NewCallback(this,
437 &DownloadManager::OnSearchComplete));
438 cancelable_consumer_.SetClientData(hs, h, observer);
439 }
440}
441
442// Query the history service for information about all persisted downloads.
443bool DownloadManager::Init(Profile* profile) {
444 DCHECK(profile);
445 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
446 shutdown_needed_ = true;
447
448 profile_ = profile;
449 request_context_ = profile_->GetRequestContext();
450
451 // 'incognito mode' will have access to past downloads, but we won't store
452 // information about new downloads while in that mode.
453 QueryHistoryForDownloads();
454
455 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
456 if (!rdh) {
457 NOTREACHED();
458 return false;
459 }
460
461 file_manager_ = rdh->download_file_manager();
462 if (!file_manager_) {
463 NOTREACHED();
464 return false;
465 }
466
467 file_loop_ = g_browser_process->file_thread()->message_loop();
468 if (!file_loop_) {
469 NOTREACHED();
470 return false;
471 }
472
473 // Get our user preference state.
474 PrefService* prefs = profile_->GetPrefs();
475 DCHECK(prefs);
476 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
477
initial.commit09911bf2008-07-26 23:55:29478 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
479
[email protected]7ae7c2cb2009-01-06 23:31:41480 // This variable is needed to resolve which CreateDirectory we want to point
481 // to. Without it, the NewRunnableFunction cannot resolve the ambiguity.
482 // TODO(estade): when file_util::CreateDirectory(wstring) is removed,
483 // get rid of |CreateDirectoryPtr|.
484 bool (*CreateDirectoryPtr)(const FilePath&) = &file_util::CreateDirectory;
[email protected]bb69e9b32008-08-14 23:08:14485 // Ensure that the download directory specified in the preferences exists.
[email protected]7ae7c2cb2009-01-06 23:31:41486 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
487 CreateDirectoryPtr, download_path()));
[email protected]bb69e9b32008-08-14 23:08:14488
initial.commit09911bf2008-07-26 23:55:29489 // We store any file extension that should be opened automatically at
490 // download completion in this pref.
491 download_util::InitializeExeTypes(&exe_types_);
492
493 std::wstring extensions_to_open =
494 prefs->GetString(prefs::kDownloadExtensionsToOpen);
495 std::vector<std::wstring> extensions;
496 SplitString(extensions_to_open, L':', &extensions);
497 for (size_t i = 0; i < extensions.size(); ++i) {
498 if (!extensions[i].empty() && !IsExecutable(extensions[i]))
499 auto_open_.insert(extensions[i]);
500 }
501
502 return true;
503}
504
505void DownloadManager::QueryHistoryForDownloads() {
506 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
507 if (hs) {
508 hs->QueryDownloads(
509 &cancelable_consumer_,
510 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
511 }
512}
513
514// We have received a message from DownloadFileManager about a new download. We
515// create a download item and store it in our download map, and inform the
516// history system of a new download. Since this method can be called while the
517// history service thread is still reading the persistent state, we do not
518// insert the new DownloadItem into 'downloads_' or inform our observers at this
519// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
520// download creation as a callback from the history thread.
521void DownloadManager::StartDownload(DownloadCreateInfo* info) {
522 DCHECK(MessageLoop::current() == ui_loop_);
523 DCHECK(info);
524
[email protected]7d3851d82008-12-12 03:26:07525 // Freeze the user's preference for showing a Save As dialog. We're going to
526 // bounce around a bunch of threads and we don't want to worry about race
527 // conditions where the user changes this pref out from under us.
528 if (*prompt_for_download_)
529 info->save_as = true;
530
initial.commit09911bf2008-07-26 23:55:29531 // Determine the proper path for a download, by choosing either the default
532 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41533 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29534 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07535 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29536 info->suggested_path = last_download_path_;
537 else
[email protected]7ae7c2cb2009-01-06 23:31:41538 info->suggested_path = download_path();
539 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29540
[email protected]7d3851d82008-12-12 03:26:07541 if (!info->save_as) {
542 // Let's check if this download is dangerous, based on its name.
[email protected]7ae7c2cb2009-01-06 23:31:41543 info->is_dangerous = IsDangerous(info->suggested_path.BaseName());
[email protected]e9ebf3fc2008-10-17 22:06:58544 }
545
initial.commit09911bf2008-07-26 23:55:29546 // We need to move over to the download thread because we don't want to stat
547 // the suggested path on the UI thread.
548 file_loop_->PostTask(FROM_HERE,
549 NewRunnableMethod(this,
550 &DownloadManager::CheckIfSuggestedPathExists,
551 info));
552}
553
554void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
555 DCHECK(info);
556
557 // Check writability of the suggested path. If we can't write to it, default
558 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41559 FilePath dir = info->suggested_path.DirName();
560 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32561 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29562 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29563 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41564 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29565 }
566
[email protected]7a256ea2008-10-17 17:34:16567 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29568
[email protected]6cade212008-12-03 00:32:22569 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58570 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41571 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32572 // Create a temporary file to hold the file until the user approves its
573 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41574 FilePath::StringType file_name;
575 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32576 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41577 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32578 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41579 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07580 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41581 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32582 }
583 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16584 } else {
585 // We know the final path, build it if necessary.
586 if (info->path_uniquifier > 0) {
587 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
588 // Setting path_uniquifier to 0 to make sure we don't try to unique it
589 // later on.
590 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07591 } else if (info->path_uniquifier == -1) {
592 // We failed to find a unique path. We have to prompt the user.
593 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16594 }
[email protected]9ccbb372008-10-10 18:50:32595 }
596
[email protected]7d3851d82008-12-12 03:26:07597 if (!info->save_as) {
598 // Create an empty file at the suggested path so that we don't allocate the
599 // same "non-existant" path to multiple downloads.
600 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ae7c2cb2009-01-06 23:31:41601 file_util::WriteFile(info->suggested_path.ToWStringHack(), "", 0);
[email protected]7d3851d82008-12-12 03:26:07602 }
603
initial.commit09911bf2008-07-26 23:55:29604 // Now we return to the UI thread.
605 ui_loop_->PostTask(FROM_HERE,
606 NewRunnableMethod(this,
607 &DownloadManager::OnPathExistenceAvailable,
608 info));
609}
610
611void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
612 DCHECK(MessageLoop::current() == ui_loop_);
613 DCHECK(info);
614
[email protected]7d3851d82008-12-12 03:26:07615 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29616 // We must ask the user for the place to put the download.
617 if (!select_file_dialog_.get())
618 select_file_dialog_ = SelectFileDialog::Create(this);
619
[email protected]a3a1d142008-12-19 00:42:30620 WebContents* contents = tab_util::GetWebContentsByID(
initial.commit09911bf2008-07-26 23:55:29621 info->render_process_id, info->render_view_id);
[email protected]7ae7c2cb2009-01-06 23:31:41622 std::wstring filter =
623 win_util::GetFileFilterFromPath(info->suggested_path.value());
initial.commit09911bf2008-07-26 23:55:29624 HWND owning_hwnd =
625 contents ? GetAncestor(contents->GetContainerHWND(), GA_ROOT) : NULL;
626 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]7ae7c2cb2009-01-06 23:31:41627 std::wstring(),
628 info->suggested_path.ToWStringHack(),
[email protected]6cade212008-12-03 00:32:22629 filter, std::wstring(),
initial.commit09911bf2008-07-26 23:55:29630 owning_hwnd, info);
631 } else {
632 // No prompting for download, just continue with the suggested name.
633 ContinueStartDownload(info, info->suggested_path);
634 }
635}
636
637void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41638 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29639 scoped_ptr<DownloadCreateInfo> infop(info);
640 info->path = target_path;
641
642 DownloadItem* download = NULL;
643 DownloadMap::iterator it = in_progress_.find(info->download_id);
644 if (it == in_progress_.end()) {
645 download = new DownloadItem(info->download_id,
646 info->path,
[email protected]7a256ea2008-10-17 17:34:16647 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29648 info->url,
[email protected]9ccbb372008-10-10 18:50:32649 info->original_name,
initial.commit09911bf2008-07-26 23:55:29650 info->start_time,
651 info->total_bytes,
652 info->render_process_id,
[email protected]9ccbb372008-10-10 18:50:32653 info->request_id,
654 info->is_dangerous);
initial.commit09911bf2008-07-26 23:55:29655 download->set_manager(this);
656 in_progress_[info->download_id] = download;
657 } else {
658 NOTREACHED(); // Should not exist!
659 return;
660 }
661
662 // If the download already completed by the time we reached this point, then
663 // notify observers that it did.
664 PendingFinishedMap::iterator pending_it =
665 pending_finished_downloads_.find(info->download_id);
666 if (pending_it != pending_finished_downloads_.end())
667 DownloadFinished(pending_it->first, pending_it->second);
668
669 download->Rename(target_path);
670
671 file_loop_->PostTask(FROM_HERE,
672 NewRunnableMethod(file_manager_,
673 &DownloadFileManager::OnFinalDownloadName,
674 download->id(),
675 target_path));
676
677 if (profile_->IsOffTheRecord()) {
678 // Fake a db handle for incognito mode, since nothing is actually stored in
679 // the database in this mode. We have to make sure that these handles don't
680 // collide with normal db handles, so we use a negative value. Eventually,
681 // they could overlap, but you'd have to do enough downloading that your ISP
682 // would likely stab you in the neck first. YMMV.
683 static int64 fake_db_handle = kUninitializedHandle - 1;
684 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
685 } else {
686 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22687 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29688 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
689 if (hs) {
690 hs->CreateDownload(
691 *info, &cancelable_consumer_,
692 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
693 }
694 }
695}
696
697// Convenience function for updating the history service for a download.
698void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
699 DCHECK(download);
700
701 // Don't store info in the database if the download was initiated while in
702 // incognito mode or if it hasn't been initialized in our database table.
703 if (download->db_handle() <= kUninitializedHandle)
704 return;
705
[email protected]6cade212008-12-03 00:32:22706 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29707 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
708 if (hs) {
709 hs->UpdateDownload(download->received_bytes(),
710 download->state(),
711 download->db_handle());
712 }
713}
714
715void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
716 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22717 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29718 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
719 if (download->db_handle() > kUninitializedHandle && hs)
720 hs->RemoveDownload(download->db_handle());
721}
722
[email protected]e93d2822009-01-30 05:59:59723void DownloadManager::RemoveDownloadsFromHistoryBetween(
724 const base::Time remove_begin,
725 const base::Time remove_end) {
[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->RemoveDownloadsBetween(remove_begin, remove_end);
730}
731
732void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
733 DownloadMap::iterator it = in_progress_.find(download_id);
734 if (it != in_progress_.end()) {
735 DownloadItem* download = it->second;
736 download->Update(size);
737 UpdateHistoryForDownload(download);
738 }
739}
740
741void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
742 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32743 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29744 // The download is done, but the user hasn't selected a final location for
745 // it yet (the Save As dialog box is probably still showing), so just keep
746 // track of the fact that this download id is complete, when the
747 // DownloadItem is constructed later we'll notify its completion then.
748 PendingFinishedMap::iterator erase_it =
749 pending_finished_downloads_.find(download_id);
750 DCHECK(erase_it == pending_finished_downloads_.end());
751 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32752 return;
initial.commit09911bf2008-07-26 23:55:29753 }
[email protected]9ccbb372008-10-10 18:50:32754
755 // Remove the id from the list of pending ids.
756 PendingFinishedMap::iterator erase_it =
757 pending_finished_downloads_.find(download_id);
758 if (erase_it != pending_finished_downloads_.end())
759 pending_finished_downloads_.erase(erase_it);
760
761 DownloadItem* download = it->second;
762 download->Finished(size);
763
764 // Clean up will happen when the history system create callback runs if we
765 // don't have a valid db_handle yet.
766 if (download->db_handle() != kUninitializedHandle) {
767 in_progress_.erase(it);
768 NotifyAboutDownloadStop();
769 UpdateHistoryForDownload(download);
770 }
771
772 // If this a dangerous download not yet validated by the user, don't do
773 // anything. When the user notifies us, it will trigger a call to
774 // ProceedWithFinishedDangerousDownload.
775 if (download->safety_state() == DownloadItem::DANGEROUS) {
776 dangerous_finished_[download_id] = download;
777 return;
778 }
779
780 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22781 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32782 // its final name before we can continue.
783 file_loop_->PostTask(FROM_HERE,
784 NewRunnableMethod(
785 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
786 download->db_handle(),
787 download->full_path(), download->original_name()));
788 return;
789 }
790 ContinueDownloadFinished(download);
791}
792
793void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
794 // If this was a dangerous download, it has now been approved and must be
795 // removed from dangerous_finished_ so it does not get deleted on shutdown.
796 DownloadMap::iterator it = dangerous_finished_.find(download->id());
797 if (it != dangerous_finished_.end())
798 dangerous_finished_.erase(it);
799
800 // Notify our observers that we are complete (the call to Finished() set the
801 // state to complete but did not notify).
802 download->UpdateObservers();
803
804 // Open the download if the user or user prefs indicate it should be.
805 const std::wstring extension =
806 file_util::GetFileExtensionFromPath(download->full_path());
807 if (download->open_when_complete() || ShouldOpenFileExtension(extension))
808 OpenDownloadInShell(download, NULL);
809}
810
811// Called on the file thread. Renames the downloaded file to its original name.
812void DownloadManager::ProceedWithFinishedDangerousDownload(
813 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41814 const FilePath& path,
815 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32816 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41817 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16818 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32819 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24820 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16821 // Make our name unique at this point, as if a dangerous file is downloading
822 // and a 2nd download is started for a file with the same name, they would
823 // have the same path. This is because we uniquify the name on download
824 // start, and at that time the first file does not exists yet, so the second
825 // file gets the same name.
826 uniquifier = GetUniquePathNumber(new_path);
827 if (uniquifier > 0)
828 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32829 success = file_util::Move(path, new_path);
830 } else {
831 NOTREACHED();
832 }
[email protected]6cade212008-12-03 00:32:22833
[email protected]9ccbb372008-10-10 18:50:32834 ui_loop_->PostTask(FROM_HERE,
835 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16836 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32837}
838
839// Call from the file thread when the finished dangerous download was renamed.
840void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
841 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41842 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16843 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32844 DownloadMap::iterator it = downloads_.find(download_handle);
845 if (it == downloads_.end()) {
846 NOTREACHED();
847 return;
848 }
849
850 DownloadItem* download = it->second;
851 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16852 if (success) {
853 // We need to update the path uniquifier so that the UI shows the right
854 // name when calling GetFileName().
855 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32856 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16857 }
[email protected]9ccbb372008-10-10 18:50:32858
859 // Continue the download finished sequence.
860 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29861}
862
863// static
864// We have to tell the ResourceDispatcherHost to cancel the download from this
[email protected]6cade212008-12-03 00:32:22865// thread, since we can't forward tasks from the file thread to the IO thread
initial.commit09911bf2008-07-26 23:55:29866// reliably (crash on shutdown race condition).
867void DownloadManager::CancelDownloadRequest(int render_process_id,
868 int request_id) {
869 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]ab820df2008-08-26 05:55:10870 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29871 if (!io_thread || !rdh)
872 return;
873 io_thread->message_loop()->PostTask(FROM_HERE,
874 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
875 rdh,
876 render_process_id,
877 request_id));
878}
879
880// static
881void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
882 int render_process_id,
883 int request_id) {
884 rdh->CancelRequest(render_process_id, request_id, false);
885}
886
887void DownloadManager::DownloadCancelled(int32 download_id) {
888 DownloadMap::iterator it = in_progress_.find(download_id);
889 if (it == in_progress_.end())
890 return;
891 DownloadItem* download = it->second;
892
893 CancelDownloadRequest(download->render_process_id(), download->request_id());
894
895 // Clean up will happen when the history system create callback runs if we
896 // don't have a valid db_handle yet.
897 if (download->db_handle() != kUninitializedHandle) {
898 in_progress_.erase(it);
899 NotifyAboutDownloadStop();
900 UpdateHistoryForDownload(download);
901 }
902
903 // Tell the file manager to cancel the download.
904 file_manager_->RemoveDownload(download->id(), this); // On the UI thread
905 file_loop_->PostTask(FROM_HERE,
906 NewRunnableMethod(file_manager_,
907 &DownloadFileManager::CancelDownload,
908 download->id()));
909}
910
911void DownloadManager::PauseDownload(int32 download_id, bool pause) {
912 DownloadMap::iterator it = in_progress_.find(download_id);
913 if (it != in_progress_.end()) {
914 DownloadItem* download = it->second;
915 if (pause == download->is_paused())
916 return;
917
918 // Inform the ResourceDispatcherHost of the new pause state.
[email protected]ab820df2008-08-26 05:55:10919 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29920 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
921 if (!io_thread || !rdh)
922 return;
923
924 io_thread->message_loop()->PostTask(FROM_HERE,
925 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
926 rdh,
927 download->render_process_id(),
928 download->request_id(),
929 pause));
930 }
931}
932
933// static
934void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
935 int render_process_id,
936 int request_id,
937 bool pause) {
938 rdh->PauseRequest(render_process_id, request_id, pause);
939}
940
[email protected]7ae7c2cb2009-01-06 23:31:41941bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:32942 // TODO(jcampan): Improve me.
943 return IsExecutable(file_util::GetFileExtensionFromPath(file_name));
944}
945
946void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:41947 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:32948 download->Rename(new_path);
949
950 // Update the history.
951
952 // No update necessary if the download was initiated while in incognito mode.
953 if (download->db_handle() <= kUninitializedHandle)
954 return;
955
[email protected]6cade212008-12-03 00:32:22956 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:32957 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
958 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:41959 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:32960}
961
initial.commit09911bf2008-07-26 23:55:29962void DownloadManager::RemoveDownload(int64 download_handle) {
963 DownloadMap::iterator it = downloads_.find(download_handle);
964 if (it == downloads_.end())
965 return;
966
967 // Make history update.
968 DownloadItem* download = it->second;
969 RemoveDownloadFromHistory(download);
970
971 // Remove from our tables and delete.
972 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32973 it = dangerous_finished_.find(download->id());
974 if (it != dangerous_finished_.end())
975 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:29976
977 // Tell observers to refresh their views.
978 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:36979
980 delete download;
initial.commit09911bf2008-07-26 23:55:29981}
982
[email protected]e93d2822009-01-30 05:59:59983int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
984 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:29985 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
986
987 int num_deleted = 0;
988 DownloadMap::iterator it = downloads_.begin();
989 while (it != downloads_.end()) {
990 DownloadItem* download = it->second;
991 DownloadItem::DownloadState state = download->state();
992 if (download->start_time() >= remove_begin &&
993 (remove_end.is_null() || download->start_time() < remove_end) &&
994 (state == DownloadItem::COMPLETE ||
995 state == DownloadItem::CANCELLED)) {
996 // Remove from the map and move to the next in the list.
997 it = downloads_.erase(it);
[email protected]a6604d92008-10-30 00:58:58998
999 // Also remove it from any completed dangerous downloads.
1000 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1001 if (dit != dangerous_finished_.end())
1002 dangerous_finished_.erase(dit);
1003
initial.commit09911bf2008-07-26 23:55:291004 delete download;
1005
1006 ++num_deleted;
1007 continue;
1008 }
1009
1010 ++it;
1011 }
1012
1013 // Tell observers to refresh their views.
1014 if (num_deleted > 0)
1015 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1016
1017 return num_deleted;
1018}
1019
[email protected]e93d2822009-01-30 05:59:591020int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1021 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291022}
1023
1024// Initiate a download of a specific URL. We send the request to the
1025// ResourceDispatcherHost, and let it send us responses like a regular
1026// download.
1027void DownloadManager::DownloadUrl(const GURL& url,
1028 const GURL& referrer,
1029 WebContents* web_contents) {
1030 DCHECK(web_contents);
1031 file_manager_->DownloadUrl(url,
1032 referrer,
1033 web_contents->process()->host_id(),
1034 web_contents->render_view_host()->routing_id(),
1035 request_context_.get());
1036}
1037
1038void DownloadManager::NotifyAboutDownloadStart() {
1039 NotificationService::current()->
1040 Notify(NOTIFY_DOWNLOAD_START, NotificationService::AllSources(),
1041 NotificationService::NoDetails());
1042}
1043
1044void DownloadManager::NotifyAboutDownloadStop() {
1045 NotificationService::current()->
1046 Notify(NOTIFY_DOWNLOAD_STOP, NotificationService::AllSources(),
1047 NotificationService::NoDetails());
1048}
1049
[email protected]7ae7c2cb2009-01-06 23:31:411050void DownloadManager::GenerateExtension(
1051 const FilePath& file_name,
1052 const std::string& mime_type,
1053 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291054 // We're worried about three things here:
1055 //
1056 // 1) Security. Many sites let users upload content, such as buddy icons, to
1057 // their web sites. We want to mitigate the case where an attacker
1058 // supplies a malicious executable with an executable file extension but an
1059 // honest site serves the content with a benign content type, such as
1060 // image/jpeg.
1061 //
1062 // 2) Usability. If the site fails to provide a file extension, we want to
1063 // guess a reasonable file extension based on the content type.
1064 //
1065 // 3) Shell integration. Some file extensions automatically integrate with
1066 // the shell. We block these extensions to prevent a malicious web site
1067 // from integrating with the user's shell.
1068
[email protected]7ae7c2cb2009-01-06 23:31:411069 static const FilePath::CharType default_extension[] =
1070 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291071
1072 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411073 FilePath::StringType extension(
1074 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291075
1076 // Rename shell-integrated extensions.
1077 if (win_util::IsShellIntegratedExtension(extension))
1078 extension.assign(default_extension);
1079
1080 std::string mime_type_from_extension;
[email protected]7ae7c2cb2009-01-06 23:31:411081 net::GetMimeTypeFromFile(file_name.ToWStringHack(),
1082 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291083 if (mime_type == mime_type_from_extension) {
1084 // The hinted extension matches the mime type. It looks like a winner.
1085 generated_extension->swap(extension);
1086 return;
1087 }
1088
1089 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1090 // We want to be careful about executable extensions. The worry here is
1091 // that a trusted web site could be tricked into dropping an executable file
1092 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101093 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291094 // We couldn't find a good extension for this content type. Use a dummy
1095 // extension instead.
1096 extension.assign(default_extension);
1097 }
1098 }
1099
1100 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101101 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291102 } else {
[email protected]6cade212008-12-03 00:32:221103 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291104 // 1. New extension is not ".txt"
1105 // 2. New extension is not the same as the already existing extension.
1106 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411107 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291108 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1109 // application/x-javascript.
[email protected]7ae7c2cb2009-01-06 23:31:411110 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101111 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]7ae7c2cb2009-01-06 23:31:411112 if (append_extension != FILE_PATH_LITERAL(".txt") &&
1113 append_extension != extension &&
initial.commit09911bf2008-07-26 23:55:291114 !IsExecutable(append_extension))
1115 extension += append_extension;
1116 }
1117 }
1118
1119 generated_extension->swap(extension);
1120}
1121
1122void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411123 FilePath* generated_name) {
1124 *generated_name = FilePath::FromWStringHack(
[email protected]8ac1a752008-07-31 19:40:371125 net::GetSuggestedFilename(GURL(info->url),
1126 info->content_disposition,
[email protected]7ae7c2cb2009-01-06 23:31:411127 L"download"));
1128 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291129
[email protected]7ae7c2cb2009-01-06 23:31:411130 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291131}
1132
1133void DownloadManager::AddObserver(Observer* observer) {
1134 observers_.AddObserver(observer);
1135 observer->ModelChanged();
1136}
1137
1138void DownloadManager::RemoveObserver(Observer* observer) {
1139 observers_.RemoveObserver(observer);
1140}
1141
1142// Post Windows Shell operations to the Download thread, to avoid blocking the
1143// user interface.
1144void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1145 DCHECK(file_manager_);
1146 file_loop_->PostTask(FROM_HERE,
1147 NewRunnableMethod(file_manager_,
1148 &DownloadFileManager::OnShowDownloadInShell,
[email protected]7ae7c2cb2009-01-06 23:31:411149 FilePath(download->full_path())));
initial.commit09911bf2008-07-26 23:55:291150}
1151
1152void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591153 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291154 DCHECK(file_manager_);
1155 file_loop_->PostTask(FROM_HERE,
1156 NewRunnableMethod(file_manager_,
1157 &DownloadFileManager::OnOpenDownloadInShell,
1158 download->full_path(), download->url(), parent_window));
1159}
1160
[email protected]7ae7c2cb2009-01-06 23:31:411161void DownloadManager::OpenFilesOfExtension(
1162 const FilePath::StringType& extension, bool open) {
initial.commit09911bf2008-07-26 23:55:291163 if (open && !IsExecutable(extension))
1164 auto_open_.insert(extension);
1165 else
1166 auto_open_.erase(extension);
1167 SaveAutoOpens();
1168}
1169
[email protected]7ae7c2cb2009-01-06 23:31:411170bool DownloadManager::ShouldOpenFileExtension(
1171 const FilePath::StringType& extension) {
[email protected]8c756ac2009-01-30 23:36:411172 // Special-case Chrome extensions as always-open.
initial.commit09911bf2008-07-26 23:55:291173 if (!IsExecutable(extension) &&
[email protected]8c756ac2009-01-30 23:36:411174 (auto_open_.find(extension) != auto_open_.end() ||
1175 extension == chrome::kExtensionFileExtension))
1176 return true;
initial.commit09911bf2008-07-26 23:55:291177 return false;
1178}
1179
[email protected]7b73d992008-12-15 20:56:461180static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291181 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461182 "text/javascript",
1183 "text/javascript;version=*",
[email protected]60ff8f912008-12-05 07:58:391184 // Some sites use binary/octet-stream to mean application/octet-stream.
1185 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461186 "binary/octet-stream"
1187};
initial.commit09911bf2008-07-26 23:55:291188
[email protected]7b73d992008-12-15 20:56:461189static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291190 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461191 "application/*+xml",
1192 "application/xml"
1193};
initial.commit09911bf2008-07-26 23:55:291194
[email protected]7b73d992008-12-15 20:56:461195// static
1196bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
1197 for (int i=0; i < arraysize(kExecutableWhiteList); ++i) {
1198 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1199 return true;
1200 }
1201 for (int i=0; i < arraysize(kExecutableBlackList); ++i) {
1202 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1203 return false;
1204 }
1205 // We consider only other application types to be executable.
1206 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291207}
1208
[email protected]7ae7c2cb2009-01-06 23:31:411209bool DownloadManager::IsExecutable(const FilePath::StringType& extension) {
initial.commit09911bf2008-07-26 23:55:291210 return exe_types_.find(extension) != exe_types_.end();
1211}
1212
1213void DownloadManager::ResetAutoOpenFiles() {
1214 auto_open_.clear();
1215 SaveAutoOpens();
1216}
1217
1218bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1219 return !auto_open_.empty();
1220}
1221
1222void DownloadManager::SaveAutoOpens() {
1223 PrefService* prefs = profile_->GetPrefs();
1224 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411225 FilePath::StringType extensions;
1226 for (std::set<FilePath::StringType>::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291227 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411228 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291229 }
1230 if (!extensions.empty())
1231 extensions.erase(extensions.size() - 1);
1232 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions);
1233 }
1234}
1235
[email protected]7ae7c2cb2009-01-06 23:31:411236void DownloadManager::FileSelected(const std::wstring& path_string,
1237 void* params) {
1238 FilePath path = FilePath::FromWStringHack(path_string);
initial.commit09911bf2008-07-26 23:55:291239 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071240 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411241 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291242 ContinueStartDownload(info, path);
1243}
1244
1245void DownloadManager::FileSelectionCanceled(void* params) {
1246 // The user didn't pick a place to save the file, so need to cancel the
1247 // download that's already in progress to the temporary location.
1248 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
1249 file_loop_->PostTask(FROM_HERE,
1250 NewRunnableMethod(file_manager_, &DownloadFileManager::CancelDownload,
1251 info->download_id));
1252}
1253
[email protected]7ae7c2cb2009-01-06 23:31:411254void DownloadManager::DeleteDownload(const FilePath& path) {
1255 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
1256 &DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321257}
1258
1259
1260void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1261 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1262 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1263 download->UpdateObservers();
1264
1265 // If the download is not complete, nothing to do. The required
1266 // post-processing will be performed when it does complete.
1267 if (download->state() != DownloadItem::COMPLETE)
1268 return;
1269
1270 file_loop_->PostTask(FROM_HERE,
1271 NewRunnableMethod(this,
1272 &DownloadManager::ProceedWithFinishedDangerousDownload,
1273 download->db_handle(), download->full_path(),
1274 download->original_name()));
1275}
1276
[email protected]763f946a2009-01-06 19:04:391277void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411278 FilePath* file_name) {
1279 // Make sure we get the right file extension
1280 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391281 GenerateExtension(*file_name, mime_type, &extension);
1282 file_util::ReplaceExtension(file_name, extension);
1283
1284 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411285 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391286 DCHECK(!leaf_name.empty());
1287 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411288 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1289 *file_name = file_name->DirName();
1290 if (file_name->value() == FilePath::kCurrentDirectory) {
1291 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391292 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411293 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391294 }
1295 }
1296}
1297
initial.commit09911bf2008-07-26 23:55:291298// Operations posted to us from the history service ----------------------------
1299
1300// The history service has retrieved all download entries. 'entries' contains
1301// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1302void DownloadManager::OnQueryDownloadEntriesComplete(
1303 std::vector<DownloadCreateInfo>* entries) {
1304 for (size_t i = 0; i < entries->size(); ++i) {
1305 DownloadItem* download = new DownloadItem(entries->at(i));
1306 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1307 downloads_[download->db_handle()] = download;
1308 download->set_manager(this);
1309 }
1310 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1311}
1312
1313
1314// Once the new DownloadItem's creation info has been committed to the history
1315// service, we associate the DownloadItem with the db handle, update our
1316// 'downloads_' map and inform observers.
1317void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1318 int64 db_handle) {
1319 DownloadMap::iterator it = in_progress_.find(info.download_id);
1320 DCHECK(it != in_progress_.end());
1321
1322 DownloadItem* download = it->second;
1323 DCHECK(download->db_handle() == kUninitializedHandle);
1324 download->set_db_handle(db_handle);
1325
1326 // Insert into our full map.
1327 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1328 downloads_[download->db_handle()] = download;
1329
1330 // The 'contents' may no longer exist if the user closed the tab before we get
1331 // this start completion event. If it does, tell the origin WebContents to
1332 // display its download shelf.
1333 TabContents* contents =
[email protected]a3a1d142008-12-19 00:42:301334 tab_util::GetWebContentsByID(info.render_process_id, info.render_view_id);
initial.commit09911bf2008-07-26 23:55:291335
1336 // If the contents no longer exists or is no longer active, we start the
1337 // download in the last active browser. This is not ideal but better than
1338 // fully hiding the download from the user. Note: non active means that the
1339 // user navigated away from the tab contents. This has nothing to do with
1340 // tab selection.
1341 if (!contents || !contents->is_active()) {
1342 Browser* last_active = BrowserList::GetLastActive();
1343 if (last_active)
1344 contents = last_active->GetSelectedTabContents();
1345 }
1346
1347 if (contents)
1348 contents->OnStartDownload(download);
1349
1350 // Inform interested objects about the new download.
1351 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1352 NotifyAboutDownloadStart();
1353
1354 // If this download has been completed before we've received the db handle,
1355 // post one final message to the history service so that it can be properly
1356 // in sync with the DownloadItem's completion status, and also inform any
1357 // observers so that they get more than just the start notification.
1358 if (download->state() != DownloadItem::IN_PROGRESS) {
1359 in_progress_.erase(it);
1360 NotifyAboutDownloadStop();
1361 UpdateHistoryForDownload(download);
1362 download->UpdateObservers();
1363 }
1364}
1365
1366// Called when the history service has retrieved the list of downloads that
1367// match the search text.
1368void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1369 std::vector<int64>* results) {
1370 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1371 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1372 if (!requestor)
1373 return;
1374
1375 std::vector<DownloadItem*> searched_downloads;
1376 for (std::vector<int64>::iterator it = results->begin();
1377 it != results->end(); ++it) {
1378 DownloadMap::iterator dit = downloads_.find(*it);
1379 if (dit != downloads_.end())
1380 searched_downloads.push_back(dit->second);
1381 }
1382
1383 requestor->SetDownloads(searched_downloads);
1384}
[email protected]905a08d2008-11-19 07:24:121385
[email protected]6cade212008-12-03 00:32:221386// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121387void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411388 last_download_path_ = FilePath();
[email protected]905a08d2008-11-19 07:24:121389}