blob: b242d84eddc3c77efb87caf48bd8b00306b99d80 [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]d83d03aa2009-11-02 21:44:3721#include "chrome/browser/chrome_thread.h"
[email protected]cdaa8652008-09-13 02:48:5922#include "chrome/browser/download/download_file.h"
[email protected]e9ef0a62009-08-11 22:50:1323#include "chrome/browser/download/download_util.h"
[email protected]866930682009-08-18 22:53:4724#include "chrome/browser/extensions/crx_installer.h"
[email protected]2a464a92009-08-01 17:58:3525#include "chrome/browser/extensions/extension_install_ui.h"
[email protected]8f783752009-04-01 23:33:4526#include "chrome/browser/extensions/extensions_service.h"
[email protected]be180c802009-10-23 06:33:3127#include "chrome/browser/net/chrome_url_request_context.h"
initial.commit09911bf2008-07-26 23:55:2928#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:2629#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2530#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]e3c404b2008-12-23 01:07:3231#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
[email protected]f3ec7742009-01-15 00:59:1632#include "chrome/browser/tab_contents/tab_util.h"
[email protected]57c6a652009-05-04 07:58:3433#include "chrome/browser/tab_contents/tab_contents.h"
[email protected]4a0380c2009-07-26 07:25:3234#include "chrome/common/chrome_constants.h"
initial.commit09911bf2008-07-26 23:55:2935#include "chrome/common/chrome_paths.h"
[email protected]5b1a0e22009-05-26 19:00:5836#include "chrome/common/extensions/extension.h"
[email protected]6657afa62009-11-04 02:15:2037#include "chrome/common/extensions/user_script.h"
[email protected]91e1bd82009-09-03 22:04:4038#include "chrome/common/notification_service.h"
39#include "chrome/common/notification_type.h"
[email protected]076700e62009-04-01 18:41:2340#include "chrome/common/platform_util.h"
initial.commit09911bf2008-07-26 23:55:2941#include "chrome/common/pref_names.h"
42#include "chrome/common/pref_service.h"
[email protected]46072d42008-07-28 14:49:3543#include "googleurl/src/gurl.h"
[email protected]d81706b82009-04-03 20:28:4444#include "grit/chromium_strings.h"
[email protected]34ac8f32009-02-22 23:03:2745#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2946#include "net/base/mime_util.h"
47#include "net/base/net_util.h"
48#include "net/url_request/url_request_context.h"
49
[email protected]b7f05882009-02-22 01:21:5650#if defined(OS_WIN)
[email protected]4a0765a2009-05-08 23:12:2551#include "app/win_util.h"
[email protected]b7f05882009-02-22 01:21:5652#include "base/registry.h"
53#include "base/win_util.h"
[email protected]a0a9577b2009-05-27 23:52:3254#endif
55
[email protected]0f44d3e2009-03-12 23:36:3056#if defined(OS_LINUX)
57#include <gtk/gtk.h>
58#endif
59
initial.commit09911bf2008-07-26 23:55:2960// Periodically update our observers.
61class DownloadItemUpdateTask : public Task {
62 public:
63 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
64 void Run() { if (item_) item_->UpdateObservers(); }
65
66 private:
67 DownloadItem* item_;
68};
69
70// Update frequency (milliseconds).
71static const int kUpdateTimeMs = 1000;
72
73// Our download table ID starts at 1, so we use 0 to represent a download that
74// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2275// database handles in incognito mode starting at -1 and progressively getting
76// more negative.
initial.commit09911bf2008-07-26 23:55:2977static const int kUninitializedHandle = 0;
78
[email protected]7a256ea2008-10-17 17:34:1679// Appends the passed the number between parenthesis the path before the
80// extension.
[email protected]7ae7c2cb2009-01-06 23:31:4181static void AppendNumberToPath(FilePath* path, int number) {
82 file_util::InsertBeforeExtension(path,
83 StringPrintf(FILE_PATH_LITERAL(" (%d)"), number));
[email protected]7a256ea2008-10-17 17:34:1684}
85
86// Attempts to find a number that can be appended to that path to make it
87// unique. If |path| does not exist, 0 is returned. If it fails to find such
88// a number, -1 is returned.
[email protected]7ae7c2cb2009-01-06 23:31:4189static int GetUniquePathNumber(const FilePath& path) {
initial.commit09911bf2008-07-26 23:55:2990 const int kMaxAttempts = 100;
91
[email protected]7a256ea2008-10-17 17:34:1692 if (!file_util::PathExists(path))
93 return 0;
initial.commit09911bf2008-07-26 23:55:2994
[email protected]7ae7c2cb2009-01-06 23:31:4195 FilePath new_path;
initial.commit09911bf2008-07-26 23:55:2996 for (int count = 1; count <= kMaxAttempts; ++count) {
[email protected]7ae7c2cb2009-01-06 23:31:4197 new_path = FilePath(path);
[email protected]7a256ea2008-10-17 17:34:1698 AppendNumberToPath(&new_path, count);
initial.commit09911bf2008-07-26 23:55:2999
[email protected]7a256ea2008-10-17 17:34:16100 if (!file_util::PathExists(new_path))
101 return count;
initial.commit09911bf2008-07-26 23:55:29102 }
103
[email protected]7a256ea2008-10-17 17:34:16104 return -1;
initial.commit09911bf2008-07-26 23:55:29105}
106
[email protected]7ae7c2cb2009-01-06 23:31:41107static bool DownloadPathIsDangerous(const FilePath& download_path) {
108 FilePath desktop_dir;
[email protected]f052118e2008-09-05 02:25:32109 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
110 NOTREACHED();
111 return false;
112 }
113 return (download_path == desktop_dir);
114}
115
initial.commit09911bf2008-07-26 23:55:29116// DownloadItem implementation -------------------------------------------------
117
118// Constructor for reading from the history service.
119DownloadItem::DownloadItem(const DownloadCreateInfo& info)
120 : id_(-1),
121 full_path_(info.path),
122 url_(info.url),
[email protected]e435d6b72009-07-25 03:15:58123 referrer_url_(info.referrer_url),
124 mime_type_(info.mime_type),
initial.commit09911bf2008-07-26 23:55:29125 total_bytes_(info.total_bytes),
126 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56127 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29128 state_(static_cast<DownloadState>(info.state)),
129 start_time_(info.start_time),
130 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29131 manager_(NULL),
132 is_paused_(false),
133 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56134 safety_state_(SAFE),
[email protected]0aad67b2009-07-15 20:34:28135 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56136 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29137 render_process_id_(-1),
[email protected]6aa4a1c02010-01-15 18:49:58138 request_id_(-1),
139 save_as_(false),
140 name_finalized_(false),
141 is_temporary_(false) {
initial.commit09911bf2008-07-26 23:55:29142 if (state_ == IN_PROGRESS)
143 state_ = CANCELLED;
144 Init(false /* don't start progress timer */);
145}
146
147// Constructor for DownloadItem created via user action in the main thread.
148DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41149 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16150 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32151 const GURL& url,
[email protected]494c06e2009-07-25 01:06:42152 const GURL& referrer_url,
[email protected]e435d6b72009-07-25 03:15:58153 const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:41154 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59155 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29156 int64 download_size,
157 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32158 int request_id,
[email protected]67f373a2009-09-22 02:44:51159 bool is_dangerous,
[email protected]a60c8ae2009-12-25 06:50:57160 bool save_as,
[email protected]6aa4a1c02010-01-15 18:49:58161 bool is_extension_install,
162 bool is_temporary)
initial.commit09911bf2008-07-26 23:55:29163 : id_(download_id),
164 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16165 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29166 url_(url),
[email protected]494c06e2009-07-25 01:06:42167 referrer_url_(referrer_url),
[email protected]e435d6b72009-07-25 03:15:58168 mime_type_(mime_type),
initial.commit09911bf2008-07-26 23:55:29169 total_bytes_(download_size),
170 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56171 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29172 state_(IN_PROGRESS),
173 start_time_(start_time),
174 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29175 manager_(NULL),
176 is_paused_(false),
177 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56178 safety_state_(is_dangerous ? DANGEROUS : SAFE),
[email protected]0aad67b2009-07-15 20:34:28179 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56180 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29181 render_process_id_(render_process_id),
[email protected]67f373a2009-09-22 02:44:51182 request_id_(request_id),
[email protected]a60c8ae2009-12-25 06:50:57183 save_as_(save_as),
[email protected]6aa4a1c02010-01-15 18:49:58184 is_extension_install_(is_extension_install),
185 name_finalized_(false),
186 is_temporary_(is_temporary) {
initial.commit09911bf2008-07-26 23:55:29187 Init(true /* start progress timer */);
188}
189
190void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41191 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29192 if (start_timer)
193 StartProgressTimer();
194}
195
196DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29197 state_ = REMOVING;
198 UpdateObservers();
199}
200
201void DownloadItem::AddObserver(Observer* observer) {
202 observers_.AddObserver(observer);
203}
204
205void DownloadItem::RemoveObserver(Observer* observer) {
206 observers_.RemoveObserver(observer);
207}
208
209void DownloadItem::UpdateObservers() {
210 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
211}
212
[email protected]6aa4a1c02010-01-15 18:49:58213void DownloadItem::NotifyObserversDownloadFileCompleted() {
214 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadFileCompleted(this));
215}
216
[email protected]45e3c122009-04-07 19:58:03217void DownloadItem::NotifyObserversDownloadOpened() {
218 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadOpened(this));
219}
220
initial.commit09911bf2008-07-26 23:55:29221// If we've received more data than we were expecting (bad server info?), revert
222// to 'unknown size mode'.
223void DownloadItem::UpdateSize(int64 bytes_so_far) {
224 received_bytes_ = bytes_so_far;
225 if (received_bytes_ > total_bytes_)
226 total_bytes_ = 0;
227}
228
229// Updates from the download thread may have been posted while this download
230// was being cancelled in the UI thread, so we'll accept them unless we're
231// complete.
232void DownloadItem::Update(int64 bytes_so_far) {
233 if (state_ == COMPLETE) {
234 NOTREACHED();
235 return;
236 }
237 UpdateSize(bytes_so_far);
238 UpdateObservers();
239}
240
[email protected]6cade212008-12-03 00:32:22241// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29242void DownloadItem::Cancel(bool update_history) {
243 if (state_ != IN_PROGRESS) {
244 // Small downloads might be complete before this method has a chance to run.
245 return;
246 }
247 state_ = CANCELLED;
248 UpdateObservers();
249 StopProgressTimer();
250 if (update_history)
251 manager_->DownloadCancelled(id_);
252}
253
254void DownloadItem::Finished(int64 size) {
255 state_ = COMPLETE;
256 UpdateSize(size);
initial.commit09911bf2008-07-26 23:55:29257 StopProgressTimer();
258}
259
[email protected]9ccbb372008-10-10 18:50:32260void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29261 Cancel(true);
262 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32263 if (delete_on_disk)
264 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29265 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22266 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29267}
268
269void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59270 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14271 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29272}
273
274void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14275 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29276}
277
[email protected]e93d2822009-01-30 05:59:59278bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29279 if (total_bytes_ <= 0)
280 return false; // We never received the content_length for this download.
281
282 int64 speed = CurrentSpeed();
283 if (speed == 0)
284 return false;
285
286 *remaining =
[email protected]e93d2822009-01-30 05:59:59287 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29288 return true;
289}
290
291int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56292 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
293 int64 diff_ms = diff.InMilliseconds();
294 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29295}
296
297int DownloadItem::PercentComplete() const {
298 int percent = -1;
299 if (total_bytes_ > 0)
300 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
301 return percent;
302}
303
[email protected]7ae7c2cb2009-01-06 23:31:41304void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29305 DCHECK(!full_path.empty());
306 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41307 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29308}
309
310void DownloadItem::TogglePause() {
311 DCHECK(state_ == IN_PROGRESS);
312 manager_->PauseDownload(id_, !is_paused_);
313 is_paused_ = !is_paused_;
314 UpdateObservers();
315}
316
[email protected]7ae7c2cb2009-01-06 23:31:41317FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32318 if (safety_state_ == DownloadItem::SAFE)
319 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16320 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41321 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16322 AppendNumberToPath(&name, path_uniquifier_);
323 return name;
324 }
[email protected]9ccbb372008-10-10 18:50:32325 return original_name_;
326}
327
initial.commit09911bf2008-07-26 23:55:29328// DownloadManager implementation ----------------------------------------------
329
330// static
331void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
332 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
333 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32334 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
335
336 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41337 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12338 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
339 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32340 NOTREACHED();
341 }
[email protected]b9636002009-03-04 00:05:25342 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
343 default_download_path);
[email protected]f052118e2008-09-05 02:25:32344
345 // If the download path is dangerous we forcefully reset it. But if we do
346 // so we set a flag to make sure we only do it once, to avoid fighting
347 // the user if he really wants it on an unsafe place such as the desktop.
348
349 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41350 FilePath current_download_dir = FilePath::FromWStringHack(
351 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32352 if (DownloadPathIsDangerous(current_download_dir)) {
353 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41354 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32355 }
356 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
357 }
initial.commit09911bf2008-07-26 23:55:29358}
359
360DownloadManager::DownloadManager()
361 : shutdown_needed_(false),
362 profile_(NULL),
[email protected]d83d03aa2009-11-02 21:44:37363 file_manager_(NULL) {
initial.commit09911bf2008-07-26 23:55:29364}
365
366DownloadManager::~DownloadManager() {
367 if (shutdown_needed_)
368 Shutdown();
369}
370
371void DownloadManager::Shutdown() {
372 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
373
374 // Stop receiving download updates
375 file_manager_->RemoveDownloadManager(this);
376
377 // Stop making history service requests
378 cancelable_consumer_.CancelAllRequests();
379
380 // 'in_progress_' may contain DownloadItems that have not finished the start
381 // complete (from the history service) and thus aren't in downloads_.
382 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32383 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29384 for (; it != in_progress_.end(); ++it) {
385 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32386 if (download->safety_state() == DownloadItem::DANGEROUS) {
387 // Forget about any download that the user did not approve.
388 // Note that we cannot call download->Remove() this would invalidate our
389 // iterator.
390 to_remove.insert(download);
391 continue;
initial.commit09911bf2008-07-26 23:55:29392 }
[email protected]9ccbb372008-10-10 18:50:32393 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
394 download->Cancel(false);
395 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29396 if (download->db_handle() == kUninitializedHandle) {
397 // An invalid handle means that 'download' does not yet exist in
398 // 'downloads_', so we have to delete it here.
399 delete download;
400 }
401 }
402
[email protected]9ccbb372008-10-10 18:50:32403 // 'dangerous_finished_' contains all complete downloads that have not been
404 // approved. They should be removed.
405 it = dangerous_finished_.begin();
406 for (; it != dangerous_finished_.end(); ++it)
407 to_remove.insert(it->second);
408
409 // Remove the dangerous download that are not approved.
410 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
411 rm_it != to_remove.end(); ++rm_it) {
412 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32413 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32414 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32415 // Same as above, delete the download if it is not in 'downloads_' (as the
416 // Remove() call above won't have deleted it).
417 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32418 delete download;
419 }
420 to_remove.clear();
421
initial.commit09911bf2008-07-26 23:55:29422 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32423 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29424 STLDeleteValues(&downloads_);
425
426 file_manager_ = NULL;
427
428 // Save our file extensions to auto open.
429 SaveAutoOpens();
430
431 // Make sure the save as dialog doesn't notify us back if we're gone before
432 // it returns.
433 if (select_file_dialog_.get())
434 select_file_dialog_->ListenerDestroyed();
435
436 shutdown_needed_ = false;
437}
438
439// Issue a history query for downloads matching 'search_text'. If 'search_text'
440// is empty, return all downloads that we know about.
441void DownloadManager::GetDownloads(Observer* observer,
442 const std::wstring& search_text) {
443 DCHECK(observer);
444
445 // Return a empty list if we've not yet received the set of downloads from the
446 // history system (we'll update all observers once we get that list in
447 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
448 std::vector<DownloadItem*> download_copy;
449 if (downloads_.empty()) {
450 observer->SetDownloads(download_copy);
451 return;
452 }
453
454 // We already know all the downloads and there is no filter, so just return a
455 // copy to the observer.
456 if (search_text.empty()) {
457 download_copy.reserve(downloads_.size());
458 for (DownloadMap::iterator it = downloads_.begin();
459 it != downloads_.end(); ++it) {
[email protected]67f373a2009-09-22 02:44:51460 if (it->second->db_handle() > kUninitializedHandle)
461 download_copy.push_back(it->second);
initial.commit09911bf2008-07-26 23:55:29462 }
463
464 // We retain ownership of the DownloadItems.
465 observer->SetDownloads(download_copy);
466 return;
467 }
468
469 // Issue a request to the history service for a list of downloads matching
470 // our search text.
471 HistoryService* hs =
472 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
473 if (hs) {
474 HistoryService::Handle h =
475 hs->SearchDownloads(search_text,
476 &cancelable_consumer_,
477 NewCallback(this,
478 &DownloadManager::OnSearchComplete));
479 cancelable_consumer_.SetClientData(hs, h, observer);
480 }
481}
482
[email protected]6aa4a1c02010-01-15 18:49:58483void DownloadManager::GetTemporaryDownloads(Observer* observer,
484 const FilePath& dir_path) {
485 DCHECK(observer);
486
487 std::vector<DownloadItem*> download_copy;
488
489 for (DownloadMap::iterator it = downloads_.begin();
490 it != downloads_.end(); ++it) {
491 if (it->second->is_temporary() &&
492 it->second->full_path().DirName() == dir_path)
493 download_copy.push_back(it->second);
494 }
495
496 observer->SetDownloads(download_copy);
497}
498
initial.commit09911bf2008-07-26 23:55:29499// Query the history service for information about all persisted downloads.
500bool DownloadManager::Init(Profile* profile) {
501 DCHECK(profile);
502 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
503 shutdown_needed_ = true;
504
505 profile_ = profile;
[email protected]be180c802009-10-23 06:33:31506 request_context_getter_ = profile_->GetRequestContext();
initial.commit09911bf2008-07-26 23:55:29507
508 // 'incognito mode' will have access to past downloads, but we won't store
509 // information about new downloads while in that mode.
510 QueryHistoryForDownloads();
511
512 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
513 if (!rdh) {
514 NOTREACHED();
515 return false;
516 }
517
518 file_manager_ = rdh->download_file_manager();
519 if (!file_manager_) {
520 NOTREACHED();
521 return false;
522 }
523
initial.commit09911bf2008-07-26 23:55:29524 // Get our user preference state.
525 PrefService* prefs = profile_->GetPrefs();
526 DCHECK(prefs);
527 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
528
initial.commit09911bf2008-07-26 23:55:29529 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
530
[email protected]bb69e9b32008-08-14 23:08:14531 // Ensure that the download directory specified in the preferences exists.
[email protected]d83d03aa2009-11-02 21:44:37532 ChromeThread::PostTask(
533 ChromeThread::FILE, FROM_HERE,
[email protected]309b7642009-12-09 03:08:50534 NewRunnableFunction(&file_util::CreateDirectory, download_path()));
initial.commit09911bf2008-07-26 23:55:29535
[email protected]2b2f8f72009-02-24 22:42:05536 // We store any file extension that should be opened automatically at
537 // download completion in this pref.
initial.commit09911bf2008-07-26 23:55:29538 std::wstring extensions_to_open =
539 prefs->GetString(prefs::kDownloadExtensionsToOpen);
540 std::vector<std::wstring> extensions;
541 SplitString(extensions_to_open, L':', &extensions);
542 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]eccb9d12009-10-28 05:40:09543 if (!extensions[i].empty() && !IsExecutableFile(
544 FilePath::FromWStringHack(extensions[i])))
[email protected]b7f05882009-02-22 01:21:56545 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29546 }
547
548 return true;
549}
550
551void DownloadManager::QueryHistoryForDownloads() {
552 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
553 if (hs) {
554 hs->QueryDownloads(
555 &cancelable_consumer_,
556 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
557 }
558}
559
560// We have received a message from DownloadFileManager about a new download. We
561// create a download item and store it in our download map, and inform the
562// history system of a new download. Since this method can be called while the
563// history service thread is still reading the persistent state, we do not
564// insert the new DownloadItem into 'downloads_' or inform our observers at this
565// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
566// download creation as a callback from the history thread.
567void DownloadManager::StartDownload(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37568 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29569 DCHECK(info);
570
[email protected]a60c8ae2009-12-25 06:50:57571 // Check whether this download is for an extension install or not.
572 if (!info->save_as) { // Allow extensions to be explicitly saved.
573 if (UserScript::HasUserScriptFileExtension(info->url) ||
574 info->mime_type == Extension::kMimeType)
575 info->is_extension_install = true;
576 }
577
[email protected]7d3851d82008-12-12 03:26:07578 // Freeze the user's preference for showing a Save As dialog. We're going to
579 // bounce around a bunch of threads and we don't want to worry about race
580 // conditions where the user changes this pref out from under us.
[email protected]7bc4f702009-09-25 22:12:38581 if (*prompt_for_download_) {
582 // But never obey the preference for extension installation. Note that we
583 // only care here about the case where an extension is installed, not when
584 // one is downloaded with "save as...".
[email protected]a60c8ae2009-12-25 06:50:57585 if (!info->is_extension_install)
[email protected]7bc4f702009-09-25 22:12:38586 info->save_as = true;
587 }
[email protected]7d3851d82008-12-12 03:26:07588
[email protected]6aa4a1c02010-01-15 18:49:58589 // Determine the proper path for a download, by either one of the following:
590 // 1) using the provided save file path.
591 // 2) using the default download directory.
592 // 3) prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41593 FilePath generated_name;
[email protected]6aa4a1c02010-01-15 18:49:58594 GenerateFileNameFromInfo(info, &generated_name);
595 if (!info->save_file_path.empty())
596 info->suggested_path = info->save_file_path;
597 else if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29598 info->suggested_path = last_download_path_;
599 else
[email protected]7ae7c2cb2009-01-06 23:31:41600 info->suggested_path = download_path();
601 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29602
[email protected]6aa4a1c02010-01-15 18:49:58603 if (!info->save_as && info->save_file_path.empty()) {
[email protected]4289d9b2009-07-25 21:17:34604 // Downloads can be marked as dangerous for two reasons:
605 // a) They have a dangerous-looking filename
606 // b) They are an extension that is not from the gallery
607 if (IsDangerous(info->suggested_path.BaseName()))
608 info->is_dangerous = true;
[email protected]a60c8ae2009-12-25 06:50:57609 else if (info->is_extension_install &&
[email protected]b7c2f252009-12-08 00:47:23610 !ExtensionsService::IsDownloadFromGallery(info->url,
611 info->referrer_url)) {
[email protected]4289d9b2009-07-25 21:17:34612 info->is_dangerous = true;
613 }
[email protected]e9ebf3fc2008-10-17 22:06:58614 }
615
initial.commit09911bf2008-07-26 23:55:29616 // We need to move over to the download thread because we don't want to stat
617 // the suggested path on the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37618 ChromeThread::PostTask(
619 ChromeThread::FILE, FROM_HERE,
620 NewRunnableMethod(
621 this, &DownloadManager::CheckIfSuggestedPathExists, info));
initial.commit09911bf2008-07-26 23:55:29622}
623
624void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
625 DCHECK(info);
626
627 // Check writability of the suggested path. If we can't write to it, default
628 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41629 FilePath dir = info->suggested_path.DirName();
630 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32631 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29632 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29633 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41634 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29635 }
636
[email protected]7a256ea2008-10-17 17:34:16637 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29638
[email protected]6cade212008-12-03 00:32:22639 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58640 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41641 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32642 // Create a temporary file to hold the file until the user approves its
643 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41644 FilePath::StringType file_name;
645 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32646 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41647 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32648 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41649 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07650 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41651 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32652 }
653 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16654 } else {
655 // We know the final path, build it if necessary.
656 if (info->path_uniquifier > 0) {
657 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
658 // Setting path_uniquifier to 0 to make sure we don't try to unique it
659 // later on.
660 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07661 } else if (info->path_uniquifier == -1) {
662 // We failed to find a unique path. We have to prompt the user.
663 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16664 }
[email protected]9ccbb372008-10-10 18:50:32665 }
666
[email protected]7d3851d82008-12-12 03:26:07667 if (!info->save_as) {
668 // Create an empty file at the suggested path so that we don't allocate the
669 // same "non-existant" path to multiple downloads.
670 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ff3f632009-10-13 18:43:35671 file_util::WriteFile(info->suggested_path, "", 0);
[email protected]7d3851d82008-12-12 03:26:07672 }
673
initial.commit09911bf2008-07-26 23:55:29674 // Now we return to the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37675 ChromeThread::PostTask(
676 ChromeThread::UI, FROM_HERE,
initial.commit09911bf2008-07-26 23:55:29677 NewRunnableMethod(this,
678 &DownloadManager::OnPathExistenceAvailable,
679 info));
680}
681
682void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37683 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29684 DCHECK(info);
685
[email protected]7d3851d82008-12-12 03:26:07686 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29687 // We must ask the user for the place to put the download.
688 if (!select_file_dialog_.get())
689 select_file_dialog_ = SelectFileDialog::Create(this);
690
[email protected]76543b92009-08-31 17:27:45691 TabContents* contents = tab_util::GetTabContentsByID(info->child_id,
692 info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08693 SelectFileDialog::FileTypeInfo file_type_info;
694 file_type_info.extensions.resize(1);
695 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24696 if (!file_type_info.extensions[0][0].empty())
697 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08698 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23699 gfx::NativeWindow owning_window =
700 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29701 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34702 string16(),
703 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08704 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30705 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29706 } else {
707 // No prompting for download, just continue with the suggested name.
708 ContinueStartDownload(info, info->suggested_path);
709 }
710}
711
712void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41713 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29714 scoped_ptr<DownloadCreateInfo> infop(info);
715 info->path = target_path;
716
717 DownloadItem* download = NULL;
718 DownloadMap::iterator it = in_progress_.find(info->download_id);
719 if (it == in_progress_.end()) {
720 download = new DownloadItem(info->download_id,
721 info->path,
[email protected]7a256ea2008-10-17 17:34:16722 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29723 info->url,
[email protected]494c06e2009-07-25 01:06:42724 info->referrer_url,
[email protected]e435d6b72009-07-25 03:15:58725 info->mime_type,
[email protected]9ccbb372008-10-10 18:50:32726 info->original_name,
initial.commit09911bf2008-07-26 23:55:29727 info->start_time,
728 info->total_bytes,
[email protected]76543b92009-08-31 17:27:45729 info->child_id,
[email protected]9ccbb372008-10-10 18:50:32730 info->request_id,
[email protected]67f373a2009-09-22 02:44:51731 info->is_dangerous,
[email protected]a60c8ae2009-12-25 06:50:57732 info->save_as,
[email protected]6aa4a1c02010-01-15 18:49:58733 info->is_extension_install,
734 !info->save_file_path.empty());
initial.commit09911bf2008-07-26 23:55:29735 download->set_manager(this);
736 in_progress_[info->download_id] = download;
737 } else {
738 NOTREACHED(); // Should not exist!
739 return;
740 }
741
[email protected]6b323782009-03-27 18:43:08742 // Called before DownloadFinished in order to avoid a race condition where we
743 // attempt to open a completed download before it has been renamed.
[email protected]d83d03aa2009-11-02 21:44:37744 ChromeThread::PostTask(
745 ChromeThread::FILE, FROM_HERE,
746 NewRunnableMethod(
747 file_manager_, &DownloadFileManager::OnFinalDownloadName,
748 download->id(), target_path, this));
[email protected]6b323782009-03-27 18:43:08749
initial.commit09911bf2008-07-26 23:55:29750 // If the download already completed by the time we reached this point, then
751 // notify observers that it did.
752 PendingFinishedMap::iterator pending_it =
753 pending_finished_downloads_.find(info->download_id);
754 if (pending_it != pending_finished_downloads_.end())
755 DownloadFinished(pending_it->first, pending_it->second);
756
757 download->Rename(target_path);
758
[email protected]67f373a2009-09-22 02:44:51759 // Do not store the download in the history database for a few special cases:
760 // - incognito mode (that is the point of this mode)
761 // - extensions (users don't think of extension installation as 'downloading')
[email protected]6aa4a1c02010-01-15 18:49:58762 // - temporary download, like in drag-and-drop
[email protected]67f373a2009-09-22 02:44:51763 // We have to make sure that these handles don't collide with normal db
764 // handles, so we use a negative value. Eventually, they could overlap, but
765 // you'd have to do enough downloading that your ISP would likely stab you in
766 // the neck first. YMMV.
[email protected]6aa4a1c02010-01-15 18:49:58767 if (profile_->IsOffTheRecord() || download->is_extension_install() ||
768 download->is_temporary()) {
initial.commit09911bf2008-07-26 23:55:29769 static int64 fake_db_handle = kUninitializedHandle - 1;
770 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
771 } else {
772 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22773 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29774 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
775 if (hs) {
776 hs->CreateDownload(
777 *info, &cancelable_consumer_,
778 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
779 }
780 }
781}
782
783// Convenience function for updating the history service for a download.
784void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
785 DCHECK(download);
786
787 // Don't store info in the database if the download was initiated while in
788 // incognito mode or if it hasn't been initialized in our database table.
789 if (download->db_handle() <= kUninitializedHandle)
790 return;
791
[email protected]6cade212008-12-03 00:32:22792 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29793 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
794 if (hs) {
795 hs->UpdateDownload(download->received_bytes(),
796 download->state(),
797 download->db_handle());
798 }
799}
800
801void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
802 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22803 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29804 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
805 if (download->db_handle() > kUninitializedHandle && hs)
806 hs->RemoveDownload(download->db_handle());
807}
808
[email protected]e93d2822009-01-30 05:59:59809void DownloadManager::RemoveDownloadsFromHistoryBetween(
810 const base::Time remove_begin,
811 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22812 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29813 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
814 if (hs)
815 hs->RemoveDownloadsBetween(remove_begin, remove_end);
816}
817
818void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
819 DownloadMap::iterator it = in_progress_.find(download_id);
820 if (it != in_progress_.end()) {
821 DownloadItem* download = it->second;
822 download->Update(size);
823 UpdateHistoryForDownload(download);
824 }
825}
826
827void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
828 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32829 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29830 // The download is done, but the user hasn't selected a final location for
831 // it yet (the Save As dialog box is probably still showing), so just keep
832 // track of the fact that this download id is complete, when the
833 // DownloadItem is constructed later we'll notify its completion then.
834 PendingFinishedMap::iterator erase_it =
835 pending_finished_downloads_.find(download_id);
836 DCHECK(erase_it == pending_finished_downloads_.end());
837 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32838 return;
initial.commit09911bf2008-07-26 23:55:29839 }
[email protected]9ccbb372008-10-10 18:50:32840
841 // Remove the id from the list of pending ids.
842 PendingFinishedMap::iterator erase_it =
843 pending_finished_downloads_.find(download_id);
844 if (erase_it != pending_finished_downloads_.end())
845 pending_finished_downloads_.erase(erase_it);
846
847 DownloadItem* download = it->second;
848 download->Finished(size);
849
850 // Clean up will happen when the history system create callback runs if we
851 // don't have a valid db_handle yet.
852 if (download->db_handle() != kUninitializedHandle) {
853 in_progress_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32854 UpdateHistoryForDownload(download);
855 }
856
857 // If this a dangerous download not yet validated by the user, don't do
858 // anything. When the user notifies us, it will trigger a call to
859 // ProceedWithFinishedDangerousDownload.
860 if (download->safety_state() == DownloadItem::DANGEROUS) {
861 dangerous_finished_[download_id] = download;
862 return;
863 }
864
865 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22866 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32867 // its final name before we can continue.
[email protected]d83d03aa2009-11-02 21:44:37868 ChromeThread::PostTask(
869 ChromeThread::FILE, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32870 NewRunnableMethod(
871 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
872 download->db_handle(),
873 download->full_path(), download->original_name()));
874 return;
875 }
876 ContinueDownloadFinished(download);
877}
878
[email protected]8f783752009-04-01 23:33:45879void DownloadManager::DownloadRenamedToFinalName(int download_id,
880 const FilePath& full_path) {
[email protected]6aa4a1c02010-01-15 18:49:58881 DownloadMap::iterator it = downloads_.begin();
882 while (it != downloads_.end()) {
883 DownloadItem* download = it->second;
884 if (download->id() == download_id) {
885 // The download file is meant to be completed if both the filename is
886 // finalized and the file data is downloaded. The ordering of these two
887 // actions is indeterministic. Thus, if we are still in downloading the
888 // file, delay the notification.
889 download->set_name_finalized(true);
890 if (download->state() == DownloadItem::COMPLETE)
891 download->NotifyObserversDownloadFileCompleted();
892 return;
893 }
894 it++;
895 }
[email protected]8f783752009-04-01 23:33:45896}
897
[email protected]9ccbb372008-10-10 18:50:32898void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
899 // If this was a dangerous download, it has now been approved and must be
900 // removed from dangerous_finished_ so it does not get deleted on shutdown.
901 DownloadMap::iterator it = dangerous_finished_.find(download->id());
902 if (it != dangerous_finished_.end())
903 dangerous_finished_.erase(it);
904
[email protected]0aad67b2009-07-15 20:34:28905 // Handle chrome extensions explicitly and skip the shell execute.
[email protected]a60c8ae2009-12-25 06:50:57906 if (download->is_extension_install()) {
[email protected]494c06e2009-07-25 01:06:42907 OpenChromeExtension(download->full_path(), download->url(),
908 download->referrer_url());
[email protected]0aad67b2009-07-15 20:34:28909 download->set_auto_opened(true);
910 } else if (download->open_when_complete() ||
[email protected]6aa4a1c02010-01-15 18:49:58911 ShouldOpenFileBasedOnExtension(download->full_path()) ||
912 download->is_temporary()) {
913 // If the download is temporary, like in drag-and-drop, do not open it but
914 // we still need to set it auto-opened so that it can be removed from the
915 // download shelf.
916 if (!download->is_temporary())
917 OpenDownloadInShell(download, NULL);
[email protected]0aad67b2009-07-15 20:34:28918 download->set_auto_opened(true);
919 }
[email protected]9ccbb372008-10-10 18:50:32920
[email protected]0aad67b2009-07-15 20:34:28921 // Notify our observers that we are complete (the call to Finished() set the
922 // state to complete but did not notify).
923 download->UpdateObservers();
[email protected]6aa4a1c02010-01-15 18:49:58924
925 // The download file is meant to be completed if both the filename is
926 // finalized and the file data is downloaded. The ordering of these two
927 // actions is indeterministic. Thus, if the filename is not finalized yet,
928 // delay the notification.
929 if (download->name_finalized())
930 download->NotifyObserversDownloadFileCompleted();
[email protected]0aad67b2009-07-15 20:34:28931}
[email protected]eccb9d12009-10-28 05:40:09932
[email protected]9ccbb372008-10-10 18:50:32933// Called on the file thread. Renames the downloaded file to its original name.
934void DownloadManager::ProceedWithFinishedDangerousDownload(
935 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41936 const FilePath& path,
937 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32938 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41939 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16940 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32941 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24942 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16943 // Make our name unique at this point, as if a dangerous file is downloading
944 // and a 2nd download is started for a file with the same name, they would
945 // have the same path. This is because we uniquify the name on download
946 // start, and at that time the first file does not exists yet, so the second
947 // file gets the same name.
948 uniquifier = GetUniquePathNumber(new_path);
949 if (uniquifier > 0)
950 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32951 success = file_util::Move(path, new_path);
952 } else {
953 NOTREACHED();
954 }
[email protected]6cade212008-12-03 00:32:22955
[email protected]d83d03aa2009-11-02 21:44:37956 ChromeThread::PostTask(
957 ChromeThread::UI, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32958 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16959 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32960}
961
962// Call from the file thread when the finished dangerous download was renamed.
963void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
964 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41965 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16966 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32967 DownloadMap::iterator it = downloads_.find(download_handle);
968 if (it == downloads_.end()) {
969 NOTREACHED();
970 return;
971 }
972
973 DownloadItem* download = it->second;
974 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16975 if (success) {
976 // We need to update the path uniquifier so that the UI shows the right
977 // name when calling GetFileName().
978 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32979 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16980 }
[email protected]9ccbb372008-10-10 18:50:32981
982 // Continue the download finished sequence.
983 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29984}
985
986// static
initial.commit09911bf2008-07-26 23:55:29987void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
988 int render_process_id,
989 int request_id) {
[email protected]d85cf072009-10-27 03:59:31990 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
initial.commit09911bf2008-07-26 23:55:29991 rdh->CancelRequest(render_process_id, request_id, false);
992}
993
994void DownloadManager::DownloadCancelled(int32 download_id) {
995 DownloadMap::iterator it = in_progress_.find(download_id);
996 if (it == in_progress_.end())
997 return;
998 DownloadItem* download = it->second;
999
initial.commit09911bf2008-07-26 23:55:291000 // Clean up will happen when the history system create callback runs if we
1001 // don't have a valid db_handle yet.
1002 if (download->db_handle() != kUninitializedHandle) {
1003 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291004 UpdateHistoryForDownload(download);
1005 }
1006
[email protected]d7d1c5c2009-08-05 23:52:501007 DownloadCancelledInternal(download_id,
1008 download->render_process_id(),
1009 download->request_id());
1010}
1011
1012void DownloadManager::DownloadCancelledInternal(int download_id,
1013 int render_process_id,
1014 int request_id) {
[email protected]d85cf072009-10-27 03:59:311015 // Cancel the network request. RDH is guaranteed to outlive the IO thread.
1016 ChromeThread::PostTask(
1017 ChromeThread::IO, FROM_HERE,
1018 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
1019 g_browser_process->resource_dispatcher_host(),
1020 render_process_id,
1021 request_id));
[email protected]d7d1c5c2009-08-05 23:52:501022
initial.commit09911bf2008-07-26 23:55:291023 // Tell the file manager to cancel the download.
[email protected]d7d1c5c2009-08-05 23:52:501024 file_manager_->RemoveDownload(download_id, this); // On the UI thread
[email protected]d83d03aa2009-11-02 21:44:371025 ChromeThread::PostTask(
1026 ChromeThread::FILE, FROM_HERE,
1027 NewRunnableMethod(
1028 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:291029}
1030
1031void DownloadManager::PauseDownload(int32 download_id, bool pause) {
1032 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]d85cf072009-10-27 03:59:311033 if (it == in_progress_.end())
1034 return;
initial.commit09911bf2008-07-26 23:55:291035
[email protected]d85cf072009-10-27 03:59:311036 DownloadItem* download = it->second;
1037 if (pause == download->is_paused())
1038 return;
initial.commit09911bf2008-07-26 23:55:291039
[email protected]d85cf072009-10-27 03:59:311040 // Inform the ResourceDispatcherHost of the new pause state.
1041 ChromeThread::PostTask(
1042 ChromeThread::IO, FROM_HERE,
1043 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
1044 g_browser_process->resource_dispatcher_host(),
1045 download->render_process_id(),
1046 download->request_id(),
1047 pause));
initial.commit09911bf2008-07-26 23:55:291048}
1049
1050// static
1051void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
1052 int render_process_id,
1053 int request_id,
1054 bool pause) {
1055 rdh->PauseRequest(render_process_id, request_id, pause);
1056}
1057
[email protected]7ae7c2cb2009-01-06 23:31:411058bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:321059 // TODO(jcampan): Improve me.
[email protected]eccb9d12009-10-28 05:40:091060 return IsExecutableFile(file_name);
[email protected]9ccbb372008-10-10 18:50:321061}
1062
1063void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:411064 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:321065 download->Rename(new_path);
1066
1067 // Update the history.
1068
1069 // No update necessary if the download was initiated while in incognito mode.
1070 if (download->db_handle() <= kUninitializedHandle)
1071 return;
1072
[email protected]6cade212008-12-03 00:32:221073 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:321074 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1075 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:411076 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:321077}
1078
initial.commit09911bf2008-07-26 23:55:291079void DownloadManager::RemoveDownload(int64 download_handle) {
1080 DownloadMap::iterator it = downloads_.find(download_handle);
1081 if (it == downloads_.end())
1082 return;
1083
1084 // Make history update.
1085 DownloadItem* download = it->second;
1086 RemoveDownloadFromHistory(download);
1087
1088 // Remove from our tables and delete.
1089 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321090 it = dangerous_finished_.find(download->id());
1091 if (it != dangerous_finished_.end())
1092 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291093
1094 // Tell observers to refresh their views.
1095 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:361096
1097 delete download;
initial.commit09911bf2008-07-26 23:55:291098}
1099
[email protected]e93d2822009-01-30 05:59:591100int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1101 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291102 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1103
initial.commit09911bf2008-07-26 23:55:291104 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:281105 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:291106 while (it != downloads_.end()) {
1107 DownloadItem* download = it->second;
1108 DownloadItem::DownloadState state = download->state();
1109 if (download->start_time() >= remove_begin &&
1110 (remove_end.is_null() || download->start_time() < remove_end) &&
1111 (state == DownloadItem::COMPLETE ||
1112 state == DownloadItem::CANCELLED)) {
1113 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561114 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581115
1116 // Also remove it from any completed dangerous downloads.
1117 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1118 if (dit != dangerous_finished_.end())
1119 dangerous_finished_.erase(dit);
1120
[email protected]78b8fcc92009-03-31 17:36:281121 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:291122
initial.commit09911bf2008-07-26 23:55:291123 continue;
1124 }
1125
1126 ++it;
1127 }
1128
1129 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281130 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291131 if (num_deleted > 0)
1132 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1133
[email protected]78b8fcc92009-03-31 17:36:281134 // Delete the download items after updating the observers.
1135 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1136 pending_deletes.clear();
1137
initial.commit09911bf2008-07-26 23:55:291138 return num_deleted;
1139}
1140
[email protected]e93d2822009-01-30 05:59:591141int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1142 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291143}
1144
[email protected]d41355e6f2009-04-07 21:21:121145int DownloadManager::RemoveAllDownloads() {
1146 // The null times make the date range unbounded.
1147 return RemoveDownloadsBetween(base::Time(), base::Time());
1148}
1149
initial.commit09911bf2008-07-26 23:55:291150// Initiate a download of a specific URL. We send the request to the
1151// ResourceDispatcherHost, and let it send us responses like a regular
1152// download.
1153void DownloadManager::DownloadUrl(const GURL& url,
1154 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:501155 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:341156 TabContents* tab_contents) {
[email protected]6aa4a1c02010-01-15 18:49:581157 file_manager_->DownloadUrl(url,
1158 referrer,
1159 referrer_charset,
1160 FilePath(),
1161 tab_contents->process()->id(),
1162 tab_contents->render_view_host()->routing_id(),
1163 request_context_getter_);
1164}
1165
1166void DownloadManager::DownloadUrlToFile(const GURL& url,
1167 const GURL& referrer,
1168 const std::string& referrer_charset,
1169 const FilePath& save_file_path,
1170 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:341171 DCHECK(tab_contents);
initial.commit09911bf2008-07-26 23:55:291172 file_manager_->DownloadUrl(url,
1173 referrer,
[email protected]be180c802009-10-23 06:33:311174 referrer_charset,
[email protected]6aa4a1c02010-01-15 18:49:581175 save_file_path,
[email protected]76543b92009-08-31 17:27:451176 tab_contents->process()->id(),
[email protected]57c6a652009-05-04 07:58:341177 tab_contents->render_view_host()->routing_id(),
[email protected]be180c802009-10-23 06:33:311178 request_context_getter_);
initial.commit09911bf2008-07-26 23:55:291179}
1180
[email protected]7ae7c2cb2009-01-06 23:31:411181void DownloadManager::GenerateExtension(
1182 const FilePath& file_name,
1183 const std::string& mime_type,
1184 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291185 // We're worried about three things here:
1186 //
1187 // 1) Security. Many sites let users upload content, such as buddy icons, to
1188 // their web sites. We want to mitigate the case where an attacker
1189 // supplies a malicious executable with an executable file extension but an
1190 // honest site serves the content with a benign content type, such as
1191 // image/jpeg.
1192 //
1193 // 2) Usability. If the site fails to provide a file extension, we want to
1194 // guess a reasonable file extension based on the content type.
1195 //
1196 // 3) Shell integration. Some file extensions automatically integrate with
1197 // the shell. We block these extensions to prevent a malicious web site
1198 // from integrating with the user's shell.
1199
[email protected]7ae7c2cb2009-01-06 23:31:411200 static const FilePath::CharType default_extension[] =
1201 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291202
1203 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411204 FilePath::StringType extension(
1205 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291206
[email protected]b7f05882009-02-22 01:21:561207#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291208 // Rename shell-integrated extensions.
1209 if (win_util::IsShellIntegratedExtension(extension))
1210 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561211#endif
initial.commit09911bf2008-07-26 23:55:291212
1213 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411214 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411215 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291216 if (mime_type == mime_type_from_extension) {
1217 // The hinted extension matches the mime type. It looks like a winner.
1218 generated_extension->swap(extension);
1219 return;
1220 }
1221
[email protected]eccb9d12009-10-28 05:40:091222 if (IsExecutableExtension(extension) && !IsExecutableMimeType(mime_type)) {
initial.commit09911bf2008-07-26 23:55:291223 // We want to be careful about executable extensions. The worry here is
1224 // that a trusted web site could be tricked into dropping an executable file
1225 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101226 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291227 // We couldn't find a good extension for this content type. Use a dummy
1228 // extension instead.
1229 extension.assign(default_extension);
1230 }
1231 }
1232
1233 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101234 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291235 } else {
[email protected]6cade212008-12-03 00:32:221236 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291237 // 1. New extension is not ".txt"
1238 // 2. New extension is not the same as the already existing extension.
1239 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411240 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291241 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1242 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371243 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1244 // servers, i.e. bug 5772.
[email protected]e32642f62009-09-11 21:58:291245 // 5. The original extension is not ".tgz" & the new extension is not "gz".
[email protected]7ae7c2cb2009-01-06 23:31:411246 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101247 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171248 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411249 append_extension != extension &&
[email protected]eccb9d12009-10-28 05:40:091250 !IsExecutableExtension(append_extension) &&
[email protected]e32642f62009-09-11 21:58:291251 !(append_extension == FILE_PATH_LITERAL("gz") &&
1252 extension == FILE_PATH_LITERAL("tgz")) &&
[email protected]e106457b2009-03-25 22:43:371253 (append_extension != FILE_PATH_LITERAL("tar") ||
1254 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171255 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291256 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171257 }
initial.commit09911bf2008-07-26 23:55:291258 }
1259 }
1260
1261 generated_extension->swap(extension);
1262}
1263
[email protected]6aa4a1c02010-01-15 18:49:581264void DownloadManager::GenerateFileNameFromInfo(DownloadCreateInfo* info,
1265 FilePath* generated_name) {
1266 GenerateFileName(GURL(info->url),
1267 info->content_disposition,
1268 info->referrer_charset,
1269 info->mime_type,
1270 generated_name);
1271}
1272
1273void DownloadManager::GenerateFileName(const GURL& url,
1274 const std::string& content_disposition,
1275 const std::string& referrer_charset,
1276 const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411277 FilePath* generated_name) {
[email protected]630947c2009-11-04 18:37:311278 std::wstring default_name =
1279 l10n_util::GetString(IDS_DEFAULT_DOWNLOAD_FILENAME);
1280#if defined(OS_WIN)
1281 FilePath default_file_path(default_name);
1282#elif defined(OS_POSIX)
1283 FilePath default_file_path(base::SysWideToNativeMB(default_name));
1284#endif
1285
[email protected]6aa4a1c02010-01-15 18:49:581286 *generated_name = net::GetSuggestedFilename(GURL(url),
1287 content_disposition,
1288 referrer_charset,
[email protected]630947c2009-11-04 18:37:311289 default_file_path);
1290
[email protected]7ae7c2cb2009-01-06 23:31:411291 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291292
[email protected]6aa4a1c02010-01-15 18:49:581293 GenerateSafeFileName(mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291294}
1295
1296void DownloadManager::AddObserver(Observer* observer) {
1297 observers_.AddObserver(observer);
1298 observer->ModelChanged();
1299}
1300
1301void DownloadManager::RemoveObserver(Observer* observer) {
1302 observers_.RemoveObserver(observer);
1303}
1304
1305// Post Windows Shell operations to the Download thread, to avoid blocking the
1306// user interface.
1307void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1308 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:371309 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:581310#if defined(OS_MACOSX)
1311 // Mac needs to run this operation on the UI thread.
1312 platform_util::ShowItemInFolder(download->full_path());
1313#else
[email protected]d83d03aa2009-11-02 21:44:371314 ChromeThread::PostTask(
1315 ChromeThread::FILE, FROM_HERE,
1316 NewRunnableMethod(
1317 file_manager_, &DownloadFileManager::OnShowDownloadInShell,
1318 FilePath(download->full_path())));
[email protected]8b6ff012009-08-18 22:29:581319#endif
initial.commit09911bf2008-07-26 23:55:291320}
1321
[email protected]8f783752009-04-01 23:33:451322void DownloadManager::OpenDownload(const DownloadItem* download,
1323 gfx::NativeView parent_window) {
[email protected]0e34d7892009-06-05 19:17:401324 // Open Chrome extensions with ExtensionsService. For everything else do shell
[email protected]8f783752009-04-01 23:33:451325 // execute.
[email protected]a60c8ae2009-12-25 06:50:571326 if (download->is_extension_install()) {
[email protected]494c06e2009-07-25 01:06:421327 OpenChromeExtension(download->full_path(), download->url(),
1328 download->referrer_url());
[email protected]8f783752009-04-01 23:33:451329 } else {
1330 OpenDownloadInShell(download, parent_window);
1331 }
1332}
1333
[email protected]c1e432a2009-07-22 21:21:481334void DownloadManager::OpenChromeExtension(const FilePath& full_path,
[email protected]494c06e2009-07-25 01:06:421335 const GURL& download_url,
1336 const GURL& referrer_url) {
[email protected]6ef635e42009-07-26 06:16:121337 // We don't support extensions in OTR mode.
[email protected]2a464a92009-08-01 17:58:351338 ExtensionsService* service = profile_->GetExtensionsService();
1339 if (service) {
[email protected]91e1bd82009-09-03 22:04:401340 NotificationService* nservice = NotificationService::current();
[email protected]ac025282009-12-16 19:16:381341 GURL nonconst_download_url = download_url;
[email protected]91e1bd82009-09-03 22:04:401342 nservice->Notify(NotificationType::EXTENSION_READY_FOR_INSTALL,
1343 Source<DownloadManager>(this),
[email protected]ac025282009-12-16 19:16:381344 Details<GURL>(&nonconst_download_url));
[email protected]a050d712009-11-06 00:40:101345 if (UserScript::HasUserScriptFileExtension(download_url)) {
[email protected]6657afa62009-11-04 02:15:201346 CrxInstaller::InstallUserScript(
1347 full_path,
1348 download_url,
1349 service->install_directory(),
1350 true, // please delete crx on completion
1351 service,
1352 new ExtensionInstallUI(profile_));
1353 } else {
1354 CrxInstaller::Start(
1355 full_path,
1356 service->install_directory(),
1357 Extension::INTERNAL,
1358 "", // no expected id
1359 true, // please delete crx on completion
1360 true, // privilege increase allowed
1361 service,
1362 new ExtensionInstallUI(profile_));
1363 }
[email protected]2a464a92009-08-01 17:58:351364 }
[email protected]8f783752009-04-01 23:33:451365}
1366
initial.commit09911bf2008-07-26 23:55:291367void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591368 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291369 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:371370 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:581371#if defined(OS_MACOSX)
1372 // Mac OS X requires opening downloads on the UI thread.
1373 platform_util::OpenItem(download->full_path());
1374#else
[email protected]d83d03aa2009-11-02 21:44:371375 ChromeThread::PostTask(
1376 ChromeThread::FILE, FROM_HERE,
1377 NewRunnableMethod(
1378 file_manager_, &DownloadFileManager::OnOpenDownloadInShell,
1379 download->full_path(), download->url(), parent_window));
[email protected]8b6ff012009-08-18 22:29:581380#endif
initial.commit09911bf2008-07-26 23:55:291381}
1382
[email protected]eccb9d12009-10-28 05:40:091383void DownloadManager::OpenFilesBasedOnExtension(
1384 const FilePath& path, bool open) {
1385 FilePath::StringType extension = path.Extension();
1386 if (extension.empty())
1387 return;
1388 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1389 extension.erase(0, 1);
1390 if (open && !IsExecutableExtension(extension))
initial.commit09911bf2008-07-26 23:55:291391 auto_open_.insert(extension);
1392 else
1393 auto_open_.erase(extension);
1394 SaveAutoOpens();
1395}
1396
[email protected]eccb9d12009-10-28 05:40:091397bool DownloadManager::ShouldOpenFileBasedOnExtension(
1398 const FilePath& path) const {
[email protected]eccb9d12009-10-28 05:40:091399 FilePath::StringType extension = path.Extension();
1400 if (extension.empty())
1401 return false;
1402 if (IsExecutableExtension(extension))
1403 return false;
[email protected]92e11c82010-01-13 06:39:561404 if (Extension::IsExtension(path))
1405 return false;
[email protected]eccb9d12009-10-28 05:40:091406 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1407 extension.erase(0, 1);
[email protected]92e11c82010-01-13 06:39:561408 if (auto_open_.find(extension) != auto_open_.end())
[email protected]8c756ac2009-01-30 23:36:411409 return true;
initial.commit09911bf2008-07-26 23:55:291410 return false;
1411}
1412
[email protected]7b73d992008-12-15 20:56:461413static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291414 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461415 "text/javascript",
1416 "text/javascript;version=*",
[email protected]54d8d452009-04-08 17:29:241417 // Registry files can cause critical changes to the MS OS behavior.
1418 // Addition of this mimetype also addresses bug 7337.
1419 "text/x-registry",
[email protected]60ff8f912008-12-05 07:58:391420 // Some sites use binary/octet-stream to mean application/octet-stream.
1421 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461422 "binary/octet-stream"
1423};
initial.commit09911bf2008-07-26 23:55:291424
[email protected]7b73d992008-12-15 20:56:461425static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291426 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461427 "application/*+xml",
1428 "application/xml"
1429};
initial.commit09911bf2008-07-26 23:55:291430
[email protected]7b73d992008-12-15 20:56:461431// static
1432bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411433 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461434 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1435 return true;
1436 }
[email protected]bae0ea12009-02-14 01:20:411437 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461438 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1439 return false;
1440 }
1441 // We consider only other application types to be executable.
1442 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291443}
1444
[email protected]eccb9d12009-10-28 05:40:091445bool DownloadManager::IsExecutableFile(const FilePath& path) const {
1446 return IsExecutableExtension(path.Extension());
1447}
1448
1449bool DownloadManager::IsExecutableExtension(
[email protected]6aa4a1c02010-01-15 18:49:581450 const FilePath::StringType& extension) {
[email protected]eccb9d12009-10-28 05:40:091451 if (extension.empty())
1452 return false;
[email protected]64da0b932009-02-24 02:30:041453 if (!IsStringASCII(extension))
1454 return false;
[email protected]a0a9577b2009-05-27 23:52:321455#if defined(OS_WIN)
[email protected]64da0b932009-02-24 02:30:041456 std::string ascii_extension = WideToASCII(extension);
[email protected]e9ef0a62009-08-11 22:50:131457#elif defined(OS_POSIX)
[email protected]a0a9577b2009-05-27 23:52:321458 std::string ascii_extension = extension;
1459#endif
[email protected]64da0b932009-02-24 02:30:041460
[email protected]eccb9d12009-10-28 05:40:091461 // Strip out leading dot if it's still there
1462 if (ascii_extension[0] == FilePath::kExtensionSeparator)
1463 ascii_extension.erase(0, 1);
1464
[email protected]6aa4a1c02010-01-15 18:49:581465 return download_util::IsExecutableExtension(ascii_extension);
initial.commit09911bf2008-07-26 23:55:291466}
1467
1468void DownloadManager::ResetAutoOpenFiles() {
1469 auto_open_.clear();
1470 SaveAutoOpens();
1471}
1472
1473bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1474 return !auto_open_.empty();
1475}
1476
1477void DownloadManager::SaveAutoOpens() {
1478 PrefService* prefs = profile_->GetPrefs();
1479 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411480 FilePath::StringType extensions;
[email protected]eccb9d12009-10-28 05:40:091481 for (AutoOpenSet::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291482 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411483 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291484 }
1485 if (!extensions.empty())
1486 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561487
1488 std::wstring extensions_w;
1489#if defined(OS_WIN)
1490 extensions_w = extensions;
1491#elif defined(OS_POSIX)
[email protected]1b5044d2009-02-24 00:04:141492 extensions_w = base::SysNativeMBToWide(extensions);
[email protected]b7f05882009-02-22 01:21:561493#endif
1494
1495 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291496 }
1497}
1498
[email protected]561abe62009-04-06 18:08:341499void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361500 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291501 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071502 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411503 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291504 ContinueStartDownload(info, path);
1505}
1506
1507void DownloadManager::FileSelectionCanceled(void* params) {
1508 // The user didn't pick a place to save the file, so need to cancel the
1509 // download that's already in progress to the temporary location.
1510 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]d7d1c5c2009-08-05 23:52:501511 DownloadCancelledInternal(info->download_id,
[email protected]76543b92009-08-31 17:27:451512 info->child_id,
[email protected]d7d1c5c2009-08-05 23:52:501513 info->request_id);
initial.commit09911bf2008-07-26 23:55:291514}
1515
[email protected]7ae7c2cb2009-01-06 23:31:411516void DownloadManager::DeleteDownload(const FilePath& path) {
[email protected]d83d03aa2009-11-02 21:44:371517 ChromeThread::PostTask(
1518 ChromeThread::FILE, FROM_HERE,
1519 NewRunnableFunction(&DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321520}
1521
1522
1523void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1524 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1525 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1526 download->UpdateObservers();
1527
1528 // If the download is not complete, nothing to do. The required
1529 // post-processing will be performed when it does complete.
1530 if (download->state() != DownloadItem::COMPLETE)
1531 return;
1532
[email protected]d83d03aa2009-11-02 21:44:371533 ChromeThread::PostTask(
1534 ChromeThread::FILE, FROM_HERE,
1535 NewRunnableMethod(
1536 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
1537 download->db_handle(), download->full_path(),
1538 download->original_name()));
[email protected]9ccbb372008-10-10 18:50:321539}
1540
[email protected]6aa4a1c02010-01-15 18:49:581541void DownloadManager::GenerateSafeFileName(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411542 FilePath* file_name) {
1543 // Make sure we get the right file extension
1544 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391545 GenerateExtension(*file_name, mime_type, &extension);
1546 file_util::ReplaceExtension(file_name, extension);
1547
[email protected]2b2f8f72009-02-24 22:42:051548#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391549 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411550 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391551 DCHECK(!leaf_name.empty());
1552 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411553 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1554 *file_name = file_name->DirName();
1555 if (file_name->value() == FilePath::kCurrentDirectory) {
1556 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391557 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411558 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391559 }
1560 }
[email protected]b7f05882009-02-22 01:21:561561#endif
[email protected]763f946a2009-01-06 19:04:391562}
1563
initial.commit09911bf2008-07-26 23:55:291564// Operations posted to us from the history service ----------------------------
1565
1566// The history service has retrieved all download entries. 'entries' contains
1567// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1568void DownloadManager::OnQueryDownloadEntriesComplete(
1569 std::vector<DownloadCreateInfo>* entries) {
1570 for (size_t i = 0; i < entries->size(); ++i) {
1571 DownloadItem* download = new DownloadItem(entries->at(i));
1572 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1573 downloads_[download->db_handle()] = download;
1574 download->set_manager(this);
1575 }
1576 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1577}
1578
initial.commit09911bf2008-07-26 23:55:291579// Once the new DownloadItem's creation info has been committed to the history
1580// service, we associate the DownloadItem with the db handle, update our
1581// 'downloads_' map and inform observers.
1582void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1583 int64 db_handle) {
1584 DownloadMap::iterator it = in_progress_.find(info.download_id);
1585 DCHECK(it != in_progress_.end());
1586
1587 DownloadItem* download = it->second;
1588 DCHECK(download->db_handle() == kUninitializedHandle);
1589 download->set_db_handle(db_handle);
1590
1591 // Insert into our full map.
1592 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1593 downloads_[download->db_handle()] = download;
1594
[email protected]5e595482009-05-06 20:16:531595 // Show in the appropropriate browser UI.
1596 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291597
1598 // Inform interested objects about the new download.
1599 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
initial.commit09911bf2008-07-26 23:55:291600
1601 // If this download has been completed before we've received the db handle,
1602 // post one final message to the history service so that it can be properly
1603 // in sync with the DownloadItem's completion status, and also inform any
1604 // observers so that they get more than just the start notification.
1605 if (download->state() != DownloadItem::IN_PROGRESS) {
1606 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291607 UpdateHistoryForDownload(download);
1608 download->UpdateObservers();
1609 }
1610}
1611
1612// Called when the history service has retrieved the list of downloads that
1613// match the search text.
1614void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1615 std::vector<int64>* results) {
1616 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1617 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1618 if (!requestor)
1619 return;
1620
1621 std::vector<DownloadItem*> searched_downloads;
1622 for (std::vector<int64>::iterator it = results->begin();
1623 it != results->end(); ++it) {
1624 DownloadMap::iterator dit = downloads_.find(*it);
1625 if (dit != downloads_.end())
1626 searched_downloads.push_back(dit->second);
1627 }
1628
1629 requestor->SetDownloads(searched_downloads);
1630}
[email protected]905a08d2008-11-19 07:24:121631
[email protected]5e595482009-05-06 20:16:531632void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1633 DownloadItem* download) {
[email protected]5e595482009-05-06 20:16:531634 // The 'contents' may no longer exist if the user closed the tab before we get
1635 // this start completion event. If it does, tell the origin TabContents to
1636 // display its download shelf.
[email protected]76543b92009-08-31 17:27:451637 TabContents* contents = tab_util::GetTabContentsByID(info.child_id,
1638 info.render_view_id);
[email protected]5e595482009-05-06 20:16:531639
1640 // If the contents no longer exists, we start the download in the last active
1641 // browser. This is not ideal but better than fully hiding the download from
1642 // the user.
1643 if (!contents) {
1644 Browser* last_active = BrowserList::GetLastActive();
1645 if (last_active)
1646 contents = last_active->GetSelectedTabContents();
1647 }
1648
1649 if (contents)
1650 contents->OnStartDownload(download);
1651}
1652
[email protected]6cade212008-12-03 00:32:221653// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121654void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411655 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381656}
1657