blob: d8e323732c32f88738ffbb2d7b6385f9709f74b0 [file] [log] [blame]
[email protected]d41355e6f2009-04-07 21:21:121// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]cdaa8652008-09-13 02:48:595#include "chrome/browser/download/download_manager.h"
initial.commit09911bf2008-07-26 23:55:296
[email protected]a92b8642009-05-05 23:38:567#include "app/l10n_util.h"
initial.commit09911bf2008-07-26 23:55:298#include "base/file_util.h"
9#include "base/logging.h"
10#include "base/message_loop.h"
11#include "base/path_service.h"
[email protected]1b5044d2009-02-24 00:04:1412#include "base/rand_util.h"
[email protected]807204142009-05-05 03:31:4413#include "base/stl_util-inl.h"
initial.commit09911bf2008-07-26 23:55:2914#include "base/string_util.h"
[email protected]1b5044d2009-02-24 00:04:1415#include "base/sys_string_conversions.h"
initial.commit09911bf2008-07-26 23:55:2916#include "base/task.h"
17#include "base/thread.h"
18#include "base/timer.h"
initial.commit09911bf2008-07-26 23:55:2919#include "chrome/browser/browser_list.h"
20#include "chrome/browser/browser_process.h"
[email protected]cdaa8652008-09-13 02:48:5921#include "chrome/browser/download/download_file.h"
[email protected]8f783752009-04-01 23:33:4522#include "chrome/browser/extensions/extensions_service.h"
initial.commit09911bf2008-07-26 23:55:2923#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:2624#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2525#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]e3c404b2008-12-23 01:07:3226#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
[email protected]f3ec7742009-01-15 00:59:1627#include "chrome/browser/tab_contents/tab_util.h"
[email protected]57c6a652009-05-04 07:58:3428#include "chrome/browser/tab_contents/tab_contents.h"
initial.commit09911bf2008-07-26 23:55:2929#include "chrome/common/chrome_paths.h"
[email protected]5b1a0e22009-05-26 19:00:5830#include "chrome/common/extensions/extension.h"
[email protected]076700e62009-04-01 18:41:2331#include "chrome/common/platform_util.h"
initial.commit09911bf2008-07-26 23:55:2932#include "chrome/common/pref_names.h"
33#include "chrome/common/pref_service.h"
[email protected]46072d42008-07-28 14:49:3534#include "googleurl/src/gurl.h"
[email protected]d81706b82009-04-03 20:28:4435#include "grit/chromium_strings.h"
[email protected]34ac8f32009-02-22 23:03:2736#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2937#include "net/base/mime_util.h"
38#include "net/base/net_util.h"
39#include "net/url_request/url_request_context.h"
40
[email protected]b7f05882009-02-22 01:21:5641#if defined(OS_WIN)
[email protected]4a0765a2009-05-08 23:12:2542#include "app/win_util.h"
[email protected]b7f05882009-02-22 01:21:5643#include "base/registry.h"
44#include "base/win_util.h"
[email protected]a0a9577b2009-05-27 23:52:3245#endif
46
47#if !defined(OS_MACOSX)
48// Used for initializing the list of dangerous extensions. We don't support it
49// yet on mac.
[email protected]b7f05882009-02-22 01:21:5650#include "chrome/browser/download/download_util.h"
[email protected]b7f05882009-02-22 01:21:5651#endif
52
[email protected]0f44d3e2009-03-12 23:36:3053#if defined(OS_LINUX)
54#include <gtk/gtk.h>
55#endif
56
initial.commit09911bf2008-07-26 23:55:2957// Periodically update our observers.
58class DownloadItemUpdateTask : public Task {
59 public:
60 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
61 void Run() { if (item_) item_->UpdateObservers(); }
62
63 private:
64 DownloadItem* item_;
65};
66
67// Update frequency (milliseconds).
68static const int kUpdateTimeMs = 1000;
69
70// Our download table ID starts at 1, so we use 0 to represent a download that
71// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2272// database handles in incognito mode starting at -1 and progressively getting
73// more negative.
initial.commit09911bf2008-07-26 23:55:2974static const int kUninitializedHandle = 0;
75
[email protected]7a256ea2008-10-17 17:34:1676// Appends the passed the number between parenthesis the path before the
77// extension.
[email protected]7ae7c2cb2009-01-06 23:31:4178static void AppendNumberToPath(FilePath* path, int number) {
79 file_util::InsertBeforeExtension(path,
80 StringPrintf(FILE_PATH_LITERAL(" (%d)"), number));
[email protected]7a256ea2008-10-17 17:34:1681}
82
83// Attempts to find a number that can be appended to that path to make it
84// unique. If |path| does not exist, 0 is returned. If it fails to find such
85// a number, -1 is returned.
[email protected]7ae7c2cb2009-01-06 23:31:4186static int GetUniquePathNumber(const FilePath& path) {
initial.commit09911bf2008-07-26 23:55:2987 const int kMaxAttempts = 100;
88
[email protected]7a256ea2008-10-17 17:34:1689 if (!file_util::PathExists(path))
90 return 0;
initial.commit09911bf2008-07-26 23:55:2991
[email protected]7ae7c2cb2009-01-06 23:31:4192 FilePath new_path;
initial.commit09911bf2008-07-26 23:55:2993 for (int count = 1; count <= kMaxAttempts; ++count) {
[email protected]7ae7c2cb2009-01-06 23:31:4194 new_path = FilePath(path);
[email protected]7a256ea2008-10-17 17:34:1695 AppendNumberToPath(&new_path, count);
initial.commit09911bf2008-07-26 23:55:2996
[email protected]7a256ea2008-10-17 17:34:1697 if (!file_util::PathExists(new_path))
98 return count;
initial.commit09911bf2008-07-26 23:55:2999 }
100
[email protected]7a256ea2008-10-17 17:34:16101 return -1;
initial.commit09911bf2008-07-26 23:55:29102}
103
[email protected]7ae7c2cb2009-01-06 23:31:41104static bool DownloadPathIsDangerous(const FilePath& download_path) {
105 FilePath desktop_dir;
[email protected]f052118e2008-09-05 02:25:32106 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
107 NOTREACHED();
108 return false;
109 }
110 return (download_path == desktop_dir);
111}
112
initial.commit09911bf2008-07-26 23:55:29113// DownloadItem implementation -------------------------------------------------
114
115// Constructor for reading from the history service.
116DownloadItem::DownloadItem(const DownloadCreateInfo& info)
117 : id_(-1),
118 full_path_(info.path),
119 url_(info.url),
[email protected]e435d6b72009-07-25 03:15:58120 referrer_url_(info.referrer_url),
121 mime_type_(info.mime_type),
initial.commit09911bf2008-07-26 23:55:29122 total_bytes_(info.total_bytes),
123 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56124 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29125 state_(static_cast<DownloadState>(info.state)),
126 start_time_(info.start_time),
127 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29128 manager_(NULL),
129 is_paused_(false),
130 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56131 safety_state_(SAFE),
[email protected]0aad67b2009-07-15 20:34:28132 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56133 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29134 render_process_id_(-1),
135 request_id_(-1) {
136 if (state_ == IN_PROGRESS)
137 state_ = CANCELLED;
138 Init(false /* don't start progress timer */);
139}
140
141// Constructor for DownloadItem created via user action in the main thread.
142DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41143 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16144 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32145 const GURL& url,
[email protected]494c06e2009-07-25 01:06:42146 const GURL& referrer_url,
[email protected]e435d6b72009-07-25 03:15:58147 const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:41148 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59149 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29150 int64 download_size,
151 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32152 int request_id,
153 bool is_dangerous)
initial.commit09911bf2008-07-26 23:55:29154 : id_(download_id),
155 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16156 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29157 url_(url),
[email protected]494c06e2009-07-25 01:06:42158 referrer_url_(referrer_url),
[email protected]e435d6b72009-07-25 03:15:58159 mime_type_(mime_type),
initial.commit09911bf2008-07-26 23:55:29160 total_bytes_(download_size),
161 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56162 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29163 state_(IN_PROGRESS),
164 start_time_(start_time),
165 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29166 manager_(NULL),
167 is_paused_(false),
168 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56169 safety_state_(is_dangerous ? DANGEROUS : SAFE),
[email protected]0aad67b2009-07-15 20:34:28170 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56171 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29172 render_process_id_(render_process_id),
173 request_id_(request_id) {
174 Init(true /* start progress timer */);
175}
176
177void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41178 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29179 if (start_timer)
180 StartProgressTimer();
181}
182
183DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29184 state_ = REMOVING;
185 UpdateObservers();
186}
187
188void DownloadItem::AddObserver(Observer* observer) {
189 observers_.AddObserver(observer);
190}
191
192void DownloadItem::RemoveObserver(Observer* observer) {
193 observers_.RemoveObserver(observer);
194}
195
196void DownloadItem::UpdateObservers() {
197 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
198}
199
[email protected]45e3c122009-04-07 19:58:03200void DownloadItem::NotifyObserversDownloadOpened() {
201 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadOpened(this));
202}
203
initial.commit09911bf2008-07-26 23:55:29204// If we've received more data than we were expecting (bad server info?), revert
205// to 'unknown size mode'.
206void DownloadItem::UpdateSize(int64 bytes_so_far) {
207 received_bytes_ = bytes_so_far;
208 if (received_bytes_ > total_bytes_)
209 total_bytes_ = 0;
210}
211
212// Updates from the download thread may have been posted while this download
213// was being cancelled in the UI thread, so we'll accept them unless we're
214// complete.
215void DownloadItem::Update(int64 bytes_so_far) {
216 if (state_ == COMPLETE) {
217 NOTREACHED();
218 return;
219 }
220 UpdateSize(bytes_so_far);
221 UpdateObservers();
222}
223
[email protected]6cade212008-12-03 00:32:22224// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29225void DownloadItem::Cancel(bool update_history) {
226 if (state_ != IN_PROGRESS) {
227 // Small downloads might be complete before this method has a chance to run.
228 return;
229 }
230 state_ = CANCELLED;
231 UpdateObservers();
232 StopProgressTimer();
233 if (update_history)
234 manager_->DownloadCancelled(id_);
235}
236
237void DownloadItem::Finished(int64 size) {
238 state_ = COMPLETE;
239 UpdateSize(size);
[email protected]22fbe5a2008-10-29 22:20:40240 UpdateObservers();
initial.commit09911bf2008-07-26 23:55:29241 StopProgressTimer();
242}
243
[email protected]9ccbb372008-10-10 18:50:32244void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29245 Cancel(true);
246 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32247 if (delete_on_disk)
248 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29249 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22250 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29251}
252
253void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59254 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14255 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29256}
257
258void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14259 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29260}
261
[email protected]e93d2822009-01-30 05:59:59262bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29263 if (total_bytes_ <= 0)
264 return false; // We never received the content_length for this download.
265
266 int64 speed = CurrentSpeed();
267 if (speed == 0)
268 return false;
269
270 *remaining =
[email protected]e93d2822009-01-30 05:59:59271 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29272 return true;
273}
274
275int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56276 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
277 int64 diff_ms = diff.InMilliseconds();
278 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29279}
280
281int DownloadItem::PercentComplete() const {
282 int percent = -1;
283 if (total_bytes_ > 0)
284 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
285 return percent;
286}
287
[email protected]7ae7c2cb2009-01-06 23:31:41288void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29289 DCHECK(!full_path.empty());
290 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41291 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29292}
293
294void DownloadItem::TogglePause() {
295 DCHECK(state_ == IN_PROGRESS);
296 manager_->PauseDownload(id_, !is_paused_);
297 is_paused_ = !is_paused_;
298 UpdateObservers();
299}
300
[email protected]7ae7c2cb2009-01-06 23:31:41301FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32302 if (safety_state_ == DownloadItem::SAFE)
303 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16304 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41305 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16306 AppendNumberToPath(&name, path_uniquifier_);
307 return name;
308 }
[email protected]9ccbb372008-10-10 18:50:32309 return original_name_;
310}
311
initial.commit09911bf2008-07-26 23:55:29312// DownloadManager implementation ----------------------------------------------
313
314// static
315void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
316 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
317 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32318 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
319
320 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41321 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12322 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
323 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32324 NOTREACHED();
325 }
[email protected]b9636002009-03-04 00:05:25326 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
327 default_download_path);
[email protected]f052118e2008-09-05 02:25:32328
329 // If the download path is dangerous we forcefully reset it. But if we do
330 // so we set a flag to make sure we only do it once, to avoid fighting
331 // the user if he really wants it on an unsafe place such as the desktop.
332
333 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41334 FilePath current_download_dir = FilePath::FromWStringHack(
335 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32336 if (DownloadPathIsDangerous(current_download_dir)) {
337 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41338 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32339 }
340 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
341 }
initial.commit09911bf2008-07-26 23:55:29342}
343
344DownloadManager::DownloadManager()
345 : shutdown_needed_(false),
346 profile_(NULL),
347 file_manager_(NULL),
348 ui_loop_(MessageLoop::current()),
349 file_loop_(NULL) {
350}
351
352DownloadManager::~DownloadManager() {
353 if (shutdown_needed_)
354 Shutdown();
355}
356
357void DownloadManager::Shutdown() {
358 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
359
360 // Stop receiving download updates
361 file_manager_->RemoveDownloadManager(this);
362
363 // Stop making history service requests
364 cancelable_consumer_.CancelAllRequests();
365
366 // 'in_progress_' may contain DownloadItems that have not finished the start
367 // complete (from the history service) and thus aren't in downloads_.
368 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32369 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29370 for (; it != in_progress_.end(); ++it) {
371 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32372 if (download->safety_state() == DownloadItem::DANGEROUS) {
373 // Forget about any download that the user did not approve.
374 // Note that we cannot call download->Remove() this would invalidate our
375 // iterator.
376 to_remove.insert(download);
377 continue;
initial.commit09911bf2008-07-26 23:55:29378 }
[email protected]9ccbb372008-10-10 18:50:32379 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
380 download->Cancel(false);
381 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29382 if (download->db_handle() == kUninitializedHandle) {
383 // An invalid handle means that 'download' does not yet exist in
384 // 'downloads_', so we have to delete it here.
385 delete download;
386 }
387 }
388
[email protected]9ccbb372008-10-10 18:50:32389 // 'dangerous_finished_' contains all complete downloads that have not been
390 // approved. They should be removed.
391 it = dangerous_finished_.begin();
392 for (; it != dangerous_finished_.end(); ++it)
393 to_remove.insert(it->second);
394
395 // Remove the dangerous download that are not approved.
396 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
397 rm_it != to_remove.end(); ++rm_it) {
398 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32399 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32400 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32401 // Same as above, delete the download if it is not in 'downloads_' (as the
402 // Remove() call above won't have deleted it).
403 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32404 delete download;
405 }
406 to_remove.clear();
407
initial.commit09911bf2008-07-26 23:55:29408 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32409 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29410 STLDeleteValues(&downloads_);
411
412 file_manager_ = NULL;
413
414 // Save our file extensions to auto open.
415 SaveAutoOpens();
416
417 // Make sure the save as dialog doesn't notify us back if we're gone before
418 // it returns.
419 if (select_file_dialog_.get())
420 select_file_dialog_->ListenerDestroyed();
421
422 shutdown_needed_ = false;
423}
424
425// Issue a history query for downloads matching 'search_text'. If 'search_text'
426// is empty, return all downloads that we know about.
427void DownloadManager::GetDownloads(Observer* observer,
428 const std::wstring& search_text) {
429 DCHECK(observer);
430
431 // Return a empty list if we've not yet received the set of downloads from the
432 // history system (we'll update all observers once we get that list in
433 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
434 std::vector<DownloadItem*> download_copy;
435 if (downloads_.empty()) {
436 observer->SetDownloads(download_copy);
437 return;
438 }
439
440 // We already know all the downloads and there is no filter, so just return a
441 // copy to the observer.
442 if (search_text.empty()) {
443 download_copy.reserve(downloads_.size());
444 for (DownloadMap::iterator it = downloads_.begin();
445 it != downloads_.end(); ++it) {
446 download_copy.push_back(it->second);
447 }
448
449 // We retain ownership of the DownloadItems.
450 observer->SetDownloads(download_copy);
451 return;
452 }
453
454 // Issue a request to the history service for a list of downloads matching
455 // our search text.
456 HistoryService* hs =
457 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
458 if (hs) {
459 HistoryService::Handle h =
460 hs->SearchDownloads(search_text,
461 &cancelable_consumer_,
462 NewCallback(this,
463 &DownloadManager::OnSearchComplete));
464 cancelable_consumer_.SetClientData(hs, h, observer);
465 }
466}
467
468// Query the history service for information about all persisted downloads.
469bool DownloadManager::Init(Profile* profile) {
470 DCHECK(profile);
471 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
472 shutdown_needed_ = true;
473
474 profile_ = profile;
475 request_context_ = profile_->GetRequestContext();
476
477 // 'incognito mode' will have access to past downloads, but we won't store
478 // information about new downloads while in that mode.
479 QueryHistoryForDownloads();
480
481 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
482 if (!rdh) {
483 NOTREACHED();
484 return false;
485 }
486
487 file_manager_ = rdh->download_file_manager();
488 if (!file_manager_) {
489 NOTREACHED();
490 return false;
491 }
492
493 file_loop_ = g_browser_process->file_thread()->message_loop();
494 if (!file_loop_) {
495 NOTREACHED();
496 return false;
497 }
498
499 // Get our user preference state.
500 PrefService* prefs = profile_->GetPrefs();
501 DCHECK(prefs);
502 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
503
initial.commit09911bf2008-07-26 23:55:29504 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
505
[email protected]7ae7c2cb2009-01-06 23:31:41506 // This variable is needed to resolve which CreateDirectory we want to point
507 // to. Without it, the NewRunnableFunction cannot resolve the ambiguity.
508 // TODO(estade): when file_util::CreateDirectory(wstring) is removed,
509 // get rid of |CreateDirectoryPtr|.
510 bool (*CreateDirectoryPtr)(const FilePath&) = &file_util::CreateDirectory;
[email protected]bb69e9b32008-08-14 23:08:14511 // Ensure that the download directory specified in the preferences exists.
[email protected]7ae7c2cb2009-01-06 23:31:41512 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
513 CreateDirectoryPtr, download_path()));
initial.commit09911bf2008-07-26 23:55:29514
[email protected]a0a9577b2009-05-27 23:52:32515#if defined(OS_WIN) || defined(OS_LINUX)
516 // We use this to determine possibly dangerous downloads.
[email protected]2b2f8f72009-02-24 22:42:05517 download_util::InitializeExeTypes(&exe_types_);
518#endif
519
520 // We store any file extension that should be opened automatically at
521 // download completion in this pref.
initial.commit09911bf2008-07-26 23:55:29522 std::wstring extensions_to_open =
523 prefs->GetString(prefs::kDownloadExtensionsToOpen);
524 std::vector<std::wstring> extensions;
525 SplitString(extensions_to_open, L':', &extensions);
526 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]b7f05882009-02-22 01:21:56527 if (!extensions[i].empty() && !IsExecutable(
528 FilePath::FromWStringHack(extensions[i]).value()))
529 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29530 }
531
532 return true;
533}
534
535void DownloadManager::QueryHistoryForDownloads() {
536 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
537 if (hs) {
538 hs->QueryDownloads(
539 &cancelable_consumer_,
540 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
541 }
542}
543
544// We have received a message from DownloadFileManager about a new download. We
545// create a download item and store it in our download map, and inform the
546// history system of a new download. Since this method can be called while the
547// history service thread is still reading the persistent state, we do not
548// insert the new DownloadItem into 'downloads_' or inform our observers at this
549// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
550// download creation as a callback from the history thread.
551void DownloadManager::StartDownload(DownloadCreateInfo* info) {
552 DCHECK(MessageLoop::current() == ui_loop_);
553 DCHECK(info);
554
[email protected]7d3851d82008-12-12 03:26:07555 // Freeze the user's preference for showing a Save As dialog. We're going to
556 // bounce around a bunch of threads and we don't want to worry about race
557 // conditions where the user changes this pref out from under us.
558 if (*prompt_for_download_)
559 info->save_as = true;
560
initial.commit09911bf2008-07-26 23:55:29561 // Determine the proper path for a download, by choosing either the default
562 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41563 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29564 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07565 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29566 info->suggested_path = last_download_path_;
567 else
[email protected]7ae7c2cb2009-01-06 23:31:41568 info->suggested_path = download_path();
569 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29570
[email protected]7d3851d82008-12-12 03:26:07571 if (!info->save_as) {
[email protected]4289d9b2009-07-25 21:17:34572 // Downloads can be marked as dangerous for two reasons:
573 // a) They have a dangerous-looking filename
574 // b) They are an extension that is not from the gallery
575 if (IsDangerous(info->suggested_path.BaseName()))
576 info->is_dangerous = true;
577 else if (info->mime_type == Extension::kMimeType &&
578 !ExtensionsService::IsDownloadFromGallery(info->url,
579 info->referrer_url)) {
580 info->is_dangerous = true;
581 }
[email protected]e9ebf3fc2008-10-17 22:06:58582 }
583
initial.commit09911bf2008-07-26 23:55:29584 // We need to move over to the download thread because we don't want to stat
585 // the suggested path on the UI thread.
586 file_loop_->PostTask(FROM_HERE,
587 NewRunnableMethod(this,
588 &DownloadManager::CheckIfSuggestedPathExists,
589 info));
590}
591
592void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
593 DCHECK(info);
594
595 // Check writability of the suggested path. If we can't write to it, default
596 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41597 FilePath dir = info->suggested_path.DirName();
598 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32599 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29600 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29601 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41602 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29603 }
604
[email protected]7a256ea2008-10-17 17:34:16605 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29606
[email protected]6cade212008-12-03 00:32:22607 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58608 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41609 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32610 // Create a temporary file to hold the file until the user approves its
611 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41612 FilePath::StringType file_name;
613 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32614 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41615 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32616 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41617 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07618 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41619 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32620 }
621 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16622 } else {
623 // We know the final path, build it if necessary.
624 if (info->path_uniquifier > 0) {
625 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
626 // Setting path_uniquifier to 0 to make sure we don't try to unique it
627 // later on.
628 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07629 } else if (info->path_uniquifier == -1) {
630 // We failed to find a unique path. We have to prompt the user.
631 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16632 }
[email protected]9ccbb372008-10-10 18:50:32633 }
634
[email protected]7d3851d82008-12-12 03:26:07635 if (!info->save_as) {
636 // Create an empty file at the suggested path so that we don't allocate the
637 // same "non-existant" path to multiple downloads.
638 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ae7c2cb2009-01-06 23:31:41639 file_util::WriteFile(info->suggested_path.ToWStringHack(), "", 0);
[email protected]7d3851d82008-12-12 03:26:07640 }
641
initial.commit09911bf2008-07-26 23:55:29642 // Now we return to the UI thread.
643 ui_loop_->PostTask(FROM_HERE,
644 NewRunnableMethod(this,
645 &DownloadManager::OnPathExistenceAvailable,
646 info));
647}
648
649void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
650 DCHECK(MessageLoop::current() == ui_loop_);
651 DCHECK(info);
652
[email protected]7d3851d82008-12-12 03:26:07653 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29654 // We must ask the user for the place to put the download.
655 if (!select_file_dialog_.get())
656 select_file_dialog_ = SelectFileDialog::Create(this);
657
[email protected]57c6a652009-05-04 07:58:34658 TabContents* contents = tab_util::GetTabContentsByID(
initial.commit09911bf2008-07-26 23:55:29659 info->render_process_id, info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08660 SelectFileDialog::FileTypeInfo file_type_info;
661 file_type_info.extensions.resize(1);
662 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24663 if (!file_type_info.extensions[0][0].empty())
664 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08665 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23666 gfx::NativeWindow owning_window =
667 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29668 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34669 string16(),
670 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08671 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30672 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29673 } else {
674 // No prompting for download, just continue with the suggested name.
675 ContinueStartDownload(info, info->suggested_path);
676 }
677}
678
679void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41680 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29681 scoped_ptr<DownloadCreateInfo> infop(info);
682 info->path = target_path;
683
684 DownloadItem* download = NULL;
685 DownloadMap::iterator it = in_progress_.find(info->download_id);
686 if (it == in_progress_.end()) {
687 download = new DownloadItem(info->download_id,
688 info->path,
[email protected]7a256ea2008-10-17 17:34:16689 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29690 info->url,
[email protected]494c06e2009-07-25 01:06:42691 info->referrer_url,
[email protected]e435d6b72009-07-25 03:15:58692 info->mime_type,
[email protected]9ccbb372008-10-10 18:50:32693 info->original_name,
initial.commit09911bf2008-07-26 23:55:29694 info->start_time,
695 info->total_bytes,
696 info->render_process_id,
[email protected]9ccbb372008-10-10 18:50:32697 info->request_id,
698 info->is_dangerous);
initial.commit09911bf2008-07-26 23:55:29699 download->set_manager(this);
700 in_progress_[info->download_id] = download;
701 } else {
702 NOTREACHED(); // Should not exist!
703 return;
704 }
705
[email protected]6b323782009-03-27 18:43:08706 // Called before DownloadFinished in order to avoid a race condition where we
707 // attempt to open a completed download before it has been renamed.
708 file_loop_->PostTask(FROM_HERE,
709 NewRunnableMethod(file_manager_,
710 &DownloadFileManager::OnFinalDownloadName,
711 download->id(),
[email protected]8f783752009-04-01 23:33:45712 target_path,
713 this));
[email protected]6b323782009-03-27 18:43:08714
initial.commit09911bf2008-07-26 23:55:29715 // If the download already completed by the time we reached this point, then
716 // notify observers that it did.
717 PendingFinishedMap::iterator pending_it =
718 pending_finished_downloads_.find(info->download_id);
719 if (pending_it != pending_finished_downloads_.end())
720 DownloadFinished(pending_it->first, pending_it->second);
721
722 download->Rename(target_path);
723
initial.commit09911bf2008-07-26 23:55:29724 if (profile_->IsOffTheRecord()) {
725 // Fake a db handle for incognito mode, since nothing is actually stored in
726 // the database in this mode. We have to make sure that these handles don't
727 // collide with normal db handles, so we use a negative value. Eventually,
728 // they could overlap, but you'd have to do enough downloading that your ISP
729 // would likely stab you in the neck first. YMMV.
730 static int64 fake_db_handle = kUninitializedHandle - 1;
731 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
732 } else {
733 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22734 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29735 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
736 if (hs) {
737 hs->CreateDownload(
738 *info, &cancelable_consumer_,
739 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
740 }
741 }
742}
743
744// Convenience function for updating the history service for a download.
745void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
746 DCHECK(download);
747
748 // Don't store info in the database if the download was initiated while in
749 // incognito mode or if it hasn't been initialized in our database table.
750 if (download->db_handle() <= kUninitializedHandle)
751 return;
752
[email protected]6cade212008-12-03 00:32:22753 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29754 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
755 if (hs) {
756 hs->UpdateDownload(download->received_bytes(),
757 download->state(),
758 download->db_handle());
759 }
760}
761
762void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
763 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22764 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29765 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
766 if (download->db_handle() > kUninitializedHandle && hs)
767 hs->RemoveDownload(download->db_handle());
768}
769
[email protected]e93d2822009-01-30 05:59:59770void DownloadManager::RemoveDownloadsFromHistoryBetween(
771 const base::Time remove_begin,
772 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22773 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29774 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
775 if (hs)
776 hs->RemoveDownloadsBetween(remove_begin, remove_end);
777}
778
779void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
780 DownloadMap::iterator it = in_progress_.find(download_id);
781 if (it != in_progress_.end()) {
782 DownloadItem* download = it->second;
783 download->Update(size);
784 UpdateHistoryForDownload(download);
785 }
786}
787
788void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
789 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32790 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29791 // The download is done, but the user hasn't selected a final location for
792 // it yet (the Save As dialog box is probably still showing), so just keep
793 // track of the fact that this download id is complete, when the
794 // DownloadItem is constructed later we'll notify its completion then.
795 PendingFinishedMap::iterator erase_it =
796 pending_finished_downloads_.find(download_id);
797 DCHECK(erase_it == pending_finished_downloads_.end());
798 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32799 return;
initial.commit09911bf2008-07-26 23:55:29800 }
[email protected]9ccbb372008-10-10 18:50:32801
802 // Remove the id from the list of pending ids.
803 PendingFinishedMap::iterator erase_it =
804 pending_finished_downloads_.find(download_id);
805 if (erase_it != pending_finished_downloads_.end())
806 pending_finished_downloads_.erase(erase_it);
807
808 DownloadItem* download = it->second;
809 download->Finished(size);
810
811 // Clean up will happen when the history system create callback runs if we
812 // don't have a valid db_handle yet.
813 if (download->db_handle() != kUninitializedHandle) {
814 in_progress_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32815 UpdateHistoryForDownload(download);
816 }
817
818 // If this a dangerous download not yet validated by the user, don't do
819 // anything. When the user notifies us, it will trigger a call to
820 // ProceedWithFinishedDangerousDownload.
821 if (download->safety_state() == DownloadItem::DANGEROUS) {
822 dangerous_finished_[download_id] = download;
823 return;
824 }
825
826 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22827 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32828 // its final name before we can continue.
829 file_loop_->PostTask(FROM_HERE,
830 NewRunnableMethod(
831 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
832 download->db_handle(),
833 download->full_path(), download->original_name()));
834 return;
835 }
836 ContinueDownloadFinished(download);
837}
838
[email protected]8f783752009-04-01 23:33:45839void DownloadManager::DownloadRenamedToFinalName(int download_id,
840 const FilePath& full_path) {
[email protected]8f783752009-04-01 23:33:45841}
842
[email protected]9ccbb372008-10-10 18:50:32843void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
844 // If this was a dangerous download, it has now been approved and must be
845 // removed from dangerous_finished_ so it does not get deleted on shutdown.
846 DownloadMap::iterator it = dangerous_finished_.find(download->id());
847 if (it != dangerous_finished_.end())
848 dangerous_finished_.erase(it);
849
[email protected]5a102892009-07-15 19:59:30850 // Open the download if the user or user prefs indicate it should be.
851 FilePath::StringType extension = download->full_path().Extension();
852 // Drop the leading period. (The auto-open list is period-less.)
853 if (extension.size() > 0)
854 extension = extension.substr(1);
855
[email protected]0aad67b2009-07-15 20:34:28856 // Handle chrome extensions explicitly and skip the shell execute.
[email protected]e435d6b72009-07-25 03:15:58857 if (download->mime_type() == Extension::kMimeType) {
[email protected]494c06e2009-07-25 01:06:42858 OpenChromeExtension(download->full_path(), download->url(),
859 download->referrer_url());
[email protected]0aad67b2009-07-15 20:34:28860 download->set_auto_opened(true);
861 } else if (download->open_when_complete() ||
862 ShouldOpenFileExtension(extension)) {
[email protected]9ccbb372008-10-10 18:50:32863 OpenDownloadInShell(download, NULL);
[email protected]0aad67b2009-07-15 20:34:28864 download->set_auto_opened(true);
865 }
[email protected]9ccbb372008-10-10 18:50:32866
[email protected]0aad67b2009-07-15 20:34:28867 // Notify our observers that we are complete (the call to Finished() set the
868 // state to complete but did not notify).
869 download->UpdateObservers();
870}
[email protected]9ccbb372008-10-10 18:50:32871// Called on the file thread. Renames the downloaded file to its original name.
872void DownloadManager::ProceedWithFinishedDangerousDownload(
873 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41874 const FilePath& path,
875 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32876 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41877 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16878 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32879 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24880 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16881 // Make our name unique at this point, as if a dangerous file is downloading
882 // and a 2nd download is started for a file with the same name, they would
883 // have the same path. This is because we uniquify the name on download
884 // start, and at that time the first file does not exists yet, so the second
885 // file gets the same name.
886 uniquifier = GetUniquePathNumber(new_path);
887 if (uniquifier > 0)
888 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32889 success = file_util::Move(path, new_path);
890 } else {
891 NOTREACHED();
892 }
[email protected]6cade212008-12-03 00:32:22893
[email protected]9ccbb372008-10-10 18:50:32894 ui_loop_->PostTask(FROM_HERE,
895 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16896 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32897}
898
899// Call from the file thread when the finished dangerous download was renamed.
900void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
901 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41902 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16903 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32904 DownloadMap::iterator it = downloads_.find(download_handle);
905 if (it == downloads_.end()) {
906 NOTREACHED();
907 return;
908 }
909
910 DownloadItem* download = it->second;
911 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16912 if (success) {
913 // We need to update the path uniquifier so that the UI shows the right
914 // name when calling GetFileName().
915 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32916 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16917 }
[email protected]9ccbb372008-10-10 18:50:32918
919 // Continue the download finished sequence.
920 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29921}
922
923// static
924// We have to tell the ResourceDispatcherHost to cancel the download from this
[email protected]6cade212008-12-03 00:32:22925// thread, since we can't forward tasks from the file thread to the IO thread
initial.commit09911bf2008-07-26 23:55:29926// reliably (crash on shutdown race condition).
927void DownloadManager::CancelDownloadRequest(int render_process_id,
928 int request_id) {
929 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]ab820df2008-08-26 05:55:10930 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29931 if (!io_thread || !rdh)
932 return;
933 io_thread->message_loop()->PostTask(FROM_HERE,
934 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
935 rdh,
936 render_process_id,
937 request_id));
938}
939
940// static
941void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
942 int render_process_id,
943 int request_id) {
944 rdh->CancelRequest(render_process_id, request_id, false);
945}
946
947void DownloadManager::DownloadCancelled(int32 download_id) {
948 DownloadMap::iterator it = in_progress_.find(download_id);
949 if (it == in_progress_.end())
950 return;
951 DownloadItem* download = it->second;
952
953 CancelDownloadRequest(download->render_process_id(), download->request_id());
954
955 // Clean up will happen when the history system create callback runs if we
956 // don't have a valid db_handle yet.
957 if (download->db_handle() != kUninitializedHandle) {
958 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:29959 UpdateHistoryForDownload(download);
960 }
961
962 // Tell the file manager to cancel the download.
963 file_manager_->RemoveDownload(download->id(), this); // On the UI thread
964 file_loop_->PostTask(FROM_HERE,
965 NewRunnableMethod(file_manager_,
966 &DownloadFileManager::CancelDownload,
967 download->id()));
968}
969
970void DownloadManager::PauseDownload(int32 download_id, bool pause) {
971 DownloadMap::iterator it = in_progress_.find(download_id);
972 if (it != in_progress_.end()) {
973 DownloadItem* download = it->second;
974 if (pause == download->is_paused())
975 return;
976
977 // Inform the ResourceDispatcherHost of the new pause state.
[email protected]ab820df2008-08-26 05:55:10978 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29979 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
980 if (!io_thread || !rdh)
981 return;
982
983 io_thread->message_loop()->PostTask(FROM_HERE,
984 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
985 rdh,
986 download->render_process_id(),
987 download->request_id(),
988 pause));
989 }
990}
991
992// static
993void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
994 int render_process_id,
995 int request_id,
996 bool pause) {
997 rdh->PauseRequest(render_process_id, request_id, pause);
998}
999
[email protected]7ae7c2cb2009-01-06 23:31:411000bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:321001 // TODO(jcampan): Improve me.
[email protected]2001fe82009-02-23 23:53:141002 FilePath::StringType extension = file_name.Extension();
1003 // Drop the leading period.
1004 if (extension.size() > 0)
1005 extension = extension.substr(1);
1006 return IsExecutable(extension);
[email protected]9ccbb372008-10-10 18:50:321007}
1008
1009void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:411010 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:321011 download->Rename(new_path);
1012
1013 // Update the history.
1014
1015 // No update necessary if the download was initiated while in incognito mode.
1016 if (download->db_handle() <= kUninitializedHandle)
1017 return;
1018
[email protected]6cade212008-12-03 00:32:221019 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:321020 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1021 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:411022 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:321023}
1024
initial.commit09911bf2008-07-26 23:55:291025void DownloadManager::RemoveDownload(int64 download_handle) {
1026 DownloadMap::iterator it = downloads_.find(download_handle);
1027 if (it == downloads_.end())
1028 return;
1029
1030 // Make history update.
1031 DownloadItem* download = it->second;
1032 RemoveDownloadFromHistory(download);
1033
1034 // Remove from our tables and delete.
1035 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321036 it = dangerous_finished_.find(download->id());
1037 if (it != dangerous_finished_.end())
1038 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291039
1040 // Tell observers to refresh their views.
1041 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:361042
1043 delete download;
initial.commit09911bf2008-07-26 23:55:291044}
1045
[email protected]e93d2822009-01-30 05:59:591046int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1047 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291048 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1049
initial.commit09911bf2008-07-26 23:55:291050 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:281051 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:291052 while (it != downloads_.end()) {
1053 DownloadItem* download = it->second;
1054 DownloadItem::DownloadState state = download->state();
1055 if (download->start_time() >= remove_begin &&
1056 (remove_end.is_null() || download->start_time() < remove_end) &&
1057 (state == DownloadItem::COMPLETE ||
1058 state == DownloadItem::CANCELLED)) {
1059 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561060 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581061
1062 // Also remove it from any completed dangerous downloads.
1063 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1064 if (dit != dangerous_finished_.end())
1065 dangerous_finished_.erase(dit);
1066
[email protected]78b8fcc92009-03-31 17:36:281067 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:291068
initial.commit09911bf2008-07-26 23:55:291069 continue;
1070 }
1071
1072 ++it;
1073 }
1074
1075 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281076 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291077 if (num_deleted > 0)
1078 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1079
[email protected]78b8fcc92009-03-31 17:36:281080 // Delete the download items after updating the observers.
1081 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1082 pending_deletes.clear();
1083
initial.commit09911bf2008-07-26 23:55:291084 return num_deleted;
1085}
1086
[email protected]e93d2822009-01-30 05:59:591087int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1088 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291089}
1090
[email protected]d41355e6f2009-04-07 21:21:121091int DownloadManager::RemoveAllDownloads() {
1092 // The null times make the date range unbounded.
1093 return RemoveDownloadsBetween(base::Time(), base::Time());
1094}
1095
initial.commit09911bf2008-07-26 23:55:291096// Initiate a download of a specific URL. We send the request to the
1097// ResourceDispatcherHost, and let it send us responses like a regular
1098// download.
1099void DownloadManager::DownloadUrl(const GURL& url,
1100 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:501101 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:341102 TabContents* tab_contents) {
1103 DCHECK(tab_contents);
[email protected]c9825a42009-05-01 22:51:501104 request_context_->set_referrer_charset(referrer_charset);
initial.commit09911bf2008-07-26 23:55:291105 file_manager_->DownloadUrl(url,
1106 referrer,
[email protected]57c6a652009-05-04 07:58:341107 tab_contents->process()->pid(),
1108 tab_contents->render_view_host()->routing_id(),
initial.commit09911bf2008-07-26 23:55:291109 request_context_.get());
1110}
1111
[email protected]7ae7c2cb2009-01-06 23:31:411112void DownloadManager::GenerateExtension(
1113 const FilePath& file_name,
1114 const std::string& mime_type,
1115 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291116 // We're worried about three things here:
1117 //
1118 // 1) Security. Many sites let users upload content, such as buddy icons, to
1119 // their web sites. We want to mitigate the case where an attacker
1120 // supplies a malicious executable with an executable file extension but an
1121 // honest site serves the content with a benign content type, such as
1122 // image/jpeg.
1123 //
1124 // 2) Usability. If the site fails to provide a file extension, we want to
1125 // guess a reasonable file extension based on the content type.
1126 //
1127 // 3) Shell integration. Some file extensions automatically integrate with
1128 // the shell. We block these extensions to prevent a malicious web site
1129 // from integrating with the user's shell.
1130
[email protected]7ae7c2cb2009-01-06 23:31:411131 static const FilePath::CharType default_extension[] =
1132 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291133
1134 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411135 FilePath::StringType extension(
1136 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291137
[email protected]b7f05882009-02-22 01:21:561138#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291139 // Rename shell-integrated extensions.
1140 if (win_util::IsShellIntegratedExtension(extension))
1141 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561142#endif
initial.commit09911bf2008-07-26 23:55:291143
1144 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411145 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411146 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291147 if (mime_type == mime_type_from_extension) {
1148 // The hinted extension matches the mime type. It looks like a winner.
1149 generated_extension->swap(extension);
1150 return;
1151 }
1152
1153 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1154 // We want to be careful about executable extensions. The worry here is
1155 // that a trusted web site could be tricked into dropping an executable file
1156 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101157 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291158 // We couldn't find a good extension for this content type. Use a dummy
1159 // extension instead.
1160 extension.assign(default_extension);
1161 }
1162 }
1163
1164 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101165 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291166 } else {
[email protected]6cade212008-12-03 00:32:221167 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291168 // 1. New extension is not ".txt"
1169 // 2. New extension is not the same as the already existing extension.
1170 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411171 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291172 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1173 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371174 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1175 // servers, i.e. bug 5772.
[email protected]7ae7c2cb2009-01-06 23:31:411176 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101177 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171178 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411179 append_extension != extension &&
[email protected]e106457b2009-03-25 22:43:371180 !IsExecutable(append_extension) &&
1181 (append_extension != FILE_PATH_LITERAL("tar") ||
1182 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171183 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291184 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171185 }
initial.commit09911bf2008-07-26 23:55:291186 }
1187 }
1188
1189 generated_extension->swap(extension);
1190}
1191
1192void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411193 FilePath* generated_name) {
1194 *generated_name = FilePath::FromWStringHack(
[email protected]8ac1a752008-07-31 19:40:371195 net::GetSuggestedFilename(GURL(info->url),
1196 info->content_disposition,
[email protected]c9825a42009-05-01 22:51:501197 info->referrer_charset,
[email protected]7ae7c2cb2009-01-06 23:31:411198 L"download"));
1199 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291200
[email protected]7ae7c2cb2009-01-06 23:31:411201 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291202}
1203
1204void DownloadManager::AddObserver(Observer* observer) {
1205 observers_.AddObserver(observer);
1206 observer->ModelChanged();
1207}
1208
1209void DownloadManager::RemoveObserver(Observer* observer) {
1210 observers_.RemoveObserver(observer);
1211}
1212
1213// Post Windows Shell operations to the Download thread, to avoid blocking the
1214// user interface.
1215void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1216 DCHECK(file_manager_);
1217 file_loop_->PostTask(FROM_HERE,
1218 NewRunnableMethod(file_manager_,
1219 &DownloadFileManager::OnShowDownloadInShell,
[email protected]7ae7c2cb2009-01-06 23:31:411220 FilePath(download->full_path())));
initial.commit09911bf2008-07-26 23:55:291221}
1222
[email protected]8f783752009-04-01 23:33:451223void DownloadManager::OpenDownload(const DownloadItem* download,
1224 gfx::NativeView parent_window) {
[email protected]0e34d7892009-06-05 19:17:401225 // Open Chrome extensions with ExtensionsService. For everything else do shell
[email protected]8f783752009-04-01 23:33:451226 // execute.
[email protected]e435d6b72009-07-25 03:15:581227 if (download->mime_type() == Extension::kMimeType) {
[email protected]494c06e2009-07-25 01:06:421228 OpenChromeExtension(download->full_path(), download->url(),
1229 download->referrer_url());
[email protected]8f783752009-04-01 23:33:451230 } else {
1231 OpenDownloadInShell(download, parent_window);
1232 }
1233}
1234
[email protected]c1e432a2009-07-22 21:21:481235void DownloadManager::OpenChromeExtension(const FilePath& full_path,
[email protected]494c06e2009-07-25 01:06:421236 const GURL& download_url,
1237 const GURL& referrer_url) {
[email protected]1bd54132009-06-11 00:05:341238 profile_->GetOriginalProfile()->GetExtensionsService()->
[email protected]494c06e2009-07-25 01:06:421239 InstallExtension(full_path, download_url, referrer_url);
[email protected]8f783752009-04-01 23:33:451240}
1241
initial.commit09911bf2008-07-26 23:55:291242void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591243 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291244 DCHECK(file_manager_);
1245 file_loop_->PostTask(FROM_HERE,
1246 NewRunnableMethod(file_manager_,
1247 &DownloadFileManager::OnOpenDownloadInShell,
1248 download->full_path(), download->url(), parent_window));
1249}
1250
[email protected]7ae7c2cb2009-01-06 23:31:411251void DownloadManager::OpenFilesOfExtension(
1252 const FilePath::StringType& extension, bool open) {
initial.commit09911bf2008-07-26 23:55:291253 if (open && !IsExecutable(extension))
1254 auto_open_.insert(extension);
1255 else
1256 auto_open_.erase(extension);
1257 SaveAutoOpens();
1258}
1259
[email protected]7ae7c2cb2009-01-06 23:31:411260bool DownloadManager::ShouldOpenFileExtension(
1261 const FilePath::StringType& extension) {
[email protected]8c756ac2009-01-30 23:36:411262 // Special-case Chrome extensions as always-open.
initial.commit09911bf2008-07-26 23:55:291263 if (!IsExecutable(extension) &&
[email protected]8c756ac2009-01-30 23:36:411264 (auto_open_.find(extension) != auto_open_.end() ||
[email protected]f1ce6e62009-06-29 20:31:291265 Extension::IsExtension(FilePath(extension))))
[email protected]8c756ac2009-01-30 23:36:411266 return true;
initial.commit09911bf2008-07-26 23:55:291267 return false;
1268}
1269
[email protected]7b73d992008-12-15 20:56:461270static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291271 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461272 "text/javascript",
1273 "text/javascript;version=*",
[email protected]54d8d452009-04-08 17:29:241274 // Registry files can cause critical changes to the MS OS behavior.
1275 // Addition of this mimetype also addresses bug 7337.
1276 "text/x-registry",
[email protected]60ff8f912008-12-05 07:58:391277 // Some sites use binary/octet-stream to mean application/octet-stream.
1278 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461279 "binary/octet-stream"
1280};
initial.commit09911bf2008-07-26 23:55:291281
[email protected]7b73d992008-12-15 20:56:461282static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291283 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461284 "application/*+xml",
1285 "application/xml"
1286};
initial.commit09911bf2008-07-26 23:55:291287
[email protected]7b73d992008-12-15 20:56:461288// static
1289bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411290 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461291 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1292 return true;
1293 }
[email protected]bae0ea12009-02-14 01:20:411294 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461295 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1296 return false;
1297 }
1298 // We consider only other application types to be executable.
1299 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291300}
1301
[email protected]7ae7c2cb2009-01-06 23:31:411302bool DownloadManager::IsExecutable(const FilePath::StringType& extension) {
[email protected]a0a9577b2009-05-27 23:52:321303#if defined(OS_MACOSX)
1304 // We don't have dangerous download support on mac yet.
1305 return false;
1306#else
[email protected]64da0b932009-02-24 02:30:041307 if (!IsStringASCII(extension))
1308 return false;
[email protected]a0a9577b2009-05-27 23:52:321309#if defined(OS_WIN)
[email protected]64da0b932009-02-24 02:30:041310 std::string ascii_extension = WideToASCII(extension);
[email protected]a0a9577b2009-05-27 23:52:321311#elif defined(OS_LINUX)
1312 std::string ascii_extension = extension;
1313#endif
[email protected]64da0b932009-02-24 02:30:041314 StringToLowerASCII(&ascii_extension);
1315
1316 return exe_types_.find(ascii_extension) != exe_types_.end();
[email protected]a0a9577b2009-05-27 23:52:321317#endif // !defined(OS_MACOSX)
initial.commit09911bf2008-07-26 23:55:291318}
1319
1320void DownloadManager::ResetAutoOpenFiles() {
1321 auto_open_.clear();
1322 SaveAutoOpens();
1323}
1324
1325bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1326 return !auto_open_.empty();
1327}
1328
1329void DownloadManager::SaveAutoOpens() {
1330 PrefService* prefs = profile_->GetPrefs();
1331 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411332 FilePath::StringType extensions;
1333 for (std::set<FilePath::StringType>::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291334 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411335 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291336 }
1337 if (!extensions.empty())
1338 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561339
1340 std::wstring extensions_w;
1341#if defined(OS_WIN)
1342 extensions_w = extensions;
1343#elif defined(OS_POSIX)
[email protected]1b5044d2009-02-24 00:04:141344 extensions_w = base::SysNativeMBToWide(extensions);
[email protected]b7f05882009-02-22 01:21:561345#endif
1346
1347 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291348 }
1349}
1350
[email protected]561abe62009-04-06 18:08:341351void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361352 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291353 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071354 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411355 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291356 ContinueStartDownload(info, path);
1357}
1358
1359void DownloadManager::FileSelectionCanceled(void* params) {
1360 // The user didn't pick a place to save the file, so need to cancel the
1361 // download that's already in progress to the temporary location.
1362 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
1363 file_loop_->PostTask(FROM_HERE,
1364 NewRunnableMethod(file_manager_, &DownloadFileManager::CancelDownload,
1365 info->download_id));
1366}
1367
[email protected]7ae7c2cb2009-01-06 23:31:411368void DownloadManager::DeleteDownload(const FilePath& path) {
1369 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
1370 &DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321371}
1372
1373
1374void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1375 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1376 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1377 download->UpdateObservers();
1378
1379 // If the download is not complete, nothing to do. The required
1380 // post-processing will be performed when it does complete.
1381 if (download->state() != DownloadItem::COMPLETE)
1382 return;
1383
1384 file_loop_->PostTask(FROM_HERE,
1385 NewRunnableMethod(this,
1386 &DownloadManager::ProceedWithFinishedDangerousDownload,
1387 download->db_handle(), download->full_path(),
1388 download->original_name()));
1389}
1390
[email protected]763f946a2009-01-06 19:04:391391void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411392 FilePath* file_name) {
1393 // Make sure we get the right file extension
1394 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391395 GenerateExtension(*file_name, mime_type, &extension);
1396 file_util::ReplaceExtension(file_name, extension);
1397
[email protected]2b2f8f72009-02-24 22:42:051398#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391399 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411400 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391401 DCHECK(!leaf_name.empty());
1402 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411403 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1404 *file_name = file_name->DirName();
1405 if (file_name->value() == FilePath::kCurrentDirectory) {
1406 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391407 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411408 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391409 }
1410 }
[email protected]b7f05882009-02-22 01:21:561411#elif defined(OS_POSIX)
1412 NOTIMPLEMENTED();
1413#endif
[email protected]763f946a2009-01-06 19:04:391414}
1415
initial.commit09911bf2008-07-26 23:55:291416// Operations posted to us from the history service ----------------------------
1417
1418// The history service has retrieved all download entries. 'entries' contains
1419// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1420void DownloadManager::OnQueryDownloadEntriesComplete(
1421 std::vector<DownloadCreateInfo>* entries) {
1422 for (size_t i = 0; i < entries->size(); ++i) {
1423 DownloadItem* download = new DownloadItem(entries->at(i));
1424 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1425 downloads_[download->db_handle()] = download;
1426 download->set_manager(this);
1427 }
1428 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1429}
1430
initial.commit09911bf2008-07-26 23:55:291431// Once the new DownloadItem's creation info has been committed to the history
1432// service, we associate the DownloadItem with the db handle, update our
1433// 'downloads_' map and inform observers.
1434void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1435 int64 db_handle) {
1436 DownloadMap::iterator it = in_progress_.find(info.download_id);
1437 DCHECK(it != in_progress_.end());
1438
1439 DownloadItem* download = it->second;
1440 DCHECK(download->db_handle() == kUninitializedHandle);
1441 download->set_db_handle(db_handle);
1442
1443 // Insert into our full map.
1444 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1445 downloads_[download->db_handle()] = download;
1446
[email protected]5e595482009-05-06 20:16:531447 // Show in the appropropriate browser UI.
1448 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291449
1450 // Inform interested objects about the new download.
1451 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
initial.commit09911bf2008-07-26 23:55:291452
1453 // If this download has been completed before we've received the db handle,
1454 // post one final message to the history service so that it can be properly
1455 // in sync with the DownloadItem's completion status, and also inform any
1456 // observers so that they get more than just the start notification.
1457 if (download->state() != DownloadItem::IN_PROGRESS) {
1458 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291459 UpdateHistoryForDownload(download);
1460 download->UpdateObservers();
1461 }
1462}
1463
1464// Called when the history service has retrieved the list of downloads that
1465// match the search text.
1466void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1467 std::vector<int64>* results) {
1468 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1469 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1470 if (!requestor)
1471 return;
1472
1473 std::vector<DownloadItem*> searched_downloads;
1474 for (std::vector<int64>::iterator it = results->begin();
1475 it != results->end(); ++it) {
1476 DownloadMap::iterator dit = downloads_.find(*it);
1477 if (dit != downloads_.end())
1478 searched_downloads.push_back(dit->second);
1479 }
1480
1481 requestor->SetDownloads(searched_downloads);
1482}
[email protected]905a08d2008-11-19 07:24:121483
[email protected]5e595482009-05-06 20:16:531484void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1485 DownloadItem* download) {
[email protected]5e595482009-05-06 20:16:531486 // The 'contents' may no longer exist if the user closed the tab before we get
1487 // this start completion event. If it does, tell the origin TabContents to
1488 // display its download shelf.
1489 TabContents* contents =
1490 tab_util::GetTabContentsByID(info.render_process_id, info.render_view_id);
1491
1492 // If the contents no longer exists, we start the download in the last active
1493 // browser. This is not ideal but better than fully hiding the download from
1494 // the user.
1495 if (!contents) {
1496 Browser* last_active = BrowserList::GetLastActive();
1497 if (last_active)
1498 contents = last_active->GetSelectedTabContents();
1499 }
1500
1501 if (contents)
1502 contents->OnStartDownload(download);
1503}
1504
[email protected]6cade212008-12-03 00:32:221505// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121506void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411507 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381508}
1509