blob: 67805817efeffad10f08bbd8adc431abf207129a [file] [log] [blame]
license.botbf09a502008-08-24 00:55:551// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
5#include <time.h>
6
[email protected]cdaa8652008-09-13 02:48:597#include "chrome/browser/download/download_manager.h"
initial.commit09911bf2008-07-26 23:55:298
9#include "base/file_util.h"
10#include "base/logging.h"
11#include "base/message_loop.h"
12#include "base/path_service.h"
13#include "base/registry.h"
14#include "base/string_util.h"
15#include "base/task.h"
16#include "base/thread.h"
17#include "base/timer.h"
[email protected]9ccbb372008-10-10 18:50:3218#include "base/rand_util.h"
initial.commit09911bf2008-07-26 23:55:2919#include "base/win_util.h"
20#include "chrome/browser/browser_list.h"
21#include "chrome/browser/browser_process.h"
[email protected]cdaa8652008-09-13 02:48:5922#include "chrome/browser/download/download_file.h"
23#include "chrome/browser/download/download_util.h"
initial.commit09911bf2008-07-26 23:55:2924#include "chrome/browser/profile.h"
25#include "chrome/browser/render_process_host.h"
26#include "chrome/browser/render_view_host.h"
27#include "chrome/browser/resource_dispatcher_host.h"
28#include "chrome/browser/tab_util.h"
29#include "chrome/browser/web_contents.h"
30#include "chrome/common/chrome_paths.h"
31#include "chrome/common/l10n_util.h"
32#include "chrome/common/notification_service.h"
33#include "chrome/common/pref_names.h"
34#include "chrome/common/pref_service.h"
35#include "chrome/common/stl_util-inl.h"
36#include "chrome/common/win_util.h"
[email protected]46072d42008-07-28 14:49:3537#include "googleurl/src/gurl.h"
initial.commit09911bf2008-07-26 23:55:2938#include "net/base/mime_util.h"
39#include "net/base/net_util.h"
40#include "net/url_request/url_request_context.h"
41
42#include "generated_resources.h"
43
[email protected]e1acf6f2008-10-27 20:43:3344using base::Time;
45using base::TimeDelta;
46
initial.commit09911bf2008-07-26 23:55:2947// Periodically update our observers.
48class DownloadItemUpdateTask : public Task {
49 public:
50 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
51 void Run() { if (item_) item_->UpdateObservers(); }
52
53 private:
54 DownloadItem* item_;
55};
56
57// Update frequency (milliseconds).
58static const int kUpdateTimeMs = 1000;
59
60// Our download table ID starts at 1, so we use 0 to represent a download that
61// has started, but has not yet had its data persisted in the table. We use fake
62// database handles in incognito mode starting at -1 and progressly getting more
63// negative.
64static const int kUninitializedHandle = 0;
65
[email protected]7a256ea2008-10-17 17:34:1666// Appends the passed the number between parenthesis the path before the
67// extension.
68static void AppendNumberToPath(std::wstring* path, int number) {
69 file_util::InsertBeforeExtension(path, StringPrintf(L" (%d)", number));
70}
71
72// Attempts to find a number that can be appended to that path to make it
73// unique. If |path| does not exist, 0 is returned. If it fails to find such
74// a number, -1 is returned.
75static int GetUniquePathNumber(const std::wstring& path) {
initial.commit09911bf2008-07-26 23:55:2976 const int kMaxAttempts = 100;
77
[email protected]7a256ea2008-10-17 17:34:1678 if (!file_util::PathExists(path))
79 return 0;
initial.commit09911bf2008-07-26 23:55:2980
81 std::wstring new_path;
82 for (int count = 1; count <= kMaxAttempts; ++count) {
[email protected]7a256ea2008-10-17 17:34:1683 new_path.assign(path);
84 AppendNumberToPath(&new_path, count);
initial.commit09911bf2008-07-26 23:55:2985
[email protected]7a256ea2008-10-17 17:34:1686 if (!file_util::PathExists(new_path))
87 return count;
initial.commit09911bf2008-07-26 23:55:2988 }
89
[email protected]7a256ea2008-10-17 17:34:1690 return -1;
initial.commit09911bf2008-07-26 23:55:2991}
92
[email protected]f052118e2008-09-05 02:25:3293static bool DownloadPathIsDangerous(const std::wstring& download_path) {
94 std::wstring desktop_dir;
95 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
96 NOTREACHED();
97 return false;
98 }
99 return (download_path == desktop_dir);
100}
101
initial.commit09911bf2008-07-26 23:55:29102// DownloadItem implementation -------------------------------------------------
103
104// Constructor for reading from the history service.
105DownloadItem::DownloadItem(const DownloadCreateInfo& info)
106 : id_(-1),
107 full_path_(info.path),
[email protected]9ccbb372008-10-10 18:50:32108 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29109 url_(info.url),
110 total_bytes_(info.total_bytes),
111 received_bytes_(info.received_bytes),
112 start_tick_(0),
113 state_(static_cast<DownloadState>(info.state)),
114 start_time_(info.start_time),
115 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29116 manager_(NULL),
[email protected]9ccbb372008-10-10 18:50:32117 safety_state_(SAFE),
initial.commit09911bf2008-07-26 23:55:29118 is_paused_(false),
119 open_when_complete_(false),
120 render_process_id_(-1),
121 request_id_(-1) {
122 if (state_ == IN_PROGRESS)
123 state_ = CANCELLED;
124 Init(false /* don't start progress timer */);
125}
126
127// Constructor for DownloadItem created via user action in the main thread.
128DownloadItem::DownloadItem(int32 download_id,
129 const std::wstring& path,
[email protected]7a256ea2008-10-17 17:34:16130 int path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29131 const std::wstring& url,
[email protected]9ccbb372008-10-10 18:50:32132 const std::wstring& original_name,
initial.commit09911bf2008-07-26 23:55:29133 const Time start_time,
134 int64 download_size,
135 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32136 int request_id,
137 bool is_dangerous)
initial.commit09911bf2008-07-26 23:55:29138 : id_(download_id),
139 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16140 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29141 url_(url),
[email protected]9ccbb372008-10-10 18:50:32142 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29143 total_bytes_(download_size),
144 received_bytes_(0),
145 start_tick_(GetTickCount()),
146 state_(IN_PROGRESS),
147 start_time_(start_time),
148 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29149 manager_(NULL),
[email protected]9ccbb372008-10-10 18:50:32150 safety_state_(is_dangerous ? DANGEROUS : SAFE),
initial.commit09911bf2008-07-26 23:55:29151 is_paused_(false),
152 open_when_complete_(false),
153 render_process_id_(render_process_id),
154 request_id_(request_id) {
155 Init(true /* start progress timer */);
156}
157
158void DownloadItem::Init(bool start_timer) {
159 file_name_ = file_util::GetFilenameFromPath(full_path_);
160 if (start_timer)
161 StartProgressTimer();
162}
163
164DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29165 state_ = REMOVING;
166 UpdateObservers();
167}
168
169void DownloadItem::AddObserver(Observer* observer) {
170 observers_.AddObserver(observer);
171}
172
173void DownloadItem::RemoveObserver(Observer* observer) {
174 observers_.RemoveObserver(observer);
175}
176
177void DownloadItem::UpdateObservers() {
178 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
179}
180
181// If we've received more data than we were expecting (bad server info?), revert
182// to 'unknown size mode'.
183void DownloadItem::UpdateSize(int64 bytes_so_far) {
184 received_bytes_ = bytes_so_far;
185 if (received_bytes_ > total_bytes_)
186 total_bytes_ = 0;
187}
188
189// Updates from the download thread may have been posted while this download
190// was being cancelled in the UI thread, so we'll accept them unless we're
191// complete.
192void DownloadItem::Update(int64 bytes_so_far) {
193 if (state_ == COMPLETE) {
194 NOTREACHED();
195 return;
196 }
197 UpdateSize(bytes_so_far);
198 UpdateObservers();
199}
200
201// Triggered by a user action
202void DownloadItem::Cancel(bool update_history) {
203 if (state_ != IN_PROGRESS) {
204 // Small downloads might be complete before this method has a chance to run.
205 return;
206 }
207 state_ = CANCELLED;
208 UpdateObservers();
209 StopProgressTimer();
210 if (update_history)
211 manager_->DownloadCancelled(id_);
212}
213
214void DownloadItem::Finished(int64 size) {
215 state_ = COMPLETE;
216 UpdateSize(size);
[email protected]22fbe5a2008-10-29 22:20:40217 UpdateObservers();
initial.commit09911bf2008-07-26 23:55:29218 StopProgressTimer();
219}
220
[email protected]9ccbb372008-10-10 18:50:32221void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29222 Cancel(true);
223 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32224 if (delete_on_disk)
225 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29226 manager_->RemoveDownload(db_handle_);
[email protected]9ccbb372008-10-10 18:50:32227 // We are now deleted.
initial.commit09911bf2008-07-26 23:55:29228}
229
230void DownloadItem::StartProgressTimer() {
[email protected]2d316662008-09-03 18:18:14231 update_timer_.Start(TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
232 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29233}
234
235void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14236 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29237}
238
239bool DownloadItem::TimeRemaining(TimeDelta* remaining) const {
240 if (total_bytes_ <= 0)
241 return false; // We never received the content_length for this download.
242
243 int64 speed = CurrentSpeed();
244 if (speed == 0)
245 return false;
246
247 *remaining =
248 TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
249 return true;
250}
251
252int64 DownloadItem::CurrentSpeed() const {
253 uintptr_t diff = GetTickCount() - start_tick_;
254 return diff == 0 ? 0 : received_bytes_ * 1000 / diff;
255}
256
257int DownloadItem::PercentComplete() const {
258 int percent = -1;
259 if (total_bytes_ > 0)
260 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
261 return percent;
262}
263
264void DownloadItem::Rename(const std::wstring& full_path) {
265 DCHECK(!full_path.empty());
266 full_path_ = full_path;
267 file_name_ = file_util::GetFilenameFromPath(full_path_);
268}
269
270void DownloadItem::TogglePause() {
271 DCHECK(state_ == IN_PROGRESS);
272 manager_->PauseDownload(id_, !is_paused_);
273 is_paused_ = !is_paused_;
274 UpdateObservers();
275}
276
[email protected]9ccbb372008-10-10 18:50:32277std::wstring DownloadItem::GetFileName() const {
278 if (safety_state_ == DownloadItem::SAFE)
279 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16280 if (path_uniquifier_ > 0) {
281 std::wstring name(original_name_);
282 AppendNumberToPath(&name, path_uniquifier_);
283 return name;
284 }
[email protected]9ccbb372008-10-10 18:50:32285 return original_name_;
286}
287
initial.commit09911bf2008-07-26 23:55:29288// DownloadManager implementation ----------------------------------------------
289
290// static
291void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
292 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
293 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32294 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
295
296 // The default download path is userprofile\download.
297 std::wstring default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12298 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
299 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32300 NOTREACHED();
301 }
[email protected]f052118e2008-09-05 02:25:32302 prefs->RegisterStringPref(prefs::kDownloadDefaultDirectory,
303 default_download_path);
304
305 // If the download path is dangerous we forcefully reset it. But if we do
306 // so we set a flag to make sure we only do it once, to avoid fighting
307 // the user if he really wants it on an unsafe place such as the desktop.
308
309 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
310 std::wstring current_download_dir =
311 prefs->GetString(prefs::kDownloadDefaultDirectory);
312 if (DownloadPathIsDangerous(current_download_dir)) {
313 prefs->SetString(prefs::kDownloadDefaultDirectory,
314 default_download_path);
315 }
316 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
317 }
initial.commit09911bf2008-07-26 23:55:29318}
319
320DownloadManager::DownloadManager()
321 : shutdown_needed_(false),
322 profile_(NULL),
323 file_manager_(NULL),
324 ui_loop_(MessageLoop::current()),
325 file_loop_(NULL) {
326}
327
328DownloadManager::~DownloadManager() {
329 if (shutdown_needed_)
330 Shutdown();
331}
332
333void DownloadManager::Shutdown() {
334 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
335
336 // Stop receiving download updates
337 file_manager_->RemoveDownloadManager(this);
338
339 // Stop making history service requests
340 cancelable_consumer_.CancelAllRequests();
341
342 // 'in_progress_' may contain DownloadItems that have not finished the start
343 // complete (from the history service) and thus aren't in downloads_.
344 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32345 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29346 for (; it != in_progress_.end(); ++it) {
347 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32348 if (download->safety_state() == DownloadItem::DANGEROUS) {
349 // Forget about any download that the user did not approve.
350 // Note that we cannot call download->Remove() this would invalidate our
351 // iterator.
352 to_remove.insert(download);
353 continue;
initial.commit09911bf2008-07-26 23:55:29354 }
[email protected]9ccbb372008-10-10 18:50:32355 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
356 download->Cancel(false);
357 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29358 if (download->db_handle() == kUninitializedHandle) {
359 // An invalid handle means that 'download' does not yet exist in
360 // 'downloads_', so we have to delete it here.
361 delete download;
362 }
363 }
364
[email protected]9ccbb372008-10-10 18:50:32365 // 'dangerous_finished_' contains all complete downloads that have not been
366 // approved. They should be removed.
367 it = dangerous_finished_.begin();
368 for (; it != dangerous_finished_.end(); ++it)
369 to_remove.insert(it->second);
370
371 // Remove the dangerous download that are not approved.
372 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
373 rm_it != to_remove.end(); ++rm_it) {
374 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32375 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32376 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32377 // Same as above, delete the download if it is not in 'downloads_' (as the
378 // Remove() call above won't have deleted it).
379 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32380 delete download;
381 }
382 to_remove.clear();
383
initial.commit09911bf2008-07-26 23:55:29384 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32385 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29386 STLDeleteValues(&downloads_);
387
388 file_manager_ = NULL;
389
390 // Save our file extensions to auto open.
391 SaveAutoOpens();
392
393 // Make sure the save as dialog doesn't notify us back if we're gone before
394 // it returns.
395 if (select_file_dialog_.get())
396 select_file_dialog_->ListenerDestroyed();
397
398 shutdown_needed_ = false;
399}
400
[email protected]905a08d2008-11-19 07:24:12401// Determines whether the "save as" dialog should be displayed to the user
402// when downloading a file.
403bool DownloadManager::ShouldDisplaySaveAsDialog(
404 const DownloadCreateInfo* info) {
405 return
406 *prompt_for_download_ || // User always wants a prompt.
407 info->save_as || // "Save as ..." operation.
408 info->path_uniquifier == -1; // Last attempt to generate a unique file
409 // name failed.
410}
411
initial.commit09911bf2008-07-26 23:55:29412// Issue a history query for downloads matching 'search_text'. If 'search_text'
413// is empty, return all downloads that we know about.
414void DownloadManager::GetDownloads(Observer* observer,
415 const std::wstring& search_text) {
416 DCHECK(observer);
417
418 // Return a empty list if we've not yet received the set of downloads from the
419 // history system (we'll update all observers once we get that list in
420 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
421 std::vector<DownloadItem*> download_copy;
422 if (downloads_.empty()) {
423 observer->SetDownloads(download_copy);
424 return;
425 }
426
427 // We already know all the downloads and there is no filter, so just return a
428 // copy to the observer.
429 if (search_text.empty()) {
430 download_copy.reserve(downloads_.size());
431 for (DownloadMap::iterator it = downloads_.begin();
432 it != downloads_.end(); ++it) {
433 download_copy.push_back(it->second);
434 }
435
436 // We retain ownership of the DownloadItems.
437 observer->SetDownloads(download_copy);
438 return;
439 }
440
441 // Issue a request to the history service for a list of downloads matching
442 // our search text.
443 HistoryService* hs =
444 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
445 if (hs) {
446 HistoryService::Handle h =
447 hs->SearchDownloads(search_text,
448 &cancelable_consumer_,
449 NewCallback(this,
450 &DownloadManager::OnSearchComplete));
451 cancelable_consumer_.SetClientData(hs, h, observer);
452 }
453}
454
455// Query the history service for information about all persisted downloads.
456bool DownloadManager::Init(Profile* profile) {
457 DCHECK(profile);
458 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
459 shutdown_needed_ = true;
460
461 profile_ = profile;
462 request_context_ = profile_->GetRequestContext();
463
464 // 'incognito mode' will have access to past downloads, but we won't store
465 // information about new downloads while in that mode.
466 QueryHistoryForDownloads();
467
468 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
469 if (!rdh) {
470 NOTREACHED();
471 return false;
472 }
473
474 file_manager_ = rdh->download_file_manager();
475 if (!file_manager_) {
476 NOTREACHED();
477 return false;
478 }
479
480 file_loop_ = g_browser_process->file_thread()->message_loop();
481 if (!file_loop_) {
482 NOTREACHED();
483 return false;
484 }
485
486 // Get our user preference state.
487 PrefService* prefs = profile_->GetPrefs();
488 DCHECK(prefs);
489 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
490
initial.commit09911bf2008-07-26 23:55:29491 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
492
[email protected]bb69e9b32008-08-14 23:08:14493 // Ensure that the download directory specified in the preferences exists.
494 file_loop_->PostTask(FROM_HERE, NewRunnableMethod(
495 file_manager_, &DownloadFileManager::CreateDirectory, *download_path_));
496
initial.commit09911bf2008-07-26 23:55:29497 // We store any file extension that should be opened automatically at
498 // download completion in this pref.
499 download_util::InitializeExeTypes(&exe_types_);
500
501 std::wstring extensions_to_open =
502 prefs->GetString(prefs::kDownloadExtensionsToOpen);
503 std::vector<std::wstring> extensions;
504 SplitString(extensions_to_open, L':', &extensions);
505 for (size_t i = 0; i < extensions.size(); ++i) {
506 if (!extensions[i].empty() && !IsExecutable(extensions[i]))
507 auto_open_.insert(extensions[i]);
508 }
509
510 return true;
511}
512
513void DownloadManager::QueryHistoryForDownloads() {
514 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
515 if (hs) {
516 hs->QueryDownloads(
517 &cancelable_consumer_,
518 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
519 }
520}
521
522// We have received a message from DownloadFileManager about a new download. We
523// create a download item and store it in our download map, and inform the
524// history system of a new download. Since this method can be called while the
525// history service thread is still reading the persistent state, we do not
526// insert the new DownloadItem into 'downloads_' or inform our observers at this
527// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
528// download creation as a callback from the history thread.
529void DownloadManager::StartDownload(DownloadCreateInfo* info) {
530 DCHECK(MessageLoop::current() == ui_loop_);
531 DCHECK(info);
532
533 // Determine the proper path for a download, by choosing either the default
534 // download directory, or prompting the user.
535 std::wstring generated_name;
536 GenerateFilename(info, &generated_name);
[email protected]905a08d2008-11-19 07:24:12537 if (ShouldDisplaySaveAsDialog(info) && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29538 info->suggested_path = last_download_path_;
539 else
540 info->suggested_path = *download_path_;
541 file_util::AppendToPath(&info->suggested_path, generated_name);
542
[email protected]e9ebf3fc2008-10-17 22:06:58543 // Let's check if this download is dangerous, based on its name.
[email protected]905a08d2008-11-19 07:24:12544 if (!ShouldDisplaySaveAsDialog(info)) {
[email protected]e9ebf3fc2008-10-17 22:06:58545 const std::wstring filename =
546 file_util::GetFilenameFromPath(info->suggested_path);
547 info->is_dangerous = IsDangerous(filename);
548 }
549
initial.commit09911bf2008-07-26 23:55:29550 // We need to move over to the download thread because we don't want to stat
551 // the suggested path on the UI thread.
552 file_loop_->PostTask(FROM_HERE,
553 NewRunnableMethod(this,
554 &DownloadManager::CheckIfSuggestedPathExists,
555 info));
556}
557
558void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
559 DCHECK(info);
560
561 // Check writability of the suggested path. If we can't write to it, default
562 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]9ccbb372008-10-10 18:50:32563 std::wstring dir = file_util::GetDirectoryFromPath(info->suggested_path);
564 const std::wstring filename =
565 file_util::GetFilenameFromPath(info->suggested_path);
566 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29567 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29568 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
569 file_util::AppendToPath(&info->suggested_path, filename);
570 }
571
[email protected]7a256ea2008-10-17 17:34:16572 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29573
[email protected]9ccbb372008-10-10 18:50:32574 // If the download is deemmed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58575 if (info->is_dangerous) {
[email protected]9ccbb372008-10-10 18:50:32576 info->original_name = file_util::GetFilenameFromPath(info->suggested_path);
577 // Create a temporary file to hold the file until the user approves its
578 // download.
579 std::wstring file_name;
580 std::wstring path;
581 while (path.empty()) {
[email protected]ddc528892008-10-16 06:46:44582 SStringPrintf(&file_name, L"unconfirmed %d.download",
[email protected]9ccbb372008-10-10 18:50:32583 base::RandInt(0, 100000));
584 path = dir;
585 file_util::AppendToPath(&path, file_name);
586 if (file_util::PathExists(path))
587 path.clear();
588 }
589 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16590 } else {
591 // We know the final path, build it if necessary.
592 if (info->path_uniquifier > 0) {
593 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
594 // Setting path_uniquifier to 0 to make sure we don't try to unique it
595 // later on.
596 info->path_uniquifier = 0;
597 }
[email protected]9ccbb372008-10-10 18:50:32598 }
599
initial.commit09911bf2008-07-26 23:55:29600 // Now we return to the UI thread.
601 ui_loop_->PostTask(FROM_HERE,
602 NewRunnableMethod(this,
603 &DownloadManager::OnPathExistenceAvailable,
604 info));
605}
606
607void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
608 DCHECK(MessageLoop::current() == ui_loop_);
609 DCHECK(info);
610
[email protected]905a08d2008-11-19 07:24:12611 if (ShouldDisplaySaveAsDialog(info)) {
initial.commit09911bf2008-07-26 23:55:29612 // We must ask the user for the place to put the download.
613 if (!select_file_dialog_.get())
614 select_file_dialog_ = SelectFileDialog::Create(this);
615
616 TabContents* contents = tab_util::GetTabContentsByID(
617 info->render_process_id, info->render_view_id);
618 HWND owning_hwnd =
619 contents ? GetAncestor(contents->GetContainerHWND(), GA_ROOT) : NULL;
620 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
621 std::wstring(), info->suggested_path,
[email protected]39a248b02008-11-12 22:10:20622 std::wstring(), std::wstring(),
initial.commit09911bf2008-07-26 23:55:29623 owning_hwnd, info);
624 } else {
625 // No prompting for download, just continue with the suggested name.
626 ContinueStartDownload(info, info->suggested_path);
627 }
628}
629
630void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
631 const std::wstring& target_path) {
632 scoped_ptr<DownloadCreateInfo> infop(info);
633 info->path = target_path;
634
635 DownloadItem* download = NULL;
636 DownloadMap::iterator it = in_progress_.find(info->download_id);
637 if (it == in_progress_.end()) {
638 download = new DownloadItem(info->download_id,
639 info->path,
[email protected]7a256ea2008-10-17 17:34:16640 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29641 info->url,
[email protected]9ccbb372008-10-10 18:50:32642 info->original_name,
initial.commit09911bf2008-07-26 23:55:29643 info->start_time,
644 info->total_bytes,
645 info->render_process_id,
[email protected]9ccbb372008-10-10 18:50:32646 info->request_id,
647 info->is_dangerous);
initial.commit09911bf2008-07-26 23:55:29648 download->set_manager(this);
649 in_progress_[info->download_id] = download;
650 } else {
651 NOTREACHED(); // Should not exist!
652 return;
653 }
654
655 // If the download already completed by the time we reached this point, then
656 // notify observers that it did.
657 PendingFinishedMap::iterator pending_it =
658 pending_finished_downloads_.find(info->download_id);
659 if (pending_it != pending_finished_downloads_.end())
660 DownloadFinished(pending_it->first, pending_it->second);
661
662 download->Rename(target_path);
663
664 file_loop_->PostTask(FROM_HERE,
665 NewRunnableMethod(file_manager_,
666 &DownloadFileManager::OnFinalDownloadName,
667 download->id(),
668 target_path));
669
670 if (profile_->IsOffTheRecord()) {
671 // Fake a db handle for incognito mode, since nothing is actually stored in
672 // the database in this mode. We have to make sure that these handles don't
673 // collide with normal db handles, so we use a negative value. Eventually,
674 // they could overlap, but you'd have to do enough downloading that your ISP
675 // would likely stab you in the neck first. YMMV.
676 static int64 fake_db_handle = kUninitializedHandle - 1;
677 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
678 } else {
679 // Update the history system with the new download.
680 // FIXME(acw|paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
681 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
682 if (hs) {
683 hs->CreateDownload(
684 *info, &cancelable_consumer_,
685 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
686 }
687 }
688}
689
690// Convenience function for updating the history service for a download.
691void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
692 DCHECK(download);
693
694 // Don't store info in the database if the download was initiated while in
695 // incognito mode or if it hasn't been initialized in our database table.
696 if (download->db_handle() <= kUninitializedHandle)
697 return;
698
699 // FIXME(acw|paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
700 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
701 if (hs) {
702 hs->UpdateDownload(download->received_bytes(),
703 download->state(),
704 download->db_handle());
705 }
706}
707
708void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
709 DCHECK(download);
710 // FIXME(acw|paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
711 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
712 if (download->db_handle() > kUninitializedHandle && hs)
713 hs->RemoveDownload(download->db_handle());
714}
715
716void DownloadManager::RemoveDownloadsFromHistoryBetween(const Time remove_begin,
717 const Time remove_end) {
718 // FIXME(acw|paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
719 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
720 if (hs)
721 hs->RemoveDownloadsBetween(remove_begin, remove_end);
722}
723
724void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
725 DownloadMap::iterator it = in_progress_.find(download_id);
726 if (it != in_progress_.end()) {
727 DownloadItem* download = it->second;
728 download->Update(size);
729 UpdateHistoryForDownload(download);
730 }
731}
732
733void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
734 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32735 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29736 // The download is done, but the user hasn't selected a final location for
737 // it yet (the Save As dialog box is probably still showing), so just keep
738 // track of the fact that this download id is complete, when the
739 // DownloadItem is constructed later we'll notify its completion then.
740 PendingFinishedMap::iterator erase_it =
741 pending_finished_downloads_.find(download_id);
742 DCHECK(erase_it == pending_finished_downloads_.end());
743 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32744 return;
initial.commit09911bf2008-07-26 23:55:29745 }
[email protected]9ccbb372008-10-10 18:50:32746
747 // Remove the id from the list of pending ids.
748 PendingFinishedMap::iterator erase_it =
749 pending_finished_downloads_.find(download_id);
750 if (erase_it != pending_finished_downloads_.end())
751 pending_finished_downloads_.erase(erase_it);
752
753 DownloadItem* download = it->second;
754 download->Finished(size);
755
756 // Clean up will happen when the history system create callback runs if we
757 // don't have a valid db_handle yet.
758 if (download->db_handle() != kUninitializedHandle) {
759 in_progress_.erase(it);
760 NotifyAboutDownloadStop();
761 UpdateHistoryForDownload(download);
762 }
763
764 // If this a dangerous download not yet validated by the user, don't do
765 // anything. When the user notifies us, it will trigger a call to
766 // ProceedWithFinishedDangerousDownload.
767 if (download->safety_state() == DownloadItem::DANGEROUS) {
768 dangerous_finished_[download_id] = download;
769 return;
770 }
771
772 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
773 // We first need to rename the donwloaded file from its temporary name to
774 // its final name before we can continue.
775 file_loop_->PostTask(FROM_HERE,
776 NewRunnableMethod(
777 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
778 download->db_handle(),
779 download->full_path(), download->original_name()));
780 return;
781 }
782 ContinueDownloadFinished(download);
783}
784
785void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
786 // If this was a dangerous download, it has now been approved and must be
787 // removed from dangerous_finished_ so it does not get deleted on shutdown.
788 DownloadMap::iterator it = dangerous_finished_.find(download->id());
789 if (it != dangerous_finished_.end())
790 dangerous_finished_.erase(it);
791
792 // Notify our observers that we are complete (the call to Finished() set the
793 // state to complete but did not notify).
794 download->UpdateObservers();
795
796 // Open the download if the user or user prefs indicate it should be.
797 const std::wstring extension =
798 file_util::GetFileExtensionFromPath(download->full_path());
799 if (download->open_when_complete() || ShouldOpenFileExtension(extension))
800 OpenDownloadInShell(download, NULL);
801}
802
803// Called on the file thread. Renames the downloaded file to its original name.
804void DownloadManager::ProceedWithFinishedDangerousDownload(
805 int64 download_handle,
806 const std::wstring& path,
807 const std::wstring& original_name) {
808 bool success = false;
809 std::wstring new_path = path;
[email protected]7a256ea2008-10-17 17:34:16810 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32811 if (file_util::PathExists(path)) {
812 new_path = file_util::GetDirectoryFromPath(new_path);
813 file_util::AppendToPath(&new_path, original_name);
[email protected]7a256ea2008-10-17 17:34:16814 // Make our name unique at this point, as if a dangerous file is downloading
815 // and a 2nd download is started for a file with the same name, they would
816 // have the same path. This is because we uniquify the name on download
817 // start, and at that time the first file does not exists yet, so the second
818 // file gets the same name.
819 uniquifier = GetUniquePathNumber(new_path);
820 if (uniquifier > 0)
821 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32822 success = file_util::Move(path, new_path);
823 } else {
824 NOTREACHED();
825 }
826
827 ui_loop_->PostTask(FROM_HERE,
828 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16829 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32830}
831
832// Call from the file thread when the finished dangerous download was renamed.
833void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
834 bool success,
[email protected]7a256ea2008-10-17 17:34:16835 const std::wstring& new_path,
836 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32837 DownloadMap::iterator it = downloads_.find(download_handle);
838 if (it == downloads_.end()) {
839 NOTREACHED();
840 return;
841 }
842
843 DownloadItem* download = it->second;
844 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16845 if (success) {
846 // We need to update the path uniquifier so that the UI shows the right
847 // name when calling GetFileName().
848 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32849 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16850 }
[email protected]9ccbb372008-10-10 18:50:32851
852 // Continue the download finished sequence.
853 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29854}
855
856// static
857// We have to tell the ResourceDispatcherHost to cancel the download from this
858// thread, since we can't forward tasks from the file thread to the io thread
859// reliably (crash on shutdown race condition).
860void DownloadManager::CancelDownloadRequest(int render_process_id,
861 int request_id) {
862 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]ab820df2008-08-26 05:55:10863 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29864 if (!io_thread || !rdh)
865 return;
866 io_thread->message_loop()->PostTask(FROM_HERE,
867 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
868 rdh,
869 render_process_id,
870 request_id));
871}
872
873// static
874void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
875 int render_process_id,
876 int request_id) {
877 rdh->CancelRequest(render_process_id, request_id, false);
878}
879
880void DownloadManager::DownloadCancelled(int32 download_id) {
881 DownloadMap::iterator it = in_progress_.find(download_id);
882 if (it == in_progress_.end())
883 return;
884 DownloadItem* download = it->second;
885
886 CancelDownloadRequest(download->render_process_id(), download->request_id());
887
888 // Clean up will happen when the history system create callback runs if we
889 // don't have a valid db_handle yet.
890 if (download->db_handle() != kUninitializedHandle) {
891 in_progress_.erase(it);
892 NotifyAboutDownloadStop();
893 UpdateHistoryForDownload(download);
894 }
895
896 // Tell the file manager to cancel the download.
897 file_manager_->RemoveDownload(download->id(), this); // On the UI thread
898 file_loop_->PostTask(FROM_HERE,
899 NewRunnableMethod(file_manager_,
900 &DownloadFileManager::CancelDownload,
901 download->id()));
902}
903
904void DownloadManager::PauseDownload(int32 download_id, bool pause) {
905 DownloadMap::iterator it = in_progress_.find(download_id);
906 if (it != in_progress_.end()) {
907 DownloadItem* download = it->second;
908 if (pause == download->is_paused())
909 return;
910
911 // Inform the ResourceDispatcherHost of the new pause state.
[email protected]ab820df2008-08-26 05:55:10912 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29913 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
914 if (!io_thread || !rdh)
915 return;
916
917 io_thread->message_loop()->PostTask(FROM_HERE,
918 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
919 rdh,
920 download->render_process_id(),
921 download->request_id(),
922 pause));
923 }
924}
925
926// static
927void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
928 int render_process_id,
929 int request_id,
930 bool pause) {
931 rdh->PauseRequest(render_process_id, request_id, pause);
932}
933
[email protected]9ccbb372008-10-10 18:50:32934bool DownloadManager::IsDangerous(const std::wstring& file_name) {
935 // TODO(jcampan): Improve me.
936 return IsExecutable(file_util::GetFileExtensionFromPath(file_name));
937}
938
939void DownloadManager::RenameDownload(DownloadItem* download,
940 const std::wstring& new_path) {
941 download->Rename(new_path);
942
943 // Update the history.
944
945 // No update necessary if the download was initiated while in incognito mode.
946 if (download->db_handle() <= kUninitializedHandle)
947 return;
948
949 // FIXME(acw|paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
950 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
951 if (hs)
952 hs->UpdateDownloadPath(new_path, download->db_handle());
953}
954
initial.commit09911bf2008-07-26 23:55:29955void DownloadManager::RemoveDownload(int64 download_handle) {
956 DownloadMap::iterator it = downloads_.find(download_handle);
957 if (it == downloads_.end())
958 return;
959
960 // Make history update.
961 DownloadItem* download = it->second;
962 RemoveDownloadFromHistory(download);
963
964 // Remove from our tables and delete.
965 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32966 it = dangerous_finished_.find(download->id());
967 if (it != dangerous_finished_.end())
968 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:29969
970 // Tell observers to refresh their views.
971 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:36972
973 delete download;
initial.commit09911bf2008-07-26 23:55:29974}
975
976int DownloadManager::RemoveDownloadsBetween(const Time remove_begin,
977 const Time remove_end) {
978 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
979
980 int num_deleted = 0;
981 DownloadMap::iterator it = downloads_.begin();
982 while (it != downloads_.end()) {
983 DownloadItem* download = it->second;
984 DownloadItem::DownloadState state = download->state();
985 if (download->start_time() >= remove_begin &&
986 (remove_end.is_null() || download->start_time() < remove_end) &&
987 (state == DownloadItem::COMPLETE ||
988 state == DownloadItem::CANCELLED)) {
989 // Remove from the map and move to the next in the list.
990 it = downloads_.erase(it);
[email protected]a6604d92008-10-30 00:58:58991
992 // Also remove it from any completed dangerous downloads.
993 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
994 if (dit != dangerous_finished_.end())
995 dangerous_finished_.erase(dit);
996
initial.commit09911bf2008-07-26 23:55:29997 delete download;
998
999 ++num_deleted;
1000 continue;
1001 }
1002
1003 ++it;
1004 }
1005
1006 // Tell observers to refresh their views.
1007 if (num_deleted > 0)
1008 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1009
1010 return num_deleted;
1011}
1012
1013int DownloadManager::RemoveDownloads(const Time remove_begin) {
1014 return RemoveDownloadsBetween(remove_begin, Time());
1015}
1016
1017// Initiate a download of a specific URL. We send the request to the
1018// ResourceDispatcherHost, and let it send us responses like a regular
1019// download.
1020void DownloadManager::DownloadUrl(const GURL& url,
1021 const GURL& referrer,
1022 WebContents* web_contents) {
1023 DCHECK(web_contents);
1024 file_manager_->DownloadUrl(url,
1025 referrer,
1026 web_contents->process()->host_id(),
1027 web_contents->render_view_host()->routing_id(),
1028 request_context_.get());
1029}
1030
1031void DownloadManager::NotifyAboutDownloadStart() {
1032 NotificationService::current()->
1033 Notify(NOTIFY_DOWNLOAD_START, NotificationService::AllSources(),
1034 NotificationService::NoDetails());
1035}
1036
1037void DownloadManager::NotifyAboutDownloadStop() {
1038 NotificationService::current()->
1039 Notify(NOTIFY_DOWNLOAD_STOP, NotificationService::AllSources(),
1040 NotificationService::NoDetails());
1041}
1042
1043void DownloadManager::GenerateExtension(const std::wstring& file_name,
1044 const std::string& mime_type,
1045 std::wstring* generated_extension) {
1046 // We're worried about three things here:
1047 //
1048 // 1) Security. Many sites let users upload content, such as buddy icons, to
1049 // their web sites. We want to mitigate the case where an attacker
1050 // supplies a malicious executable with an executable file extension but an
1051 // honest site serves the content with a benign content type, such as
1052 // image/jpeg.
1053 //
1054 // 2) Usability. If the site fails to provide a file extension, we want to
1055 // guess a reasonable file extension based on the content type.
1056 //
1057 // 3) Shell integration. Some file extensions automatically integrate with
1058 // the shell. We block these extensions to prevent a malicious web site
1059 // from integrating with the user's shell.
1060
1061 static const wchar_t default_extension[] = L"download";
1062
1063 // See if our file name already contains an extension.
1064 std::wstring extension(file_util::GetFileExtensionFromPath(file_name));
1065
1066 // Rename shell-integrated extensions.
1067 if (win_util::IsShellIntegratedExtension(extension))
1068 extension.assign(default_extension);
1069
1070 std::string mime_type_from_extension;
[email protected]a9bb6f692008-07-30 16:40:101071 net::GetMimeTypeFromFile(file_name, &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291072 if (mime_type == mime_type_from_extension) {
1073 // The hinted extension matches the mime type. It looks like a winner.
1074 generated_extension->swap(extension);
1075 return;
1076 }
1077
1078 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1079 // We want to be careful about executable extensions. The worry here is
1080 // that a trusted web site could be tricked into dropping an executable file
1081 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101082 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291083 // We couldn't find a good extension for this content type. Use a dummy
1084 // extension instead.
1085 extension.assign(default_extension);
1086 }
1087 }
1088
1089 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101090 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291091 } else {
1092 // Append entension generated from the mime type if:
1093 // 1. New extension is not ".txt"
1094 // 2. New extension is not the same as the already existing extension.
1095 // 3. New extension is not executable. This action mitigates the case when
1096 // an execuatable is hidden in a benign file extension;
1097 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1098 // application/x-javascript.
1099 std::wstring append_extension;
[email protected]a9bb6f692008-07-30 16:40:101100 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
initial.commit09911bf2008-07-26 23:55:291101 if (append_extension != L".txt" && append_extension != extension &&
1102 !IsExecutable(append_extension))
1103 extension += append_extension;
1104 }
1105 }
1106
1107 generated_extension->swap(extension);
1108}
1109
1110void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
1111 std::wstring* generated_name) {
1112 std::wstring file_name =
[email protected]8ac1a752008-07-31 19:40:371113 net::GetSuggestedFilename(GURL(info->url),
1114 info->content_disposition,
1115 L"download");
initial.commit09911bf2008-07-26 23:55:291116 DCHECK(!file_name.empty());
1117
1118 // Make sure we get the right file extension.
1119 std::wstring extension;
1120 GenerateExtension(file_name, info->mime_type, &extension);
1121 file_util::ReplaceExtension(&file_name, extension);
1122
1123 // Prepend "_" to the file name if it's a reserved name
1124 if (win_util::IsReservedName(file_name))
1125 file_name = std::wstring(L"_") + file_name;
1126
1127 generated_name->assign(file_name);
1128}
1129
1130void DownloadManager::AddObserver(Observer* observer) {
1131 observers_.AddObserver(observer);
1132 observer->ModelChanged();
1133}
1134
1135void DownloadManager::RemoveObserver(Observer* observer) {
1136 observers_.RemoveObserver(observer);
1137}
1138
1139// Post Windows Shell operations to the Download thread, to avoid blocking the
1140// user interface.
1141void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1142 DCHECK(file_manager_);
1143 file_loop_->PostTask(FROM_HERE,
1144 NewRunnableMethod(file_manager_,
1145 &DownloadFileManager::OnShowDownloadInShell,
1146 download->full_path()));
1147}
1148
1149void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
1150 HWND parent_window) {
1151 DCHECK(file_manager_);
1152 file_loop_->PostTask(FROM_HERE,
1153 NewRunnableMethod(file_manager_,
1154 &DownloadFileManager::OnOpenDownloadInShell,
1155 download->full_path(), download->url(), parent_window));
1156}
1157
1158void DownloadManager::OpenFilesOfExtension(const std::wstring& extension,
1159 bool open) {
1160 if (open && !IsExecutable(extension))
1161 auto_open_.insert(extension);
1162 else
1163 auto_open_.erase(extension);
1164 SaveAutoOpens();
1165}
1166
1167bool DownloadManager::ShouldOpenFileExtension(const std::wstring& extension) {
1168 if (!IsExecutable(extension) &&
1169 auto_open_.find(extension) != auto_open_.end())
1170 return true;
1171 return false;
1172}
1173
1174// static
1175bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
1176 // JavaScript is just as powerful as EXE.
[email protected]a9bb6f692008-07-30 16:40:101177 if (net::MatchesMimeType("text/javascript", mime_type))
initial.commit09911bf2008-07-26 23:55:291178 return true;
[email protected]a9bb6f692008-07-30 16:40:101179 if (net::MatchesMimeType("text/javascript;version=*", mime_type))
initial.commit09911bf2008-07-26 23:55:291180 return true;
1181
1182 // We don't consider other non-application types to be executable.
[email protected]a9bb6f692008-07-30 16:40:101183 if (!net::MatchesMimeType("application/*", mime_type))
initial.commit09911bf2008-07-26 23:55:291184 return false;
1185
1186 // These application types are not executable.
[email protected]a9bb6f692008-07-30 16:40:101187 if (net::MatchesMimeType("application/*+xml", mime_type))
initial.commit09911bf2008-07-26 23:55:291188 return false;
[email protected]a9bb6f692008-07-30 16:40:101189 if (net::MatchesMimeType("application/xml", mime_type))
initial.commit09911bf2008-07-26 23:55:291190 return false;
1191
1192 return true;
1193}
1194
1195bool DownloadManager::IsExecutable(const std::wstring& extension) {
1196 return exe_types_.find(extension) != exe_types_.end();
1197}
1198
1199void DownloadManager::ResetAutoOpenFiles() {
1200 auto_open_.clear();
1201 SaveAutoOpens();
1202}
1203
1204bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1205 return !auto_open_.empty();
1206}
1207
1208void DownloadManager::SaveAutoOpens() {
1209 PrefService* prefs = profile_->GetPrefs();
1210 if (prefs) {
1211 std::wstring extensions;
1212 for (std::set<std::wstring>::iterator it = auto_open_.begin();
1213 it != auto_open_.end(); ++it) {
1214 extensions += *it + L":";
1215 }
1216 if (!extensions.empty())
1217 extensions.erase(extensions.size() - 1);
1218 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions);
1219 }
1220}
1221
1222void DownloadManager::FileSelected(const std::wstring& path, void* params) {
1223 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]905a08d2008-11-19 07:24:121224 if (ShouldDisplaySaveAsDialog(info))
initial.commit09911bf2008-07-26 23:55:291225 last_download_path_ = file_util::GetDirectoryFromPath(path);
1226 ContinueStartDownload(info, path);
1227}
1228
1229void DownloadManager::FileSelectionCanceled(void* params) {
1230 // The user didn't pick a place to save the file, so need to cancel the
1231 // download that's already in progress to the temporary location.
1232 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
1233 file_loop_->PostTask(FROM_HERE,
1234 NewRunnableMethod(file_manager_, &DownloadFileManager::CancelDownload,
1235 info->download_id));
1236}
1237
[email protected]9ccbb372008-10-10 18:50:321238void DownloadManager::DeleteDownload(const std::wstring& path) {
1239 file_loop_->PostTask(FROM_HERE, NewRunnableMethod(
1240 file_manager_, &DownloadFileManager::DeleteFile, path));
1241}
1242
1243
1244void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1245 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1246 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1247 download->UpdateObservers();
1248
1249 // If the download is not complete, nothing to do. The required
1250 // post-processing will be performed when it does complete.
1251 if (download->state() != DownloadItem::COMPLETE)
1252 return;
1253
1254 file_loop_->PostTask(FROM_HERE,
1255 NewRunnableMethod(this,
1256 &DownloadManager::ProceedWithFinishedDangerousDownload,
1257 download->db_handle(), download->full_path(),
1258 download->original_name()));
1259}
1260
initial.commit09911bf2008-07-26 23:55:291261// Operations posted to us from the history service ----------------------------
1262
1263// The history service has retrieved all download entries. 'entries' contains
1264// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1265void DownloadManager::OnQueryDownloadEntriesComplete(
1266 std::vector<DownloadCreateInfo>* entries) {
1267 for (size_t i = 0; i < entries->size(); ++i) {
1268 DownloadItem* download = new DownloadItem(entries->at(i));
1269 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1270 downloads_[download->db_handle()] = download;
1271 download->set_manager(this);
1272 }
1273 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1274}
1275
1276
1277// Once the new DownloadItem's creation info has been committed to the history
1278// service, we associate the DownloadItem with the db handle, update our
1279// 'downloads_' map and inform observers.
1280void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1281 int64 db_handle) {
1282 DownloadMap::iterator it = in_progress_.find(info.download_id);
1283 DCHECK(it != in_progress_.end());
1284
1285 DownloadItem* download = it->second;
1286 DCHECK(download->db_handle() == kUninitializedHandle);
1287 download->set_db_handle(db_handle);
1288
1289 // Insert into our full map.
1290 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1291 downloads_[download->db_handle()] = download;
1292
1293 // The 'contents' may no longer exist if the user closed the tab before we get
1294 // this start completion event. If it does, tell the origin WebContents to
1295 // display its download shelf.
1296 TabContents* contents =
1297 tab_util::GetTabContentsByID(info.render_process_id, info.render_view_id);
1298
1299 // If the contents no longer exists or is no longer active, we start the
1300 // download in the last active browser. This is not ideal but better than
1301 // fully hiding the download from the user. Note: non active means that the
1302 // user navigated away from the tab contents. This has nothing to do with
1303 // tab selection.
1304 if (!contents || !contents->is_active()) {
1305 Browser* last_active = BrowserList::GetLastActive();
1306 if (last_active)
1307 contents = last_active->GetSelectedTabContents();
1308 }
1309
1310 if (contents)
1311 contents->OnStartDownload(download);
1312
1313 // Inform interested objects about the new download.
1314 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1315 NotifyAboutDownloadStart();
1316
1317 // If this download has been completed before we've received the db handle,
1318 // post one final message to the history service so that it can be properly
1319 // in sync with the DownloadItem's completion status, and also inform any
1320 // observers so that they get more than just the start notification.
1321 if (download->state() != DownloadItem::IN_PROGRESS) {
1322 in_progress_.erase(it);
1323 NotifyAboutDownloadStop();
1324 UpdateHistoryForDownload(download);
1325 download->UpdateObservers();
1326 }
1327}
1328
1329// Called when the history service has retrieved the list of downloads that
1330// match the search text.
1331void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1332 std::vector<int64>* results) {
1333 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1334 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1335 if (!requestor)
1336 return;
1337
1338 std::vector<DownloadItem*> searched_downloads;
1339 for (std::vector<int64>::iterator it = results->begin();
1340 it != results->end(); ++it) {
1341 DownloadMap::iterator dit = downloads_.find(*it);
1342 if (dit != downloads_.end())
1343 searched_downloads.push_back(dit->second);
1344 }
1345
1346 requestor->SetDownloads(searched_downloads);
1347}
[email protected]905a08d2008-11-19 07:24:121348
1349// Clears the last download path, used to initialize "save as" dialogs.
1350void DownloadManager::ClearLastDownloadPath() {
1351 last_download_path_.clear();
1352}