blob: 50f29107cdc38fc119d51a7530a360f0e922794a [file] [log] [blame]
license.botbf09a502008-08-24 00:55:551// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]cdaa8652008-09-13 02:48:595#include "chrome/browser/download/download_manager.h"
initial.commit09911bf2008-07-26 23:55:296
7#include "base/file_util.h"
8#include "base/logging.h"
9#include "base/message_loop.h"
10#include "base/path_service.h"
[email protected]1b5044d2009-02-24 00:04:1411#include "base/rand_util.h"
initial.commit09911bf2008-07-26 23:55:2912#include "base/string_util.h"
[email protected]1b5044d2009-02-24 00:04:1413#include "base/sys_string_conversions.h"
initial.commit09911bf2008-07-26 23:55:2914#include "base/task.h"
15#include "base/thread.h"
16#include "base/timer.h"
initial.commit09911bf2008-07-26 23:55:2917#include "chrome/browser/browser_list.h"
18#include "chrome/browser/browser_process.h"
[email protected]cdaa8652008-09-13 02:48:5919#include "chrome/browser/download/download_file.h"
[email protected]8c756ac2009-01-30 23:36:4120#include "chrome/browser/extensions/extension.h"
initial.commit09911bf2008-07-26 23:55:2921#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:2622#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2523#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]e3c404b2008-12-23 01:07:3224#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
[email protected]f3ec7742009-01-15 00:59:1625#include "chrome/browser/tab_contents/tab_util.h"
26#include "chrome/browser/tab_contents/web_contents.h"
[email protected]8c756ac2009-01-30 23:36:4127#include "chrome/common/chrome_constants.h"
initial.commit09911bf2008-07-26 23:55:2928#include "chrome/common/chrome_paths.h"
29#include "chrome/common/l10n_util.h"
30#include "chrome/common/notification_service.h"
31#include "chrome/common/pref_names.h"
32#include "chrome/common/pref_service.h"
33#include "chrome/common/stl_util-inl.h"
[email protected]46072d42008-07-28 14:49:3534#include "googleurl/src/gurl.h"
[email protected]34ac8f32009-02-22 23:03:2735#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2936#include "net/base/mime_util.h"
37#include "net/base/net_util.h"
38#include "net/url_request/url_request_context.h"
39
[email protected]b7f05882009-02-22 01:21:5640#if defined(OS_WIN)
41// TODO(port): some of these need porting.
42#include "base/registry.h"
43#include "base/win_util.h"
44#include "chrome/browser/download/download_util.h"
45#include "chrome/common/win_util.h"
46#endif
47
initial.commit09911bf2008-07-26 23:55:2948// Periodically update our observers.
49class DownloadItemUpdateTask : public Task {
50 public:
51 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
52 void Run() { if (item_) item_->UpdateObservers(); }
53
54 private:
55 DownloadItem* item_;
56};
57
58// Update frequency (milliseconds).
59static const int kUpdateTimeMs = 1000;
60
61// Our download table ID starts at 1, so we use 0 to represent a download that
62// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2263// database handles in incognito mode starting at -1 and progressively getting
64// more negative.
initial.commit09911bf2008-07-26 23:55:2965static const int kUninitializedHandle = 0;
66
[email protected]7a256ea2008-10-17 17:34:1667// Appends the passed the number between parenthesis the path before the
68// extension.
[email protected]7ae7c2cb2009-01-06 23:31:4169static void AppendNumberToPath(FilePath* path, int number) {
70 file_util::InsertBeforeExtension(path,
71 StringPrintf(FILE_PATH_LITERAL(" (%d)"), number));
[email protected]7a256ea2008-10-17 17:34:1672}
73
74// Attempts to find a number that can be appended to that path to make it
75// unique. If |path| does not exist, 0 is returned. If it fails to find such
76// a number, -1 is returned.
[email protected]7ae7c2cb2009-01-06 23:31:4177static int GetUniquePathNumber(const FilePath& path) {
initial.commit09911bf2008-07-26 23:55:2978 const int kMaxAttempts = 100;
79
[email protected]7a256ea2008-10-17 17:34:1680 if (!file_util::PathExists(path))
81 return 0;
initial.commit09911bf2008-07-26 23:55:2982
[email protected]7ae7c2cb2009-01-06 23:31:4183 FilePath new_path;
initial.commit09911bf2008-07-26 23:55:2984 for (int count = 1; count <= kMaxAttempts; ++count) {
[email protected]7ae7c2cb2009-01-06 23:31:4185 new_path = FilePath(path);
[email protected]7a256ea2008-10-17 17:34:1686 AppendNumberToPath(&new_path, count);
initial.commit09911bf2008-07-26 23:55:2987
[email protected]7a256ea2008-10-17 17:34:1688 if (!file_util::PathExists(new_path))
89 return count;
initial.commit09911bf2008-07-26 23:55:2990 }
91
[email protected]7a256ea2008-10-17 17:34:1692 return -1;
initial.commit09911bf2008-07-26 23:55:2993}
94
[email protected]7ae7c2cb2009-01-06 23:31:4195static bool DownloadPathIsDangerous(const FilePath& download_path) {
96 FilePath desktop_dir;
[email protected]f052118e2008-09-05 02:25:3297 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
98 NOTREACHED();
99 return false;
100 }
101 return (download_path == desktop_dir);
102}
[email protected]f052118e2008-09-05 02:25:32103
initial.commit09911bf2008-07-26 23:55:29104// DownloadItem implementation -------------------------------------------------
105
106// Constructor for reading from the history service.
107DownloadItem::DownloadItem(const DownloadCreateInfo& info)
108 : id_(-1),
109 full_path_(info.path),
110 url_(info.url),
111 total_bytes_(info.total_bytes),
112 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56113 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29114 state_(static_cast<DownloadState>(info.state)),
115 start_time_(info.start_time),
116 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29117 manager_(NULL),
118 is_paused_(false),
119 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56120 safety_state_(SAFE),
121 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29122 render_process_id_(-1),
123 request_id_(-1) {
124 if (state_ == IN_PROGRESS)
125 state_ = CANCELLED;
126 Init(false /* don't start progress timer */);
127}
128
129// Constructor for DownloadItem created via user action in the main thread.
130DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41131 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16132 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32133 const GURL& url,
[email protected]7ae7c2cb2009-01-06 23:31:41134 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59135 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29136 int64 download_size,
137 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32138 int request_id,
139 bool is_dangerous)
initial.commit09911bf2008-07-26 23:55:29140 : id_(download_id),
141 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16142 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29143 url_(url),
144 total_bytes_(download_size),
145 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56146 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29147 state_(IN_PROGRESS),
148 start_time_(start_time),
149 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29150 manager_(NULL),
151 is_paused_(false),
152 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56153 safety_state_(is_dangerous ? DANGEROUS : SAFE),
154 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29155 render_process_id_(render_process_id),
156 request_id_(request_id) {
157 Init(true /* start progress timer */);
158}
159
160void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41161 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29162 if (start_timer)
163 StartProgressTimer();
164}
165
166DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29167 state_ = REMOVING;
168 UpdateObservers();
169}
170
171void DownloadItem::AddObserver(Observer* observer) {
172 observers_.AddObserver(observer);
173}
174
175void DownloadItem::RemoveObserver(Observer* observer) {
176 observers_.RemoveObserver(observer);
177}
178
179void DownloadItem::UpdateObservers() {
180 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
181}
182
183// If we've received more data than we were expecting (bad server info?), revert
184// to 'unknown size mode'.
185void DownloadItem::UpdateSize(int64 bytes_so_far) {
186 received_bytes_ = bytes_so_far;
187 if (received_bytes_ > total_bytes_)
188 total_bytes_ = 0;
189}
190
191// Updates from the download thread may have been posted while this download
192// was being cancelled in the UI thread, so we'll accept them unless we're
193// complete.
194void DownloadItem::Update(int64 bytes_so_far) {
195 if (state_ == COMPLETE) {
196 NOTREACHED();
197 return;
198 }
199 UpdateSize(bytes_so_far);
200 UpdateObservers();
201}
202
[email protected]6cade212008-12-03 00:32:22203// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29204void DownloadItem::Cancel(bool update_history) {
205 if (state_ != IN_PROGRESS) {
206 // Small downloads might be complete before this method has a chance to run.
207 return;
208 }
209 state_ = CANCELLED;
210 UpdateObservers();
211 StopProgressTimer();
212 if (update_history)
213 manager_->DownloadCancelled(id_);
214}
215
216void DownloadItem::Finished(int64 size) {
217 state_ = COMPLETE;
218 UpdateSize(size);
[email protected]22fbe5a2008-10-29 22:20:40219 UpdateObservers();
initial.commit09911bf2008-07-26 23:55:29220 StopProgressTimer();
221}
222
[email protected]9ccbb372008-10-10 18:50:32223void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29224 Cancel(true);
225 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32226 if (delete_on_disk)
227 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29228 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22229 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29230}
231
232void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59233 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14234 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29235}
236
237void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14238 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29239}
240
[email protected]e93d2822009-01-30 05:59:59241bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29242 if (total_bytes_ <= 0)
243 return false; // We never received the content_length for this download.
244
245 int64 speed = CurrentSpeed();
246 if (speed == 0)
247 return false;
248
249 *remaining =
[email protected]e93d2822009-01-30 05:59:59250 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29251 return true;
252}
253
254int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56255 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
256 int64 diff_ms = diff.InMilliseconds();
257 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29258}
259
260int DownloadItem::PercentComplete() const {
261 int percent = -1;
262 if (total_bytes_ > 0)
263 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
264 return percent;
265}
266
[email protected]7ae7c2cb2009-01-06 23:31:41267void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29268 DCHECK(!full_path.empty());
269 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41270 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29271}
272
273void DownloadItem::TogglePause() {
274 DCHECK(state_ == IN_PROGRESS);
275 manager_->PauseDownload(id_, !is_paused_);
276 is_paused_ = !is_paused_;
277 UpdateObservers();
278}
279
[email protected]7ae7c2cb2009-01-06 23:31:41280FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32281 if (safety_state_ == DownloadItem::SAFE)
282 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16283 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41284 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16285 AppendNumberToPath(&name, path_uniquifier_);
286 return name;
287 }
[email protected]9ccbb372008-10-10 18:50:32288 return original_name_;
289}
290
initial.commit09911bf2008-07-26 23:55:29291// DownloadManager implementation ----------------------------------------------
292
293// static
294void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
295 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
296 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32297 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
298
[email protected]f052118e2008-09-05 02:25:32299 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41300 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12301 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
302 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32303 NOTREACHED();
304 }
[email protected]b9636002009-03-04 00:05:25305 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
306 default_download_path);
[email protected]f052118e2008-09-05 02:25:32307
308 // If the download path is dangerous we forcefully reset it. But if we do
309 // so we set a flag to make sure we only do it once, to avoid fighting
310 // the user if he really wants it on an unsafe place such as the desktop.
311
312 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41313 FilePath current_download_dir = FilePath::FromWStringHack(
314 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32315 if (DownloadPathIsDangerous(current_download_dir)) {
316 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41317 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32318 }
319 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
320 }
initial.commit09911bf2008-07-26 23:55:29321}
322
323DownloadManager::DownloadManager()
324 : shutdown_needed_(false),
325 profile_(NULL),
326 file_manager_(NULL),
327 ui_loop_(MessageLoop::current()),
328 file_loop_(NULL) {
329}
330
331DownloadManager::~DownloadManager() {
332 if (shutdown_needed_)
333 Shutdown();
334}
335
336void DownloadManager::Shutdown() {
337 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
338
339 // Stop receiving download updates
340 file_manager_->RemoveDownloadManager(this);
341
342 // Stop making history service requests
343 cancelable_consumer_.CancelAllRequests();
344
345 // 'in_progress_' may contain DownloadItems that have not finished the start
346 // complete (from the history service) and thus aren't in downloads_.
347 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32348 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29349 for (; it != in_progress_.end(); ++it) {
350 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32351 if (download->safety_state() == DownloadItem::DANGEROUS) {
352 // Forget about any download that the user did not approve.
353 // Note that we cannot call download->Remove() this would invalidate our
354 // iterator.
355 to_remove.insert(download);
356 continue;
initial.commit09911bf2008-07-26 23:55:29357 }
[email protected]9ccbb372008-10-10 18:50:32358 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
359 download->Cancel(false);
360 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29361 if (download->db_handle() == kUninitializedHandle) {
362 // An invalid handle means that 'download' does not yet exist in
363 // 'downloads_', so we have to delete it here.
364 delete download;
365 }
366 }
367
[email protected]9ccbb372008-10-10 18:50:32368 // 'dangerous_finished_' contains all complete downloads that have not been
369 // approved. They should be removed.
370 it = dangerous_finished_.begin();
371 for (; it != dangerous_finished_.end(); ++it)
372 to_remove.insert(it->second);
373
374 // Remove the dangerous download that are not approved.
375 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
376 rm_it != to_remove.end(); ++rm_it) {
377 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32378 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32379 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32380 // Same as above, delete the download if it is not in 'downloads_' (as the
381 // Remove() call above won't have deleted it).
382 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32383 delete download;
384 }
385 to_remove.clear();
386
initial.commit09911bf2008-07-26 23:55:29387 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32388 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29389 STLDeleteValues(&downloads_);
390
391 file_manager_ = NULL;
392
393 // Save our file extensions to auto open.
394 SaveAutoOpens();
395
396 // Make sure the save as dialog doesn't notify us back if we're gone before
397 // it returns.
398 if (select_file_dialog_.get())
399 select_file_dialog_->ListenerDestroyed();
400
401 shutdown_needed_ = false;
402}
403
404// Issue a history query for downloads matching 'search_text'. If 'search_text'
405// is empty, return all downloads that we know about.
406void DownloadManager::GetDownloads(Observer* observer,
407 const std::wstring& search_text) {
408 DCHECK(observer);
409
410 // Return a empty list if we've not yet received the set of downloads from the
411 // history system (we'll update all observers once we get that list in
412 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
413 std::vector<DownloadItem*> download_copy;
414 if (downloads_.empty()) {
415 observer->SetDownloads(download_copy);
416 return;
417 }
418
419 // We already know all the downloads and there is no filter, so just return a
420 // copy to the observer.
421 if (search_text.empty()) {
422 download_copy.reserve(downloads_.size());
423 for (DownloadMap::iterator it = downloads_.begin();
424 it != downloads_.end(); ++it) {
425 download_copy.push_back(it->second);
426 }
427
428 // We retain ownership of the DownloadItems.
429 observer->SetDownloads(download_copy);
430 return;
431 }
432
433 // Issue a request to the history service for a list of downloads matching
434 // our search text.
435 HistoryService* hs =
436 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
437 if (hs) {
438 HistoryService::Handle h =
439 hs->SearchDownloads(search_text,
440 &cancelable_consumer_,
441 NewCallback(this,
442 &DownloadManager::OnSearchComplete));
443 cancelable_consumer_.SetClientData(hs, h, observer);
444 }
445}
446
447// Query the history service for information about all persisted downloads.
448bool DownloadManager::Init(Profile* profile) {
449 DCHECK(profile);
450 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
451 shutdown_needed_ = true;
452
453 profile_ = profile;
454 request_context_ = profile_->GetRequestContext();
455
456 // 'incognito mode' will have access to past downloads, but we won't store
457 // information about new downloads while in that mode.
458 QueryHistoryForDownloads();
459
460 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
461 if (!rdh) {
462 NOTREACHED();
463 return false;
464 }
465
466 file_manager_ = rdh->download_file_manager();
467 if (!file_manager_) {
468 NOTREACHED();
469 return false;
470 }
471
472 file_loop_ = g_browser_process->file_thread()->message_loop();
473 if (!file_loop_) {
474 NOTREACHED();
475 return false;
476 }
477
478 // Get our user preference state.
479 PrefService* prefs = profile_->GetPrefs();
480 DCHECK(prefs);
481 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
482
initial.commit09911bf2008-07-26 23:55:29483 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
484
[email protected]7ae7c2cb2009-01-06 23:31:41485 // This variable is needed to resolve which CreateDirectory we want to point
486 // to. Without it, the NewRunnableFunction cannot resolve the ambiguity.
487 // TODO(estade): when file_util::CreateDirectory(wstring) is removed,
488 // get rid of |CreateDirectoryPtr|.
489 bool (*CreateDirectoryPtr)(const FilePath&) = &file_util::CreateDirectory;
[email protected]bb69e9b32008-08-14 23:08:14490 // Ensure that the download directory specified in the preferences exists.
[email protected]7ae7c2cb2009-01-06 23:31:41491 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
492 CreateDirectoryPtr, download_path()));
initial.commit09911bf2008-07-26 23:55:29493
[email protected]2b2f8f72009-02-24 22:42:05494#if defined(OS_WIN)
495 // We use this on windows to determine possibly dangerous downloads.
496 download_util::InitializeExeTypes(&exe_types_);
497#endif
498
499 // We store any file extension that should be opened automatically at
500 // download completion in this pref.
initial.commit09911bf2008-07-26 23:55:29501 std::wstring extensions_to_open =
502 prefs->GetString(prefs::kDownloadExtensionsToOpen);
503 std::vector<std::wstring> extensions;
504 SplitString(extensions_to_open, L':', &extensions);
505 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]b7f05882009-02-22 01:21:56506 if (!extensions[i].empty() && !IsExecutable(
507 FilePath::FromWStringHack(extensions[i]).value()))
508 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29509 }
510
511 return true;
512}
513
514void DownloadManager::QueryHistoryForDownloads() {
515 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
516 if (hs) {
517 hs->QueryDownloads(
518 &cancelable_consumer_,
519 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
520 }
521}
522
523// We have received a message from DownloadFileManager about a new download. We
524// create a download item and store it in our download map, and inform the
525// history system of a new download. Since this method can be called while the
526// history service thread is still reading the persistent state, we do not
527// insert the new DownloadItem into 'downloads_' or inform our observers at this
528// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
529// download creation as a callback from the history thread.
530void DownloadManager::StartDownload(DownloadCreateInfo* info) {
531 DCHECK(MessageLoop::current() == ui_loop_);
532 DCHECK(info);
533
[email protected]7d3851d82008-12-12 03:26:07534 // Freeze the user's preference for showing a Save As dialog. We're going to
535 // bounce around a bunch of threads and we don't want to worry about race
536 // conditions where the user changes this pref out from under us.
537 if (*prompt_for_download_)
538 info->save_as = true;
539
initial.commit09911bf2008-07-26 23:55:29540 // Determine the proper path for a download, by choosing either the default
541 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41542 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29543 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07544 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29545 info->suggested_path = last_download_path_;
546 else
[email protected]7ae7c2cb2009-01-06 23:31:41547 info->suggested_path = download_path();
548 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29549
[email protected]7d3851d82008-12-12 03:26:07550 if (!info->save_as) {
551 // Let's check if this download is dangerous, based on its name.
[email protected]7ae7c2cb2009-01-06 23:31:41552 info->is_dangerous = IsDangerous(info->suggested_path.BaseName());
[email protected]e9ebf3fc2008-10-17 22:06:58553 }
554
initial.commit09911bf2008-07-26 23:55:29555 // We need to move over to the download thread because we don't want to stat
556 // the suggested path on the UI thread.
557 file_loop_->PostTask(FROM_HERE,
558 NewRunnableMethod(this,
559 &DownloadManager::CheckIfSuggestedPathExists,
560 info));
561}
562
563void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
564 DCHECK(info);
565
566 // Check writability of the suggested path. If we can't write to it, default
567 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41568 FilePath dir = info->suggested_path.DirName();
569 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32570 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29571 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29572 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41573 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29574 }
575
[email protected]7a256ea2008-10-17 17:34:16576 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29577
[email protected]6cade212008-12-03 00:32:22578 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58579 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41580 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32581 // Create a temporary file to hold the file until the user approves its
582 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41583 FilePath::StringType file_name;
584 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32585 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41586 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32587 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41588 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07589 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41590 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32591 }
592 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16593 } else {
594 // We know the final path, build it if necessary.
595 if (info->path_uniquifier > 0) {
596 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
597 // Setting path_uniquifier to 0 to make sure we don't try to unique it
598 // later on.
599 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07600 } else if (info->path_uniquifier == -1) {
601 // We failed to find a unique path. We have to prompt the user.
602 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16603 }
[email protected]9ccbb372008-10-10 18:50:32604 }
605
[email protected]7d3851d82008-12-12 03:26:07606 if (!info->save_as) {
607 // Create an empty file at the suggested path so that we don't allocate the
608 // same "non-existant" path to multiple downloads.
609 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ae7c2cb2009-01-06 23:31:41610 file_util::WriteFile(info->suggested_path.ToWStringHack(), "", 0);
[email protected]7d3851d82008-12-12 03:26:07611 }
612
initial.commit09911bf2008-07-26 23:55:29613 // Now we return to the UI thread.
614 ui_loop_->PostTask(FROM_HERE,
615 NewRunnableMethod(this,
616 &DownloadManager::OnPathExistenceAvailable,
617 info));
618}
619
620void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]b7f05882009-02-22 01:21:56621#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29622 DCHECK(MessageLoop::current() == ui_loop_);
623 DCHECK(info);
624
[email protected]7d3851d82008-12-12 03:26:07625 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29626 // We must ask the user for the place to put the download.
627 if (!select_file_dialog_.get())
628 select_file_dialog_ = SelectFileDialog::Create(this);
629
[email protected]a3a1d142008-12-19 00:42:30630 WebContents* contents = tab_util::GetWebContentsByID(
initial.commit09911bf2008-07-26 23:55:29631 info->render_process_id, info->render_view_id);
[email protected]7ae7c2cb2009-01-06 23:31:41632 std::wstring filter =
633 win_util::GetFileFilterFromPath(info->suggested_path.value());
initial.commit09911bf2008-07-26 23:55:29634 HWND owning_hwnd =
[email protected]92edc472009-02-10 20:32:06635 contents ? GetAncestor(contents->GetNativeView(), GA_ROOT) : NULL;
initial.commit09911bf2008-07-26 23:55:29636 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]7ae7c2cb2009-01-06 23:31:41637 std::wstring(),
638 info->suggested_path.ToWStringHack(),
[email protected]6cade212008-12-03 00:32:22639 filter, std::wstring(),
initial.commit09911bf2008-07-26 23:55:29640 owning_hwnd, info);
641 } else {
642 // No prompting for download, just continue with the suggested name.
643 ContinueStartDownload(info, info->suggested_path);
644 }
[email protected]b7f05882009-02-22 01:21:56645#elif defined(OS_POSIX)
646 // TODO(port): port this file -- need dialogs.
647 NOTIMPLEMENTED();
648#endif
initial.commit09911bf2008-07-26 23:55:29649}
650
651void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41652 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29653 scoped_ptr<DownloadCreateInfo> infop(info);
654 info->path = target_path;
655
656 DownloadItem* download = NULL;
657 DownloadMap::iterator it = in_progress_.find(info->download_id);
658 if (it == in_progress_.end()) {
659 download = new DownloadItem(info->download_id,
660 info->path,
[email protected]7a256ea2008-10-17 17:34:16661 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29662 info->url,
[email protected]9ccbb372008-10-10 18:50:32663 info->original_name,
initial.commit09911bf2008-07-26 23:55:29664 info->start_time,
665 info->total_bytes,
666 info->render_process_id,
[email protected]9ccbb372008-10-10 18:50:32667 info->request_id,
668 info->is_dangerous);
initial.commit09911bf2008-07-26 23:55:29669 download->set_manager(this);
670 in_progress_[info->download_id] = download;
671 } else {
672 NOTREACHED(); // Should not exist!
673 return;
674 }
675
676 // If the download already completed by the time we reached this point, then
677 // notify observers that it did.
678 PendingFinishedMap::iterator pending_it =
679 pending_finished_downloads_.find(info->download_id);
680 if (pending_it != pending_finished_downloads_.end())
681 DownloadFinished(pending_it->first, pending_it->second);
682
683 download->Rename(target_path);
684
685 file_loop_->PostTask(FROM_HERE,
686 NewRunnableMethod(file_manager_,
687 &DownloadFileManager::OnFinalDownloadName,
688 download->id(),
689 target_path));
690
691 if (profile_->IsOffTheRecord()) {
692 // Fake a db handle for incognito mode, since nothing is actually stored in
693 // the database in this mode. We have to make sure that these handles don't
694 // collide with normal db handles, so we use a negative value. Eventually,
695 // they could overlap, but you'd have to do enough downloading that your ISP
696 // would likely stab you in the neck first. YMMV.
697 static int64 fake_db_handle = kUninitializedHandle - 1;
698 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
699 } else {
700 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22701 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29702 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
703 if (hs) {
704 hs->CreateDownload(
705 *info, &cancelable_consumer_,
706 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
707 }
708 }
709}
710
711// Convenience function for updating the history service for a download.
712void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
713 DCHECK(download);
714
715 // Don't store info in the database if the download was initiated while in
716 // incognito mode or if it hasn't been initialized in our database table.
717 if (download->db_handle() <= kUninitializedHandle)
718 return;
719
[email protected]6cade212008-12-03 00:32:22720 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29721 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
722 if (hs) {
723 hs->UpdateDownload(download->received_bytes(),
724 download->state(),
725 download->db_handle());
726 }
727}
728
729void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
730 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22731 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29732 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
733 if (download->db_handle() > kUninitializedHandle && hs)
734 hs->RemoveDownload(download->db_handle());
735}
736
[email protected]e93d2822009-01-30 05:59:59737void DownloadManager::RemoveDownloadsFromHistoryBetween(
738 const base::Time remove_begin,
739 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22740 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29741 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
742 if (hs)
743 hs->RemoveDownloadsBetween(remove_begin, remove_end);
744}
745
746void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
747 DownloadMap::iterator it = in_progress_.find(download_id);
748 if (it != in_progress_.end()) {
749 DownloadItem* download = it->second;
750 download->Update(size);
751 UpdateHistoryForDownload(download);
752 }
753}
754
755void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
756 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32757 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29758 // The download is done, but the user hasn't selected a final location for
759 // it yet (the Save As dialog box is probably still showing), so just keep
760 // track of the fact that this download id is complete, when the
761 // DownloadItem is constructed later we'll notify its completion then.
762 PendingFinishedMap::iterator erase_it =
763 pending_finished_downloads_.find(download_id);
764 DCHECK(erase_it == pending_finished_downloads_.end());
765 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32766 return;
initial.commit09911bf2008-07-26 23:55:29767 }
[email protected]9ccbb372008-10-10 18:50:32768
769 // Remove the id from the list of pending ids.
770 PendingFinishedMap::iterator erase_it =
771 pending_finished_downloads_.find(download_id);
772 if (erase_it != pending_finished_downloads_.end())
773 pending_finished_downloads_.erase(erase_it);
774
775 DownloadItem* download = it->second;
776 download->Finished(size);
777
778 // Clean up will happen when the history system create callback runs if we
779 // don't have a valid db_handle yet.
780 if (download->db_handle() != kUninitializedHandle) {
781 in_progress_.erase(it);
782 NotifyAboutDownloadStop();
783 UpdateHistoryForDownload(download);
784 }
785
786 // If this a dangerous download not yet validated by the user, don't do
787 // anything. When the user notifies us, it will trigger a call to
788 // ProceedWithFinishedDangerousDownload.
789 if (download->safety_state() == DownloadItem::DANGEROUS) {
790 dangerous_finished_[download_id] = download;
791 return;
792 }
793
794 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22795 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32796 // its final name before we can continue.
797 file_loop_->PostTask(FROM_HERE,
798 NewRunnableMethod(
799 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
800 download->db_handle(),
801 download->full_path(), download->original_name()));
802 return;
803 }
804 ContinueDownloadFinished(download);
805}
806
807void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
808 // If this was a dangerous download, it has now been approved and must be
809 // removed from dangerous_finished_ so it does not get deleted on shutdown.
810 DownloadMap::iterator it = dangerous_finished_.find(download->id());
811 if (it != dangerous_finished_.end())
812 dangerous_finished_.erase(it);
813
814 // Notify our observers that we are complete (the call to Finished() set the
815 // state to complete but did not notify).
816 download->UpdateObservers();
817
818 // Open the download if the user or user prefs indicate it should be.
[email protected]2001fe82009-02-23 23:53:14819 FilePath::StringType extension = download->full_path().Extension();
820 // Drop the leading period.
821 if (extension.size() > 0)
822 extension = extension.substr(1);
[email protected]9ccbb372008-10-10 18:50:32823 if (download->open_when_complete() || ShouldOpenFileExtension(extension))
824 OpenDownloadInShell(download, NULL);
825}
826
827// Called on the file thread. Renames the downloaded file to its original name.
828void DownloadManager::ProceedWithFinishedDangerousDownload(
829 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41830 const FilePath& path,
831 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32832 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41833 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16834 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32835 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24836 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16837 // Make our name unique at this point, as if a dangerous file is downloading
838 // and a 2nd download is started for a file with the same name, they would
839 // have the same path. This is because we uniquify the name on download
840 // start, and at that time the first file does not exists yet, so the second
841 // file gets the same name.
842 uniquifier = GetUniquePathNumber(new_path);
843 if (uniquifier > 0)
844 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32845 success = file_util::Move(path, new_path);
846 } else {
847 NOTREACHED();
848 }
[email protected]6cade212008-12-03 00:32:22849
[email protected]9ccbb372008-10-10 18:50:32850 ui_loop_->PostTask(FROM_HERE,
851 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16852 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32853}
854
855// Call from the file thread when the finished dangerous download was renamed.
856void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
857 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41858 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16859 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32860 DownloadMap::iterator it = downloads_.find(download_handle);
861 if (it == downloads_.end()) {
862 NOTREACHED();
863 return;
864 }
865
866 DownloadItem* download = it->second;
867 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16868 if (success) {
869 // We need to update the path uniquifier so that the UI shows the right
870 // name when calling GetFileName().
871 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32872 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16873 }
[email protected]9ccbb372008-10-10 18:50:32874
875 // Continue the download finished sequence.
876 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29877}
878
879// static
880// We have to tell the ResourceDispatcherHost to cancel the download from this
[email protected]6cade212008-12-03 00:32:22881// thread, since we can't forward tasks from the file thread to the IO thread
initial.commit09911bf2008-07-26 23:55:29882// reliably (crash on shutdown race condition).
883void DownloadManager::CancelDownloadRequest(int render_process_id,
884 int request_id) {
885 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]ab820df2008-08-26 05:55:10886 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29887 if (!io_thread || !rdh)
888 return;
889 io_thread->message_loop()->PostTask(FROM_HERE,
890 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
891 rdh,
892 render_process_id,
893 request_id));
894}
895
896// static
897void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
898 int render_process_id,
899 int request_id) {
900 rdh->CancelRequest(render_process_id, request_id, false);
901}
902
903void DownloadManager::DownloadCancelled(int32 download_id) {
904 DownloadMap::iterator it = in_progress_.find(download_id);
905 if (it == in_progress_.end())
906 return;
907 DownloadItem* download = it->second;
908
909 CancelDownloadRequest(download->render_process_id(), download->request_id());
910
911 // Clean up will happen when the history system create callback runs if we
912 // don't have a valid db_handle yet.
913 if (download->db_handle() != kUninitializedHandle) {
914 in_progress_.erase(it);
915 NotifyAboutDownloadStop();
916 UpdateHistoryForDownload(download);
917 }
918
919 // Tell the file manager to cancel the download.
920 file_manager_->RemoveDownload(download->id(), this); // On the UI thread
921 file_loop_->PostTask(FROM_HERE,
922 NewRunnableMethod(file_manager_,
923 &DownloadFileManager::CancelDownload,
924 download->id()));
925}
926
927void DownloadManager::PauseDownload(int32 download_id, bool pause) {
928 DownloadMap::iterator it = in_progress_.find(download_id);
929 if (it != in_progress_.end()) {
930 DownloadItem* download = it->second;
931 if (pause == download->is_paused())
932 return;
933
934 // Inform the ResourceDispatcherHost of the new pause state.
[email protected]ab820df2008-08-26 05:55:10935 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29936 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
937 if (!io_thread || !rdh)
938 return;
939
940 io_thread->message_loop()->PostTask(FROM_HERE,
941 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
942 rdh,
943 download->render_process_id(),
944 download->request_id(),
945 pause));
946 }
947}
948
949// static
950void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
951 int render_process_id,
952 int request_id,
953 bool pause) {
954 rdh->PauseRequest(render_process_id, request_id, pause);
955}
956
[email protected]7ae7c2cb2009-01-06 23:31:41957bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:32958 // TODO(jcampan): Improve me.
[email protected]2001fe82009-02-23 23:53:14959 FilePath::StringType extension = file_name.Extension();
960 // Drop the leading period.
961 if (extension.size() > 0)
962 extension = extension.substr(1);
963 return IsExecutable(extension);
[email protected]9ccbb372008-10-10 18:50:32964}
965
966void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:41967 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:32968 download->Rename(new_path);
969
970 // Update the history.
971
972 // No update necessary if the download was initiated while in incognito mode.
973 if (download->db_handle() <= kUninitializedHandle)
974 return;
975
[email protected]6cade212008-12-03 00:32:22976 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:32977 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
978 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:41979 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:32980}
981
initial.commit09911bf2008-07-26 23:55:29982void DownloadManager::RemoveDownload(int64 download_handle) {
983 DownloadMap::iterator it = downloads_.find(download_handle);
984 if (it == downloads_.end())
985 return;
986
987 // Make history update.
988 DownloadItem* download = it->second;
989 RemoveDownloadFromHistory(download);
990
991 // Remove from our tables and delete.
992 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32993 it = dangerous_finished_.find(download->id());
994 if (it != dangerous_finished_.end())
995 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:29996
997 // Tell observers to refresh their views.
998 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:36999
1000 delete download;
initial.commit09911bf2008-07-26 23:55:291001}
1002
[email protected]e93d2822009-01-30 05:59:591003int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1004 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291005 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1006
1007 int num_deleted = 0;
1008 DownloadMap::iterator it = downloads_.begin();
1009 while (it != downloads_.end()) {
1010 DownloadItem* download = it->second;
1011 DownloadItem::DownloadState state = download->state();
1012 if (download->start_time() >= remove_begin &&
1013 (remove_end.is_null() || download->start_time() < remove_end) &&
1014 (state == DownloadItem::COMPLETE ||
1015 state == DownloadItem::CANCELLED)) {
1016 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561017 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581018
1019 // Also remove it from any completed dangerous downloads.
1020 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1021 if (dit != dangerous_finished_.end())
1022 dangerous_finished_.erase(dit);
1023
initial.commit09911bf2008-07-26 23:55:291024 delete download;
1025
1026 ++num_deleted;
1027 continue;
1028 }
1029
1030 ++it;
1031 }
1032
1033 // Tell observers to refresh their views.
1034 if (num_deleted > 0)
1035 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1036
1037 return num_deleted;
1038}
1039
[email protected]e93d2822009-01-30 05:59:591040int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1041 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291042}
1043
1044// Initiate a download of a specific URL. We send the request to the
1045// ResourceDispatcherHost, and let it send us responses like a regular
1046// download.
1047void DownloadManager::DownloadUrl(const GURL& url,
1048 const GURL& referrer,
1049 WebContents* web_contents) {
1050 DCHECK(web_contents);
1051 file_manager_->DownloadUrl(url,
1052 referrer,
1053 web_contents->process()->host_id(),
1054 web_contents->render_view_host()->routing_id(),
1055 request_context_.get());
1056}
1057
1058void DownloadManager::NotifyAboutDownloadStart() {
[email protected]bfd04a62009-02-01 18:16:561059 NotificationService::current()->Notify(
1060 NotificationType::DOWNLOAD_START,
1061 NotificationService::AllSources(),
1062 NotificationService::NoDetails());
initial.commit09911bf2008-07-26 23:55:291063}
1064
1065void DownloadManager::NotifyAboutDownloadStop() {
[email protected]bfd04a62009-02-01 18:16:561066 NotificationService::current()->Notify(
1067 NotificationType::DOWNLOAD_STOP,
1068 NotificationService::AllSources(),
1069 NotificationService::NoDetails());
initial.commit09911bf2008-07-26 23:55:291070}
1071
[email protected]7ae7c2cb2009-01-06 23:31:411072void DownloadManager::GenerateExtension(
1073 const FilePath& file_name,
1074 const std::string& mime_type,
1075 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291076 // We're worried about three things here:
1077 //
1078 // 1) Security. Many sites let users upload content, such as buddy icons, to
1079 // their web sites. We want to mitigate the case where an attacker
1080 // supplies a malicious executable with an executable file extension but an
1081 // honest site serves the content with a benign content type, such as
1082 // image/jpeg.
1083 //
1084 // 2) Usability. If the site fails to provide a file extension, we want to
1085 // guess a reasonable file extension based on the content type.
1086 //
1087 // 3) Shell integration. Some file extensions automatically integrate with
1088 // the shell. We block these extensions to prevent a malicious web site
1089 // from integrating with the user's shell.
1090
[email protected]7ae7c2cb2009-01-06 23:31:411091 static const FilePath::CharType default_extension[] =
1092 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291093
1094 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411095 FilePath::StringType extension(
1096 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291097
[email protected]b7f05882009-02-22 01:21:561098#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291099 // Rename shell-integrated extensions.
1100 if (win_util::IsShellIntegratedExtension(extension))
1101 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561102#endif
initial.commit09911bf2008-07-26 23:55:291103
1104 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411105 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411106 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291107 if (mime_type == mime_type_from_extension) {
1108 // The hinted extension matches the mime type. It looks like a winner.
1109 generated_extension->swap(extension);
1110 return;
1111 }
1112
1113 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1114 // We want to be careful about executable extensions. The worry here is
1115 // that a trusted web site could be tricked into dropping an executable file
1116 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101117 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291118 // We couldn't find a good extension for this content type. Use a dummy
1119 // extension instead.
1120 extension.assign(default_extension);
1121 }
1122 }
1123
1124 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101125 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291126 } else {
[email protected]6cade212008-12-03 00:32:221127 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291128 // 1. New extension is not ".txt"
1129 // 2. New extension is not the same as the already existing extension.
1130 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411131 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291132 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1133 // application/x-javascript.
[email protected]7ae7c2cb2009-01-06 23:31:411134 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101135 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171136 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411137 append_extension != extension &&
[email protected]3f156552009-02-09 19:44:171138 !IsExecutable(append_extension)) {
1139 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291140 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171141 }
initial.commit09911bf2008-07-26 23:55:291142 }
1143 }
1144
1145 generated_extension->swap(extension);
1146}
1147
1148void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411149 FilePath* generated_name) {
1150 *generated_name = FilePath::FromWStringHack(
[email protected]8ac1a752008-07-31 19:40:371151 net::GetSuggestedFilename(GURL(info->url),
1152 info->content_disposition,
[email protected]7ae7c2cb2009-01-06 23:31:411153 L"download"));
1154 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291155
[email protected]7ae7c2cb2009-01-06 23:31:411156 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291157}
1158
1159void DownloadManager::AddObserver(Observer* observer) {
1160 observers_.AddObserver(observer);
1161 observer->ModelChanged();
1162}
1163
1164void DownloadManager::RemoveObserver(Observer* observer) {
1165 observers_.RemoveObserver(observer);
1166}
1167
1168// Post Windows Shell operations to the Download thread, to avoid blocking the
1169// user interface.
1170void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1171 DCHECK(file_manager_);
1172 file_loop_->PostTask(FROM_HERE,
1173 NewRunnableMethod(file_manager_,
1174 &DownloadFileManager::OnShowDownloadInShell,
[email protected]7ae7c2cb2009-01-06 23:31:411175 FilePath(download->full_path())));
initial.commit09911bf2008-07-26 23:55:291176}
1177
1178void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591179 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291180 DCHECK(file_manager_);
1181 file_loop_->PostTask(FROM_HERE,
1182 NewRunnableMethod(file_manager_,
1183 &DownloadFileManager::OnOpenDownloadInShell,
1184 download->full_path(), download->url(), parent_window));
1185}
1186
[email protected]7ae7c2cb2009-01-06 23:31:411187void DownloadManager::OpenFilesOfExtension(
1188 const FilePath::StringType& extension, bool open) {
initial.commit09911bf2008-07-26 23:55:291189 if (open && !IsExecutable(extension))
1190 auto_open_.insert(extension);
1191 else
1192 auto_open_.erase(extension);
1193 SaveAutoOpens();
1194}
1195
[email protected]7ae7c2cb2009-01-06 23:31:411196bool DownloadManager::ShouldOpenFileExtension(
1197 const FilePath::StringType& extension) {
[email protected]8c756ac2009-01-30 23:36:411198 // Special-case Chrome extensions as always-open.
initial.commit09911bf2008-07-26 23:55:291199 if (!IsExecutable(extension) &&
[email protected]8c756ac2009-01-30 23:36:411200 (auto_open_.find(extension) != auto_open_.end() ||
1201 extension == chrome::kExtensionFileExtension))
1202 return true;
initial.commit09911bf2008-07-26 23:55:291203 return false;
1204}
1205
[email protected]7b73d992008-12-15 20:56:461206static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291207 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461208 "text/javascript",
1209 "text/javascript;version=*",
[email protected]60ff8f912008-12-05 07:58:391210 // Some sites use binary/octet-stream to mean application/octet-stream.
1211 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461212 "binary/octet-stream"
1213};
initial.commit09911bf2008-07-26 23:55:291214
[email protected]7b73d992008-12-15 20:56:461215static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291216 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461217 "application/*+xml",
1218 "application/xml"
1219};
initial.commit09911bf2008-07-26 23:55:291220
[email protected]7b73d992008-12-15 20:56:461221// static
1222bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411223 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461224 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1225 return true;
1226 }
[email protected]bae0ea12009-02-14 01:20:411227 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461228 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1229 return false;
1230 }
1231 // We consider only other application types to be executable.
1232 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291233}
1234
[email protected]7ae7c2cb2009-01-06 23:31:411235bool DownloadManager::IsExecutable(const FilePath::StringType& extension) {
[email protected]64da0b932009-02-24 02:30:041236#if defined(OS_WIN)
1237 if (!IsStringASCII(extension))
1238 return false;
1239 std::string ascii_extension = WideToASCII(extension);
1240 StringToLowerASCII(&ascii_extension);
1241
1242 return exe_types_.find(ascii_extension) != exe_types_.end();
1243#elif defined(OS_POSIX)
1244 // TODO(port): we misght not want to call this function on other platforms.
1245 // Figure it out.
1246 NOTIMPLEMENTED();
1247 return false;
1248#endif
initial.commit09911bf2008-07-26 23:55:291249}
1250
1251void DownloadManager::ResetAutoOpenFiles() {
1252 auto_open_.clear();
1253 SaveAutoOpens();
1254}
1255
1256bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1257 return !auto_open_.empty();
1258}
1259
1260void DownloadManager::SaveAutoOpens() {
1261 PrefService* prefs = profile_->GetPrefs();
1262 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411263 FilePath::StringType extensions;
1264 for (std::set<FilePath::StringType>::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291265 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411266 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291267 }
1268 if (!extensions.empty())
1269 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561270
1271 std::wstring extensions_w;
1272#if defined(OS_WIN)
1273 extensions_w = extensions;
1274#elif defined(OS_POSIX)
[email protected]1b5044d2009-02-24 00:04:141275 extensions_w = base::SysNativeMBToWide(extensions);
[email protected]b7f05882009-02-22 01:21:561276#endif
1277
1278 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291279 }
1280}
1281
[email protected]7ae7c2cb2009-01-06 23:31:411282void DownloadManager::FileSelected(const std::wstring& path_string,
1283 void* params) {
1284 FilePath path = FilePath::FromWStringHack(path_string);
initial.commit09911bf2008-07-26 23:55:291285 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071286 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411287 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291288 ContinueStartDownload(info, path);
1289}
1290
1291void DownloadManager::FileSelectionCanceled(void* params) {
1292 // The user didn't pick a place to save the file, so need to cancel the
1293 // download that's already in progress to the temporary location.
1294 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
1295 file_loop_->PostTask(FROM_HERE,
1296 NewRunnableMethod(file_manager_, &DownloadFileManager::CancelDownload,
1297 info->download_id));
1298}
1299
[email protected]7ae7c2cb2009-01-06 23:31:411300void DownloadManager::DeleteDownload(const FilePath& path) {
1301 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
1302 &DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321303}
1304
1305
1306void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1307 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1308 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1309 download->UpdateObservers();
1310
1311 // If the download is not complete, nothing to do. The required
1312 // post-processing will be performed when it does complete.
1313 if (download->state() != DownloadItem::COMPLETE)
1314 return;
1315
1316 file_loop_->PostTask(FROM_HERE,
1317 NewRunnableMethod(this,
1318 &DownloadManager::ProceedWithFinishedDangerousDownload,
1319 download->db_handle(), download->full_path(),
1320 download->original_name()));
1321}
1322
[email protected]763f946a2009-01-06 19:04:391323void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411324 FilePath* file_name) {
1325 // Make sure we get the right file extension
1326 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391327 GenerateExtension(*file_name, mime_type, &extension);
1328 file_util::ReplaceExtension(file_name, extension);
1329
[email protected]2b2f8f72009-02-24 22:42:051330#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391331 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411332 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391333 DCHECK(!leaf_name.empty());
[email protected]763f946a2009-01-06 19:04:391334 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411335 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1336 *file_name = file_name->DirName();
1337 if (file_name->value() == FilePath::kCurrentDirectory) {
1338 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391339 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411340 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391341 }
1342 }
[email protected]b7f05882009-02-22 01:21:561343#elif defined(OS_POSIX)
1344 NOTIMPLEMENTED();
1345#endif
[email protected]763f946a2009-01-06 19:04:391346}
1347
initial.commit09911bf2008-07-26 23:55:291348// Operations posted to us from the history service ----------------------------
1349
1350// The history service has retrieved all download entries. 'entries' contains
1351// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1352void DownloadManager::OnQueryDownloadEntriesComplete(
1353 std::vector<DownloadCreateInfo>* entries) {
1354 for (size_t i = 0; i < entries->size(); ++i) {
1355 DownloadItem* download = new DownloadItem(entries->at(i));
1356 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1357 downloads_[download->db_handle()] = download;
1358 download->set_manager(this);
1359 }
1360 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1361}
1362
1363
1364// Once the new DownloadItem's creation info has been committed to the history
1365// service, we associate the DownloadItem with the db handle, update our
1366// 'downloads_' map and inform observers.
1367void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1368 int64 db_handle) {
1369 DownloadMap::iterator it = in_progress_.find(info.download_id);
1370 DCHECK(it != in_progress_.end());
1371
1372 DownloadItem* download = it->second;
1373 DCHECK(download->db_handle() == kUninitializedHandle);
1374 download->set_db_handle(db_handle);
1375
1376 // Insert into our full map.
1377 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1378 downloads_[download->db_handle()] = download;
1379
1380 // The 'contents' may no longer exist if the user closed the tab before we get
1381 // this start completion event. If it does, tell the origin WebContents to
1382 // display its download shelf.
1383 TabContents* contents =
[email protected]a3a1d142008-12-19 00:42:301384 tab_util::GetWebContentsByID(info.render_process_id, info.render_view_id);
initial.commit09911bf2008-07-26 23:55:291385
1386 // If the contents no longer exists or is no longer active, we start the
1387 // download in the last active browser. This is not ideal but better than
1388 // fully hiding the download from the user. Note: non active means that the
1389 // user navigated away from the tab contents. This has nothing to do with
1390 // tab selection.
1391 if (!contents || !contents->is_active()) {
1392 Browser* last_active = BrowserList::GetLastActive();
1393 if (last_active)
1394 contents = last_active->GetSelectedTabContents();
1395 }
1396
1397 if (contents)
1398 contents->OnStartDownload(download);
1399
1400 // Inform interested objects about the new download.
1401 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1402 NotifyAboutDownloadStart();
1403
1404 // If this download has been completed before we've received the db handle,
1405 // post one final message to the history service so that it can be properly
1406 // in sync with the DownloadItem's completion status, and also inform any
1407 // observers so that they get more than just the start notification.
1408 if (download->state() != DownloadItem::IN_PROGRESS) {
1409 in_progress_.erase(it);
1410 NotifyAboutDownloadStop();
1411 UpdateHistoryForDownload(download);
1412 download->UpdateObservers();
1413 }
1414}
1415
1416// Called when the history service has retrieved the list of downloads that
1417// match the search text.
1418void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1419 std::vector<int64>* results) {
1420 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1421 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1422 if (!requestor)
1423 return;
1424
1425 std::vector<DownloadItem*> searched_downloads;
1426 for (std::vector<int64>::iterator it = results->begin();
1427 it != results->end(); ++it) {
1428 DownloadMap::iterator dit = downloads_.find(*it);
1429 if (dit != downloads_.end())
1430 searched_downloads.push_back(dit->second);
1431 }
1432
1433 requestor->SetDownloads(searched_downloads);
1434}
[email protected]905a08d2008-11-19 07:24:121435
[email protected]6cade212008-12-03 00:32:221436// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121437void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411438 last_download_path_ = FilePath();
[email protected]905a08d2008-11-19 07:24:121439}