blob: 21642efd2c9cce177b4cd6d33b5714d75c6a35c9 [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),
138 request_id_(-1) {
139 if (state_ == IN_PROGRESS)
140 state_ = CANCELLED;
141 Init(false /* don't start progress timer */);
142}
143
144// Constructor for DownloadItem created via user action in the main thread.
145DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41146 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16147 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32148 const GURL& url,
[email protected]494c06e2009-07-25 01:06:42149 const GURL& referrer_url,
[email protected]e435d6b72009-07-25 03:15:58150 const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:41151 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59152 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29153 int64 download_size,
154 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32155 int request_id,
[email protected]67f373a2009-09-22 02:44:51156 bool is_dangerous,
157 bool save_as)
initial.commit09911bf2008-07-26 23:55:29158 : id_(download_id),
159 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16160 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29161 url_(url),
[email protected]494c06e2009-07-25 01:06:42162 referrer_url_(referrer_url),
[email protected]e435d6b72009-07-25 03:15:58163 mime_type_(mime_type),
initial.commit09911bf2008-07-26 23:55:29164 total_bytes_(download_size),
165 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56166 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29167 state_(IN_PROGRESS),
168 start_time_(start_time),
169 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29170 manager_(NULL),
171 is_paused_(false),
172 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56173 safety_state_(is_dangerous ? DANGEROUS : SAFE),
[email protected]0aad67b2009-07-15 20:34:28174 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56175 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29176 render_process_id_(render_process_id),
[email protected]67f373a2009-09-22 02:44:51177 request_id_(request_id),
178 save_as_(save_as) {
initial.commit09911bf2008-07-26 23:55:29179 Init(true /* start progress timer */);
180}
181
182void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41183 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29184 if (start_timer)
185 StartProgressTimer();
186}
187
188DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29189 state_ = REMOVING;
190 UpdateObservers();
191}
192
193void DownloadItem::AddObserver(Observer* observer) {
194 observers_.AddObserver(observer);
195}
196
197void DownloadItem::RemoveObserver(Observer* observer) {
198 observers_.RemoveObserver(observer);
199}
200
201void DownloadItem::UpdateObservers() {
202 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
203}
204
[email protected]45e3c122009-04-07 19:58:03205void DownloadItem::NotifyObserversDownloadOpened() {
206 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadOpened(this));
207}
208
initial.commit09911bf2008-07-26 23:55:29209// If we've received more data than we were expecting (bad server info?), revert
210// to 'unknown size mode'.
211void DownloadItem::UpdateSize(int64 bytes_so_far) {
212 received_bytes_ = bytes_so_far;
213 if (received_bytes_ > total_bytes_)
214 total_bytes_ = 0;
215}
216
217// Updates from the download thread may have been posted while this download
218// was being cancelled in the UI thread, so we'll accept them unless we're
219// complete.
220void DownloadItem::Update(int64 bytes_so_far) {
221 if (state_ == COMPLETE) {
222 NOTREACHED();
223 return;
224 }
225 UpdateSize(bytes_so_far);
226 UpdateObservers();
227}
228
[email protected]6cade212008-12-03 00:32:22229// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29230void DownloadItem::Cancel(bool update_history) {
231 if (state_ != IN_PROGRESS) {
232 // Small downloads might be complete before this method has a chance to run.
233 return;
234 }
235 state_ = CANCELLED;
236 UpdateObservers();
237 StopProgressTimer();
238 if (update_history)
239 manager_->DownloadCancelled(id_);
240}
241
242void DownloadItem::Finished(int64 size) {
243 state_ = COMPLETE;
244 UpdateSize(size);
initial.commit09911bf2008-07-26 23:55:29245 StopProgressTimer();
246}
247
[email protected]9ccbb372008-10-10 18:50:32248void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29249 Cancel(true);
250 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32251 if (delete_on_disk)
252 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29253 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22254 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29255}
256
257void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59258 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14259 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29260}
261
262void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14263 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29264}
265
[email protected]e93d2822009-01-30 05:59:59266bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29267 if (total_bytes_ <= 0)
268 return false; // We never received the content_length for this download.
269
270 int64 speed = CurrentSpeed();
271 if (speed == 0)
272 return false;
273
274 *remaining =
[email protected]e93d2822009-01-30 05:59:59275 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29276 return true;
277}
278
279int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56280 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
281 int64 diff_ms = diff.InMilliseconds();
282 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29283}
284
285int DownloadItem::PercentComplete() const {
286 int percent = -1;
287 if (total_bytes_ > 0)
288 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
289 return percent;
290}
291
[email protected]7ae7c2cb2009-01-06 23:31:41292void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29293 DCHECK(!full_path.empty());
294 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41295 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29296}
297
298void DownloadItem::TogglePause() {
299 DCHECK(state_ == IN_PROGRESS);
300 manager_->PauseDownload(id_, !is_paused_);
301 is_paused_ = !is_paused_;
302 UpdateObservers();
303}
304
[email protected]7ae7c2cb2009-01-06 23:31:41305FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32306 if (safety_state_ == DownloadItem::SAFE)
307 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16308 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41309 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16310 AppendNumberToPath(&name, path_uniquifier_);
311 return name;
312 }
[email protected]9ccbb372008-10-10 18:50:32313 return original_name_;
314}
315
initial.commit09911bf2008-07-26 23:55:29316// DownloadManager implementation ----------------------------------------------
317
318// static
319void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
320 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
321 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32322 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
323
324 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41325 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12326 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
327 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32328 NOTREACHED();
329 }
[email protected]b9636002009-03-04 00:05:25330 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
331 default_download_path);
[email protected]f052118e2008-09-05 02:25:32332
333 // If the download path is dangerous we forcefully reset it. But if we do
334 // so we set a flag to make sure we only do it once, to avoid fighting
335 // the user if he really wants it on an unsafe place such as the desktop.
336
337 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41338 FilePath current_download_dir = FilePath::FromWStringHack(
339 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32340 if (DownloadPathIsDangerous(current_download_dir)) {
341 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41342 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32343 }
344 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
345 }
initial.commit09911bf2008-07-26 23:55:29346}
347
348DownloadManager::DownloadManager()
349 : shutdown_needed_(false),
350 profile_(NULL),
[email protected]d83d03aa2009-11-02 21:44:37351 file_manager_(NULL) {
initial.commit09911bf2008-07-26 23:55:29352}
353
354DownloadManager::~DownloadManager() {
355 if (shutdown_needed_)
356 Shutdown();
357}
358
359void DownloadManager::Shutdown() {
360 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
361
362 // Stop receiving download updates
363 file_manager_->RemoveDownloadManager(this);
364
365 // Stop making history service requests
366 cancelable_consumer_.CancelAllRequests();
367
368 // 'in_progress_' may contain DownloadItems that have not finished the start
369 // complete (from the history service) and thus aren't in downloads_.
370 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32371 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29372 for (; it != in_progress_.end(); ++it) {
373 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32374 if (download->safety_state() == DownloadItem::DANGEROUS) {
375 // Forget about any download that the user did not approve.
376 // Note that we cannot call download->Remove() this would invalidate our
377 // iterator.
378 to_remove.insert(download);
379 continue;
initial.commit09911bf2008-07-26 23:55:29380 }
[email protected]9ccbb372008-10-10 18:50:32381 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
382 download->Cancel(false);
383 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29384 if (download->db_handle() == kUninitializedHandle) {
385 // An invalid handle means that 'download' does not yet exist in
386 // 'downloads_', so we have to delete it here.
387 delete download;
388 }
389 }
390
[email protected]9ccbb372008-10-10 18:50:32391 // 'dangerous_finished_' contains all complete downloads that have not been
392 // approved. They should be removed.
393 it = dangerous_finished_.begin();
394 for (; it != dangerous_finished_.end(); ++it)
395 to_remove.insert(it->second);
396
397 // Remove the dangerous download that are not approved.
398 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
399 rm_it != to_remove.end(); ++rm_it) {
400 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32401 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32402 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32403 // Same as above, delete the download if it is not in 'downloads_' (as the
404 // Remove() call above won't have deleted it).
405 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32406 delete download;
407 }
408 to_remove.clear();
409
initial.commit09911bf2008-07-26 23:55:29410 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32411 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29412 STLDeleteValues(&downloads_);
413
414 file_manager_ = NULL;
415
416 // Save our file extensions to auto open.
417 SaveAutoOpens();
418
419 // Make sure the save as dialog doesn't notify us back if we're gone before
420 // it returns.
421 if (select_file_dialog_.get())
422 select_file_dialog_->ListenerDestroyed();
423
424 shutdown_needed_ = false;
425}
426
427// Issue a history query for downloads matching 'search_text'. If 'search_text'
428// is empty, return all downloads that we know about.
429void DownloadManager::GetDownloads(Observer* observer,
430 const std::wstring& search_text) {
431 DCHECK(observer);
432
433 // Return a empty list if we've not yet received the set of downloads from the
434 // history system (we'll update all observers once we get that list in
435 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
436 std::vector<DownloadItem*> download_copy;
437 if (downloads_.empty()) {
438 observer->SetDownloads(download_copy);
439 return;
440 }
441
442 // We already know all the downloads and there is no filter, so just return a
443 // copy to the observer.
444 if (search_text.empty()) {
445 download_copy.reserve(downloads_.size());
446 for (DownloadMap::iterator it = downloads_.begin();
447 it != downloads_.end(); ++it) {
[email protected]67f373a2009-09-22 02:44:51448 if (it->second->db_handle() > kUninitializedHandle)
449 download_copy.push_back(it->second);
initial.commit09911bf2008-07-26 23:55:29450 }
451
452 // We retain ownership of the DownloadItems.
453 observer->SetDownloads(download_copy);
454 return;
455 }
456
457 // Issue a request to the history service for a list of downloads matching
458 // our search text.
459 HistoryService* hs =
460 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
461 if (hs) {
462 HistoryService::Handle h =
463 hs->SearchDownloads(search_text,
464 &cancelable_consumer_,
465 NewCallback(this,
466 &DownloadManager::OnSearchComplete));
467 cancelable_consumer_.SetClientData(hs, h, observer);
468 }
469}
470
471// Query the history service for information about all persisted downloads.
472bool DownloadManager::Init(Profile* profile) {
473 DCHECK(profile);
474 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
475 shutdown_needed_ = true;
476
477 profile_ = profile;
[email protected]be180c802009-10-23 06:33:31478 request_context_getter_ = profile_->GetRequestContext();
initial.commit09911bf2008-07-26 23:55:29479
480 // 'incognito mode' will have access to past downloads, but we won't store
481 // information about new downloads while in that mode.
482 QueryHistoryForDownloads();
483
484 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
485 if (!rdh) {
486 NOTREACHED();
487 return false;
488 }
489
490 file_manager_ = rdh->download_file_manager();
491 if (!file_manager_) {
492 NOTREACHED();
493 return false;
494 }
495
initial.commit09911bf2008-07-26 23:55:29496 // Get our user preference state.
497 PrefService* prefs = profile_->GetPrefs();
498 DCHECK(prefs);
499 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
500
initial.commit09911bf2008-07-26 23:55:29501 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
502
[email protected]bb69e9b32008-08-14 23:08:14503 // Ensure that the download directory specified in the preferences exists.
[email protected]d83d03aa2009-11-02 21:44:37504 ChromeThread::PostTask(
505 ChromeThread::FILE, FROM_HERE,
[email protected]309b7642009-12-09 03:08:50506 NewRunnableFunction(&file_util::CreateDirectory, download_path()));
initial.commit09911bf2008-07-26 23:55:29507
[email protected]a0a9577b2009-05-27 23:52:32508 // We use this to determine possibly dangerous downloads.
[email protected]2b2f8f72009-02-24 22:42:05509 download_util::InitializeExeTypes(&exe_types_);
[email protected]2b2f8f72009-02-24 22:42:05510
511 // We store any file extension that should be opened automatically at
512 // download completion in this pref.
initial.commit09911bf2008-07-26 23:55:29513 std::wstring extensions_to_open =
514 prefs->GetString(prefs::kDownloadExtensionsToOpen);
515 std::vector<std::wstring> extensions;
516 SplitString(extensions_to_open, L':', &extensions);
517 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]eccb9d12009-10-28 05:40:09518 if (!extensions[i].empty() && !IsExecutableFile(
519 FilePath::FromWStringHack(extensions[i])))
[email protected]b7f05882009-02-22 01:21:56520 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29521 }
522
523 return true;
524}
525
526void DownloadManager::QueryHistoryForDownloads() {
527 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
528 if (hs) {
529 hs->QueryDownloads(
530 &cancelable_consumer_,
531 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
532 }
533}
534
535// We have received a message from DownloadFileManager about a new download. We
536// create a download item and store it in our download map, and inform the
537// history system of a new download. Since this method can be called while the
538// history service thread is still reading the persistent state, we do not
539// insert the new DownloadItem into 'downloads_' or inform our observers at this
540// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
541// download creation as a callback from the history thread.
542void DownloadManager::StartDownload(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37543 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29544 DCHECK(info);
545
[email protected]7d3851d82008-12-12 03:26:07546 // Freeze the user's preference for showing a Save As dialog. We're going to
547 // bounce around a bunch of threads and we don't want to worry about race
548 // conditions where the user changes this pref out from under us.
[email protected]7bc4f702009-09-25 22:12:38549 if (*prompt_for_download_) {
550 // But never obey the preference for extension installation. Note that we
551 // only care here about the case where an extension is installed, not when
552 // one is downloaded with "save as...".
553 if (!IsExtensionInstall(info))
554 info->save_as = true;
555 }
[email protected]7d3851d82008-12-12 03:26:07556
initial.commit09911bf2008-07-26 23:55:29557 // Determine the proper path for a download, by choosing either the default
558 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41559 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29560 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07561 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29562 info->suggested_path = last_download_path_;
563 else
[email protected]7ae7c2cb2009-01-06 23:31:41564 info->suggested_path = download_path();
565 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29566
[email protected]7d3851d82008-12-12 03:26:07567 if (!info->save_as) {
[email protected]4289d9b2009-07-25 21:17:34568 // Downloads can be marked as dangerous for two reasons:
569 // a) They have a dangerous-looking filename
570 // b) They are an extension that is not from the gallery
571 if (IsDangerous(info->suggested_path.BaseName()))
572 info->is_dangerous = true;
[email protected]67f373a2009-09-22 02:44:51573 else if (IsExtensionInstall(info) &&
[email protected]b7c2f252009-12-08 00:47:23574 !ExtensionsService::IsDownloadFromGallery(info->url,
575 info->referrer_url)) {
[email protected]4289d9b2009-07-25 21:17:34576 info->is_dangerous = true;
577 }
[email protected]e9ebf3fc2008-10-17 22:06:58578 }
579
initial.commit09911bf2008-07-26 23:55:29580 // We need to move over to the download thread because we don't want to stat
581 // the suggested path on the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37582 ChromeThread::PostTask(
583 ChromeThread::FILE, FROM_HERE,
584 NewRunnableMethod(
585 this, &DownloadManager::CheckIfSuggestedPathExists, info));
initial.commit09911bf2008-07-26 23:55:29586}
587
588void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
589 DCHECK(info);
590
591 // Check writability of the suggested path. If we can't write to it, default
592 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41593 FilePath dir = info->suggested_path.DirName();
594 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32595 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29596 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29597 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41598 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29599 }
600
[email protected]7a256ea2008-10-17 17:34:16601 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29602
[email protected]6cade212008-12-03 00:32:22603 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58604 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41605 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32606 // Create a temporary file to hold the file until the user approves its
607 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41608 FilePath::StringType file_name;
609 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32610 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41611 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32612 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41613 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07614 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41615 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32616 }
617 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16618 } else {
619 // We know the final path, build it if necessary.
620 if (info->path_uniquifier > 0) {
621 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
622 // Setting path_uniquifier to 0 to make sure we don't try to unique it
623 // later on.
624 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07625 } else if (info->path_uniquifier == -1) {
626 // We failed to find a unique path. We have to prompt the user.
627 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16628 }
[email protected]9ccbb372008-10-10 18:50:32629 }
630
[email protected]7d3851d82008-12-12 03:26:07631 if (!info->save_as) {
632 // Create an empty file at the suggested path so that we don't allocate the
633 // same "non-existant" path to multiple downloads.
634 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ff3f632009-10-13 18:43:35635 file_util::WriteFile(info->suggested_path, "", 0);
[email protected]7d3851d82008-12-12 03:26:07636 }
637
initial.commit09911bf2008-07-26 23:55:29638 // Now we return to the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37639 ChromeThread::PostTask(
640 ChromeThread::UI, FROM_HERE,
initial.commit09911bf2008-07-26 23:55:29641 NewRunnableMethod(this,
642 &DownloadManager::OnPathExistenceAvailable,
643 info));
644}
645
646void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37647 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29648 DCHECK(info);
649
[email protected]7d3851d82008-12-12 03:26:07650 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29651 // We must ask the user for the place to put the download.
652 if (!select_file_dialog_.get())
653 select_file_dialog_ = SelectFileDialog::Create(this);
654
[email protected]76543b92009-08-31 17:27:45655 TabContents* contents = tab_util::GetTabContentsByID(info->child_id,
656 info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08657 SelectFileDialog::FileTypeInfo file_type_info;
658 file_type_info.extensions.resize(1);
659 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24660 if (!file_type_info.extensions[0][0].empty())
661 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08662 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23663 gfx::NativeWindow owning_window =
664 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29665 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34666 string16(),
667 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08668 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30669 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29670 } else {
671 // No prompting for download, just continue with the suggested name.
672 ContinueStartDownload(info, info->suggested_path);
673 }
674}
675
676void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41677 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29678 scoped_ptr<DownloadCreateInfo> infop(info);
679 info->path = target_path;
680
681 DownloadItem* download = NULL;
682 DownloadMap::iterator it = in_progress_.find(info->download_id);
683 if (it == in_progress_.end()) {
684 download = new DownloadItem(info->download_id,
685 info->path,
[email protected]7a256ea2008-10-17 17:34:16686 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29687 info->url,
[email protected]494c06e2009-07-25 01:06:42688 info->referrer_url,
[email protected]e435d6b72009-07-25 03:15:58689 info->mime_type,
[email protected]9ccbb372008-10-10 18:50:32690 info->original_name,
initial.commit09911bf2008-07-26 23:55:29691 info->start_time,
692 info->total_bytes,
[email protected]76543b92009-08-31 17:27:45693 info->child_id,
[email protected]9ccbb372008-10-10 18:50:32694 info->request_id,
[email protected]67f373a2009-09-22 02:44:51695 info->is_dangerous,
696 info->save_as);
initial.commit09911bf2008-07-26 23:55:29697 download->set_manager(this);
698 in_progress_[info->download_id] = download;
699 } else {
700 NOTREACHED(); // Should not exist!
701 return;
702 }
703
[email protected]6b323782009-03-27 18:43:08704 // Called before DownloadFinished in order to avoid a race condition where we
705 // attempt to open a completed download before it has been renamed.
[email protected]d83d03aa2009-11-02 21:44:37706 ChromeThread::PostTask(
707 ChromeThread::FILE, FROM_HERE,
708 NewRunnableMethod(
709 file_manager_, &DownloadFileManager::OnFinalDownloadName,
710 download->id(), target_path, this));
[email protected]6b323782009-03-27 18:43:08711
initial.commit09911bf2008-07-26 23:55:29712 // If the download already completed by the time we reached this point, then
713 // notify observers that it did.
714 PendingFinishedMap::iterator pending_it =
715 pending_finished_downloads_.find(info->download_id);
716 if (pending_it != pending_finished_downloads_.end())
717 DownloadFinished(pending_it->first, pending_it->second);
718
719 download->Rename(target_path);
720
[email protected]67f373a2009-09-22 02:44:51721 // Do not store the download in the history database for a few special cases:
722 // - incognito mode (that is the point of this mode)
723 // - extensions (users don't think of extension installation as 'downloading')
724 // We have to make sure that these handles don't collide with normal db
725 // handles, so we use a negative value. Eventually, they could overlap, but
726 // you'd have to do enough downloading that your ISP would likely stab you in
727 // the neck first. YMMV.
728 if (profile_->IsOffTheRecord() || IsExtensionInstall(download)) {
initial.commit09911bf2008-07-26 23:55:29729 static int64 fake_db_handle = kUninitializedHandle - 1;
730 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
731 } else {
732 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22733 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29734 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
735 if (hs) {
736 hs->CreateDownload(
737 *info, &cancelable_consumer_,
738 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
739 }
740 }
741}
742
743// Convenience function for updating the history service for a download.
744void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
745 DCHECK(download);
746
747 // Don't store info in the database if the download was initiated while in
748 // incognito mode or if it hasn't been initialized in our database table.
749 if (download->db_handle() <= kUninitializedHandle)
750 return;
751
[email protected]6cade212008-12-03 00:32:22752 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29753 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
754 if (hs) {
755 hs->UpdateDownload(download->received_bytes(),
756 download->state(),
757 download->db_handle());
758 }
759}
760
761void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
762 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22763 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29764 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
765 if (download->db_handle() > kUninitializedHandle && hs)
766 hs->RemoveDownload(download->db_handle());
767}
768
[email protected]e93d2822009-01-30 05:59:59769void DownloadManager::RemoveDownloadsFromHistoryBetween(
770 const base::Time remove_begin,
771 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22772 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29773 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
774 if (hs)
775 hs->RemoveDownloadsBetween(remove_begin, remove_end);
776}
777
778void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
779 DownloadMap::iterator it = in_progress_.find(download_id);
780 if (it != in_progress_.end()) {
781 DownloadItem* download = it->second;
782 download->Update(size);
783 UpdateHistoryForDownload(download);
784 }
785}
786
787void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
788 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32789 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29790 // The download is done, but the user hasn't selected a final location for
791 // it yet (the Save As dialog box is probably still showing), so just keep
792 // track of the fact that this download id is complete, when the
793 // DownloadItem is constructed later we'll notify its completion then.
794 PendingFinishedMap::iterator erase_it =
795 pending_finished_downloads_.find(download_id);
796 DCHECK(erase_it == pending_finished_downloads_.end());
797 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32798 return;
initial.commit09911bf2008-07-26 23:55:29799 }
[email protected]9ccbb372008-10-10 18:50:32800
801 // Remove the id from the list of pending ids.
802 PendingFinishedMap::iterator erase_it =
803 pending_finished_downloads_.find(download_id);
804 if (erase_it != pending_finished_downloads_.end())
805 pending_finished_downloads_.erase(erase_it);
806
807 DownloadItem* download = it->second;
808 download->Finished(size);
809
810 // Clean up will happen when the history system create callback runs if we
811 // don't have a valid db_handle yet.
812 if (download->db_handle() != kUninitializedHandle) {
813 in_progress_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32814 UpdateHistoryForDownload(download);
815 }
816
817 // If this a dangerous download not yet validated by the user, don't do
818 // anything. When the user notifies us, it will trigger a call to
819 // ProceedWithFinishedDangerousDownload.
820 if (download->safety_state() == DownloadItem::DANGEROUS) {
821 dangerous_finished_[download_id] = download;
822 return;
823 }
824
825 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22826 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32827 // its final name before we can continue.
[email protected]d83d03aa2009-11-02 21:44:37828 ChromeThread::PostTask(
829 ChromeThread::FILE, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32830 NewRunnableMethod(
831 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
832 download->db_handle(),
833 download->full_path(), download->original_name()));
834 return;
835 }
836 ContinueDownloadFinished(download);
837}
838
[email protected]8f783752009-04-01 23:33:45839void DownloadManager::DownloadRenamedToFinalName(int download_id,
840 const FilePath& full_path) {
[email protected]8f783752009-04-01 23:33:45841}
842
[email protected]9ccbb372008-10-10 18:50:32843void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
844 // If this was a dangerous download, it has now been approved and must be
845 // removed from dangerous_finished_ so it does not get deleted on shutdown.
846 DownloadMap::iterator it = dangerous_finished_.find(download->id());
847 if (it != dangerous_finished_.end())
848 dangerous_finished_.erase(it);
849
[email protected]0aad67b2009-07-15 20:34:28850 // Handle chrome extensions explicitly and skip the shell execute.
[email protected]67f373a2009-09-22 02:44:51851 if (IsExtensionInstall(download)) {
[email protected]494c06e2009-07-25 01:06:42852 OpenChromeExtension(download->full_path(), download->url(),
853 download->referrer_url());
[email protected]0aad67b2009-07-15 20:34:28854 download->set_auto_opened(true);
855 } else if (download->open_when_complete() ||
[email protected]eccb9d12009-10-28 05:40:09856 ShouldOpenFileBasedOnExtension(download->full_path())) {
[email protected]9ccbb372008-10-10 18:50:32857 OpenDownloadInShell(download, NULL);
[email protected]0aad67b2009-07-15 20:34:28858 download->set_auto_opened(true);
859 }
[email protected]9ccbb372008-10-10 18:50:32860
[email protected]0aad67b2009-07-15 20:34:28861 // Notify our observers that we are complete (the call to Finished() set the
862 // state to complete but did not notify).
863 download->UpdateObservers();
864}
[email protected]eccb9d12009-10-28 05:40:09865
[email protected]9ccbb372008-10-10 18:50:32866// Called on the file thread. Renames the downloaded file to its original name.
867void DownloadManager::ProceedWithFinishedDangerousDownload(
868 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41869 const FilePath& path,
870 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32871 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41872 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16873 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32874 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24875 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16876 // Make our name unique at this point, as if a dangerous file is downloading
877 // and a 2nd download is started for a file with the same name, they would
878 // have the same path. This is because we uniquify the name on download
879 // start, and at that time the first file does not exists yet, so the second
880 // file gets the same name.
881 uniquifier = GetUniquePathNumber(new_path);
882 if (uniquifier > 0)
883 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32884 success = file_util::Move(path, new_path);
885 } else {
886 NOTREACHED();
887 }
[email protected]6cade212008-12-03 00:32:22888
[email protected]d83d03aa2009-11-02 21:44:37889 ChromeThread::PostTask(
890 ChromeThread::UI, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32891 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16892 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32893}
894
895// Call from the file thread when the finished dangerous download was renamed.
896void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
897 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41898 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16899 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32900 DownloadMap::iterator it = downloads_.find(download_handle);
901 if (it == downloads_.end()) {
902 NOTREACHED();
903 return;
904 }
905
906 DownloadItem* download = it->second;
907 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16908 if (success) {
909 // We need to update the path uniquifier so that the UI shows the right
910 // name when calling GetFileName().
911 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32912 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16913 }
[email protected]9ccbb372008-10-10 18:50:32914
915 // Continue the download finished sequence.
916 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29917}
918
919// static
initial.commit09911bf2008-07-26 23:55:29920void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
921 int render_process_id,
922 int request_id) {
[email protected]d85cf072009-10-27 03:59:31923 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
initial.commit09911bf2008-07-26 23:55:29924 rdh->CancelRequest(render_process_id, request_id, false);
925}
926
927void DownloadManager::DownloadCancelled(int32 download_id) {
928 DownloadMap::iterator it = in_progress_.find(download_id);
929 if (it == in_progress_.end())
930 return;
931 DownloadItem* download = it->second;
932
initial.commit09911bf2008-07-26 23:55:29933 // Clean up will happen when the history system create callback runs if we
934 // don't have a valid db_handle yet.
935 if (download->db_handle() != kUninitializedHandle) {
936 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:29937 UpdateHistoryForDownload(download);
938 }
939
[email protected]d7d1c5c2009-08-05 23:52:50940 DownloadCancelledInternal(download_id,
941 download->render_process_id(),
942 download->request_id());
943}
944
945void DownloadManager::DownloadCancelledInternal(int download_id,
946 int render_process_id,
947 int request_id) {
[email protected]d85cf072009-10-27 03:59:31948 // Cancel the network request. RDH is guaranteed to outlive the IO thread.
949 ChromeThread::PostTask(
950 ChromeThread::IO, FROM_HERE,
951 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
952 g_browser_process->resource_dispatcher_host(),
953 render_process_id,
954 request_id));
[email protected]d7d1c5c2009-08-05 23:52:50955
initial.commit09911bf2008-07-26 23:55:29956 // Tell the file manager to cancel the download.
[email protected]d7d1c5c2009-08-05 23:52:50957 file_manager_->RemoveDownload(download_id, this); // On the UI thread
[email protected]d83d03aa2009-11-02 21:44:37958 ChromeThread::PostTask(
959 ChromeThread::FILE, FROM_HERE,
960 NewRunnableMethod(
961 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:29962}
963
964void DownloadManager::PauseDownload(int32 download_id, bool pause) {
965 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]d85cf072009-10-27 03:59:31966 if (it == in_progress_.end())
967 return;
initial.commit09911bf2008-07-26 23:55:29968
[email protected]d85cf072009-10-27 03:59:31969 DownloadItem* download = it->second;
970 if (pause == download->is_paused())
971 return;
initial.commit09911bf2008-07-26 23:55:29972
[email protected]d85cf072009-10-27 03:59:31973 // Inform the ResourceDispatcherHost of the new pause state.
974 ChromeThread::PostTask(
975 ChromeThread::IO, FROM_HERE,
976 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
977 g_browser_process->resource_dispatcher_host(),
978 download->render_process_id(),
979 download->request_id(),
980 pause));
initial.commit09911bf2008-07-26 23:55:29981}
982
983// static
984void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
985 int render_process_id,
986 int request_id,
987 bool pause) {
988 rdh->PauseRequest(render_process_id, request_id, pause);
989}
990
[email protected]7ae7c2cb2009-01-06 23:31:41991bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:32992 // TODO(jcampan): Improve me.
[email protected]eccb9d12009-10-28 05:40:09993 return IsExecutableFile(file_name);
[email protected]9ccbb372008-10-10 18:50:32994}
995
996void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:41997 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:32998 download->Rename(new_path);
999
1000 // Update the history.
1001
1002 // No update necessary if the download was initiated while in incognito mode.
1003 if (download->db_handle() <= kUninitializedHandle)
1004 return;
1005
[email protected]6cade212008-12-03 00:32:221006 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:321007 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1008 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:411009 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:321010}
1011
initial.commit09911bf2008-07-26 23:55:291012void DownloadManager::RemoveDownload(int64 download_handle) {
1013 DownloadMap::iterator it = downloads_.find(download_handle);
1014 if (it == downloads_.end())
1015 return;
1016
1017 // Make history update.
1018 DownloadItem* download = it->second;
1019 RemoveDownloadFromHistory(download);
1020
1021 // Remove from our tables and delete.
1022 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321023 it = dangerous_finished_.find(download->id());
1024 if (it != dangerous_finished_.end())
1025 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291026
1027 // Tell observers to refresh their views.
1028 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:361029
1030 delete download;
initial.commit09911bf2008-07-26 23:55:291031}
1032
[email protected]e93d2822009-01-30 05:59:591033int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1034 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291035 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1036
initial.commit09911bf2008-07-26 23:55:291037 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:281038 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:291039 while (it != downloads_.end()) {
1040 DownloadItem* download = it->second;
1041 DownloadItem::DownloadState state = download->state();
1042 if (download->start_time() >= remove_begin &&
1043 (remove_end.is_null() || download->start_time() < remove_end) &&
1044 (state == DownloadItem::COMPLETE ||
1045 state == DownloadItem::CANCELLED)) {
1046 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561047 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581048
1049 // Also remove it from any completed dangerous downloads.
1050 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1051 if (dit != dangerous_finished_.end())
1052 dangerous_finished_.erase(dit);
1053
[email protected]78b8fcc92009-03-31 17:36:281054 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:291055
initial.commit09911bf2008-07-26 23:55:291056 continue;
1057 }
1058
1059 ++it;
1060 }
1061
1062 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281063 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291064 if (num_deleted > 0)
1065 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1066
[email protected]78b8fcc92009-03-31 17:36:281067 // Delete the download items after updating the observers.
1068 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1069 pending_deletes.clear();
1070
initial.commit09911bf2008-07-26 23:55:291071 return num_deleted;
1072}
1073
[email protected]e93d2822009-01-30 05:59:591074int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1075 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291076}
1077
[email protected]d41355e6f2009-04-07 21:21:121078int DownloadManager::RemoveAllDownloads() {
1079 // The null times make the date range unbounded.
1080 return RemoveDownloadsBetween(base::Time(), base::Time());
1081}
1082
initial.commit09911bf2008-07-26 23:55:291083// Initiate a download of a specific URL. We send the request to the
1084// ResourceDispatcherHost, and let it send us responses like a regular
1085// download.
1086void DownloadManager::DownloadUrl(const GURL& url,
1087 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:501088 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:341089 TabContents* tab_contents) {
1090 DCHECK(tab_contents);
initial.commit09911bf2008-07-26 23:55:291091 file_manager_->DownloadUrl(url,
1092 referrer,
[email protected]be180c802009-10-23 06:33:311093 referrer_charset,
[email protected]76543b92009-08-31 17:27:451094 tab_contents->process()->id(),
[email protected]57c6a652009-05-04 07:58:341095 tab_contents->render_view_host()->routing_id(),
[email protected]be180c802009-10-23 06:33:311096 request_context_getter_);
initial.commit09911bf2008-07-26 23:55:291097}
1098
[email protected]7ae7c2cb2009-01-06 23:31:411099void DownloadManager::GenerateExtension(
1100 const FilePath& file_name,
1101 const std::string& mime_type,
1102 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291103 // We're worried about three things here:
1104 //
1105 // 1) Security. Many sites let users upload content, such as buddy icons, to
1106 // their web sites. We want to mitigate the case where an attacker
1107 // supplies a malicious executable with an executable file extension but an
1108 // honest site serves the content with a benign content type, such as
1109 // image/jpeg.
1110 //
1111 // 2) Usability. If the site fails to provide a file extension, we want to
1112 // guess a reasonable file extension based on the content type.
1113 //
1114 // 3) Shell integration. Some file extensions automatically integrate with
1115 // the shell. We block these extensions to prevent a malicious web site
1116 // from integrating with the user's shell.
1117
[email protected]7ae7c2cb2009-01-06 23:31:411118 static const FilePath::CharType default_extension[] =
1119 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291120
1121 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411122 FilePath::StringType extension(
1123 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291124
[email protected]b7f05882009-02-22 01:21:561125#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291126 // Rename shell-integrated extensions.
1127 if (win_util::IsShellIntegratedExtension(extension))
1128 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561129#endif
initial.commit09911bf2008-07-26 23:55:291130
1131 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411132 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411133 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291134 if (mime_type == mime_type_from_extension) {
1135 // The hinted extension matches the mime type. It looks like a winner.
1136 generated_extension->swap(extension);
1137 return;
1138 }
1139
[email protected]eccb9d12009-10-28 05:40:091140 if (IsExecutableExtension(extension) && !IsExecutableMimeType(mime_type)) {
initial.commit09911bf2008-07-26 23:55:291141 // We want to be careful about executable extensions. The worry here is
1142 // that a trusted web site could be tricked into dropping an executable file
1143 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101144 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291145 // We couldn't find a good extension for this content type. Use a dummy
1146 // extension instead.
1147 extension.assign(default_extension);
1148 }
1149 }
1150
1151 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101152 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291153 } else {
[email protected]6cade212008-12-03 00:32:221154 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291155 // 1. New extension is not ".txt"
1156 // 2. New extension is not the same as the already existing extension.
1157 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411158 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291159 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1160 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371161 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1162 // servers, i.e. bug 5772.
[email protected]e32642f62009-09-11 21:58:291163 // 5. The original extension is not ".tgz" & the new extension is not "gz".
[email protected]7ae7c2cb2009-01-06 23:31:411164 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101165 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171166 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411167 append_extension != extension &&
[email protected]eccb9d12009-10-28 05:40:091168 !IsExecutableExtension(append_extension) &&
[email protected]e32642f62009-09-11 21:58:291169 !(append_extension == FILE_PATH_LITERAL("gz") &&
1170 extension == FILE_PATH_LITERAL("tgz")) &&
[email protected]e106457b2009-03-25 22:43:371171 (append_extension != FILE_PATH_LITERAL("tar") ||
1172 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171173 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291174 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171175 }
initial.commit09911bf2008-07-26 23:55:291176 }
1177 }
1178
1179 generated_extension->swap(extension);
1180}
1181
1182void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411183 FilePath* generated_name) {
[email protected]630947c2009-11-04 18:37:311184 std::wstring default_name =
1185 l10n_util::GetString(IDS_DEFAULT_DOWNLOAD_FILENAME);
1186#if defined(OS_WIN)
1187 FilePath default_file_path(default_name);
1188#elif defined(OS_POSIX)
1189 FilePath default_file_path(base::SysWideToNativeMB(default_name));
1190#endif
1191
[email protected]de2943352009-10-22 23:06:121192 *generated_name = net::GetSuggestedFilename(GURL(info->url),
1193 info->content_disposition,
1194 info->referrer_charset,
[email protected]630947c2009-11-04 18:37:311195 default_file_path);
1196
[email protected]7ae7c2cb2009-01-06 23:31:411197 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291198
[email protected]7ae7c2cb2009-01-06 23:31:411199 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291200}
1201
1202void DownloadManager::AddObserver(Observer* observer) {
1203 observers_.AddObserver(observer);
1204 observer->ModelChanged();
1205}
1206
1207void DownloadManager::RemoveObserver(Observer* observer) {
1208 observers_.RemoveObserver(observer);
1209}
1210
1211// Post Windows Shell operations to the Download thread, to avoid blocking the
1212// user interface.
1213void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1214 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:371215 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:581216#if defined(OS_MACOSX)
1217 // Mac needs to run this operation on the UI thread.
1218 platform_util::ShowItemInFolder(download->full_path());
1219#else
[email protected]d83d03aa2009-11-02 21:44:371220 ChromeThread::PostTask(
1221 ChromeThread::FILE, FROM_HERE,
1222 NewRunnableMethod(
1223 file_manager_, &DownloadFileManager::OnShowDownloadInShell,
1224 FilePath(download->full_path())));
[email protected]8b6ff012009-08-18 22:29:581225#endif
initial.commit09911bf2008-07-26 23:55:291226}
1227
[email protected]8f783752009-04-01 23:33:451228void DownloadManager::OpenDownload(const DownloadItem* download,
1229 gfx::NativeView parent_window) {
[email protected]0e34d7892009-06-05 19:17:401230 // Open Chrome extensions with ExtensionsService. For everything else do shell
[email protected]8f783752009-04-01 23:33:451231 // execute.
[email protected]67f373a2009-09-22 02:44:511232 if (IsExtensionInstall(download)) {
[email protected]494c06e2009-07-25 01:06:421233 OpenChromeExtension(download->full_path(), download->url(),
1234 download->referrer_url());
[email protected]8f783752009-04-01 23:33:451235 } else {
1236 OpenDownloadInShell(download, parent_window);
1237 }
1238}
1239
[email protected]c1e432a2009-07-22 21:21:481240void DownloadManager::OpenChromeExtension(const FilePath& full_path,
[email protected]494c06e2009-07-25 01:06:421241 const GURL& download_url,
1242 const GURL& referrer_url) {
[email protected]6ef635e42009-07-26 06:16:121243 // We don't support extensions in OTR mode.
[email protected]2a464a92009-08-01 17:58:351244 ExtensionsService* service = profile_->GetExtensionsService();
1245 if (service) {
[email protected]91e1bd82009-09-03 22:04:401246 NotificationService* nservice = NotificationService::current();
[email protected]ac025282009-12-16 19:16:381247 GURL nonconst_download_url = download_url;
[email protected]91e1bd82009-09-03 22:04:401248 nservice->Notify(NotificationType::EXTENSION_READY_FOR_INSTALL,
1249 Source<DownloadManager>(this),
[email protected]ac025282009-12-16 19:16:381250 Details<GURL>(&nonconst_download_url));
[email protected]a050d712009-11-06 00:40:101251 if (UserScript::HasUserScriptFileExtension(download_url)) {
[email protected]6657afa62009-11-04 02:15:201252 CrxInstaller::InstallUserScript(
1253 full_path,
1254 download_url,
1255 service->install_directory(),
1256 true, // please delete crx on completion
1257 service,
1258 new ExtensionInstallUI(profile_));
1259 } else {
1260 CrxInstaller::Start(
1261 full_path,
1262 service->install_directory(),
1263 Extension::INTERNAL,
1264 "", // no expected id
1265 true, // please delete crx on completion
1266 true, // privilege increase allowed
1267 service,
1268 new ExtensionInstallUI(profile_));
1269 }
[email protected]2a464a92009-08-01 17:58:351270 }
[email protected]8f783752009-04-01 23:33:451271}
1272
initial.commit09911bf2008-07-26 23:55:291273void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591274 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291275 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:371276 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:581277#if defined(OS_MACOSX)
1278 // Mac OS X requires opening downloads on the UI thread.
1279 platform_util::OpenItem(download->full_path());
1280#else
[email protected]d83d03aa2009-11-02 21:44:371281 ChromeThread::PostTask(
1282 ChromeThread::FILE, FROM_HERE,
1283 NewRunnableMethod(
1284 file_manager_, &DownloadFileManager::OnOpenDownloadInShell,
1285 download->full_path(), download->url(), parent_window));
[email protected]8b6ff012009-08-18 22:29:581286#endif
initial.commit09911bf2008-07-26 23:55:291287}
1288
[email protected]eccb9d12009-10-28 05:40:091289void DownloadManager::OpenFilesBasedOnExtension(
1290 const FilePath& path, bool open) {
1291 FilePath::StringType extension = path.Extension();
1292 if (extension.empty())
1293 return;
1294 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1295 extension.erase(0, 1);
1296 if (open && !IsExecutableExtension(extension))
initial.commit09911bf2008-07-26 23:55:291297 auto_open_.insert(extension);
1298 else
1299 auto_open_.erase(extension);
1300 SaveAutoOpens();
1301}
1302
[email protected]eccb9d12009-10-28 05:40:091303bool DownloadManager::ShouldOpenFileBasedOnExtension(
1304 const FilePath& path) const {
[email protected]8c756ac2009-01-30 23:36:411305 // Special-case Chrome extensions as always-open.
[email protected]eccb9d12009-10-28 05:40:091306 FilePath::StringType extension = path.Extension();
1307 if (extension.empty())
1308 return false;
1309 if (IsExecutableExtension(extension))
1310 return false;
1311 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1312 extension.erase(0, 1);
1313 if (auto_open_.find(extension) != auto_open_.end() ||
1314 Extension::IsExtension(path))
[email protected]8c756ac2009-01-30 23:36:411315 return true;
initial.commit09911bf2008-07-26 23:55:291316 return false;
1317}
1318
[email protected]7b73d992008-12-15 20:56:461319static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291320 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461321 "text/javascript",
1322 "text/javascript;version=*",
[email protected]54d8d452009-04-08 17:29:241323 // Registry files can cause critical changes to the MS OS behavior.
1324 // Addition of this mimetype also addresses bug 7337.
1325 "text/x-registry",
[email protected]60ff8f912008-12-05 07:58:391326 // Some sites use binary/octet-stream to mean application/octet-stream.
1327 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461328 "binary/octet-stream"
1329};
initial.commit09911bf2008-07-26 23:55:291330
[email protected]7b73d992008-12-15 20:56:461331static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291332 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461333 "application/*+xml",
1334 "application/xml"
1335};
initial.commit09911bf2008-07-26 23:55:291336
[email protected]7b73d992008-12-15 20:56:461337// static
1338bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411339 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461340 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1341 return true;
1342 }
[email protected]bae0ea12009-02-14 01:20:411343 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461344 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1345 return false;
1346 }
1347 // We consider only other application types to be executable.
1348 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291349}
1350
[email protected]eccb9d12009-10-28 05:40:091351bool DownloadManager::IsExecutableFile(const FilePath& path) const {
1352 return IsExecutableExtension(path.Extension());
1353}
1354
1355bool DownloadManager::IsExecutableExtension(
1356 const FilePath::StringType& extension) const {
1357 if (extension.empty())
1358 return false;
[email protected]64da0b932009-02-24 02:30:041359 if (!IsStringASCII(extension))
1360 return false;
[email protected]a0a9577b2009-05-27 23:52:321361#if defined(OS_WIN)
[email protected]64da0b932009-02-24 02:30:041362 std::string ascii_extension = WideToASCII(extension);
[email protected]e9ef0a62009-08-11 22:50:131363#elif defined(OS_POSIX)
[email protected]a0a9577b2009-05-27 23:52:321364 std::string ascii_extension = extension;
1365#endif
[email protected]64da0b932009-02-24 02:30:041366 StringToLowerASCII(&ascii_extension);
1367
[email protected]eccb9d12009-10-28 05:40:091368 // Strip out leading dot if it's still there
1369 if (ascii_extension[0] == FilePath::kExtensionSeparator)
1370 ascii_extension.erase(0, 1);
1371
[email protected]64da0b932009-02-24 02:30:041372 return exe_types_.find(ascii_extension) != exe_types_.end();
initial.commit09911bf2008-07-26 23:55:291373}
1374
1375void DownloadManager::ResetAutoOpenFiles() {
1376 auto_open_.clear();
1377 SaveAutoOpens();
1378}
1379
1380bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1381 return !auto_open_.empty();
1382}
1383
1384void DownloadManager::SaveAutoOpens() {
1385 PrefService* prefs = profile_->GetPrefs();
1386 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411387 FilePath::StringType extensions;
[email protected]eccb9d12009-10-28 05:40:091388 for (AutoOpenSet::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291389 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411390 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291391 }
1392 if (!extensions.empty())
1393 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561394
1395 std::wstring extensions_w;
1396#if defined(OS_WIN)
1397 extensions_w = extensions;
1398#elif defined(OS_POSIX)
[email protected]1b5044d2009-02-24 00:04:141399 extensions_w = base::SysNativeMBToWide(extensions);
[email protected]b7f05882009-02-22 01:21:561400#endif
1401
1402 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291403 }
1404}
1405
[email protected]561abe62009-04-06 18:08:341406void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361407 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291408 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071409 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411410 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291411 ContinueStartDownload(info, path);
1412}
1413
1414void DownloadManager::FileSelectionCanceled(void* params) {
1415 // The user didn't pick a place to save the file, so need to cancel the
1416 // download that's already in progress to the temporary location.
1417 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]d7d1c5c2009-08-05 23:52:501418 DownloadCancelledInternal(info->download_id,
[email protected]76543b92009-08-31 17:27:451419 info->child_id,
[email protected]d7d1c5c2009-08-05 23:52:501420 info->request_id);
initial.commit09911bf2008-07-26 23:55:291421}
1422
[email protected]7ae7c2cb2009-01-06 23:31:411423void DownloadManager::DeleteDownload(const FilePath& path) {
[email protected]d83d03aa2009-11-02 21:44:371424 ChromeThread::PostTask(
1425 ChromeThread::FILE, FROM_HERE,
1426 NewRunnableFunction(&DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321427}
1428
1429
1430void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1431 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1432 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1433 download->UpdateObservers();
1434
1435 // If the download is not complete, nothing to do. The required
1436 // post-processing will be performed when it does complete.
1437 if (download->state() != DownloadItem::COMPLETE)
1438 return;
1439
[email protected]d83d03aa2009-11-02 21:44:371440 ChromeThread::PostTask(
1441 ChromeThread::FILE, FROM_HERE,
1442 NewRunnableMethod(
1443 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
1444 download->db_handle(), download->full_path(),
1445 download->original_name()));
[email protected]9ccbb372008-10-10 18:50:321446}
1447
[email protected]763f946a2009-01-06 19:04:391448void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411449 FilePath* file_name) {
1450 // Make sure we get the right file extension
1451 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391452 GenerateExtension(*file_name, mime_type, &extension);
1453 file_util::ReplaceExtension(file_name, extension);
1454
[email protected]2b2f8f72009-02-24 22:42:051455#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391456 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411457 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391458 DCHECK(!leaf_name.empty());
1459 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411460 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1461 *file_name = file_name->DirName();
1462 if (file_name->value() == FilePath::kCurrentDirectory) {
1463 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391464 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411465 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391466 }
1467 }
[email protected]b7f05882009-02-22 01:21:561468#endif
[email protected]763f946a2009-01-06 19:04:391469}
1470
[email protected]f1b11d32009-10-09 22:51:391471bool DownloadManager::IsExtensionInstall(const DownloadItem* item) {
[email protected]6657afa62009-11-04 02:15:201472 if (item->save_as())
1473 return false;
1474
[email protected]a050d712009-11-06 00:40:101475 if (UserScript::HasUserScriptFileExtension(item->url()))
[email protected]6657afa62009-11-04 02:15:201476 return true;
1477
1478 return item->mime_type() == Extension::kMimeType;
[email protected]f1b11d32009-10-09 22:51:391479}
1480
1481bool DownloadManager::IsExtensionInstall(const DownloadCreateInfo* info) {
[email protected]6657afa62009-11-04 02:15:201482 if (info->save_as)
1483 return false;
1484
[email protected]a050d712009-11-06 00:40:101485 if (UserScript::HasUserScriptFileExtension(info->url))
[email protected]6657afa62009-11-04 02:15:201486 return true;
1487
1488 return info->mime_type == Extension::kMimeType;
[email protected]f1b11d32009-10-09 22:51:391489}
1490
initial.commit09911bf2008-07-26 23:55:291491// Operations posted to us from the history service ----------------------------
1492
1493// The history service has retrieved all download entries. 'entries' contains
1494// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1495void DownloadManager::OnQueryDownloadEntriesComplete(
1496 std::vector<DownloadCreateInfo>* entries) {
1497 for (size_t i = 0; i < entries->size(); ++i) {
1498 DownloadItem* download = new DownloadItem(entries->at(i));
1499 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1500 downloads_[download->db_handle()] = download;
1501 download->set_manager(this);
1502 }
1503 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1504}
1505
initial.commit09911bf2008-07-26 23:55:291506// Once the new DownloadItem's creation info has been committed to the history
1507// service, we associate the DownloadItem with the db handle, update our
1508// 'downloads_' map and inform observers.
1509void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1510 int64 db_handle) {
1511 DownloadMap::iterator it = in_progress_.find(info.download_id);
1512 DCHECK(it != in_progress_.end());
1513
1514 DownloadItem* download = it->second;
1515 DCHECK(download->db_handle() == kUninitializedHandle);
1516 download->set_db_handle(db_handle);
1517
1518 // Insert into our full map.
1519 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1520 downloads_[download->db_handle()] = download;
1521
[email protected]5e595482009-05-06 20:16:531522 // Show in the appropropriate browser UI.
1523 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291524
1525 // Inform interested objects about the new download.
1526 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
initial.commit09911bf2008-07-26 23:55:291527
1528 // If this download has been completed before we've received the db handle,
1529 // post one final message to the history service so that it can be properly
1530 // in sync with the DownloadItem's completion status, and also inform any
1531 // observers so that they get more than just the start notification.
1532 if (download->state() != DownloadItem::IN_PROGRESS) {
1533 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291534 UpdateHistoryForDownload(download);
1535 download->UpdateObservers();
1536 }
1537}
1538
1539// Called when the history service has retrieved the list of downloads that
1540// match the search text.
1541void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1542 std::vector<int64>* results) {
1543 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1544 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1545 if (!requestor)
1546 return;
1547
1548 std::vector<DownloadItem*> searched_downloads;
1549 for (std::vector<int64>::iterator it = results->begin();
1550 it != results->end(); ++it) {
1551 DownloadMap::iterator dit = downloads_.find(*it);
1552 if (dit != downloads_.end())
1553 searched_downloads.push_back(dit->second);
1554 }
1555
1556 requestor->SetDownloads(searched_downloads);
1557}
[email protected]905a08d2008-11-19 07:24:121558
[email protected]5e595482009-05-06 20:16:531559void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1560 DownloadItem* download) {
[email protected]5e595482009-05-06 20:16:531561 // The 'contents' may no longer exist if the user closed the tab before we get
1562 // this start completion event. If it does, tell the origin TabContents to
1563 // display its download shelf.
[email protected]76543b92009-08-31 17:27:451564 TabContents* contents = tab_util::GetTabContentsByID(info.child_id,
1565 info.render_view_id);
[email protected]5e595482009-05-06 20:16:531566
1567 // If the contents no longer exists, we start the download in the last active
1568 // browser. This is not ideal but better than fully hiding the download from
1569 // the user.
1570 if (!contents) {
1571 Browser* last_active = BrowserList::GetLastActive();
1572 if (last_active)
1573 contents = last_active->GetSelectedTabContents();
1574 }
1575
1576 if (contents)
1577 contents->OnStartDownload(download);
1578}
1579
[email protected]6cade212008-12-03 00:32:221580// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121581void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411582 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381583}
1584