blob: 01ea2d0aa89efd31af3af02b702a1e9a7b54a887 [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),
120 total_bytes_(info.total_bytes),
121 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56122 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29123 state_(static_cast<DownloadState>(info.state)),
124 start_time_(info.start_time),
125 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29126 manager_(NULL),
127 is_paused_(false),
128 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56129 safety_state_(SAFE),
[email protected]0aad67b2009-07-15 20:34:28130 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56131 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29132 render_process_id_(-1),
133 request_id_(-1) {
134 if (state_ == IN_PROGRESS)
135 state_ = CANCELLED;
136 Init(false /* don't start progress timer */);
137}
138
139// Constructor for DownloadItem created via user action in the main thread.
140DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41141 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16142 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32143 const GURL& url,
[email protected]494c06e2009-07-25 01:06:42144 const GURL& referrer_url,
[email protected]7ae7c2cb2009-01-06 23:31:41145 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59146 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29147 int64 download_size,
148 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32149 int request_id,
150 bool is_dangerous)
initial.commit09911bf2008-07-26 23:55:29151 : id_(download_id),
152 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16153 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29154 url_(url),
[email protected]494c06e2009-07-25 01:06:42155 referrer_url_(referrer_url),
initial.commit09911bf2008-07-26 23:55:29156 total_bytes_(download_size),
157 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56158 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29159 state_(IN_PROGRESS),
160 start_time_(start_time),
161 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29162 manager_(NULL),
163 is_paused_(false),
164 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56165 safety_state_(is_dangerous ? DANGEROUS : SAFE),
[email protected]0aad67b2009-07-15 20:34:28166 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56167 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29168 render_process_id_(render_process_id),
169 request_id_(request_id) {
170 Init(true /* start progress timer */);
171}
172
173void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41174 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29175 if (start_timer)
176 StartProgressTimer();
177}
178
179DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29180 state_ = REMOVING;
181 UpdateObservers();
182}
183
184void DownloadItem::AddObserver(Observer* observer) {
185 observers_.AddObserver(observer);
186}
187
188void DownloadItem::RemoveObserver(Observer* observer) {
189 observers_.RemoveObserver(observer);
190}
191
192void DownloadItem::UpdateObservers() {
193 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
194}
195
[email protected]45e3c122009-04-07 19:58:03196void DownloadItem::NotifyObserversDownloadOpened() {
197 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadOpened(this));
198}
199
initial.commit09911bf2008-07-26 23:55:29200// If we've received more data than we were expecting (bad server info?), revert
201// to 'unknown size mode'.
202void DownloadItem::UpdateSize(int64 bytes_so_far) {
203 received_bytes_ = bytes_so_far;
204 if (received_bytes_ > total_bytes_)
205 total_bytes_ = 0;
206}
207
208// Updates from the download thread may have been posted while this download
209// was being cancelled in the UI thread, so we'll accept them unless we're
210// complete.
211void DownloadItem::Update(int64 bytes_so_far) {
212 if (state_ == COMPLETE) {
213 NOTREACHED();
214 return;
215 }
216 UpdateSize(bytes_so_far);
217 UpdateObservers();
218}
219
[email protected]6cade212008-12-03 00:32:22220// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29221void DownloadItem::Cancel(bool update_history) {
222 if (state_ != IN_PROGRESS) {
223 // Small downloads might be complete before this method has a chance to run.
224 return;
225 }
226 state_ = CANCELLED;
227 UpdateObservers();
228 StopProgressTimer();
229 if (update_history)
230 manager_->DownloadCancelled(id_);
231}
232
233void DownloadItem::Finished(int64 size) {
234 state_ = COMPLETE;
235 UpdateSize(size);
[email protected]22fbe5a2008-10-29 22:20:40236 UpdateObservers();
initial.commit09911bf2008-07-26 23:55:29237 StopProgressTimer();
238}
239
[email protected]9ccbb372008-10-10 18:50:32240void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29241 Cancel(true);
242 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32243 if (delete_on_disk)
244 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29245 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22246 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29247}
248
249void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59250 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14251 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29252}
253
254void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14255 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29256}
257
[email protected]e93d2822009-01-30 05:59:59258bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29259 if (total_bytes_ <= 0)
260 return false; // We never received the content_length for this download.
261
262 int64 speed = CurrentSpeed();
263 if (speed == 0)
264 return false;
265
266 *remaining =
[email protected]e93d2822009-01-30 05:59:59267 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29268 return true;
269}
270
271int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56272 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
273 int64 diff_ms = diff.InMilliseconds();
274 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29275}
276
277int DownloadItem::PercentComplete() const {
278 int percent = -1;
279 if (total_bytes_ > 0)
280 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
281 return percent;
282}
283
[email protected]7ae7c2cb2009-01-06 23:31:41284void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29285 DCHECK(!full_path.empty());
286 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41287 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29288}
289
290void DownloadItem::TogglePause() {
291 DCHECK(state_ == IN_PROGRESS);
292 manager_->PauseDownload(id_, !is_paused_);
293 is_paused_ = !is_paused_;
294 UpdateObservers();
295}
296
[email protected]7ae7c2cb2009-01-06 23:31:41297FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32298 if (safety_state_ == DownloadItem::SAFE)
299 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16300 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41301 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16302 AppendNumberToPath(&name, path_uniquifier_);
303 return name;
304 }
[email protected]9ccbb372008-10-10 18:50:32305 return original_name_;
306}
307
initial.commit09911bf2008-07-26 23:55:29308// DownloadManager implementation ----------------------------------------------
309
310// static
311void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
312 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
313 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32314 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
315
316 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41317 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12318 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
319 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32320 NOTREACHED();
321 }
[email protected]b9636002009-03-04 00:05:25322 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
323 default_download_path);
[email protected]f052118e2008-09-05 02:25:32324
325 // If the download path is dangerous we forcefully reset it. But if we do
326 // so we set a flag to make sure we only do it once, to avoid fighting
327 // the user if he really wants it on an unsafe place such as the desktop.
328
329 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41330 FilePath current_download_dir = FilePath::FromWStringHack(
331 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32332 if (DownloadPathIsDangerous(current_download_dir)) {
333 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41334 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32335 }
336 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
337 }
initial.commit09911bf2008-07-26 23:55:29338}
339
340DownloadManager::DownloadManager()
341 : shutdown_needed_(false),
342 profile_(NULL),
343 file_manager_(NULL),
344 ui_loop_(MessageLoop::current()),
345 file_loop_(NULL) {
346}
347
348DownloadManager::~DownloadManager() {
349 if (shutdown_needed_)
350 Shutdown();
351}
352
353void DownloadManager::Shutdown() {
354 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
355
356 // Stop receiving download updates
357 file_manager_->RemoveDownloadManager(this);
358
359 // Stop making history service requests
360 cancelable_consumer_.CancelAllRequests();
361
362 // 'in_progress_' may contain DownloadItems that have not finished the start
363 // complete (from the history service) and thus aren't in downloads_.
364 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32365 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29366 for (; it != in_progress_.end(); ++it) {
367 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32368 if (download->safety_state() == DownloadItem::DANGEROUS) {
369 // Forget about any download that the user did not approve.
370 // Note that we cannot call download->Remove() this would invalidate our
371 // iterator.
372 to_remove.insert(download);
373 continue;
initial.commit09911bf2008-07-26 23:55:29374 }
[email protected]9ccbb372008-10-10 18:50:32375 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
376 download->Cancel(false);
377 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29378 if (download->db_handle() == kUninitializedHandle) {
379 // An invalid handle means that 'download' does not yet exist in
380 // 'downloads_', so we have to delete it here.
381 delete download;
382 }
383 }
384
[email protected]9ccbb372008-10-10 18:50:32385 // 'dangerous_finished_' contains all complete downloads that have not been
386 // approved. They should be removed.
387 it = dangerous_finished_.begin();
388 for (; it != dangerous_finished_.end(); ++it)
389 to_remove.insert(it->second);
390
391 // Remove the dangerous download that are not approved.
392 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
393 rm_it != to_remove.end(); ++rm_it) {
394 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32395 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32396 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32397 // Same as above, delete the download if it is not in 'downloads_' (as the
398 // Remove() call above won't have deleted it).
399 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32400 delete download;
401 }
402 to_remove.clear();
403
initial.commit09911bf2008-07-26 23:55:29404 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32405 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29406 STLDeleteValues(&downloads_);
407
408 file_manager_ = NULL;
409
410 // Save our file extensions to auto open.
411 SaveAutoOpens();
412
413 // Make sure the save as dialog doesn't notify us back if we're gone before
414 // it returns.
415 if (select_file_dialog_.get())
416 select_file_dialog_->ListenerDestroyed();
417
418 shutdown_needed_ = false;
419}
420
421// Issue a history query for downloads matching 'search_text'. If 'search_text'
422// is empty, return all downloads that we know about.
423void DownloadManager::GetDownloads(Observer* observer,
424 const std::wstring& search_text) {
425 DCHECK(observer);
426
427 // Return a empty list if we've not yet received the set of downloads from the
428 // history system (we'll update all observers once we get that list in
429 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
430 std::vector<DownloadItem*> download_copy;
431 if (downloads_.empty()) {
432 observer->SetDownloads(download_copy);
433 return;
434 }
435
436 // We already know all the downloads and there is no filter, so just return a
437 // copy to the observer.
438 if (search_text.empty()) {
439 download_copy.reserve(downloads_.size());
440 for (DownloadMap::iterator it = downloads_.begin();
441 it != downloads_.end(); ++it) {
442 download_copy.push_back(it->second);
443 }
444
445 // We retain ownership of the DownloadItems.
446 observer->SetDownloads(download_copy);
447 return;
448 }
449
450 // Issue a request to the history service for a list of downloads matching
451 // our search text.
452 HistoryService* hs =
453 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
454 if (hs) {
455 HistoryService::Handle h =
456 hs->SearchDownloads(search_text,
457 &cancelable_consumer_,
458 NewCallback(this,
459 &DownloadManager::OnSearchComplete));
460 cancelable_consumer_.SetClientData(hs, h, observer);
461 }
462}
463
464// Query the history service for information about all persisted downloads.
465bool DownloadManager::Init(Profile* profile) {
466 DCHECK(profile);
467 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
468 shutdown_needed_ = true;
469
470 profile_ = profile;
471 request_context_ = profile_->GetRequestContext();
472
473 // 'incognito mode' will have access to past downloads, but we won't store
474 // information about new downloads while in that mode.
475 QueryHistoryForDownloads();
476
477 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
478 if (!rdh) {
479 NOTREACHED();
480 return false;
481 }
482
483 file_manager_ = rdh->download_file_manager();
484 if (!file_manager_) {
485 NOTREACHED();
486 return false;
487 }
488
489 file_loop_ = g_browser_process->file_thread()->message_loop();
490 if (!file_loop_) {
491 NOTREACHED();
492 return false;
493 }
494
495 // Get our user preference state.
496 PrefService* prefs = profile_->GetPrefs();
497 DCHECK(prefs);
498 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
499
initial.commit09911bf2008-07-26 23:55:29500 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
501
[email protected]7ae7c2cb2009-01-06 23:31:41502 // This variable is needed to resolve which CreateDirectory we want to point
503 // to. Without it, the NewRunnableFunction cannot resolve the ambiguity.
504 // TODO(estade): when file_util::CreateDirectory(wstring) is removed,
505 // get rid of |CreateDirectoryPtr|.
506 bool (*CreateDirectoryPtr)(const FilePath&) = &file_util::CreateDirectory;
[email protected]bb69e9b32008-08-14 23:08:14507 // Ensure that the download directory specified in the preferences exists.
[email protected]7ae7c2cb2009-01-06 23:31:41508 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
509 CreateDirectoryPtr, download_path()));
initial.commit09911bf2008-07-26 23:55:29510
[email protected]a0a9577b2009-05-27 23:52:32511#if defined(OS_WIN) || defined(OS_LINUX)
512 // We use this to determine possibly dangerous downloads.
[email protected]2b2f8f72009-02-24 22:42:05513 download_util::InitializeExeTypes(&exe_types_);
514#endif
515
516 // We store any file extension that should be opened automatically at
517 // download completion in this pref.
initial.commit09911bf2008-07-26 23:55:29518 std::wstring extensions_to_open =
519 prefs->GetString(prefs::kDownloadExtensionsToOpen);
520 std::vector<std::wstring> extensions;
521 SplitString(extensions_to_open, L':', &extensions);
522 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]b7f05882009-02-22 01:21:56523 if (!extensions[i].empty() && !IsExecutable(
524 FilePath::FromWStringHack(extensions[i]).value()))
525 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29526 }
527
528 return true;
529}
530
531void DownloadManager::QueryHistoryForDownloads() {
532 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
533 if (hs) {
534 hs->QueryDownloads(
535 &cancelable_consumer_,
536 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
537 }
538}
539
540// We have received a message from DownloadFileManager about a new download. We
541// create a download item and store it in our download map, and inform the
542// history system of a new download. Since this method can be called while the
543// history service thread is still reading the persistent state, we do not
544// insert the new DownloadItem into 'downloads_' or inform our observers at this
545// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
546// download creation as a callback from the history thread.
547void DownloadManager::StartDownload(DownloadCreateInfo* info) {
548 DCHECK(MessageLoop::current() == ui_loop_);
549 DCHECK(info);
550
[email protected]7d3851d82008-12-12 03:26:07551 // Freeze the user's preference for showing a Save As dialog. We're going to
552 // bounce around a bunch of threads and we don't want to worry about race
553 // conditions where the user changes this pref out from under us.
554 if (*prompt_for_download_)
555 info->save_as = true;
556
initial.commit09911bf2008-07-26 23:55:29557 // Determine the proper path for a download, by choosing either the default
558 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41559 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29560 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07561 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29562 info->suggested_path = last_download_path_;
563 else
[email protected]7ae7c2cb2009-01-06 23:31:41564 info->suggested_path = download_path();
565 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29566
[email protected]7d3851d82008-12-12 03:26:07567 if (!info->save_as) {
568 // Let's check if this download is dangerous, based on its name.
[email protected]7ae7c2cb2009-01-06 23:31:41569 info->is_dangerous = IsDangerous(info->suggested_path.BaseName());
[email protected]e9ebf3fc2008-10-17 22:06:58570 }
571
initial.commit09911bf2008-07-26 23:55:29572 // We need to move over to the download thread because we don't want to stat
573 // the suggested path on the UI thread.
574 file_loop_->PostTask(FROM_HERE,
575 NewRunnableMethod(this,
576 &DownloadManager::CheckIfSuggestedPathExists,
577 info));
578}
579
580void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
581 DCHECK(info);
582
583 // Check writability of the suggested path. If we can't write to it, default
584 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41585 FilePath dir = info->suggested_path.DirName();
586 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32587 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29588 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29589 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41590 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29591 }
592
[email protected]7a256ea2008-10-17 17:34:16593 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29594
[email protected]6cade212008-12-03 00:32:22595 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58596 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41597 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32598 // Create a temporary file to hold the file until the user approves its
599 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41600 FilePath::StringType file_name;
601 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32602 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41603 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32604 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41605 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07606 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41607 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32608 }
609 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16610 } else {
611 // We know the final path, build it if necessary.
612 if (info->path_uniquifier > 0) {
613 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
614 // Setting path_uniquifier to 0 to make sure we don't try to unique it
615 // later on.
616 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07617 } else if (info->path_uniquifier == -1) {
618 // We failed to find a unique path. We have to prompt the user.
619 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16620 }
[email protected]9ccbb372008-10-10 18:50:32621 }
622
[email protected]7d3851d82008-12-12 03:26:07623 if (!info->save_as) {
624 // Create an empty file at the suggested path so that we don't allocate the
625 // same "non-existant" path to multiple downloads.
626 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ae7c2cb2009-01-06 23:31:41627 file_util::WriteFile(info->suggested_path.ToWStringHack(), "", 0);
[email protected]7d3851d82008-12-12 03:26:07628 }
629
initial.commit09911bf2008-07-26 23:55:29630 // Now we return to the UI thread.
631 ui_loop_->PostTask(FROM_HERE,
632 NewRunnableMethod(this,
633 &DownloadManager::OnPathExistenceAvailable,
634 info));
635}
636
637void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
638 DCHECK(MessageLoop::current() == ui_loop_);
639 DCHECK(info);
640
[email protected]7d3851d82008-12-12 03:26:07641 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29642 // We must ask the user for the place to put the download.
643 if (!select_file_dialog_.get())
644 select_file_dialog_ = SelectFileDialog::Create(this);
645
[email protected]57c6a652009-05-04 07:58:34646 TabContents* contents = tab_util::GetTabContentsByID(
initial.commit09911bf2008-07-26 23:55:29647 info->render_process_id, info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08648 SelectFileDialog::FileTypeInfo file_type_info;
649 file_type_info.extensions.resize(1);
650 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24651 if (!file_type_info.extensions[0][0].empty())
652 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08653 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23654 gfx::NativeWindow owning_window =
655 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29656 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34657 string16(),
658 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08659 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30660 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29661 } else {
662 // No prompting for download, just continue with the suggested name.
663 ContinueStartDownload(info, info->suggested_path);
664 }
665}
666
667void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41668 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29669 scoped_ptr<DownloadCreateInfo> infop(info);
670 info->path = target_path;
671
672 DownloadItem* download = NULL;
673 DownloadMap::iterator it = in_progress_.find(info->download_id);
674 if (it == in_progress_.end()) {
675 download = new DownloadItem(info->download_id,
676 info->path,
[email protected]7a256ea2008-10-17 17:34:16677 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29678 info->url,
[email protected]494c06e2009-07-25 01:06:42679 info->referrer_url,
[email protected]9ccbb372008-10-10 18:50:32680 info->original_name,
initial.commit09911bf2008-07-26 23:55:29681 info->start_time,
682 info->total_bytes,
683 info->render_process_id,
[email protected]9ccbb372008-10-10 18:50:32684 info->request_id,
685 info->is_dangerous);
initial.commit09911bf2008-07-26 23:55:29686 download->set_manager(this);
687 in_progress_[info->download_id] = download;
688 } else {
689 NOTREACHED(); // Should not exist!
690 return;
691 }
692
[email protected]6b323782009-03-27 18:43:08693 // Called before DownloadFinished in order to avoid a race condition where we
694 // attempt to open a completed download before it has been renamed.
695 file_loop_->PostTask(FROM_HERE,
696 NewRunnableMethod(file_manager_,
697 &DownloadFileManager::OnFinalDownloadName,
698 download->id(),
[email protected]8f783752009-04-01 23:33:45699 target_path,
700 this));
[email protected]6b323782009-03-27 18:43:08701
initial.commit09911bf2008-07-26 23:55:29702 // If the download already completed by the time we reached this point, then
703 // notify observers that it did.
704 PendingFinishedMap::iterator pending_it =
705 pending_finished_downloads_.find(info->download_id);
706 if (pending_it != pending_finished_downloads_.end())
707 DownloadFinished(pending_it->first, pending_it->second);
708
709 download->Rename(target_path);
710
initial.commit09911bf2008-07-26 23:55:29711 if (profile_->IsOffTheRecord()) {
712 // Fake a db handle for incognito mode, since nothing is actually stored in
713 // the database in this mode. We have to make sure that these handles don't
714 // collide with normal db handles, so we use a negative value. Eventually,
715 // they could overlap, but you'd have to do enough downloading that your ISP
716 // would likely stab you in the neck first. YMMV.
717 static int64 fake_db_handle = kUninitializedHandle - 1;
718 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
719 } else {
720 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22721 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29722 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
723 if (hs) {
724 hs->CreateDownload(
725 *info, &cancelable_consumer_,
726 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
727 }
728 }
729}
730
731// Convenience function for updating the history service for a download.
732void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
733 DCHECK(download);
734
735 // Don't store info in the database if the download was initiated while in
736 // incognito mode or if it hasn't been initialized in our database table.
737 if (download->db_handle() <= kUninitializedHandle)
738 return;
739
[email protected]6cade212008-12-03 00:32:22740 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29741 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
742 if (hs) {
743 hs->UpdateDownload(download->received_bytes(),
744 download->state(),
745 download->db_handle());
746 }
747}
748
749void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
750 DCHECK(download);
[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 (download->db_handle() > kUninitializedHandle && hs)
754 hs->RemoveDownload(download->db_handle());
755}
756
[email protected]e93d2822009-01-30 05:59:59757void DownloadManager::RemoveDownloadsFromHistoryBetween(
758 const base::Time remove_begin,
759 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22760 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29761 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
762 if (hs)
763 hs->RemoveDownloadsBetween(remove_begin, remove_end);
764}
765
766void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
767 DownloadMap::iterator it = in_progress_.find(download_id);
768 if (it != in_progress_.end()) {
769 DownloadItem* download = it->second;
770 download->Update(size);
771 UpdateHistoryForDownload(download);
772 }
773}
774
775void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
776 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32777 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29778 // The download is done, but the user hasn't selected a final location for
779 // it yet (the Save As dialog box is probably still showing), so just keep
780 // track of the fact that this download id is complete, when the
781 // DownloadItem is constructed later we'll notify its completion then.
782 PendingFinishedMap::iterator erase_it =
783 pending_finished_downloads_.find(download_id);
784 DCHECK(erase_it == pending_finished_downloads_.end());
785 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32786 return;
initial.commit09911bf2008-07-26 23:55:29787 }
[email protected]9ccbb372008-10-10 18:50:32788
789 // Remove the id from the list of pending ids.
790 PendingFinishedMap::iterator erase_it =
791 pending_finished_downloads_.find(download_id);
792 if (erase_it != pending_finished_downloads_.end())
793 pending_finished_downloads_.erase(erase_it);
794
795 DownloadItem* download = it->second;
796 download->Finished(size);
797
798 // Clean up will happen when the history system create callback runs if we
799 // don't have a valid db_handle yet.
800 if (download->db_handle() != kUninitializedHandle) {
801 in_progress_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32802 UpdateHistoryForDownload(download);
803 }
804
805 // If this a dangerous download not yet validated by the user, don't do
806 // anything. When the user notifies us, it will trigger a call to
807 // ProceedWithFinishedDangerousDownload.
808 if (download->safety_state() == DownloadItem::DANGEROUS) {
809 dangerous_finished_[download_id] = download;
810 return;
811 }
812
813 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22814 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32815 // its final name before we can continue.
816 file_loop_->PostTask(FROM_HERE,
817 NewRunnableMethod(
818 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
819 download->db_handle(),
820 download->full_path(), download->original_name()));
821 return;
822 }
823 ContinueDownloadFinished(download);
824}
825
[email protected]8f783752009-04-01 23:33:45826void DownloadManager::DownloadRenamedToFinalName(int download_id,
827 const FilePath& full_path) {
[email protected]8f783752009-04-01 23:33:45828}
829
[email protected]9ccbb372008-10-10 18:50:32830void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
831 // If this was a dangerous download, it has now been approved and must be
832 // removed from dangerous_finished_ so it does not get deleted on shutdown.
833 DownloadMap::iterator it = dangerous_finished_.find(download->id());
834 if (it != dangerous_finished_.end())
835 dangerous_finished_.erase(it);
836
[email protected]5a102892009-07-15 19:59:30837 // Open the download if the user or user prefs indicate it should be.
838 FilePath::StringType extension = download->full_path().Extension();
839 // Drop the leading period. (The auto-open list is period-less.)
840 if (extension.size() > 0)
841 extension = extension.substr(1);
842
[email protected]0aad67b2009-07-15 20:34:28843 // Handle chrome extensions explicitly and skip the shell execute.
844 if (Extension::IsExtension(download->full_path())) {
[email protected]494c06e2009-07-25 01:06:42845 OpenChromeExtension(download->full_path(), download->url(),
846 download->referrer_url());
[email protected]0aad67b2009-07-15 20:34:28847 download->set_auto_opened(true);
848 } else if (download->open_when_complete() ||
849 ShouldOpenFileExtension(extension)) {
[email protected]9ccbb372008-10-10 18:50:32850 OpenDownloadInShell(download, NULL);
[email protected]0aad67b2009-07-15 20:34:28851 download->set_auto_opened(true);
852 }
[email protected]9ccbb372008-10-10 18:50:32853
[email protected]0aad67b2009-07-15 20:34:28854 // Notify our observers that we are complete (the call to Finished() set the
855 // state to complete but did not notify).
856 download->UpdateObservers();
857}
[email protected]9ccbb372008-10-10 18:50:32858// Called on the file thread. Renames the downloaded file to its original name.
859void DownloadManager::ProceedWithFinishedDangerousDownload(
860 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41861 const FilePath& path,
862 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32863 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41864 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16865 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32866 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24867 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16868 // Make our name unique at this point, as if a dangerous file is downloading
869 // and a 2nd download is started for a file with the same name, they would
870 // have the same path. This is because we uniquify the name on download
871 // start, and at that time the first file does not exists yet, so the second
872 // file gets the same name.
873 uniquifier = GetUniquePathNumber(new_path);
874 if (uniquifier > 0)
875 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32876 success = file_util::Move(path, new_path);
877 } else {
878 NOTREACHED();
879 }
[email protected]6cade212008-12-03 00:32:22880
[email protected]9ccbb372008-10-10 18:50:32881 ui_loop_->PostTask(FROM_HERE,
882 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16883 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32884}
885
886// Call from the file thread when the finished dangerous download was renamed.
887void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
888 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41889 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16890 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32891 DownloadMap::iterator it = downloads_.find(download_handle);
892 if (it == downloads_.end()) {
893 NOTREACHED();
894 return;
895 }
896
897 DownloadItem* download = it->second;
898 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16899 if (success) {
900 // We need to update the path uniquifier so that the UI shows the right
901 // name when calling GetFileName().
902 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32903 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16904 }
[email protected]9ccbb372008-10-10 18:50:32905
906 // Continue the download finished sequence.
907 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29908}
909
910// static
911// We have to tell the ResourceDispatcherHost to cancel the download from this
[email protected]6cade212008-12-03 00:32:22912// thread, since we can't forward tasks from the file thread to the IO thread
initial.commit09911bf2008-07-26 23:55:29913// reliably (crash on shutdown race condition).
914void DownloadManager::CancelDownloadRequest(int render_process_id,
915 int request_id) {
916 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]ab820df2008-08-26 05:55:10917 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29918 if (!io_thread || !rdh)
919 return;
920 io_thread->message_loop()->PostTask(FROM_HERE,
921 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
922 rdh,
923 render_process_id,
924 request_id));
925}
926
927// static
928void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
929 int render_process_id,
930 int request_id) {
931 rdh->CancelRequest(render_process_id, request_id, false);
932}
933
934void DownloadManager::DownloadCancelled(int32 download_id) {
935 DownloadMap::iterator it = in_progress_.find(download_id);
936 if (it == in_progress_.end())
937 return;
938 DownloadItem* download = it->second;
939
940 CancelDownloadRequest(download->render_process_id(), download->request_id());
941
942 // Clean up will happen when the history system create callback runs if we
943 // don't have a valid db_handle yet.
944 if (download->db_handle() != kUninitializedHandle) {
945 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:29946 UpdateHistoryForDownload(download);
947 }
948
949 // Tell the file manager to cancel the download.
950 file_manager_->RemoveDownload(download->id(), this); // On the UI thread
951 file_loop_->PostTask(FROM_HERE,
952 NewRunnableMethod(file_manager_,
953 &DownloadFileManager::CancelDownload,
954 download->id()));
955}
956
957void DownloadManager::PauseDownload(int32 download_id, bool pause) {
958 DownloadMap::iterator it = in_progress_.find(download_id);
959 if (it != in_progress_.end()) {
960 DownloadItem* download = it->second;
961 if (pause == download->is_paused())
962 return;
963
964 // Inform the ResourceDispatcherHost of the new pause state.
[email protected]ab820df2008-08-26 05:55:10965 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29966 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
967 if (!io_thread || !rdh)
968 return;
969
970 io_thread->message_loop()->PostTask(FROM_HERE,
971 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
972 rdh,
973 download->render_process_id(),
974 download->request_id(),
975 pause));
976 }
977}
978
979// static
980void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
981 int render_process_id,
982 int request_id,
983 bool pause) {
984 rdh->PauseRequest(render_process_id, request_id, pause);
985}
986
[email protected]7ae7c2cb2009-01-06 23:31:41987bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:32988 // TODO(jcampan): Improve me.
[email protected]2001fe82009-02-23 23:53:14989 FilePath::StringType extension = file_name.Extension();
990 // Drop the leading period.
991 if (extension.size() > 0)
992 extension = extension.substr(1);
993 return IsExecutable(extension);
[email protected]9ccbb372008-10-10 18:50:32994}
995
996void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:41997 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:32998 download->Rename(new_path);
999
1000 // Update the history.
1001
1002 // No update necessary if the download was initiated while in incognito mode.
1003 if (download->db_handle() <= kUninitializedHandle)
1004 return;
1005
[email protected]6cade212008-12-03 00:32:221006 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:321007 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1008 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:411009 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:321010}
1011
initial.commit09911bf2008-07-26 23:55:291012void DownloadManager::RemoveDownload(int64 download_handle) {
1013 DownloadMap::iterator it = downloads_.find(download_handle);
1014 if (it == downloads_.end())
1015 return;
1016
1017 // Make history update.
1018 DownloadItem* download = it->second;
1019 RemoveDownloadFromHistory(download);
1020
1021 // Remove from our tables and delete.
1022 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321023 it = dangerous_finished_.find(download->id());
1024 if (it != dangerous_finished_.end())
1025 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291026
1027 // Tell observers to refresh their views.
1028 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:361029
1030 delete download;
initial.commit09911bf2008-07-26 23:55:291031}
1032
[email protected]e93d2822009-01-30 05:59:591033int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1034 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291035 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1036
initial.commit09911bf2008-07-26 23:55:291037 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:281038 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:291039 while (it != downloads_.end()) {
1040 DownloadItem* download = it->second;
1041 DownloadItem::DownloadState state = download->state();
1042 if (download->start_time() >= remove_begin &&
1043 (remove_end.is_null() || download->start_time() < remove_end) &&
1044 (state == DownloadItem::COMPLETE ||
1045 state == DownloadItem::CANCELLED)) {
1046 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561047 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581048
1049 // Also remove it from any completed dangerous downloads.
1050 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1051 if (dit != dangerous_finished_.end())
1052 dangerous_finished_.erase(dit);
1053
[email protected]78b8fcc92009-03-31 17:36:281054 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:291055
initial.commit09911bf2008-07-26 23:55:291056 continue;
1057 }
1058
1059 ++it;
1060 }
1061
1062 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281063 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291064 if (num_deleted > 0)
1065 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1066
[email protected]78b8fcc92009-03-31 17:36:281067 // Delete the download items after updating the observers.
1068 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1069 pending_deletes.clear();
1070
initial.commit09911bf2008-07-26 23:55:291071 return num_deleted;
1072}
1073
[email protected]e93d2822009-01-30 05:59:591074int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1075 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291076}
1077
[email protected]d41355e6f2009-04-07 21:21:121078int DownloadManager::RemoveAllDownloads() {
1079 // The null times make the date range unbounded.
1080 return RemoveDownloadsBetween(base::Time(), base::Time());
1081}
1082
initial.commit09911bf2008-07-26 23:55:291083// Initiate a download of a specific URL. We send the request to the
1084// ResourceDispatcherHost, and let it send us responses like a regular
1085// download.
1086void DownloadManager::DownloadUrl(const GURL& url,
1087 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:501088 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:341089 TabContents* tab_contents) {
1090 DCHECK(tab_contents);
[email protected]c9825a42009-05-01 22:51:501091 request_context_->set_referrer_charset(referrer_charset);
initial.commit09911bf2008-07-26 23:55:291092 file_manager_->DownloadUrl(url,
1093 referrer,
[email protected]57c6a652009-05-04 07:58:341094 tab_contents->process()->pid(),
1095 tab_contents->render_view_host()->routing_id(),
initial.commit09911bf2008-07-26 23:55:291096 request_context_.get());
1097}
1098
[email protected]7ae7c2cb2009-01-06 23:31:411099void DownloadManager::GenerateExtension(
1100 const FilePath& file_name,
1101 const std::string& mime_type,
1102 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291103 // We're worried about three things here:
1104 //
1105 // 1) Security. Many sites let users upload content, such as buddy icons, to
1106 // their web sites. We want to mitigate the case where an attacker
1107 // supplies a malicious executable with an executable file extension but an
1108 // honest site serves the content with a benign content type, such as
1109 // image/jpeg.
1110 //
1111 // 2) Usability. If the site fails to provide a file extension, we want to
1112 // guess a reasonable file extension based on the content type.
1113 //
1114 // 3) Shell integration. Some file extensions automatically integrate with
1115 // the shell. We block these extensions to prevent a malicious web site
1116 // from integrating with the user's shell.
1117
[email protected]7ae7c2cb2009-01-06 23:31:411118 static const FilePath::CharType default_extension[] =
1119 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291120
1121 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411122 FilePath::StringType extension(
1123 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291124
[email protected]b7f05882009-02-22 01:21:561125#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291126 // Rename shell-integrated extensions.
1127 if (win_util::IsShellIntegratedExtension(extension))
1128 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561129#endif
initial.commit09911bf2008-07-26 23:55:291130
1131 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411132 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411133 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291134 if (mime_type == mime_type_from_extension) {
1135 // The hinted extension matches the mime type. It looks like a winner.
1136 generated_extension->swap(extension);
1137 return;
1138 }
1139
1140 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1141 // We want to be careful about executable extensions. The worry here is
1142 // that a trusted web site could be tricked into dropping an executable file
1143 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101144 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291145 // We couldn't find a good extension for this content type. Use a dummy
1146 // extension instead.
1147 extension.assign(default_extension);
1148 }
1149 }
1150
1151 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101152 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291153 } else {
[email protected]6cade212008-12-03 00:32:221154 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291155 // 1. New extension is not ".txt"
1156 // 2. New extension is not the same as the already existing extension.
1157 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411158 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291159 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1160 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371161 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1162 // servers, i.e. bug 5772.
[email protected]7ae7c2cb2009-01-06 23:31:411163 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101164 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171165 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411166 append_extension != extension &&
[email protected]e106457b2009-03-25 22:43:371167 !IsExecutable(append_extension) &&
1168 (append_extension != FILE_PATH_LITERAL("tar") ||
1169 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171170 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291171 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171172 }
initial.commit09911bf2008-07-26 23:55:291173 }
1174 }
1175
1176 generated_extension->swap(extension);
1177}
1178
1179void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411180 FilePath* generated_name) {
1181 *generated_name = FilePath::FromWStringHack(
[email protected]8ac1a752008-07-31 19:40:371182 net::GetSuggestedFilename(GURL(info->url),
1183 info->content_disposition,
[email protected]c9825a42009-05-01 22:51:501184 info->referrer_charset,
[email protected]7ae7c2cb2009-01-06 23:31:411185 L"download"));
1186 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291187
[email protected]7ae7c2cb2009-01-06 23:31:411188 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291189}
1190
1191void DownloadManager::AddObserver(Observer* observer) {
1192 observers_.AddObserver(observer);
1193 observer->ModelChanged();
1194}
1195
1196void DownloadManager::RemoveObserver(Observer* observer) {
1197 observers_.RemoveObserver(observer);
1198}
1199
1200// Post Windows Shell operations to the Download thread, to avoid blocking the
1201// user interface.
1202void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1203 DCHECK(file_manager_);
1204 file_loop_->PostTask(FROM_HERE,
1205 NewRunnableMethod(file_manager_,
1206 &DownloadFileManager::OnShowDownloadInShell,
[email protected]7ae7c2cb2009-01-06 23:31:411207 FilePath(download->full_path())));
initial.commit09911bf2008-07-26 23:55:291208}
1209
[email protected]8f783752009-04-01 23:33:451210void DownloadManager::OpenDownload(const DownloadItem* download,
1211 gfx::NativeView parent_window) {
[email protected]0e34d7892009-06-05 19:17:401212 // Open Chrome extensions with ExtensionsService. For everything else do shell
[email protected]8f783752009-04-01 23:33:451213 // execute.
[email protected]f1ce6e62009-06-29 20:31:291214 if (Extension::IsExtension(download->full_path())) {
[email protected]494c06e2009-07-25 01:06:421215 OpenChromeExtension(download->full_path(), download->url(),
1216 download->referrer_url());
[email protected]8f783752009-04-01 23:33:451217 } else {
1218 OpenDownloadInShell(download, parent_window);
1219 }
1220}
1221
[email protected]c1e432a2009-07-22 21:21:481222void DownloadManager::OpenChromeExtension(const FilePath& full_path,
[email protected]494c06e2009-07-25 01:06:421223 const GURL& download_url,
1224 const GURL& referrer_url) {
[email protected]1bd54132009-06-11 00:05:341225 profile_->GetOriginalProfile()->GetExtensionsService()->
[email protected]494c06e2009-07-25 01:06:421226 InstallExtension(full_path, download_url, referrer_url);
[email protected]8f783752009-04-01 23:33:451227}
1228
initial.commit09911bf2008-07-26 23:55:291229void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591230 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291231 DCHECK(file_manager_);
1232 file_loop_->PostTask(FROM_HERE,
1233 NewRunnableMethod(file_manager_,
1234 &DownloadFileManager::OnOpenDownloadInShell,
1235 download->full_path(), download->url(), parent_window));
1236}
1237
[email protected]7ae7c2cb2009-01-06 23:31:411238void DownloadManager::OpenFilesOfExtension(
1239 const FilePath::StringType& extension, bool open) {
initial.commit09911bf2008-07-26 23:55:291240 if (open && !IsExecutable(extension))
1241 auto_open_.insert(extension);
1242 else
1243 auto_open_.erase(extension);
1244 SaveAutoOpens();
1245}
1246
[email protected]7ae7c2cb2009-01-06 23:31:411247bool DownloadManager::ShouldOpenFileExtension(
1248 const FilePath::StringType& extension) {
[email protected]8c756ac2009-01-30 23:36:411249 // Special-case Chrome extensions as always-open.
initial.commit09911bf2008-07-26 23:55:291250 if (!IsExecutable(extension) &&
[email protected]8c756ac2009-01-30 23:36:411251 (auto_open_.find(extension) != auto_open_.end() ||
[email protected]f1ce6e62009-06-29 20:31:291252 Extension::IsExtension(FilePath(extension))))
[email protected]8c756ac2009-01-30 23:36:411253 return true;
initial.commit09911bf2008-07-26 23:55:291254 return false;
1255}
1256
[email protected]7b73d992008-12-15 20:56:461257static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291258 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461259 "text/javascript",
1260 "text/javascript;version=*",
[email protected]54d8d452009-04-08 17:29:241261 // Registry files can cause critical changes to the MS OS behavior.
1262 // Addition of this mimetype also addresses bug 7337.
1263 "text/x-registry",
[email protected]60ff8f912008-12-05 07:58:391264 // Some sites use binary/octet-stream to mean application/octet-stream.
1265 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461266 "binary/octet-stream"
1267};
initial.commit09911bf2008-07-26 23:55:291268
[email protected]7b73d992008-12-15 20:56:461269static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291270 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461271 "application/*+xml",
1272 "application/xml"
1273};
initial.commit09911bf2008-07-26 23:55:291274
[email protected]7b73d992008-12-15 20:56:461275// static
1276bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411277 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461278 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1279 return true;
1280 }
[email protected]bae0ea12009-02-14 01:20:411281 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461282 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1283 return false;
1284 }
1285 // We consider only other application types to be executable.
1286 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291287}
1288
[email protected]7ae7c2cb2009-01-06 23:31:411289bool DownloadManager::IsExecutable(const FilePath::StringType& extension) {
[email protected]a0a9577b2009-05-27 23:52:321290#if defined(OS_MACOSX)
1291 // We don't have dangerous download support on mac yet.
1292 return false;
1293#else
[email protected]64da0b932009-02-24 02:30:041294 if (!IsStringASCII(extension))
1295 return false;
[email protected]a0a9577b2009-05-27 23:52:321296#if defined(OS_WIN)
[email protected]64da0b932009-02-24 02:30:041297 std::string ascii_extension = WideToASCII(extension);
[email protected]a0a9577b2009-05-27 23:52:321298#elif defined(OS_LINUX)
1299 std::string ascii_extension = extension;
1300#endif
[email protected]64da0b932009-02-24 02:30:041301 StringToLowerASCII(&ascii_extension);
1302
1303 return exe_types_.find(ascii_extension) != exe_types_.end();
[email protected]a0a9577b2009-05-27 23:52:321304#endif // !defined(OS_MACOSX)
initial.commit09911bf2008-07-26 23:55:291305}
1306
1307void DownloadManager::ResetAutoOpenFiles() {
1308 auto_open_.clear();
1309 SaveAutoOpens();
1310}
1311
1312bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1313 return !auto_open_.empty();
1314}
1315
1316void DownloadManager::SaveAutoOpens() {
1317 PrefService* prefs = profile_->GetPrefs();
1318 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411319 FilePath::StringType extensions;
1320 for (std::set<FilePath::StringType>::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291321 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411322 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291323 }
1324 if (!extensions.empty())
1325 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561326
1327 std::wstring extensions_w;
1328#if defined(OS_WIN)
1329 extensions_w = extensions;
1330#elif defined(OS_POSIX)
[email protected]1b5044d2009-02-24 00:04:141331 extensions_w = base::SysNativeMBToWide(extensions);
[email protected]b7f05882009-02-22 01:21:561332#endif
1333
1334 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291335 }
1336}
1337
[email protected]561abe62009-04-06 18:08:341338void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361339 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291340 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071341 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411342 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291343 ContinueStartDownload(info, path);
1344}
1345
1346void DownloadManager::FileSelectionCanceled(void* params) {
1347 // The user didn't pick a place to save the file, so need to cancel the
1348 // download that's already in progress to the temporary location.
1349 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
1350 file_loop_->PostTask(FROM_HERE,
1351 NewRunnableMethod(file_manager_, &DownloadFileManager::CancelDownload,
1352 info->download_id));
1353}
1354
[email protected]7ae7c2cb2009-01-06 23:31:411355void DownloadManager::DeleteDownload(const FilePath& path) {
1356 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
1357 &DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321358}
1359
1360
1361void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1362 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1363 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1364 download->UpdateObservers();
1365
1366 // If the download is not complete, nothing to do. The required
1367 // post-processing will be performed when it does complete.
1368 if (download->state() != DownloadItem::COMPLETE)
1369 return;
1370
1371 file_loop_->PostTask(FROM_HERE,
1372 NewRunnableMethod(this,
1373 &DownloadManager::ProceedWithFinishedDangerousDownload,
1374 download->db_handle(), download->full_path(),
1375 download->original_name()));
1376}
1377
[email protected]763f946a2009-01-06 19:04:391378void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411379 FilePath* file_name) {
1380 // Make sure we get the right file extension
1381 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391382 GenerateExtension(*file_name, mime_type, &extension);
1383 file_util::ReplaceExtension(file_name, extension);
1384
[email protected]2b2f8f72009-02-24 22:42:051385#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391386 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411387 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391388 DCHECK(!leaf_name.empty());
1389 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411390 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1391 *file_name = file_name->DirName();
1392 if (file_name->value() == FilePath::kCurrentDirectory) {
1393 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391394 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411395 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391396 }
1397 }
[email protected]b7f05882009-02-22 01:21:561398#elif defined(OS_POSIX)
1399 NOTIMPLEMENTED();
1400#endif
[email protected]763f946a2009-01-06 19:04:391401}
1402
initial.commit09911bf2008-07-26 23:55:291403// Operations posted to us from the history service ----------------------------
1404
1405// The history service has retrieved all download entries. 'entries' contains
1406// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1407void DownloadManager::OnQueryDownloadEntriesComplete(
1408 std::vector<DownloadCreateInfo>* entries) {
1409 for (size_t i = 0; i < entries->size(); ++i) {
1410 DownloadItem* download = new DownloadItem(entries->at(i));
1411 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1412 downloads_[download->db_handle()] = download;
1413 download->set_manager(this);
1414 }
1415 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1416}
1417
initial.commit09911bf2008-07-26 23:55:291418// Once the new DownloadItem's creation info has been committed to the history
1419// service, we associate the DownloadItem with the db handle, update our
1420// 'downloads_' map and inform observers.
1421void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1422 int64 db_handle) {
1423 DownloadMap::iterator it = in_progress_.find(info.download_id);
1424 DCHECK(it != in_progress_.end());
1425
1426 DownloadItem* download = it->second;
1427 DCHECK(download->db_handle() == kUninitializedHandle);
1428 download->set_db_handle(db_handle);
1429
1430 // Insert into our full map.
1431 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1432 downloads_[download->db_handle()] = download;
1433
[email protected]5e595482009-05-06 20:16:531434 // Show in the appropropriate browser UI.
1435 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291436
1437 // Inform interested objects about the new download.
1438 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
initial.commit09911bf2008-07-26 23:55:291439
1440 // If this download has been completed before we've received the db handle,
1441 // post one final message to the history service so that it can be properly
1442 // in sync with the DownloadItem's completion status, and also inform any
1443 // observers so that they get more than just the start notification.
1444 if (download->state() != DownloadItem::IN_PROGRESS) {
1445 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291446 UpdateHistoryForDownload(download);
1447 download->UpdateObservers();
1448 }
1449}
1450
1451// Called when the history service has retrieved the list of downloads that
1452// match the search text.
1453void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1454 std::vector<int64>* results) {
1455 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1456 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1457 if (!requestor)
1458 return;
1459
1460 std::vector<DownloadItem*> searched_downloads;
1461 for (std::vector<int64>::iterator it = results->begin();
1462 it != results->end(); ++it) {
1463 DownloadMap::iterator dit = downloads_.find(*it);
1464 if (dit != downloads_.end())
1465 searched_downloads.push_back(dit->second);
1466 }
1467
1468 requestor->SetDownloads(searched_downloads);
1469}
[email protected]905a08d2008-11-19 07:24:121470
[email protected]5e595482009-05-06 20:16:531471void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1472 DownloadItem* download) {
[email protected]5e595482009-05-06 20:16:531473 // The 'contents' may no longer exist if the user closed the tab before we get
1474 // this start completion event. If it does, tell the origin TabContents to
1475 // display its download shelf.
1476 TabContents* contents =
1477 tab_util::GetTabContentsByID(info.render_process_id, info.render_view_id);
1478
1479 // If the contents no longer exists, we start the download in the last active
1480 // browser. This is not ideal but better than fully hiding the download from
1481 // the user.
1482 if (!contents) {
1483 Browser* last_active = BrowserList::GetLastActive();
1484 if (last_active)
1485 contents = last_active->GetSelectedTabContents();
1486 }
1487
1488 if (contents)
1489 contents->OnStartDownload(download);
1490}
1491
[email protected]6cade212008-12-03 00:32:221492// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121493void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411494 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381495}
1496