blob: c2024d06a5f81ef166986f144ff3b0658c001965 [file] [log] [blame]
[email protected]d41355e6f2009-04-07 21:21:121// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]cdaa8652008-09-13 02:48:595#include "chrome/browser/download/download_manager.h"
initial.commit09911bf2008-07-26 23:55:296
[email protected]a92b8642009-05-05 23:38:567#include "app/l10n_util.h"
initial.commit09911bf2008-07-26 23:55:298#include "base/file_util.h"
9#include "base/logging.h"
10#include "base/message_loop.h"
11#include "base/path_service.h"
[email protected]1b5044d2009-02-24 00:04:1412#include "base/rand_util.h"
[email protected]807204142009-05-05 03:31:4413#include "base/stl_util-inl.h"
initial.commit09911bf2008-07-26 23:55:2914#include "base/string_util.h"
[email protected]1b5044d2009-02-24 00:04:1415#include "base/sys_string_conversions.h"
initial.commit09911bf2008-07-26 23:55:2916#include "base/task.h"
17#include "base/thread.h"
18#include "base/timer.h"
initial.commit09911bf2008-07-26 23:55:2919#include "chrome/browser/browser_list.h"
20#include "chrome/browser/browser_process.h"
[email protected]cdaa8652008-09-13 02:48:5921#include "chrome/browser/download/download_file.h"
[email protected]8f783752009-04-01 23:33:4522#include "chrome/browser/extensions/extensions_service.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"
[email protected]57c6a652009-05-04 07:58:3428#include "chrome/browser/tab_contents/tab_contents.h"
initial.commit09911bf2008-07-26 23:55:2929#include "chrome/common/chrome_paths.h"
[email protected]5b1a0e22009-05-26 19:00:5830#include "chrome/common/extensions/extension.h"
[email protected]076700e62009-04-01 18:41:2331#include "chrome/common/platform_util.h"
initial.commit09911bf2008-07-26 23:55:2932#include "chrome/common/pref_names.h"
33#include "chrome/common/pref_service.h"
[email protected]46072d42008-07-28 14:49:3534#include "googleurl/src/gurl.h"
[email protected]d81706b82009-04-03 20:28:4435#include "grit/chromium_strings.h"
[email protected]34ac8f32009-02-22 23:03:2736#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2937#include "net/base/mime_util.h"
38#include "net/base/net_util.h"
39#include "net/url_request/url_request_context.h"
40
[email protected]b7f05882009-02-22 01:21:5641#if defined(OS_WIN)
[email protected]4a0765a2009-05-08 23:12:2542#include "app/win_util.h"
[email protected]b7f05882009-02-22 01:21:5643#include "base/registry.h"
44#include "base/win_util.h"
[email protected]a0a9577b2009-05-27 23:52:3245#endif
46
47#if !defined(OS_MACOSX)
48// Used for initializing the list of dangerous extensions. We don't support it
49// yet on mac.
[email protected]b7f05882009-02-22 01:21:5650#include "chrome/browser/download/download_util.h"
[email protected]b7f05882009-02-22 01:21:5651#endif
52
[email protected]0f44d3e2009-03-12 23:36:3053#if defined(OS_LINUX)
54#include <gtk/gtk.h>
55#endif
56
initial.commit09911bf2008-07-26 23:55:2957// Periodically update our observers.
58class DownloadItemUpdateTask : public Task {
59 public:
60 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
61 void Run() { if (item_) item_->UpdateObservers(); }
62
63 private:
64 DownloadItem* item_;
65};
66
67// Update frequency (milliseconds).
68static const int kUpdateTimeMs = 1000;
69
70// Our download table ID starts at 1, so we use 0 to represent a download that
71// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2272// database handles in incognito mode starting at -1 and progressively getting
73// more negative.
initial.commit09911bf2008-07-26 23:55:2974static const int kUninitializedHandle = 0;
75
[email protected]7a256ea2008-10-17 17:34:1676// Appends the passed the number between parenthesis the path before the
77// extension.
[email protected]7ae7c2cb2009-01-06 23:31:4178static void AppendNumberToPath(FilePath* path, int number) {
79 file_util::InsertBeforeExtension(path,
80 StringPrintf(FILE_PATH_LITERAL(" (%d)"), number));
[email protected]7a256ea2008-10-17 17:34:1681}
82
83// Attempts to find a number that can be appended to that path to make it
84// unique. If |path| does not exist, 0 is returned. If it fails to find such
85// a number, -1 is returned.
[email protected]7ae7c2cb2009-01-06 23:31:4186static int GetUniquePathNumber(const FilePath& path) {
initial.commit09911bf2008-07-26 23:55:2987 const int kMaxAttempts = 100;
88
[email protected]7a256ea2008-10-17 17:34:1689 if (!file_util::PathExists(path))
90 return 0;
initial.commit09911bf2008-07-26 23:55:2991
[email protected]7ae7c2cb2009-01-06 23:31:4192 FilePath new_path;
initial.commit09911bf2008-07-26 23:55:2993 for (int count = 1; count <= kMaxAttempts; ++count) {
[email protected]7ae7c2cb2009-01-06 23:31:4194 new_path = FilePath(path);
[email protected]7a256ea2008-10-17 17:34:1695 AppendNumberToPath(&new_path, count);
initial.commit09911bf2008-07-26 23:55:2996
[email protected]7a256ea2008-10-17 17:34:1697 if (!file_util::PathExists(new_path))
98 return count;
initial.commit09911bf2008-07-26 23:55:2999 }
100
[email protected]7a256ea2008-10-17 17:34:16101 return -1;
initial.commit09911bf2008-07-26 23:55:29102}
103
[email protected]7ae7c2cb2009-01-06 23:31:41104static bool DownloadPathIsDangerous(const FilePath& download_path) {
105 FilePath desktop_dir;
[email protected]f052118e2008-09-05 02:25:32106 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
107 NOTREACHED();
108 return false;
109 }
110 return (download_path == desktop_dir);
111}
112
initial.commit09911bf2008-07-26 23:55:29113// DownloadItem implementation -------------------------------------------------
114
115// Constructor for reading from the history service.
116DownloadItem::DownloadItem(const DownloadCreateInfo& info)
117 : id_(-1),
118 full_path_(info.path),
119 url_(info.url),
120 total_bytes_(info.total_bytes),
121 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56122 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29123 state_(static_cast<DownloadState>(info.state)),
124 start_time_(info.start_time),
125 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29126 manager_(NULL),
127 is_paused_(false),
128 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56129 safety_state_(SAFE),
[email protected]0aad67b2009-07-15 20:34:28130 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56131 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29132 render_process_id_(-1),
133 request_id_(-1) {
134 if (state_ == IN_PROGRESS)
135 state_ = CANCELLED;
136 Init(false /* don't start progress timer */);
137}
138
139// Constructor for DownloadItem created via user action in the main thread.
140DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41141 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16142 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32143 const GURL& url,
[email protected]7ae7c2cb2009-01-06 23:31:41144 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59145 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29146 int64 download_size,
147 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32148 int request_id,
149 bool is_dangerous)
initial.commit09911bf2008-07-26 23:55:29150 : id_(download_id),
151 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16152 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29153 url_(url),
154 total_bytes_(download_size),
155 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56156 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29157 state_(IN_PROGRESS),
158 start_time_(start_time),
159 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29160 manager_(NULL),
161 is_paused_(false),
162 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56163 safety_state_(is_dangerous ? DANGEROUS : SAFE),
[email protected]0aad67b2009-07-15 20:34:28164 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56165 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29166 render_process_id_(render_process_id),
167 request_id_(request_id) {
168 Init(true /* start progress timer */);
169}
170
171void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41172 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29173 if (start_timer)
174 StartProgressTimer();
175}
176
177DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29178 state_ = REMOVING;
179 UpdateObservers();
180}
181
182void DownloadItem::AddObserver(Observer* observer) {
183 observers_.AddObserver(observer);
184}
185
186void DownloadItem::RemoveObserver(Observer* observer) {
187 observers_.RemoveObserver(observer);
188}
189
190void DownloadItem::UpdateObservers() {
191 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
192}
193
[email protected]45e3c122009-04-07 19:58:03194void DownloadItem::NotifyObserversDownloadOpened() {
195 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadOpened(this));
196}
197
initial.commit09911bf2008-07-26 23:55:29198// If we've received more data than we were expecting (bad server info?), revert
199// to 'unknown size mode'.
200void DownloadItem::UpdateSize(int64 bytes_so_far) {
201 received_bytes_ = bytes_so_far;
202 if (received_bytes_ > total_bytes_)
203 total_bytes_ = 0;
204}
205
206// Updates from the download thread may have been posted while this download
207// was being cancelled in the UI thread, so we'll accept them unless we're
208// complete.
209void DownloadItem::Update(int64 bytes_so_far) {
210 if (state_ == COMPLETE) {
211 NOTREACHED();
212 return;
213 }
214 UpdateSize(bytes_so_far);
215 UpdateObservers();
216}
217
[email protected]6cade212008-12-03 00:32:22218// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29219void DownloadItem::Cancel(bool update_history) {
220 if (state_ != IN_PROGRESS) {
221 // Small downloads might be complete before this method has a chance to run.
222 return;
223 }
224 state_ = CANCELLED;
225 UpdateObservers();
226 StopProgressTimer();
227 if (update_history)
228 manager_->DownloadCancelled(id_);
229}
230
231void DownloadItem::Finished(int64 size) {
232 state_ = COMPLETE;
233 UpdateSize(size);
[email protected]22fbe5a2008-10-29 22:20:40234 UpdateObservers();
initial.commit09911bf2008-07-26 23:55:29235 StopProgressTimer();
236}
237
[email protected]9ccbb372008-10-10 18:50:32238void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29239 Cancel(true);
240 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32241 if (delete_on_disk)
242 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29243 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22244 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29245}
246
247void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59248 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14249 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29250}
251
252void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14253 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29254}
255
[email protected]e93d2822009-01-30 05:59:59256bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29257 if (total_bytes_ <= 0)
258 return false; // We never received the content_length for this download.
259
260 int64 speed = CurrentSpeed();
261 if (speed == 0)
262 return false;
263
264 *remaining =
[email protected]e93d2822009-01-30 05:59:59265 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29266 return true;
267}
268
269int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56270 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
271 int64 diff_ms = diff.InMilliseconds();
272 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29273}
274
275int DownloadItem::PercentComplete() const {
276 int percent = -1;
277 if (total_bytes_ > 0)
278 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
279 return percent;
280}
281
[email protected]7ae7c2cb2009-01-06 23:31:41282void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29283 DCHECK(!full_path.empty());
284 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41285 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29286}
287
288void DownloadItem::TogglePause() {
289 DCHECK(state_ == IN_PROGRESS);
290 manager_->PauseDownload(id_, !is_paused_);
291 is_paused_ = !is_paused_;
292 UpdateObservers();
293}
294
[email protected]7ae7c2cb2009-01-06 23:31:41295FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32296 if (safety_state_ == DownloadItem::SAFE)
297 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16298 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41299 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16300 AppendNumberToPath(&name, path_uniquifier_);
301 return name;
302 }
[email protected]9ccbb372008-10-10 18:50:32303 return original_name_;
304}
305
initial.commit09911bf2008-07-26 23:55:29306// DownloadManager implementation ----------------------------------------------
307
308// static
309void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
310 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
311 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32312 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
313
314 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41315 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12316 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
317 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32318 NOTREACHED();
319 }
[email protected]b9636002009-03-04 00:05:25320 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
321 default_download_path);
[email protected]f052118e2008-09-05 02:25:32322
323 // If the download path is dangerous we forcefully reset it. But if we do
324 // so we set a flag to make sure we only do it once, to avoid fighting
325 // the user if he really wants it on an unsafe place such as the desktop.
326
327 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41328 FilePath current_download_dir = FilePath::FromWStringHack(
329 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32330 if (DownloadPathIsDangerous(current_download_dir)) {
331 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41332 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32333 }
334 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
335 }
initial.commit09911bf2008-07-26 23:55:29336}
337
338DownloadManager::DownloadManager()
339 : shutdown_needed_(false),
340 profile_(NULL),
341 file_manager_(NULL),
342 ui_loop_(MessageLoop::current()),
343 file_loop_(NULL) {
344}
345
346DownloadManager::~DownloadManager() {
347 if (shutdown_needed_)
348 Shutdown();
349}
350
351void DownloadManager::Shutdown() {
352 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
353
354 // Stop receiving download updates
355 file_manager_->RemoveDownloadManager(this);
356
357 // Stop making history service requests
358 cancelable_consumer_.CancelAllRequests();
359
360 // 'in_progress_' may contain DownloadItems that have not finished the start
361 // complete (from the history service) and thus aren't in downloads_.
362 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32363 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29364 for (; it != in_progress_.end(); ++it) {
365 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32366 if (download->safety_state() == DownloadItem::DANGEROUS) {
367 // Forget about any download that the user did not approve.
368 // Note that we cannot call download->Remove() this would invalidate our
369 // iterator.
370 to_remove.insert(download);
371 continue;
initial.commit09911bf2008-07-26 23:55:29372 }
[email protected]9ccbb372008-10-10 18:50:32373 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
374 download->Cancel(false);
375 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29376 if (download->db_handle() == kUninitializedHandle) {
377 // An invalid handle means that 'download' does not yet exist in
378 // 'downloads_', so we have to delete it here.
379 delete download;
380 }
381 }
382
[email protected]9ccbb372008-10-10 18:50:32383 // 'dangerous_finished_' contains all complete downloads that have not been
384 // approved. They should be removed.
385 it = dangerous_finished_.begin();
386 for (; it != dangerous_finished_.end(); ++it)
387 to_remove.insert(it->second);
388
389 // Remove the dangerous download that are not approved.
390 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
391 rm_it != to_remove.end(); ++rm_it) {
392 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32393 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32394 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32395 // Same as above, delete the download if it is not in 'downloads_' (as the
396 // Remove() call above won't have deleted it).
397 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32398 delete download;
399 }
400 to_remove.clear();
401
initial.commit09911bf2008-07-26 23:55:29402 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32403 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29404 STLDeleteValues(&downloads_);
405
406 file_manager_ = NULL;
407
408 // Save our file extensions to auto open.
409 SaveAutoOpens();
410
411 // Make sure the save as dialog doesn't notify us back if we're gone before
412 // it returns.
413 if (select_file_dialog_.get())
414 select_file_dialog_->ListenerDestroyed();
415
416 shutdown_needed_ = false;
417}
418
419// Issue a history query for downloads matching 'search_text'. If 'search_text'
420// is empty, return all downloads that we know about.
421void DownloadManager::GetDownloads(Observer* observer,
422 const std::wstring& search_text) {
423 DCHECK(observer);
424
425 // Return a empty list if we've not yet received the set of downloads from the
426 // history system (we'll update all observers once we get that list in
427 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
428 std::vector<DownloadItem*> download_copy;
429 if (downloads_.empty()) {
430 observer->SetDownloads(download_copy);
431 return;
432 }
433
434 // We already know all the downloads and there is no filter, so just return a
435 // copy to the observer.
436 if (search_text.empty()) {
437 download_copy.reserve(downloads_.size());
438 for (DownloadMap::iterator it = downloads_.begin();
439 it != downloads_.end(); ++it) {
440 download_copy.push_back(it->second);
441 }
442
443 // We retain ownership of the DownloadItems.
444 observer->SetDownloads(download_copy);
445 return;
446 }
447
448 // Issue a request to the history service for a list of downloads matching
449 // our search text.
450 HistoryService* hs =
451 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
452 if (hs) {
453 HistoryService::Handle h =
454 hs->SearchDownloads(search_text,
455 &cancelable_consumer_,
456 NewCallback(this,
457 &DownloadManager::OnSearchComplete));
458 cancelable_consumer_.SetClientData(hs, h, observer);
459 }
460}
461
462// Query the history service for information about all persisted downloads.
463bool DownloadManager::Init(Profile* profile) {
464 DCHECK(profile);
465 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
466 shutdown_needed_ = true;
467
468 profile_ = profile;
469 request_context_ = profile_->GetRequestContext();
470
471 // 'incognito mode' will have access to past downloads, but we won't store
472 // information about new downloads while in that mode.
473 QueryHistoryForDownloads();
474
475 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
476 if (!rdh) {
477 NOTREACHED();
478 return false;
479 }
480
481 file_manager_ = rdh->download_file_manager();
482 if (!file_manager_) {
483 NOTREACHED();
484 return false;
485 }
486
487 file_loop_ = g_browser_process->file_thread()->message_loop();
488 if (!file_loop_) {
489 NOTREACHED();
490 return false;
491 }
492
493 // Get our user preference state.
494 PrefService* prefs = profile_->GetPrefs();
495 DCHECK(prefs);
496 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
497
initial.commit09911bf2008-07-26 23:55:29498 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
499
[email protected]7ae7c2cb2009-01-06 23:31:41500 // This variable is needed to resolve which CreateDirectory we want to point
501 // to. Without it, the NewRunnableFunction cannot resolve the ambiguity.
502 // TODO(estade): when file_util::CreateDirectory(wstring) is removed,
503 // get rid of |CreateDirectoryPtr|.
504 bool (*CreateDirectoryPtr)(const FilePath&) = &file_util::CreateDirectory;
[email protected]bb69e9b32008-08-14 23:08:14505 // Ensure that the download directory specified in the preferences exists.
[email protected]7ae7c2cb2009-01-06 23:31:41506 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
507 CreateDirectoryPtr, download_path()));
initial.commit09911bf2008-07-26 23:55:29508
[email protected]a0a9577b2009-05-27 23:52:32509#if defined(OS_WIN) || defined(OS_LINUX)
510 // We use this to determine possibly dangerous downloads.
[email protected]2b2f8f72009-02-24 22:42:05511 download_util::InitializeExeTypes(&exe_types_);
512#endif
513
514 // We store any file extension that should be opened automatically at
515 // download completion in this pref.
initial.commit09911bf2008-07-26 23:55:29516 std::wstring extensions_to_open =
517 prefs->GetString(prefs::kDownloadExtensionsToOpen);
518 std::vector<std::wstring> extensions;
519 SplitString(extensions_to_open, L':', &extensions);
520 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]b7f05882009-02-22 01:21:56521 if (!extensions[i].empty() && !IsExecutable(
522 FilePath::FromWStringHack(extensions[i]).value()))
523 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29524 }
525
526 return true;
527}
528
529void DownloadManager::QueryHistoryForDownloads() {
530 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
531 if (hs) {
532 hs->QueryDownloads(
533 &cancelable_consumer_,
534 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
535 }
536}
537
538// We have received a message from DownloadFileManager about a new download. We
539// create a download item and store it in our download map, and inform the
540// history system of a new download. Since this method can be called while the
541// history service thread is still reading the persistent state, we do not
542// insert the new DownloadItem into 'downloads_' or inform our observers at this
543// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
544// download creation as a callback from the history thread.
545void DownloadManager::StartDownload(DownloadCreateInfo* info) {
546 DCHECK(MessageLoop::current() == ui_loop_);
547 DCHECK(info);
548
[email protected]7d3851d82008-12-12 03:26:07549 // Freeze the user's preference for showing a Save As dialog. We're going to
550 // bounce around a bunch of threads and we don't want to worry about race
551 // conditions where the user changes this pref out from under us.
552 if (*prompt_for_download_)
553 info->save_as = true;
554
initial.commit09911bf2008-07-26 23:55:29555 // Determine the proper path for a download, by choosing either the default
556 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41557 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29558 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07559 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29560 info->suggested_path = last_download_path_;
561 else
[email protected]7ae7c2cb2009-01-06 23:31:41562 info->suggested_path = download_path();
563 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29564
[email protected]7d3851d82008-12-12 03:26:07565 if (!info->save_as) {
566 // Let's check if this download is dangerous, based on its name.
[email protected]7ae7c2cb2009-01-06 23:31:41567 info->is_dangerous = IsDangerous(info->suggested_path.BaseName());
[email protected]e9ebf3fc2008-10-17 22:06:58568 }
569
initial.commit09911bf2008-07-26 23:55:29570 // We need to move over to the download thread because we don't want to stat
571 // the suggested path on the UI thread.
572 file_loop_->PostTask(FROM_HERE,
573 NewRunnableMethod(this,
574 &DownloadManager::CheckIfSuggestedPathExists,
575 info));
576}
577
578void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
579 DCHECK(info);
580
581 // Check writability of the suggested path. If we can't write to it, default
582 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41583 FilePath dir = info->suggested_path.DirName();
584 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32585 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29586 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29587 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41588 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29589 }
590
[email protected]7a256ea2008-10-17 17:34:16591 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29592
[email protected]6cade212008-12-03 00:32:22593 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58594 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41595 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32596 // Create a temporary file to hold the file until the user approves its
597 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41598 FilePath::StringType file_name;
599 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32600 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41601 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32602 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41603 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07604 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41605 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32606 }
607 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16608 } else {
609 // We know the final path, build it if necessary.
610 if (info->path_uniquifier > 0) {
611 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
612 // Setting path_uniquifier to 0 to make sure we don't try to unique it
613 // later on.
614 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07615 } else if (info->path_uniquifier == -1) {
616 // We failed to find a unique path. We have to prompt the user.
617 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16618 }
[email protected]9ccbb372008-10-10 18:50:32619 }
620
[email protected]7d3851d82008-12-12 03:26:07621 if (!info->save_as) {
622 // Create an empty file at the suggested path so that we don't allocate the
623 // same "non-existant" path to multiple downloads.
624 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ae7c2cb2009-01-06 23:31:41625 file_util::WriteFile(info->suggested_path.ToWStringHack(), "", 0);
[email protected]7d3851d82008-12-12 03:26:07626 }
627
initial.commit09911bf2008-07-26 23:55:29628 // Now we return to the UI thread.
629 ui_loop_->PostTask(FROM_HERE,
630 NewRunnableMethod(this,
631 &DownloadManager::OnPathExistenceAvailable,
632 info));
633}
634
635void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
636 DCHECK(MessageLoop::current() == ui_loop_);
637 DCHECK(info);
638
[email protected]7d3851d82008-12-12 03:26:07639 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29640 // We must ask the user for the place to put the download.
641 if (!select_file_dialog_.get())
642 select_file_dialog_ = SelectFileDialog::Create(this);
643
[email protected]57c6a652009-05-04 07:58:34644 TabContents* contents = tab_util::GetTabContentsByID(
initial.commit09911bf2008-07-26 23:55:29645 info->render_process_id, info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08646 SelectFileDialog::FileTypeInfo file_type_info;
647 file_type_info.extensions.resize(1);
648 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24649 if (!file_type_info.extensions[0][0].empty())
650 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08651 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23652 gfx::NativeWindow owning_window =
653 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29654 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34655 string16(),
656 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08657 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30658 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29659 } else {
660 // No prompting for download, just continue with the suggested name.
661 ContinueStartDownload(info, info->suggested_path);
662 }
663}
664
665void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41666 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29667 scoped_ptr<DownloadCreateInfo> infop(info);
668 info->path = target_path;
669
670 DownloadItem* download = NULL;
671 DownloadMap::iterator it = in_progress_.find(info->download_id);
672 if (it == in_progress_.end()) {
673 download = new DownloadItem(info->download_id,
674 info->path,
[email protected]7a256ea2008-10-17 17:34:16675 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29676 info->url,
[email protected]9ccbb372008-10-10 18:50:32677 info->original_name,
initial.commit09911bf2008-07-26 23:55:29678 info->start_time,
679 info->total_bytes,
680 info->render_process_id,
[email protected]9ccbb372008-10-10 18:50:32681 info->request_id,
682 info->is_dangerous);
initial.commit09911bf2008-07-26 23:55:29683 download->set_manager(this);
684 in_progress_[info->download_id] = download;
685 } else {
686 NOTREACHED(); // Should not exist!
687 return;
688 }
689
[email protected]6b323782009-03-27 18:43:08690 // Called before DownloadFinished in order to avoid a race condition where we
691 // attempt to open a completed download before it has been renamed.
692 file_loop_->PostTask(FROM_HERE,
693 NewRunnableMethod(file_manager_,
694 &DownloadFileManager::OnFinalDownloadName,
695 download->id(),
[email protected]8f783752009-04-01 23:33:45696 target_path,
697 this));
[email protected]6b323782009-03-27 18:43:08698
initial.commit09911bf2008-07-26 23:55:29699 // If the download already completed by the time we reached this point, then
700 // notify observers that it did.
701 PendingFinishedMap::iterator pending_it =
702 pending_finished_downloads_.find(info->download_id);
703 if (pending_it != pending_finished_downloads_.end())
704 DownloadFinished(pending_it->first, pending_it->second);
705
706 download->Rename(target_path);
707
initial.commit09911bf2008-07-26 23:55:29708 if (profile_->IsOffTheRecord()) {
709 // Fake a db handle for incognito mode, since nothing is actually stored in
710 // the database in this mode. We have to make sure that these handles don't
711 // collide with normal db handles, so we use a negative value. Eventually,
712 // they could overlap, but you'd have to do enough downloading that your ISP
713 // would likely stab you in the neck first. YMMV.
714 static int64 fake_db_handle = kUninitializedHandle - 1;
715 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
716 } else {
717 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22718 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29719 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
720 if (hs) {
721 hs->CreateDownload(
722 *info, &cancelable_consumer_,
723 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
724 }
725 }
726}
727
728// Convenience function for updating the history service for a download.
729void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
730 DCHECK(download);
731
732 // Don't store info in the database if the download was initiated while in
733 // incognito mode or if it hasn't been initialized in our database table.
734 if (download->db_handle() <= kUninitializedHandle)
735 return;
736
[email protected]6cade212008-12-03 00:32:22737 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29738 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
739 if (hs) {
740 hs->UpdateDownload(download->received_bytes(),
741 download->state(),
742 download->db_handle());
743 }
744}
745
746void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
747 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22748 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29749 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
750 if (download->db_handle() > kUninitializedHandle && hs)
751 hs->RemoveDownload(download->db_handle());
752}
753
[email protected]e93d2822009-01-30 05:59:59754void DownloadManager::RemoveDownloadsFromHistoryBetween(
755 const base::Time remove_begin,
756 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22757 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29758 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
759 if (hs)
760 hs->RemoveDownloadsBetween(remove_begin, remove_end);
761}
762
763void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
764 DownloadMap::iterator it = in_progress_.find(download_id);
765 if (it != in_progress_.end()) {
766 DownloadItem* download = it->second;
767 download->Update(size);
768 UpdateHistoryForDownload(download);
769 }
770}
771
772void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
773 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32774 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29775 // The download is done, but the user hasn't selected a final location for
776 // it yet (the Save As dialog box is probably still showing), so just keep
777 // track of the fact that this download id is complete, when the
778 // DownloadItem is constructed later we'll notify its completion then.
779 PendingFinishedMap::iterator erase_it =
780 pending_finished_downloads_.find(download_id);
781 DCHECK(erase_it == pending_finished_downloads_.end());
782 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32783 return;
initial.commit09911bf2008-07-26 23:55:29784 }
[email protected]9ccbb372008-10-10 18:50:32785
786 // Remove the id from the list of pending ids.
787 PendingFinishedMap::iterator erase_it =
788 pending_finished_downloads_.find(download_id);
789 if (erase_it != pending_finished_downloads_.end())
790 pending_finished_downloads_.erase(erase_it);
791
792 DownloadItem* download = it->second;
793 download->Finished(size);
794
795 // Clean up will happen when the history system create callback runs if we
796 // don't have a valid db_handle yet.
797 if (download->db_handle() != kUninitializedHandle) {
798 in_progress_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32799 UpdateHistoryForDownload(download);
800 }
801
802 // If this a dangerous download not yet validated by the user, don't do
803 // anything. When the user notifies us, it will trigger a call to
804 // ProceedWithFinishedDangerousDownload.
805 if (download->safety_state() == DownloadItem::DANGEROUS) {
806 dangerous_finished_[download_id] = download;
807 return;
808 }
809
810 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22811 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32812 // its final name before we can continue.
813 file_loop_->PostTask(FROM_HERE,
814 NewRunnableMethod(
815 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
816 download->db_handle(),
817 download->full_path(), download->original_name()));
818 return;
819 }
820 ContinueDownloadFinished(download);
821}
822
[email protected]8f783752009-04-01 23:33:45823void DownloadManager::DownloadRenamedToFinalName(int download_id,
824 const FilePath& full_path) {
[email protected]8f783752009-04-01 23:33:45825}
826
[email protected]9ccbb372008-10-10 18:50:32827void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
828 // If this was a dangerous download, it has now been approved and must be
829 // removed from dangerous_finished_ so it does not get deleted on shutdown.
830 DownloadMap::iterator it = dangerous_finished_.find(download->id());
831 if (it != dangerous_finished_.end())
832 dangerous_finished_.erase(it);
833
[email protected]5a102892009-07-15 19:59:30834 // Open the download if the user or user prefs indicate it should be.
835 FilePath::StringType extension = download->full_path().Extension();
836 // Drop the leading period. (The auto-open list is period-less.)
837 if (extension.size() > 0)
838 extension = extension.substr(1);
839
[email protected]0aad67b2009-07-15 20:34:28840 // Handle chrome extensions explicitly and skip the shell execute.
841 if (Extension::IsExtension(download->full_path())) {
842 OpenChromeExtension(download->full_path());
843 download->set_auto_opened(true);
844 } else if (download->open_when_complete() ||
845 ShouldOpenFileExtension(extension)) {
[email protected]9ccbb372008-10-10 18:50:32846 OpenDownloadInShell(download, NULL);
[email protected]0aad67b2009-07-15 20:34:28847 download->set_auto_opened(true);
848 }
[email protected]9ccbb372008-10-10 18:50:32849
[email protected]0aad67b2009-07-15 20:34:28850 // Notify our observers that we are complete (the call to Finished() set the
851 // state to complete but did not notify).
852 download->UpdateObservers();
853}
[email protected]9ccbb372008-10-10 18:50:32854// Called on the file thread. Renames the downloaded file to its original name.
855void DownloadManager::ProceedWithFinishedDangerousDownload(
856 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41857 const FilePath& path,
858 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32859 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41860 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16861 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32862 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24863 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16864 // Make our name unique at this point, as if a dangerous file is downloading
865 // and a 2nd download is started for a file with the same name, they would
866 // have the same path. This is because we uniquify the name on download
867 // start, and at that time the first file does not exists yet, so the second
868 // file gets the same name.
869 uniquifier = GetUniquePathNumber(new_path);
870 if (uniquifier > 0)
871 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32872 success = file_util::Move(path, new_path);
873 } else {
874 NOTREACHED();
875 }
[email protected]6cade212008-12-03 00:32:22876
[email protected]9ccbb372008-10-10 18:50:32877 ui_loop_->PostTask(FROM_HERE,
878 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16879 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32880}
881
882// Call from the file thread when the finished dangerous download was renamed.
883void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
884 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41885 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16886 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32887 DownloadMap::iterator it = downloads_.find(download_handle);
888 if (it == downloads_.end()) {
889 NOTREACHED();
890 return;
891 }
892
893 DownloadItem* download = it->second;
894 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16895 if (success) {
896 // We need to update the path uniquifier so that the UI shows the right
897 // name when calling GetFileName().
898 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32899 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16900 }
[email protected]9ccbb372008-10-10 18:50:32901
902 // Continue the download finished sequence.
903 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29904}
905
906// static
907// We have to tell the ResourceDispatcherHost to cancel the download from this
[email protected]6cade212008-12-03 00:32:22908// thread, since we can't forward tasks from the file thread to the IO thread
initial.commit09911bf2008-07-26 23:55:29909// reliably (crash on shutdown race condition).
910void DownloadManager::CancelDownloadRequest(int render_process_id,
911 int request_id) {
912 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]ab820df2008-08-26 05:55:10913 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29914 if (!io_thread || !rdh)
915 return;
916 io_thread->message_loop()->PostTask(FROM_HERE,
917 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
918 rdh,
919 render_process_id,
920 request_id));
921}
922
923// static
924void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
925 int render_process_id,
926 int request_id) {
927 rdh->CancelRequest(render_process_id, request_id, false);
928}
929
930void DownloadManager::DownloadCancelled(int32 download_id) {
931 DownloadMap::iterator it = in_progress_.find(download_id);
932 if (it == in_progress_.end())
933 return;
934 DownloadItem* download = it->second;
935
936 CancelDownloadRequest(download->render_process_id(), download->request_id());
937
938 // Clean up will happen when the history system create callback runs if we
939 // don't have a valid db_handle yet.
940 if (download->db_handle() != kUninitializedHandle) {
941 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:29942 UpdateHistoryForDownload(download);
943 }
944
945 // Tell the file manager to cancel the download.
946 file_manager_->RemoveDownload(download->id(), this); // On the UI thread
947 file_loop_->PostTask(FROM_HERE,
948 NewRunnableMethod(file_manager_,
949 &DownloadFileManager::CancelDownload,
950 download->id()));
951}
952
953void DownloadManager::PauseDownload(int32 download_id, bool pause) {
954 DownloadMap::iterator it = in_progress_.find(download_id);
955 if (it != in_progress_.end()) {
956 DownloadItem* download = it->second;
957 if (pause == download->is_paused())
958 return;
959
960 // Inform the ResourceDispatcherHost of the new pause state.
[email protected]ab820df2008-08-26 05:55:10961 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29962 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
963 if (!io_thread || !rdh)
964 return;
965
966 io_thread->message_loop()->PostTask(FROM_HERE,
967 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
968 rdh,
969 download->render_process_id(),
970 download->request_id(),
971 pause));
972 }
973}
974
975// static
976void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
977 int render_process_id,
978 int request_id,
979 bool pause) {
980 rdh->PauseRequest(render_process_id, request_id, pause);
981}
982
[email protected]7ae7c2cb2009-01-06 23:31:41983bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:32984 // TODO(jcampan): Improve me.
[email protected]2001fe82009-02-23 23:53:14985 FilePath::StringType extension = file_name.Extension();
986 // Drop the leading period.
987 if (extension.size() > 0)
988 extension = extension.substr(1);
989 return IsExecutable(extension);
[email protected]9ccbb372008-10-10 18:50:32990}
991
992void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:41993 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:32994 download->Rename(new_path);
995
996 // Update the history.
997
998 // No update necessary if the download was initiated while in incognito mode.
999 if (download->db_handle() <= kUninitializedHandle)
1000 return;
1001
[email protected]6cade212008-12-03 00:32:221002 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:321003 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1004 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:411005 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:321006}
1007
initial.commit09911bf2008-07-26 23:55:291008void DownloadManager::RemoveDownload(int64 download_handle) {
1009 DownloadMap::iterator it = downloads_.find(download_handle);
1010 if (it == downloads_.end())
1011 return;
1012
1013 // Make history update.
1014 DownloadItem* download = it->second;
1015 RemoveDownloadFromHistory(download);
1016
1017 // Remove from our tables and delete.
1018 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321019 it = dangerous_finished_.find(download->id());
1020 if (it != dangerous_finished_.end())
1021 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291022
1023 // Tell observers to refresh their views.
1024 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:361025
1026 delete download;
initial.commit09911bf2008-07-26 23:55:291027}
1028
[email protected]e93d2822009-01-30 05:59:591029int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1030 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291031 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1032
initial.commit09911bf2008-07-26 23:55:291033 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:281034 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:291035 while (it != downloads_.end()) {
1036 DownloadItem* download = it->second;
1037 DownloadItem::DownloadState state = download->state();
1038 if (download->start_time() >= remove_begin &&
1039 (remove_end.is_null() || download->start_time() < remove_end) &&
1040 (state == DownloadItem::COMPLETE ||
1041 state == DownloadItem::CANCELLED)) {
1042 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561043 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581044
1045 // Also remove it from any completed dangerous downloads.
1046 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1047 if (dit != dangerous_finished_.end())
1048 dangerous_finished_.erase(dit);
1049
[email protected]78b8fcc92009-03-31 17:36:281050 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:291051
initial.commit09911bf2008-07-26 23:55:291052 continue;
1053 }
1054
1055 ++it;
1056 }
1057
1058 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281059 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291060 if (num_deleted > 0)
1061 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1062
[email protected]78b8fcc92009-03-31 17:36:281063 // Delete the download items after updating the observers.
1064 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1065 pending_deletes.clear();
1066
initial.commit09911bf2008-07-26 23:55:291067 return num_deleted;
1068}
1069
[email protected]e93d2822009-01-30 05:59:591070int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1071 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291072}
1073
[email protected]d41355e6f2009-04-07 21:21:121074int DownloadManager::RemoveAllDownloads() {
1075 // The null times make the date range unbounded.
1076 return RemoveDownloadsBetween(base::Time(), base::Time());
1077}
1078
initial.commit09911bf2008-07-26 23:55:291079// Initiate a download of a specific URL. We send the request to the
1080// ResourceDispatcherHost, and let it send us responses like a regular
1081// download.
1082void DownloadManager::DownloadUrl(const GURL& url,
1083 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:501084 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:341085 TabContents* tab_contents) {
1086 DCHECK(tab_contents);
[email protected]c9825a42009-05-01 22:51:501087 request_context_->set_referrer_charset(referrer_charset);
initial.commit09911bf2008-07-26 23:55:291088 file_manager_->DownloadUrl(url,
1089 referrer,
[email protected]57c6a652009-05-04 07:58:341090 tab_contents->process()->pid(),
1091 tab_contents->render_view_host()->routing_id(),
initial.commit09911bf2008-07-26 23:55:291092 request_context_.get());
1093}
1094
[email protected]7ae7c2cb2009-01-06 23:31:411095void DownloadManager::GenerateExtension(
1096 const FilePath& file_name,
1097 const std::string& mime_type,
1098 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291099 // We're worried about three things here:
1100 //
1101 // 1) Security. Many sites let users upload content, such as buddy icons, to
1102 // their web sites. We want to mitigate the case where an attacker
1103 // supplies a malicious executable with an executable file extension but an
1104 // honest site serves the content with a benign content type, such as
1105 // image/jpeg.
1106 //
1107 // 2) Usability. If the site fails to provide a file extension, we want to
1108 // guess a reasonable file extension based on the content type.
1109 //
1110 // 3) Shell integration. Some file extensions automatically integrate with
1111 // the shell. We block these extensions to prevent a malicious web site
1112 // from integrating with the user's shell.
1113
[email protected]7ae7c2cb2009-01-06 23:31:411114 static const FilePath::CharType default_extension[] =
1115 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291116
1117 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411118 FilePath::StringType extension(
1119 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291120
[email protected]b7f05882009-02-22 01:21:561121#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291122 // Rename shell-integrated extensions.
1123 if (win_util::IsShellIntegratedExtension(extension))
1124 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561125#endif
initial.commit09911bf2008-07-26 23:55:291126
1127 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411128 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411129 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291130 if (mime_type == mime_type_from_extension) {
1131 // The hinted extension matches the mime type. It looks like a winner.
1132 generated_extension->swap(extension);
1133 return;
1134 }
1135
1136 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1137 // We want to be careful about executable extensions. The worry here is
1138 // that a trusted web site could be tricked into dropping an executable file
1139 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101140 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291141 // We couldn't find a good extension for this content type. Use a dummy
1142 // extension instead.
1143 extension.assign(default_extension);
1144 }
1145 }
1146
1147 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101148 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291149 } else {
[email protected]6cade212008-12-03 00:32:221150 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291151 // 1. New extension is not ".txt"
1152 // 2. New extension is not the same as the already existing extension.
1153 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411154 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291155 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1156 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371157 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1158 // servers, i.e. bug 5772.
[email protected]7ae7c2cb2009-01-06 23:31:411159 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101160 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171161 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411162 append_extension != extension &&
[email protected]e106457b2009-03-25 22:43:371163 !IsExecutable(append_extension) &&
1164 (append_extension != FILE_PATH_LITERAL("tar") ||
1165 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171166 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291167 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171168 }
initial.commit09911bf2008-07-26 23:55:291169 }
1170 }
1171
1172 generated_extension->swap(extension);
1173}
1174
1175void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411176 FilePath* generated_name) {
1177 *generated_name = FilePath::FromWStringHack(
[email protected]8ac1a752008-07-31 19:40:371178 net::GetSuggestedFilename(GURL(info->url),
1179 info->content_disposition,
[email protected]c9825a42009-05-01 22:51:501180 info->referrer_charset,
[email protected]7ae7c2cb2009-01-06 23:31:411181 L"download"));
1182 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291183
[email protected]7ae7c2cb2009-01-06 23:31:411184 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291185}
1186
1187void DownloadManager::AddObserver(Observer* observer) {
1188 observers_.AddObserver(observer);
1189 observer->ModelChanged();
1190}
1191
1192void DownloadManager::RemoveObserver(Observer* observer) {
1193 observers_.RemoveObserver(observer);
1194}
1195
1196// Post Windows Shell operations to the Download thread, to avoid blocking the
1197// user interface.
1198void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1199 DCHECK(file_manager_);
1200 file_loop_->PostTask(FROM_HERE,
1201 NewRunnableMethod(file_manager_,
1202 &DownloadFileManager::OnShowDownloadInShell,
[email protected]7ae7c2cb2009-01-06 23:31:411203 FilePath(download->full_path())));
initial.commit09911bf2008-07-26 23:55:291204}
1205
[email protected]8f783752009-04-01 23:33:451206void DownloadManager::OpenDownload(const DownloadItem* download,
1207 gfx::NativeView parent_window) {
[email protected]0e34d7892009-06-05 19:17:401208 // Open Chrome extensions with ExtensionsService. For everything else do shell
[email protected]8f783752009-04-01 23:33:451209 // execute.
[email protected]f1ce6e62009-06-29 20:31:291210 if (Extension::IsExtension(download->full_path())) {
[email protected]8f783752009-04-01 23:33:451211 OpenChromeExtension(download->full_path());
1212 } else {
1213 OpenDownloadInShell(download, parent_window);
1214 }
1215}
1216
1217void DownloadManager::OpenChromeExtension(const FilePath& full_path) {
[email protected]1bd54132009-06-11 00:05:341218 profile_->GetOriginalProfile()->GetExtensionsService()->
1219 InstallExtension(full_path);
[email protected]8f783752009-04-01 23:33:451220}
1221
initial.commit09911bf2008-07-26 23:55:291222void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591223 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291224 DCHECK(file_manager_);
1225 file_loop_->PostTask(FROM_HERE,
1226 NewRunnableMethod(file_manager_,
1227 &DownloadFileManager::OnOpenDownloadInShell,
1228 download->full_path(), download->url(), parent_window));
1229}
1230
[email protected]7ae7c2cb2009-01-06 23:31:411231void DownloadManager::OpenFilesOfExtension(
1232 const FilePath::StringType& extension, bool open) {
initial.commit09911bf2008-07-26 23:55:291233 if (open && !IsExecutable(extension))
1234 auto_open_.insert(extension);
1235 else
1236 auto_open_.erase(extension);
1237 SaveAutoOpens();
1238}
1239
[email protected]7ae7c2cb2009-01-06 23:31:411240bool DownloadManager::ShouldOpenFileExtension(
1241 const FilePath::StringType& extension) {
[email protected]8c756ac2009-01-30 23:36:411242 // Special-case Chrome extensions as always-open.
initial.commit09911bf2008-07-26 23:55:291243 if (!IsExecutable(extension) &&
[email protected]8c756ac2009-01-30 23:36:411244 (auto_open_.find(extension) != auto_open_.end() ||
[email protected]f1ce6e62009-06-29 20:31:291245 Extension::IsExtension(FilePath(extension))))
[email protected]8c756ac2009-01-30 23:36:411246 return true;
initial.commit09911bf2008-07-26 23:55:291247 return false;
1248}
1249
[email protected]7b73d992008-12-15 20:56:461250static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291251 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461252 "text/javascript",
1253 "text/javascript;version=*",
[email protected]54d8d452009-04-08 17:29:241254 // Registry files can cause critical changes to the MS OS behavior.
1255 // Addition of this mimetype also addresses bug 7337.
1256 "text/x-registry",
[email protected]60ff8f912008-12-05 07:58:391257 // Some sites use binary/octet-stream to mean application/octet-stream.
1258 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461259 "binary/octet-stream"
1260};
initial.commit09911bf2008-07-26 23:55:291261
[email protected]7b73d992008-12-15 20:56:461262static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291263 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461264 "application/*+xml",
1265 "application/xml"
1266};
initial.commit09911bf2008-07-26 23:55:291267
[email protected]7b73d992008-12-15 20:56:461268// static
1269bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411270 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461271 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1272 return true;
1273 }
[email protected]bae0ea12009-02-14 01:20:411274 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461275 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1276 return false;
1277 }
1278 // We consider only other application types to be executable.
1279 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291280}
1281
[email protected]7ae7c2cb2009-01-06 23:31:411282bool DownloadManager::IsExecutable(const FilePath::StringType& extension) {
[email protected]a0a9577b2009-05-27 23:52:321283#if defined(OS_MACOSX)
1284 // We don't have dangerous download support on mac yet.
1285 return false;
1286#else
[email protected]64da0b932009-02-24 02:30:041287 if (!IsStringASCII(extension))
1288 return false;
[email protected]a0a9577b2009-05-27 23:52:321289#if defined(OS_WIN)
[email protected]64da0b932009-02-24 02:30:041290 std::string ascii_extension = WideToASCII(extension);
[email protected]a0a9577b2009-05-27 23:52:321291#elif defined(OS_LINUX)
1292 std::string ascii_extension = extension;
1293#endif
[email protected]64da0b932009-02-24 02:30:041294 StringToLowerASCII(&ascii_extension);
1295
1296 return exe_types_.find(ascii_extension) != exe_types_.end();
[email protected]a0a9577b2009-05-27 23:52:321297#endif // !defined(OS_MACOSX)
initial.commit09911bf2008-07-26 23:55:291298}
1299
1300void DownloadManager::ResetAutoOpenFiles() {
1301 auto_open_.clear();
1302 SaveAutoOpens();
1303}
1304
1305bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1306 return !auto_open_.empty();
1307}
1308
1309void DownloadManager::SaveAutoOpens() {
1310 PrefService* prefs = profile_->GetPrefs();
1311 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411312 FilePath::StringType extensions;
1313 for (std::set<FilePath::StringType>::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291314 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411315 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291316 }
1317 if (!extensions.empty())
1318 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561319
1320 std::wstring extensions_w;
1321#if defined(OS_WIN)
1322 extensions_w = extensions;
1323#elif defined(OS_POSIX)
[email protected]1b5044d2009-02-24 00:04:141324 extensions_w = base::SysNativeMBToWide(extensions);
[email protected]b7f05882009-02-22 01:21:561325#endif
1326
1327 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291328 }
1329}
1330
[email protected]561abe62009-04-06 18:08:341331void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361332 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291333 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071334 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411335 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291336 ContinueStartDownload(info, path);
1337}
1338
1339void DownloadManager::FileSelectionCanceled(void* params) {
1340 // The user didn't pick a place to save the file, so need to cancel the
1341 // download that's already in progress to the temporary location.
1342 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
1343 file_loop_->PostTask(FROM_HERE,
1344 NewRunnableMethod(file_manager_, &DownloadFileManager::CancelDownload,
1345 info->download_id));
1346}
1347
[email protected]7ae7c2cb2009-01-06 23:31:411348void DownloadManager::DeleteDownload(const FilePath& path) {
1349 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
1350 &DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321351}
1352
1353
1354void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1355 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1356 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1357 download->UpdateObservers();
1358
1359 // If the download is not complete, nothing to do. The required
1360 // post-processing will be performed when it does complete.
1361 if (download->state() != DownloadItem::COMPLETE)
1362 return;
1363
1364 file_loop_->PostTask(FROM_HERE,
1365 NewRunnableMethod(this,
1366 &DownloadManager::ProceedWithFinishedDangerousDownload,
1367 download->db_handle(), download->full_path(),
1368 download->original_name()));
1369}
1370
[email protected]763f946a2009-01-06 19:04:391371void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411372 FilePath* file_name) {
1373 // Make sure we get the right file extension
1374 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391375 GenerateExtension(*file_name, mime_type, &extension);
1376 file_util::ReplaceExtension(file_name, extension);
1377
[email protected]2b2f8f72009-02-24 22:42:051378#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391379 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411380 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391381 DCHECK(!leaf_name.empty());
1382 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411383 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1384 *file_name = file_name->DirName();
1385 if (file_name->value() == FilePath::kCurrentDirectory) {
1386 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391387 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411388 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391389 }
1390 }
[email protected]b7f05882009-02-22 01:21:561391#elif defined(OS_POSIX)
1392 NOTIMPLEMENTED();
1393#endif
[email protected]763f946a2009-01-06 19:04:391394}
1395
initial.commit09911bf2008-07-26 23:55:291396// Operations posted to us from the history service ----------------------------
1397
1398// The history service has retrieved all download entries. 'entries' contains
1399// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1400void DownloadManager::OnQueryDownloadEntriesComplete(
1401 std::vector<DownloadCreateInfo>* entries) {
1402 for (size_t i = 0; i < entries->size(); ++i) {
1403 DownloadItem* download = new DownloadItem(entries->at(i));
1404 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1405 downloads_[download->db_handle()] = download;
1406 download->set_manager(this);
1407 }
1408 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1409}
1410
initial.commit09911bf2008-07-26 23:55:291411// Once the new DownloadItem's creation info has been committed to the history
1412// service, we associate the DownloadItem with the db handle, update our
1413// 'downloads_' map and inform observers.
1414void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1415 int64 db_handle) {
1416 DownloadMap::iterator it = in_progress_.find(info.download_id);
1417 DCHECK(it != in_progress_.end());
1418
1419 DownloadItem* download = it->second;
1420 DCHECK(download->db_handle() == kUninitializedHandle);
1421 download->set_db_handle(db_handle);
1422
1423 // Insert into our full map.
1424 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1425 downloads_[download->db_handle()] = download;
1426
[email protected]5e595482009-05-06 20:16:531427 // Show in the appropropriate browser UI.
1428 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291429
1430 // Inform interested objects about the new download.
1431 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
initial.commit09911bf2008-07-26 23:55:291432
1433 // If this download has been completed before we've received the db handle,
1434 // post one final message to the history service so that it can be properly
1435 // in sync with the DownloadItem's completion status, and also inform any
1436 // observers so that they get more than just the start notification.
1437 if (download->state() != DownloadItem::IN_PROGRESS) {
1438 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291439 UpdateHistoryForDownload(download);
1440 download->UpdateObservers();
1441 }
1442}
1443
1444// Called when the history service has retrieved the list of downloads that
1445// match the search text.
1446void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1447 std::vector<int64>* results) {
1448 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1449 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1450 if (!requestor)
1451 return;
1452
1453 std::vector<DownloadItem*> searched_downloads;
1454 for (std::vector<int64>::iterator it = results->begin();
1455 it != results->end(); ++it) {
1456 DownloadMap::iterator dit = downloads_.find(*it);
1457 if (dit != downloads_.end())
1458 searched_downloads.push_back(dit->second);
1459 }
1460
1461 requestor->SetDownloads(searched_downloads);
1462}
[email protected]905a08d2008-11-19 07:24:121463
[email protected]5e595482009-05-06 20:16:531464void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1465 DownloadItem* download) {
[email protected]5e595482009-05-06 20:16:531466 // The 'contents' may no longer exist if the user closed the tab before we get
1467 // this start completion event. If it does, tell the origin TabContents to
1468 // display its download shelf.
1469 TabContents* contents =
1470 tab_util::GetTabContentsByID(info.render_process_id, info.render_view_id);
1471
1472 // If the contents no longer exists, we start the download in the last active
1473 // browser. This is not ideal but better than fully hiding the download from
1474 // the user.
1475 if (!contents) {
1476 Browser* last_active = BrowserList::GetLastActive();
1477 if (last_active)
1478 contents = last_active->GetSelectedTabContents();
1479 }
1480
1481 if (contents)
1482 contents->OnStartDownload(download);
1483}
1484
[email protected]6cade212008-12-03 00:32:221485// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121486void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411487 last_download_path_ = FilePath();
[email protected]0aad67b2009-07-15 20:34:281488}