blob: 98b0e327c351d3af816baf252f2afc2f62df4864 [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
[email protected]0f44d3e2009-03-12 23:36:3048#if defined(OS_LINUX)
49#include <gtk/gtk.h>
50#endif
51
initial.commit09911bf2008-07-26 23:55:2952// Periodically update our observers.
53class DownloadItemUpdateTask : public Task {
54 public:
55 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
56 void Run() { if (item_) item_->UpdateObservers(); }
57
58 private:
59 DownloadItem* item_;
60};
61
62// Update frequency (milliseconds).
63static const int kUpdateTimeMs = 1000;
64
65// Our download table ID starts at 1, so we use 0 to represent a download that
66// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2267// database handles in incognito mode starting at -1 and progressively getting
68// more negative.
initial.commit09911bf2008-07-26 23:55:2969static const int kUninitializedHandle = 0;
70
[email protected]7a256ea2008-10-17 17:34:1671// Appends the passed the number between parenthesis the path before the
72// extension.
[email protected]7ae7c2cb2009-01-06 23:31:4173static void AppendNumberToPath(FilePath* path, int number) {
74 file_util::InsertBeforeExtension(path,
75 StringPrintf(FILE_PATH_LITERAL(" (%d)"), number));
[email protected]7a256ea2008-10-17 17:34:1676}
77
78// Attempts to find a number that can be appended to that path to make it
79// unique. If |path| does not exist, 0 is returned. If it fails to find such
80// a number, -1 is returned.
[email protected]7ae7c2cb2009-01-06 23:31:4181static int GetUniquePathNumber(const FilePath& path) {
initial.commit09911bf2008-07-26 23:55:2982 const int kMaxAttempts = 100;
83
[email protected]7a256ea2008-10-17 17:34:1684 if (!file_util::PathExists(path))
85 return 0;
initial.commit09911bf2008-07-26 23:55:2986
[email protected]7ae7c2cb2009-01-06 23:31:4187 FilePath new_path;
initial.commit09911bf2008-07-26 23:55:2988 for (int count = 1; count <= kMaxAttempts; ++count) {
[email protected]7ae7c2cb2009-01-06 23:31:4189 new_path = FilePath(path);
[email protected]7a256ea2008-10-17 17:34:1690 AppendNumberToPath(&new_path, count);
initial.commit09911bf2008-07-26 23:55:2991
[email protected]7a256ea2008-10-17 17:34:1692 if (!file_util::PathExists(new_path))
93 return count;
initial.commit09911bf2008-07-26 23:55:2994 }
95
[email protected]7a256ea2008-10-17 17:34:1696 return -1;
initial.commit09911bf2008-07-26 23:55:2997}
98
[email protected]7ae7c2cb2009-01-06 23:31:4199static bool DownloadPathIsDangerous(const FilePath& download_path) {
100 FilePath desktop_dir;
[email protected]f052118e2008-09-05 02:25:32101 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
102 NOTREACHED();
103 return false;
104 }
105 return (download_path == desktop_dir);
106}
107
initial.commit09911bf2008-07-26 23:55:29108// DownloadItem implementation -------------------------------------------------
109
110// Constructor for reading from the history service.
111DownloadItem::DownloadItem(const DownloadCreateInfo& info)
112 : id_(-1),
113 full_path_(info.path),
114 url_(info.url),
115 total_bytes_(info.total_bytes),
116 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56117 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29118 state_(static_cast<DownloadState>(info.state)),
119 start_time_(info.start_time),
120 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29121 manager_(NULL),
122 is_paused_(false),
123 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56124 safety_state_(SAFE),
125 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29126 render_process_id_(-1),
127 request_id_(-1) {
128 if (state_ == IN_PROGRESS)
129 state_ = CANCELLED;
130 Init(false /* don't start progress timer */);
131}
132
133// Constructor for DownloadItem created via user action in the main thread.
134DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41135 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16136 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32137 const GURL& url,
[email protected]7ae7c2cb2009-01-06 23:31:41138 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59139 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29140 int64 download_size,
141 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32142 int request_id,
143 bool is_dangerous)
initial.commit09911bf2008-07-26 23:55:29144 : id_(download_id),
145 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16146 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29147 url_(url),
148 total_bytes_(download_size),
149 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56150 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29151 state_(IN_PROGRESS),
152 start_time_(start_time),
153 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29154 manager_(NULL),
155 is_paused_(false),
156 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56157 safety_state_(is_dangerous ? DANGEROUS : SAFE),
158 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29159 render_process_id_(render_process_id),
160 request_id_(request_id) {
161 Init(true /* start progress timer */);
162}
163
164void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41165 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29166 if (start_timer)
167 StartProgressTimer();
168}
169
170DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29171 state_ = REMOVING;
172 UpdateObservers();
173}
174
175void DownloadItem::AddObserver(Observer* observer) {
176 observers_.AddObserver(observer);
177}
178
179void DownloadItem::RemoveObserver(Observer* observer) {
180 observers_.RemoveObserver(observer);
181}
182
183void DownloadItem::UpdateObservers() {
184 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
185}
186
187// If we've received more data than we were expecting (bad server info?), revert
188// to 'unknown size mode'.
189void DownloadItem::UpdateSize(int64 bytes_so_far) {
190 received_bytes_ = bytes_so_far;
191 if (received_bytes_ > total_bytes_)
192 total_bytes_ = 0;
193}
194
195// Updates from the download thread may have been posted while this download
196// was being cancelled in the UI thread, so we'll accept them unless we're
197// complete.
198void DownloadItem::Update(int64 bytes_so_far) {
199 if (state_ == COMPLETE) {
200 NOTREACHED();
201 return;
202 }
203 UpdateSize(bytes_so_far);
204 UpdateObservers();
205}
206
[email protected]6cade212008-12-03 00:32:22207// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29208void DownloadItem::Cancel(bool update_history) {
209 if (state_ != IN_PROGRESS) {
210 // Small downloads might be complete before this method has a chance to run.
211 return;
212 }
213 state_ = CANCELLED;
214 UpdateObservers();
215 StopProgressTimer();
216 if (update_history)
217 manager_->DownloadCancelled(id_);
218}
219
220void DownloadItem::Finished(int64 size) {
221 state_ = COMPLETE;
222 UpdateSize(size);
[email protected]22fbe5a2008-10-29 22:20:40223 UpdateObservers();
initial.commit09911bf2008-07-26 23:55:29224 StopProgressTimer();
225}
226
[email protected]9ccbb372008-10-10 18:50:32227void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29228 Cancel(true);
229 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32230 if (delete_on_disk)
231 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29232 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22233 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29234}
235
236void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59237 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14238 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29239}
240
241void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14242 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29243}
244
[email protected]e93d2822009-01-30 05:59:59245bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29246 if (total_bytes_ <= 0)
247 return false; // We never received the content_length for this download.
248
249 int64 speed = CurrentSpeed();
250 if (speed == 0)
251 return false;
252
253 *remaining =
[email protected]e93d2822009-01-30 05:59:59254 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29255 return true;
256}
257
258int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56259 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
260 int64 diff_ms = diff.InMilliseconds();
261 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29262}
263
264int DownloadItem::PercentComplete() const {
265 int percent = -1;
266 if (total_bytes_ > 0)
267 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
268 return percent;
269}
270
[email protected]7ae7c2cb2009-01-06 23:31:41271void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29272 DCHECK(!full_path.empty());
273 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41274 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29275}
276
277void DownloadItem::TogglePause() {
278 DCHECK(state_ == IN_PROGRESS);
279 manager_->PauseDownload(id_, !is_paused_);
280 is_paused_ = !is_paused_;
281 UpdateObservers();
282}
283
[email protected]7ae7c2cb2009-01-06 23:31:41284FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32285 if (safety_state_ == DownloadItem::SAFE)
286 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16287 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41288 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16289 AppendNumberToPath(&name, path_uniquifier_);
290 return name;
291 }
[email protected]9ccbb372008-10-10 18:50:32292 return original_name_;
293}
294
initial.commit09911bf2008-07-26 23:55:29295// DownloadManager implementation ----------------------------------------------
296
297// static
298void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
299 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
300 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32301 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
302
303 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41304 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12305 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
306 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32307 NOTREACHED();
308 }
[email protected]b9636002009-03-04 00:05:25309 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
310 default_download_path);
[email protected]f052118e2008-09-05 02:25:32311
312 // If the download path is dangerous we forcefully reset it. But if we do
313 // so we set a flag to make sure we only do it once, to avoid fighting
314 // the user if he really wants it on an unsafe place such as the desktop.
315
316 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41317 FilePath current_download_dir = FilePath::FromWStringHack(
318 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32319 if (DownloadPathIsDangerous(current_download_dir)) {
320 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41321 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32322 }
323 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
324 }
initial.commit09911bf2008-07-26 23:55:29325}
326
327DownloadManager::DownloadManager()
328 : shutdown_needed_(false),
329 profile_(NULL),
330 file_manager_(NULL),
331 ui_loop_(MessageLoop::current()),
332 file_loop_(NULL) {
333}
334
335DownloadManager::~DownloadManager() {
336 if (shutdown_needed_)
337 Shutdown();
338}
339
340void DownloadManager::Shutdown() {
341 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
342
343 // Stop receiving download updates
344 file_manager_->RemoveDownloadManager(this);
345
346 // Stop making history service requests
347 cancelable_consumer_.CancelAllRequests();
348
349 // 'in_progress_' may contain DownloadItems that have not finished the start
350 // complete (from the history service) and thus aren't in downloads_.
351 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32352 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29353 for (; it != in_progress_.end(); ++it) {
354 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32355 if (download->safety_state() == DownloadItem::DANGEROUS) {
356 // Forget about any download that the user did not approve.
357 // Note that we cannot call download->Remove() this would invalidate our
358 // iterator.
359 to_remove.insert(download);
360 continue;
initial.commit09911bf2008-07-26 23:55:29361 }
[email protected]9ccbb372008-10-10 18:50:32362 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
363 download->Cancel(false);
364 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29365 if (download->db_handle() == kUninitializedHandle) {
366 // An invalid handle means that 'download' does not yet exist in
367 // 'downloads_', so we have to delete it here.
368 delete download;
369 }
370 }
371
[email protected]9ccbb372008-10-10 18:50:32372 // 'dangerous_finished_' contains all complete downloads that have not been
373 // approved. They should be removed.
374 it = dangerous_finished_.begin();
375 for (; it != dangerous_finished_.end(); ++it)
376 to_remove.insert(it->second);
377
378 // Remove the dangerous download that are not approved.
379 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
380 rm_it != to_remove.end(); ++rm_it) {
381 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32382 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32383 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32384 // Same as above, delete the download if it is not in 'downloads_' (as the
385 // Remove() call above won't have deleted it).
386 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32387 delete download;
388 }
389 to_remove.clear();
390
initial.commit09911bf2008-07-26 23:55:29391 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32392 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29393 STLDeleteValues(&downloads_);
394
395 file_manager_ = NULL;
396
397 // Save our file extensions to auto open.
398 SaveAutoOpens();
399
400 // Make sure the save as dialog doesn't notify us back if we're gone before
401 // it returns.
402 if (select_file_dialog_.get())
403 select_file_dialog_->ListenerDestroyed();
404
405 shutdown_needed_ = false;
406}
407
408// Issue a history query for downloads matching 'search_text'. If 'search_text'
409// is empty, return all downloads that we know about.
410void DownloadManager::GetDownloads(Observer* observer,
411 const std::wstring& search_text) {
412 DCHECK(observer);
413
414 // Return a empty list if we've not yet received the set of downloads from the
415 // history system (we'll update all observers once we get that list in
416 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
417 std::vector<DownloadItem*> download_copy;
418 if (downloads_.empty()) {
419 observer->SetDownloads(download_copy);
420 return;
421 }
422
423 // We already know all the downloads and there is no filter, so just return a
424 // copy to the observer.
425 if (search_text.empty()) {
426 download_copy.reserve(downloads_.size());
427 for (DownloadMap::iterator it = downloads_.begin();
428 it != downloads_.end(); ++it) {
429 download_copy.push_back(it->second);
430 }
431
432 // We retain ownership of the DownloadItems.
433 observer->SetDownloads(download_copy);
434 return;
435 }
436
437 // Issue a request to the history service for a list of downloads matching
438 // our search text.
439 HistoryService* hs =
440 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
441 if (hs) {
442 HistoryService::Handle h =
443 hs->SearchDownloads(search_text,
444 &cancelable_consumer_,
445 NewCallback(this,
446 &DownloadManager::OnSearchComplete));
447 cancelable_consumer_.SetClientData(hs, h, observer);
448 }
449}
450
451// Query the history service for information about all persisted downloads.
452bool DownloadManager::Init(Profile* profile) {
453 DCHECK(profile);
454 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
455 shutdown_needed_ = true;
456
457 profile_ = profile;
458 request_context_ = profile_->GetRequestContext();
459
460 // 'incognito mode' will have access to past downloads, but we won't store
461 // information about new downloads while in that mode.
462 QueryHistoryForDownloads();
463
464 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
465 if (!rdh) {
466 NOTREACHED();
467 return false;
468 }
469
470 file_manager_ = rdh->download_file_manager();
471 if (!file_manager_) {
472 NOTREACHED();
473 return false;
474 }
475
476 file_loop_ = g_browser_process->file_thread()->message_loop();
477 if (!file_loop_) {
478 NOTREACHED();
479 return false;
480 }
481
482 // Get our user preference state.
483 PrefService* prefs = profile_->GetPrefs();
484 DCHECK(prefs);
485 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
486
initial.commit09911bf2008-07-26 23:55:29487 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
488
[email protected]7ae7c2cb2009-01-06 23:31:41489 // This variable is needed to resolve which CreateDirectory we want to point
490 // to. Without it, the NewRunnableFunction cannot resolve the ambiguity.
491 // TODO(estade): when file_util::CreateDirectory(wstring) is removed,
492 // get rid of |CreateDirectoryPtr|.
493 bool (*CreateDirectoryPtr)(const FilePath&) = &file_util::CreateDirectory;
[email protected]bb69e9b32008-08-14 23:08:14494 // Ensure that the download directory specified in the preferences exists.
[email protected]7ae7c2cb2009-01-06 23:31:41495 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
496 CreateDirectoryPtr, download_path()));
initial.commit09911bf2008-07-26 23:55:29497
[email protected]2b2f8f72009-02-24 22:42:05498#if defined(OS_WIN)
499 // We use this on windows to determine possibly dangerous downloads.
500 download_util::InitializeExeTypes(&exe_types_);
501#endif
502
503 // We store any file extension that should be opened automatically at
504 // download completion in this pref.
initial.commit09911bf2008-07-26 23:55:29505 std::wstring extensions_to_open =
506 prefs->GetString(prefs::kDownloadExtensionsToOpen);
507 std::vector<std::wstring> extensions;
508 SplitString(extensions_to_open, L':', &extensions);
509 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]b7f05882009-02-22 01:21:56510 if (!extensions[i].empty() && !IsExecutable(
511 FilePath::FromWStringHack(extensions[i]).value()))
512 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29513 }
514
515 return true;
516}
517
518void DownloadManager::QueryHistoryForDownloads() {
519 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
520 if (hs) {
521 hs->QueryDownloads(
522 &cancelable_consumer_,
523 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
524 }
525}
526
527// We have received a message from DownloadFileManager about a new download. We
528// create a download item and store it in our download map, and inform the
529// history system of a new download. Since this method can be called while the
530// history service thread is still reading the persistent state, we do not
531// insert the new DownloadItem into 'downloads_' or inform our observers at this
532// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
533// download creation as a callback from the history thread.
534void DownloadManager::StartDownload(DownloadCreateInfo* info) {
535 DCHECK(MessageLoop::current() == ui_loop_);
536 DCHECK(info);
537
[email protected]7d3851d82008-12-12 03:26:07538 // Freeze the user's preference for showing a Save As dialog. We're going to
539 // bounce around a bunch of threads and we don't want to worry about race
540 // conditions where the user changes this pref out from under us.
541 if (*prompt_for_download_)
542 info->save_as = true;
543
initial.commit09911bf2008-07-26 23:55:29544 // Determine the proper path for a download, by choosing either the default
545 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41546 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29547 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07548 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29549 info->suggested_path = last_download_path_;
550 else
[email protected]7ae7c2cb2009-01-06 23:31:41551 info->suggested_path = download_path();
552 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29553
[email protected]7d3851d82008-12-12 03:26:07554 if (!info->save_as) {
555 // Let's check if this download is dangerous, based on its name.
[email protected]7ae7c2cb2009-01-06 23:31:41556 info->is_dangerous = IsDangerous(info->suggested_path.BaseName());
[email protected]e9ebf3fc2008-10-17 22:06:58557 }
558
initial.commit09911bf2008-07-26 23:55:29559 // We need to move over to the download thread because we don't want to stat
560 // the suggested path on the UI thread.
561 file_loop_->PostTask(FROM_HERE,
562 NewRunnableMethod(this,
563 &DownloadManager::CheckIfSuggestedPathExists,
564 info));
565}
566
567void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
568 DCHECK(info);
569
570 // Check writability of the suggested path. If we can't write to it, default
571 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41572 FilePath dir = info->suggested_path.DirName();
573 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32574 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29575 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29576 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41577 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29578 }
579
[email protected]7a256ea2008-10-17 17:34:16580 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29581
[email protected]6cade212008-12-03 00:32:22582 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58583 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41584 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32585 // Create a temporary file to hold the file until the user approves its
586 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41587 FilePath::StringType file_name;
588 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32589 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41590 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32591 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41592 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07593 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41594 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32595 }
596 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16597 } else {
598 // We know the final path, build it if necessary.
599 if (info->path_uniquifier > 0) {
600 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
601 // Setting path_uniquifier to 0 to make sure we don't try to unique it
602 // later on.
603 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07604 } else if (info->path_uniquifier == -1) {
605 // We failed to find a unique path. We have to prompt the user.
606 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16607 }
[email protected]9ccbb372008-10-10 18:50:32608 }
609
[email protected]7d3851d82008-12-12 03:26:07610 if (!info->save_as) {
611 // Create an empty file at the suggested path so that we don't allocate the
612 // same "non-existant" path to multiple downloads.
613 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ae7c2cb2009-01-06 23:31:41614 file_util::WriteFile(info->suggested_path.ToWStringHack(), "", 0);
[email protected]7d3851d82008-12-12 03:26:07615 }
616
initial.commit09911bf2008-07-26 23:55:29617 // Now we return to the UI thread.
618 ui_loop_->PostTask(FROM_HERE,
619 NewRunnableMethod(this,
620 &DownloadManager::OnPathExistenceAvailable,
621 info));
622}
623
624void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]0f44d3e2009-03-12 23:36:30625#if defined(OS_WIN) || defined(OS_LINUX)
initial.commit09911bf2008-07-26 23:55:29626 DCHECK(MessageLoop::current() == ui_loop_);
627 DCHECK(info);
628
[email protected]7d3851d82008-12-12 03:26:07629 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29630 // We must ask the user for the place to put the download.
631 if (!select_file_dialog_.get())
632 select_file_dialog_ = SelectFileDialog::Create(this);
633
[email protected]a3a1d142008-12-19 00:42:30634 WebContents* contents = tab_util::GetWebContentsByID(
initial.commit09911bf2008-07-26 23:55:29635 info->render_process_id, info->render_view_id);
[email protected]0f44d3e2009-03-12 23:36:30636#if defined(OS_WIN)
[email protected]7ae7c2cb2009-01-06 23:31:41637 std::wstring filter =
638 win_util::GetFileFilterFromPath(info->suggested_path.value());
[email protected]0f44d3e2009-03-12 23:36:30639 gfx::NativeWindow owning_window =
[email protected]92edc472009-02-10 20:32:06640 contents ? GetAncestor(contents->GetNativeView(), GA_ROOT) : NULL;
[email protected]0f44d3e2009-03-12 23:36:30641#elif defined(OS_LINUX)
642 std::wstring filter;
643 gfx::NativeWindow owning_window = contents ?
644 GTK_WINDOW(gtk_widget_get_toplevel(contents->GetNativeView())) :
645 NULL;
646#endif
initial.commit09911bf2008-07-26 23:55:29647 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]7ae7c2cb2009-01-06 23:31:41648 std::wstring(),
649 info->suggested_path.ToWStringHack(),
[email protected]6cade212008-12-03 00:32:22650 filter, std::wstring(),
[email protected]0f44d3e2009-03-12 23:36:30651 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29652 } else {
653 // No prompting for download, just continue with the suggested name.
654 ContinueStartDownload(info, info->suggested_path);
655 }
[email protected]0f44d3e2009-03-12 23:36:30656#elif defined(OS_MACOSX)
[email protected]b7f05882009-02-22 01:21:56657 // TODO(port): port this file -- need dialogs.
658 NOTIMPLEMENTED();
659#endif
initial.commit09911bf2008-07-26 23:55:29660}
661
662void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41663 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29664 scoped_ptr<DownloadCreateInfo> infop(info);
665 info->path = target_path;
666
667 DownloadItem* download = NULL;
668 DownloadMap::iterator it = in_progress_.find(info->download_id);
669 if (it == in_progress_.end()) {
670 download = new DownloadItem(info->download_id,
671 info->path,
[email protected]7a256ea2008-10-17 17:34:16672 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29673 info->url,
[email protected]9ccbb372008-10-10 18:50:32674 info->original_name,
initial.commit09911bf2008-07-26 23:55:29675 info->start_time,
676 info->total_bytes,
677 info->render_process_id,
[email protected]9ccbb372008-10-10 18:50:32678 info->request_id,
679 info->is_dangerous);
initial.commit09911bf2008-07-26 23:55:29680 download->set_manager(this);
681 in_progress_[info->download_id] = download;
682 } else {
683 NOTREACHED(); // Should not exist!
684 return;
685 }
686
687 // If the download already completed by the time we reached this point, then
688 // notify observers that it did.
689 PendingFinishedMap::iterator pending_it =
690 pending_finished_downloads_.find(info->download_id);
691 if (pending_it != pending_finished_downloads_.end())
692 DownloadFinished(pending_it->first, pending_it->second);
693
694 download->Rename(target_path);
695
696 file_loop_->PostTask(FROM_HERE,
697 NewRunnableMethod(file_manager_,
698 &DownloadFileManager::OnFinalDownloadName,
699 download->id(),
700 target_path));
701
702 if (profile_->IsOffTheRecord()) {
703 // Fake a db handle for incognito mode, since nothing is actually stored in
704 // the database in this mode. We have to make sure that these handles don't
705 // collide with normal db handles, so we use a negative value. Eventually,
706 // they could overlap, but you'd have to do enough downloading that your ISP
707 // would likely stab you in the neck first. YMMV.
708 static int64 fake_db_handle = kUninitializedHandle - 1;
709 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
710 } else {
711 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22712 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29713 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
714 if (hs) {
715 hs->CreateDownload(
716 *info, &cancelable_consumer_,
717 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
718 }
719 }
720}
721
722// Convenience function for updating the history service for a download.
723void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
724 DCHECK(download);
725
726 // Don't store info in the database if the download was initiated while in
727 // incognito mode or if it hasn't been initialized in our database table.
728 if (download->db_handle() <= kUninitializedHandle)
729 return;
730
[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 (hs) {
734 hs->UpdateDownload(download->received_bytes(),
735 download->state(),
736 download->db_handle());
737 }
738}
739
740void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
741 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22742 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29743 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
744 if (download->db_handle() > kUninitializedHandle && hs)
745 hs->RemoveDownload(download->db_handle());
746}
747
[email protected]e93d2822009-01-30 05:59:59748void DownloadManager::RemoveDownloadsFromHistoryBetween(
749 const base::Time remove_begin,
750 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22751 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29752 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
753 if (hs)
754 hs->RemoveDownloadsBetween(remove_begin, remove_end);
755}
756
757void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
758 DownloadMap::iterator it = in_progress_.find(download_id);
759 if (it != in_progress_.end()) {
760 DownloadItem* download = it->second;
761 download->Update(size);
762 UpdateHistoryForDownload(download);
763 }
764}
765
766void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
767 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32768 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29769 // The download is done, but the user hasn't selected a final location for
770 // it yet (the Save As dialog box is probably still showing), so just keep
771 // track of the fact that this download id is complete, when the
772 // DownloadItem is constructed later we'll notify its completion then.
773 PendingFinishedMap::iterator erase_it =
774 pending_finished_downloads_.find(download_id);
775 DCHECK(erase_it == pending_finished_downloads_.end());
776 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32777 return;
initial.commit09911bf2008-07-26 23:55:29778 }
[email protected]9ccbb372008-10-10 18:50:32779
780 // Remove the id from the list of pending ids.
781 PendingFinishedMap::iterator erase_it =
782 pending_finished_downloads_.find(download_id);
783 if (erase_it != pending_finished_downloads_.end())
784 pending_finished_downloads_.erase(erase_it);
785
786 DownloadItem* download = it->second;
787 download->Finished(size);
788
789 // Clean up will happen when the history system create callback runs if we
790 // don't have a valid db_handle yet.
791 if (download->db_handle() != kUninitializedHandle) {
792 in_progress_.erase(it);
793 NotifyAboutDownloadStop();
794 UpdateHistoryForDownload(download);
795 }
796
797 // If this a dangerous download not yet validated by the user, don't do
798 // anything. When the user notifies us, it will trigger a call to
799 // ProceedWithFinishedDangerousDownload.
800 if (download->safety_state() == DownloadItem::DANGEROUS) {
801 dangerous_finished_[download_id] = download;
802 return;
803 }
804
805 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22806 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32807 // its final name before we can continue.
808 file_loop_->PostTask(FROM_HERE,
809 NewRunnableMethod(
810 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
811 download->db_handle(),
812 download->full_path(), download->original_name()));
813 return;
814 }
815 ContinueDownloadFinished(download);
816}
817
818void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
819 // If this was a dangerous download, it has now been approved and must be
820 // removed from dangerous_finished_ so it does not get deleted on shutdown.
821 DownloadMap::iterator it = dangerous_finished_.find(download->id());
822 if (it != dangerous_finished_.end())
823 dangerous_finished_.erase(it);
824
825 // Notify our observers that we are complete (the call to Finished() set the
826 // state to complete but did not notify).
827 download->UpdateObservers();
828
829 // Open the download if the user or user prefs indicate it should be.
[email protected]2001fe82009-02-23 23:53:14830 FilePath::StringType extension = download->full_path().Extension();
831 // Drop the leading period.
832 if (extension.size() > 0)
833 extension = extension.substr(1);
[email protected]9ccbb372008-10-10 18:50:32834 if (download->open_when_complete() || ShouldOpenFileExtension(extension))
835 OpenDownloadInShell(download, NULL);
836}
837
838// Called on the file thread. Renames the downloaded file to its original name.
839void DownloadManager::ProceedWithFinishedDangerousDownload(
840 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41841 const FilePath& path,
842 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32843 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41844 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16845 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32846 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24847 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16848 // Make our name unique at this point, as if a dangerous file is downloading
849 // and a 2nd download is started for a file with the same name, they would
850 // have the same path. This is because we uniquify the name on download
851 // start, and at that time the first file does not exists yet, so the second
852 // file gets the same name.
853 uniquifier = GetUniquePathNumber(new_path);
854 if (uniquifier > 0)
855 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32856 success = file_util::Move(path, new_path);
857 } else {
858 NOTREACHED();
859 }
[email protected]6cade212008-12-03 00:32:22860
[email protected]9ccbb372008-10-10 18:50:32861 ui_loop_->PostTask(FROM_HERE,
862 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16863 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32864}
865
866// Call from the file thread when the finished dangerous download was renamed.
867void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
868 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41869 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16870 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32871 DownloadMap::iterator it = downloads_.find(download_handle);
872 if (it == downloads_.end()) {
873 NOTREACHED();
874 return;
875 }
876
877 DownloadItem* download = it->second;
878 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16879 if (success) {
880 // We need to update the path uniquifier so that the UI shows the right
881 // name when calling GetFileName().
882 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32883 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16884 }
[email protected]9ccbb372008-10-10 18:50:32885
886 // Continue the download finished sequence.
887 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29888}
889
890// static
891// We have to tell the ResourceDispatcherHost to cancel the download from this
[email protected]6cade212008-12-03 00:32:22892// thread, since we can't forward tasks from the file thread to the IO thread
initial.commit09911bf2008-07-26 23:55:29893// reliably (crash on shutdown race condition).
894void DownloadManager::CancelDownloadRequest(int render_process_id,
895 int request_id) {
896 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]ab820df2008-08-26 05:55:10897 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29898 if (!io_thread || !rdh)
899 return;
900 io_thread->message_loop()->PostTask(FROM_HERE,
901 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
902 rdh,
903 render_process_id,
904 request_id));
905}
906
907// static
908void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
909 int render_process_id,
910 int request_id) {
911 rdh->CancelRequest(render_process_id, request_id, false);
912}
913
914void DownloadManager::DownloadCancelled(int32 download_id) {
915 DownloadMap::iterator it = in_progress_.find(download_id);
916 if (it == in_progress_.end())
917 return;
918 DownloadItem* download = it->second;
919
920 CancelDownloadRequest(download->render_process_id(), download->request_id());
921
922 // Clean up will happen when the history system create callback runs if we
923 // don't have a valid db_handle yet.
924 if (download->db_handle() != kUninitializedHandle) {
925 in_progress_.erase(it);
926 NotifyAboutDownloadStop();
927 UpdateHistoryForDownload(download);
928 }
929
930 // Tell the file manager to cancel the download.
931 file_manager_->RemoveDownload(download->id(), this); // On the UI thread
932 file_loop_->PostTask(FROM_HERE,
933 NewRunnableMethod(file_manager_,
934 &DownloadFileManager::CancelDownload,
935 download->id()));
936}
937
938void DownloadManager::PauseDownload(int32 download_id, bool pause) {
939 DownloadMap::iterator it = in_progress_.find(download_id);
940 if (it != in_progress_.end()) {
941 DownloadItem* download = it->second;
942 if (pause == download->is_paused())
943 return;
944
945 // Inform the ResourceDispatcherHost of the new pause state.
[email protected]ab820df2008-08-26 05:55:10946 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29947 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
948 if (!io_thread || !rdh)
949 return;
950
951 io_thread->message_loop()->PostTask(FROM_HERE,
952 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
953 rdh,
954 download->render_process_id(),
955 download->request_id(),
956 pause));
957 }
958}
959
960// static
961void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
962 int render_process_id,
963 int request_id,
964 bool pause) {
965 rdh->PauseRequest(render_process_id, request_id, pause);
966}
967
[email protected]7ae7c2cb2009-01-06 23:31:41968bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:32969 // TODO(jcampan): Improve me.
[email protected]2001fe82009-02-23 23:53:14970 FilePath::StringType extension = file_name.Extension();
971 // Drop the leading period.
972 if (extension.size() > 0)
973 extension = extension.substr(1);
974 return IsExecutable(extension);
[email protected]9ccbb372008-10-10 18:50:32975}
976
977void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:41978 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:32979 download->Rename(new_path);
980
981 // Update the history.
982
983 // No update necessary if the download was initiated while in incognito mode.
984 if (download->db_handle() <= kUninitializedHandle)
985 return;
986
[email protected]6cade212008-12-03 00:32:22987 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:32988 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
989 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:41990 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:32991}
992
initial.commit09911bf2008-07-26 23:55:29993void DownloadManager::RemoveDownload(int64 download_handle) {
994 DownloadMap::iterator it = downloads_.find(download_handle);
995 if (it == downloads_.end())
996 return;
997
998 // Make history update.
999 DownloadItem* download = it->second;
1000 RemoveDownloadFromHistory(download);
1001
1002 // Remove from our tables and delete.
1003 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321004 it = dangerous_finished_.find(download->id());
1005 if (it != dangerous_finished_.end())
1006 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291007
1008 // Tell observers to refresh their views.
1009 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:361010
1011 delete download;
initial.commit09911bf2008-07-26 23:55:291012}
1013
[email protected]e93d2822009-01-30 05:59:591014int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1015 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291016 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1017
1018 int num_deleted = 0;
1019 DownloadMap::iterator it = downloads_.begin();
1020 while (it != downloads_.end()) {
1021 DownloadItem* download = it->second;
1022 DownloadItem::DownloadState state = download->state();
1023 if (download->start_time() >= remove_begin &&
1024 (remove_end.is_null() || download->start_time() < remove_end) &&
1025 (state == DownloadItem::COMPLETE ||
1026 state == DownloadItem::CANCELLED)) {
1027 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561028 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581029
1030 // Also remove it from any completed dangerous downloads.
1031 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1032 if (dit != dangerous_finished_.end())
1033 dangerous_finished_.erase(dit);
1034
initial.commit09911bf2008-07-26 23:55:291035 delete download;
1036
1037 ++num_deleted;
1038 continue;
1039 }
1040
1041 ++it;
1042 }
1043
1044 // Tell observers to refresh their views.
1045 if (num_deleted > 0)
1046 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1047
1048 return num_deleted;
1049}
1050
[email protected]e93d2822009-01-30 05:59:591051int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1052 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291053}
1054
1055// Initiate a download of a specific URL. We send the request to the
1056// ResourceDispatcherHost, and let it send us responses like a regular
1057// download.
1058void DownloadManager::DownloadUrl(const GURL& url,
1059 const GURL& referrer,
1060 WebContents* web_contents) {
1061 DCHECK(web_contents);
1062 file_manager_->DownloadUrl(url,
1063 referrer,
[email protected]4566f132009-03-12 01:55:131064 web_contents->process()->pid(),
initial.commit09911bf2008-07-26 23:55:291065 web_contents->render_view_host()->routing_id(),
1066 request_context_.get());
1067}
1068
1069void DownloadManager::NotifyAboutDownloadStart() {
[email protected]bfd04a62009-02-01 18:16:561070 NotificationService::current()->Notify(
1071 NotificationType::DOWNLOAD_START,
1072 NotificationService::AllSources(),
1073 NotificationService::NoDetails());
initial.commit09911bf2008-07-26 23:55:291074}
1075
1076void DownloadManager::NotifyAboutDownloadStop() {
[email protected]bfd04a62009-02-01 18:16:561077 NotificationService::current()->Notify(
1078 NotificationType::DOWNLOAD_STOP,
1079 NotificationService::AllSources(),
1080 NotificationService::NoDetails());
initial.commit09911bf2008-07-26 23:55:291081}
1082
[email protected]7ae7c2cb2009-01-06 23:31:411083void DownloadManager::GenerateExtension(
1084 const FilePath& file_name,
1085 const std::string& mime_type,
1086 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291087 // We're worried about three things here:
1088 //
1089 // 1) Security. Many sites let users upload content, such as buddy icons, to
1090 // their web sites. We want to mitigate the case where an attacker
1091 // supplies a malicious executable with an executable file extension but an
1092 // honest site serves the content with a benign content type, such as
1093 // image/jpeg.
1094 //
1095 // 2) Usability. If the site fails to provide a file extension, we want to
1096 // guess a reasonable file extension based on the content type.
1097 //
1098 // 3) Shell integration. Some file extensions automatically integrate with
1099 // the shell. We block these extensions to prevent a malicious web site
1100 // from integrating with the user's shell.
1101
[email protected]7ae7c2cb2009-01-06 23:31:411102 static const FilePath::CharType default_extension[] =
1103 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291104
1105 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411106 FilePath::StringType extension(
1107 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291108
[email protected]b7f05882009-02-22 01:21:561109#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291110 // Rename shell-integrated extensions.
1111 if (win_util::IsShellIntegratedExtension(extension))
1112 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561113#endif
initial.commit09911bf2008-07-26 23:55:291114
1115 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411116 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411117 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291118 if (mime_type == mime_type_from_extension) {
1119 // The hinted extension matches the mime type. It looks like a winner.
1120 generated_extension->swap(extension);
1121 return;
1122 }
1123
1124 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1125 // We want to be careful about executable extensions. The worry here is
1126 // that a trusted web site could be tricked into dropping an executable file
1127 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101128 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291129 // We couldn't find a good extension for this content type. Use a dummy
1130 // extension instead.
1131 extension.assign(default_extension);
1132 }
1133 }
1134
1135 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101136 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291137 } else {
[email protected]6cade212008-12-03 00:32:221138 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291139 // 1. New extension is not ".txt"
1140 // 2. New extension is not the same as the already existing extension.
1141 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411142 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291143 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1144 // application/x-javascript.
[email protected]7ae7c2cb2009-01-06 23:31:411145 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101146 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171147 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411148 append_extension != extension &&
[email protected]3f156552009-02-09 19:44:171149 !IsExecutable(append_extension)) {
1150 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291151 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171152 }
initial.commit09911bf2008-07-26 23:55:291153 }
1154 }
1155
1156 generated_extension->swap(extension);
1157}
1158
1159void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411160 FilePath* generated_name) {
1161 *generated_name = FilePath::FromWStringHack(
[email protected]8ac1a752008-07-31 19:40:371162 net::GetSuggestedFilename(GURL(info->url),
1163 info->content_disposition,
[email protected]7ae7c2cb2009-01-06 23:31:411164 L"download"));
1165 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291166
[email protected]7ae7c2cb2009-01-06 23:31:411167 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291168}
1169
1170void DownloadManager::AddObserver(Observer* observer) {
1171 observers_.AddObserver(observer);
1172 observer->ModelChanged();
1173}
1174
1175void DownloadManager::RemoveObserver(Observer* observer) {
1176 observers_.RemoveObserver(observer);
1177}
1178
1179// Post Windows Shell operations to the Download thread, to avoid blocking the
1180// user interface.
1181void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1182 DCHECK(file_manager_);
1183 file_loop_->PostTask(FROM_HERE,
1184 NewRunnableMethod(file_manager_,
1185 &DownloadFileManager::OnShowDownloadInShell,
[email protected]7ae7c2cb2009-01-06 23:31:411186 FilePath(download->full_path())));
initial.commit09911bf2008-07-26 23:55:291187}
1188
1189void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591190 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291191 DCHECK(file_manager_);
1192 file_loop_->PostTask(FROM_HERE,
1193 NewRunnableMethod(file_manager_,
1194 &DownloadFileManager::OnOpenDownloadInShell,
1195 download->full_path(), download->url(), parent_window));
1196}
1197
[email protected]7ae7c2cb2009-01-06 23:31:411198void DownloadManager::OpenFilesOfExtension(
1199 const FilePath::StringType& extension, bool open) {
initial.commit09911bf2008-07-26 23:55:291200 if (open && !IsExecutable(extension))
1201 auto_open_.insert(extension);
1202 else
1203 auto_open_.erase(extension);
1204 SaveAutoOpens();
1205}
1206
[email protected]7ae7c2cb2009-01-06 23:31:411207bool DownloadManager::ShouldOpenFileExtension(
1208 const FilePath::StringType& extension) {
[email protected]8c756ac2009-01-30 23:36:411209 // Special-case Chrome extensions as always-open.
initial.commit09911bf2008-07-26 23:55:291210 if (!IsExecutable(extension) &&
[email protected]8c756ac2009-01-30 23:36:411211 (auto_open_.find(extension) != auto_open_.end() ||
1212 extension == chrome::kExtensionFileExtension))
1213 return true;
initial.commit09911bf2008-07-26 23:55:291214 return false;
1215}
1216
[email protected]7b73d992008-12-15 20:56:461217static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291218 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461219 "text/javascript",
1220 "text/javascript;version=*",
[email protected]60ff8f912008-12-05 07:58:391221 // Some sites use binary/octet-stream to mean application/octet-stream.
1222 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461223 "binary/octet-stream"
1224};
initial.commit09911bf2008-07-26 23:55:291225
[email protected]7b73d992008-12-15 20:56:461226static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291227 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461228 "application/*+xml",
1229 "application/xml"
1230};
initial.commit09911bf2008-07-26 23:55:291231
[email protected]7b73d992008-12-15 20:56:461232// static
1233bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411234 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461235 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1236 return true;
1237 }
[email protected]bae0ea12009-02-14 01:20:411238 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461239 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1240 return false;
1241 }
1242 // We consider only other application types to be executable.
1243 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291244}
1245
[email protected]7ae7c2cb2009-01-06 23:31:411246bool DownloadManager::IsExecutable(const FilePath::StringType& extension) {
[email protected]64da0b932009-02-24 02:30:041247#if defined(OS_WIN)
1248 if (!IsStringASCII(extension))
1249 return false;
1250 std::string ascii_extension = WideToASCII(extension);
1251 StringToLowerASCII(&ascii_extension);
1252
1253 return exe_types_.find(ascii_extension) != exe_types_.end();
1254#elif defined(OS_POSIX)
1255 // TODO(port): we misght not want to call this function on other platforms.
1256 // Figure it out.
1257 NOTIMPLEMENTED();
1258 return false;
1259#endif
initial.commit09911bf2008-07-26 23:55:291260}
1261
1262void DownloadManager::ResetAutoOpenFiles() {
1263 auto_open_.clear();
1264 SaveAutoOpens();
1265}
1266
1267bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1268 return !auto_open_.empty();
1269}
1270
1271void DownloadManager::SaveAutoOpens() {
1272 PrefService* prefs = profile_->GetPrefs();
1273 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411274 FilePath::StringType extensions;
1275 for (std::set<FilePath::StringType>::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291276 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411277 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291278 }
1279 if (!extensions.empty())
1280 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561281
1282 std::wstring extensions_w;
1283#if defined(OS_WIN)
1284 extensions_w = extensions;
1285#elif defined(OS_POSIX)
[email protected]1b5044d2009-02-24 00:04:141286 extensions_w = base::SysNativeMBToWide(extensions);
[email protected]b7f05882009-02-22 01:21:561287#endif
1288
1289 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291290 }
1291}
1292
[email protected]7ae7c2cb2009-01-06 23:31:411293void DownloadManager::FileSelected(const std::wstring& path_string,
1294 void* params) {
1295 FilePath path = FilePath::FromWStringHack(path_string);
initial.commit09911bf2008-07-26 23:55:291296 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071297 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411298 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291299 ContinueStartDownload(info, path);
1300}
1301
1302void DownloadManager::FileSelectionCanceled(void* params) {
1303 // The user didn't pick a place to save the file, so need to cancel the
1304 // download that's already in progress to the temporary location.
1305 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
1306 file_loop_->PostTask(FROM_HERE,
1307 NewRunnableMethod(file_manager_, &DownloadFileManager::CancelDownload,
1308 info->download_id));
1309}
1310
[email protected]7ae7c2cb2009-01-06 23:31:411311void DownloadManager::DeleteDownload(const FilePath& path) {
1312 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
1313 &DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321314}
1315
1316
1317void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1318 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1319 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1320 download->UpdateObservers();
1321
1322 // If the download is not complete, nothing to do. The required
1323 // post-processing will be performed when it does complete.
1324 if (download->state() != DownloadItem::COMPLETE)
1325 return;
1326
1327 file_loop_->PostTask(FROM_HERE,
1328 NewRunnableMethod(this,
1329 &DownloadManager::ProceedWithFinishedDangerousDownload,
1330 download->db_handle(), download->full_path(),
1331 download->original_name()));
1332}
1333
[email protected]763f946a2009-01-06 19:04:391334void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411335 FilePath* file_name) {
1336 // Make sure we get the right file extension
1337 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391338 GenerateExtension(*file_name, mime_type, &extension);
1339 file_util::ReplaceExtension(file_name, extension);
1340
[email protected]2b2f8f72009-02-24 22:42:051341#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391342 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411343 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391344 DCHECK(!leaf_name.empty());
1345 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411346 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1347 *file_name = file_name->DirName();
1348 if (file_name->value() == FilePath::kCurrentDirectory) {
1349 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391350 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411351 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391352 }
1353 }
[email protected]b7f05882009-02-22 01:21:561354#elif defined(OS_POSIX)
1355 NOTIMPLEMENTED();
1356#endif
[email protected]763f946a2009-01-06 19:04:391357}
1358
initial.commit09911bf2008-07-26 23:55:291359// Operations posted to us from the history service ----------------------------
1360
1361// The history service has retrieved all download entries. 'entries' contains
1362// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1363void DownloadManager::OnQueryDownloadEntriesComplete(
1364 std::vector<DownloadCreateInfo>* entries) {
1365 for (size_t i = 0; i < entries->size(); ++i) {
1366 DownloadItem* download = new DownloadItem(entries->at(i));
1367 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1368 downloads_[download->db_handle()] = download;
1369 download->set_manager(this);
1370 }
1371 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1372}
1373
initial.commit09911bf2008-07-26 23:55:291374// Once the new DownloadItem's creation info has been committed to the history
1375// service, we associate the DownloadItem with the db handle, update our
1376// 'downloads_' map and inform observers.
1377void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1378 int64 db_handle) {
1379 DownloadMap::iterator it = in_progress_.find(info.download_id);
1380 DCHECK(it != in_progress_.end());
1381
1382 DownloadItem* download = it->second;
1383 DCHECK(download->db_handle() == kUninitializedHandle);
1384 download->set_db_handle(db_handle);
1385
1386 // Insert into our full map.
1387 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1388 downloads_[download->db_handle()] = download;
1389
1390 // The 'contents' may no longer exist if the user closed the tab before we get
1391 // this start completion event. If it does, tell the origin WebContents to
1392 // display its download shelf.
1393 TabContents* contents =
[email protected]a3a1d142008-12-19 00:42:301394 tab_util::GetWebContentsByID(info.render_process_id, info.render_view_id);
initial.commit09911bf2008-07-26 23:55:291395
1396 // If the contents no longer exists or is no longer active, we start the
1397 // download in the last active browser. This is not ideal but better than
1398 // fully hiding the download from the user. Note: non active means that the
1399 // user navigated away from the tab contents. This has nothing to do with
1400 // tab selection.
1401 if (!contents || !contents->is_active()) {
1402 Browser* last_active = BrowserList::GetLastActive();
1403 if (last_active)
1404 contents = last_active->GetSelectedTabContents();
1405 }
1406
1407 if (contents)
1408 contents->OnStartDownload(download);
1409
1410 // Inform interested objects about the new download.
1411 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1412 NotifyAboutDownloadStart();
1413
1414 // If this download has been completed before we've received the db handle,
1415 // post one final message to the history service so that it can be properly
1416 // in sync with the DownloadItem's completion status, and also inform any
1417 // observers so that they get more than just the start notification.
1418 if (download->state() != DownloadItem::IN_PROGRESS) {
1419 in_progress_.erase(it);
1420 NotifyAboutDownloadStop();
1421 UpdateHistoryForDownload(download);
1422 download->UpdateObservers();
1423 }
1424}
1425
1426// Called when the history service has retrieved the list of downloads that
1427// match the search text.
1428void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1429 std::vector<int64>* results) {
1430 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1431 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1432 if (!requestor)
1433 return;
1434
1435 std::vector<DownloadItem*> searched_downloads;
1436 for (std::vector<int64>::iterator it = results->begin();
1437 it != results->end(); ++it) {
1438 DownloadMap::iterator dit = downloads_.find(*it);
1439 if (dit != downloads_.end())
1440 searched_downloads.push_back(dit->second);
1441 }
1442
1443 requestor->SetDownloads(searched_downloads);
1444}
[email protected]905a08d2008-11-19 07:24:121445
[email protected]6cade212008-12-03 00:32:221446// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121447void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411448 last_download_path_ = FilePath();
[email protected]905a08d2008-11-19 07:24:121449}