blob: 53288072911763cfc4c8cc1054967a2236844afc [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
[email protected]6cade212008-12-03 00:32:2262// database handles in incognito mode starting at -1 and progressively getting
63// more negative.
initial.commit09911bf2008-07-26 23:55:2964static 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
[email protected]6cade212008-12-03 00:32:22201// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29202void 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]6cade212008-12-03 00:32:22227 // We have now been 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)) {
[email protected]6cade212008-12-03 00:32:22310 std::wstring current_download_dir =
[email protected]f052118e2008-09-05 02:25:32311 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
initial.commit09911bf2008-07-26 23:55:29401// Issue a history query for downloads matching 'search_text'. If 'search_text'
402// is empty, return all downloads that we know about.
403void DownloadManager::GetDownloads(Observer* observer,
404 const std::wstring& search_text) {
405 DCHECK(observer);
406
407 // Return a empty list if we've not yet received the set of downloads from the
408 // history system (we'll update all observers once we get that list in
409 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
410 std::vector<DownloadItem*> download_copy;
411 if (downloads_.empty()) {
412 observer->SetDownloads(download_copy);
413 return;
414 }
415
416 // We already know all the downloads and there is no filter, so just return a
417 // copy to the observer.
418 if (search_text.empty()) {
419 download_copy.reserve(downloads_.size());
420 for (DownloadMap::iterator it = downloads_.begin();
421 it != downloads_.end(); ++it) {
422 download_copy.push_back(it->second);
423 }
424
425 // We retain ownership of the DownloadItems.
426 observer->SetDownloads(download_copy);
427 return;
428 }
429
430 // Issue a request to the history service for a list of downloads matching
431 // our search text.
432 HistoryService* hs =
433 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
434 if (hs) {
435 HistoryService::Handle h =
436 hs->SearchDownloads(search_text,
437 &cancelable_consumer_,
438 NewCallback(this,
439 &DownloadManager::OnSearchComplete));
440 cancelable_consumer_.SetClientData(hs, h, observer);
441 }
442}
443
444// Query the history service for information about all persisted downloads.
445bool DownloadManager::Init(Profile* profile) {
446 DCHECK(profile);
447 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
448 shutdown_needed_ = true;
449
450 profile_ = profile;
451 request_context_ = profile_->GetRequestContext();
452
453 // 'incognito mode' will have access to past downloads, but we won't store
454 // information about new downloads while in that mode.
455 QueryHistoryForDownloads();
456
457 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
458 if (!rdh) {
459 NOTREACHED();
460 return false;
461 }
462
463 file_manager_ = rdh->download_file_manager();
464 if (!file_manager_) {
465 NOTREACHED();
466 return false;
467 }
468
469 file_loop_ = g_browser_process->file_thread()->message_loop();
470 if (!file_loop_) {
471 NOTREACHED();
472 return false;
473 }
474
475 // Get our user preference state.
476 PrefService* prefs = profile_->GetPrefs();
477 DCHECK(prefs);
478 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
479
initial.commit09911bf2008-07-26 23:55:29480 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
481
[email protected]bb69e9b32008-08-14 23:08:14482 // Ensure that the download directory specified in the preferences exists.
483 file_loop_->PostTask(FROM_HERE, NewRunnableMethod(
484 file_manager_, &DownloadFileManager::CreateDirectory, *download_path_));
485
initial.commit09911bf2008-07-26 23:55:29486 // We store any file extension that should be opened automatically at
487 // download completion in this pref.
488 download_util::InitializeExeTypes(&exe_types_);
489
490 std::wstring extensions_to_open =
491 prefs->GetString(prefs::kDownloadExtensionsToOpen);
492 std::vector<std::wstring> extensions;
493 SplitString(extensions_to_open, L':', &extensions);
494 for (size_t i = 0; i < extensions.size(); ++i) {
495 if (!extensions[i].empty() && !IsExecutable(extensions[i]))
496 auto_open_.insert(extensions[i]);
497 }
498
499 return true;
500}
501
502void DownloadManager::QueryHistoryForDownloads() {
503 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
504 if (hs) {
505 hs->QueryDownloads(
506 &cancelable_consumer_,
507 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
508 }
509}
510
511// We have received a message from DownloadFileManager about a new download. We
512// create a download item and store it in our download map, and inform the
513// history system of a new download. Since this method can be called while the
514// history service thread is still reading the persistent state, we do not
515// insert the new DownloadItem into 'downloads_' or inform our observers at this
516// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
517// download creation as a callback from the history thread.
518void DownloadManager::StartDownload(DownloadCreateInfo* info) {
519 DCHECK(MessageLoop::current() == ui_loop_);
520 DCHECK(info);
521
[email protected]7d3851d82008-12-12 03:26:07522 // Freeze the user's preference for showing a Save As dialog. We're going to
523 // bounce around a bunch of threads and we don't want to worry about race
524 // conditions where the user changes this pref out from under us.
525 if (*prompt_for_download_)
526 info->save_as = true;
527
initial.commit09911bf2008-07-26 23:55:29528 // Determine the proper path for a download, by choosing either the default
529 // download directory, or prompting the user.
530 std::wstring generated_name;
531 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07532 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29533 info->suggested_path = last_download_path_;
534 else
535 info->suggested_path = *download_path_;
536 file_util::AppendToPath(&info->suggested_path, generated_name);
537
[email protected]7d3851d82008-12-12 03:26:07538 if (!info->save_as) {
539 // Let's check if this download is dangerous, based on its name.
[email protected]e9ebf3fc2008-10-17 22:06:58540 const std::wstring filename =
541 file_util::GetFilenameFromPath(info->suggested_path);
542 info->is_dangerous = IsDangerous(filename);
543 }
544
initial.commit09911bf2008-07-26 23:55:29545 // We need to move over to the download thread because we don't want to stat
546 // the suggested path on the UI thread.
547 file_loop_->PostTask(FROM_HERE,
548 NewRunnableMethod(this,
549 &DownloadManager::CheckIfSuggestedPathExists,
550 info));
551}
552
553void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
554 DCHECK(info);
555
556 // Check writability of the suggested path. If we can't write to it, default
557 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]9ccbb372008-10-10 18:50:32558 std::wstring dir = file_util::GetDirectoryFromPath(info->suggested_path);
559 const std::wstring filename =
560 file_util::GetFilenameFromPath(info->suggested_path);
561 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29562 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29563 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
564 file_util::AppendToPath(&info->suggested_path, filename);
565 }
566
[email protected]7a256ea2008-10-17 17:34:16567 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29568
[email protected]6cade212008-12-03 00:32:22569 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58570 if (info->is_dangerous) {
[email protected]9ccbb372008-10-10 18:50:32571 info->original_name = file_util::GetFilenameFromPath(info->suggested_path);
572 // Create a temporary file to hold the file until the user approves its
573 // download.
574 std::wstring file_name;
575 std::wstring path;
576 while (path.empty()) {
[email protected]ddc528892008-10-16 06:46:44577 SStringPrintf(&file_name, L"unconfirmed %d.download",
[email protected]9ccbb372008-10-10 18:50:32578 base::RandInt(0, 100000));
[email protected]7d3851d82008-12-12 03:26:07579 path = dir;
580 file_util::AppendToPath(&path, file_name);
581 if (file_util::PathExists(path))
582 path.clear();
[email protected]9ccbb372008-10-10 18:50:32583 }
584 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16585 } else {
586 // We know the final path, build it if necessary.
587 if (info->path_uniquifier > 0) {
588 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
589 // Setting path_uniquifier to 0 to make sure we don't try to unique it
590 // later on.
591 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07592 } else if (info->path_uniquifier == -1) {
593 // We failed to find a unique path. We have to prompt the user.
594 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16595 }
[email protected]9ccbb372008-10-10 18:50:32596 }
597
[email protected]7d3851d82008-12-12 03:26:07598 if (!info->save_as) {
599 // Create an empty file at the suggested path so that we don't allocate the
600 // same "non-existant" path to multiple downloads.
601 // See: http://code.google.com/p/chromium/issues/detail?id=3662
602 file_util::WriteFile(info->suggested_path, "", 0);
603 }
604
initial.commit09911bf2008-07-26 23:55:29605 // Now we return to the UI thread.
606 ui_loop_->PostTask(FROM_HERE,
607 NewRunnableMethod(this,
608 &DownloadManager::OnPathExistenceAvailable,
609 info));
610}
611
612void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
613 DCHECK(MessageLoop::current() == ui_loop_);
614 DCHECK(info);
615
[email protected]7d3851d82008-12-12 03:26:07616 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29617 // We must ask the user for the place to put the download.
618 if (!select_file_dialog_.get())
619 select_file_dialog_ = SelectFileDialog::Create(this);
620
621 TabContents* contents = tab_util::GetTabContentsByID(
622 info->render_process_id, info->render_view_id);
[email protected]6cade212008-12-03 00:32:22623 std::wstring filter = win_util::GetFileFilterFromPath(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29624 HWND owning_hwnd =
625 contents ? GetAncestor(contents->GetContainerHWND(), GA_ROOT) : NULL;
626 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
627 std::wstring(), info->suggested_path,
[email protected]6cade212008-12-03 00:32:22628 filter, std::wstring(),
initial.commit09911bf2008-07-26 23:55:29629 owning_hwnd, info);
630 } else {
631 // No prompting for download, just continue with the suggested name.
632 ContinueStartDownload(info, info->suggested_path);
633 }
634}
635
636void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
637 const std::wstring& target_path) {
638 scoped_ptr<DownloadCreateInfo> infop(info);
639 info->path = target_path;
640
641 DownloadItem* download = NULL;
642 DownloadMap::iterator it = in_progress_.find(info->download_id);
643 if (it == in_progress_.end()) {
644 download = new DownloadItem(info->download_id,
645 info->path,
[email protected]7a256ea2008-10-17 17:34:16646 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29647 info->url,
[email protected]9ccbb372008-10-10 18:50:32648 info->original_name,
initial.commit09911bf2008-07-26 23:55:29649 info->start_time,
650 info->total_bytes,
651 info->render_process_id,
[email protected]9ccbb372008-10-10 18:50:32652 info->request_id,
653 info->is_dangerous);
initial.commit09911bf2008-07-26 23:55:29654 download->set_manager(this);
655 in_progress_[info->download_id] = download;
656 } else {
657 NOTREACHED(); // Should not exist!
658 return;
659 }
660
661 // If the download already completed by the time we reached this point, then
662 // notify observers that it did.
663 PendingFinishedMap::iterator pending_it =
664 pending_finished_downloads_.find(info->download_id);
665 if (pending_it != pending_finished_downloads_.end())
666 DownloadFinished(pending_it->first, pending_it->second);
667
668 download->Rename(target_path);
669
670 file_loop_->PostTask(FROM_HERE,
671 NewRunnableMethod(file_manager_,
672 &DownloadFileManager::OnFinalDownloadName,
673 download->id(),
674 target_path));
675
676 if (profile_->IsOffTheRecord()) {
677 // Fake a db handle for incognito mode, since nothing is actually stored in
678 // the database in this mode. We have to make sure that these handles don't
679 // collide with normal db handles, so we use a negative value. Eventually,
680 // they could overlap, but you'd have to do enough downloading that your ISP
681 // would likely stab you in the neck first. YMMV.
682 static int64 fake_db_handle = kUninitializedHandle - 1;
683 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
684 } else {
685 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22686 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29687 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
688 if (hs) {
689 hs->CreateDownload(
690 *info, &cancelable_consumer_,
691 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
692 }
693 }
694}
695
696// Convenience function for updating the history service for a download.
697void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
698 DCHECK(download);
699
700 // Don't store info in the database if the download was initiated while in
701 // incognito mode or if it hasn't been initialized in our database table.
702 if (download->db_handle() <= kUninitializedHandle)
703 return;
704
[email protected]6cade212008-12-03 00:32:22705 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29706 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
707 if (hs) {
708 hs->UpdateDownload(download->received_bytes(),
709 download->state(),
710 download->db_handle());
711 }
712}
713
714void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
715 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22716 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29717 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
718 if (download->db_handle() > kUninitializedHandle && hs)
719 hs->RemoveDownload(download->db_handle());
720}
721
722void DownloadManager::RemoveDownloadsFromHistoryBetween(const Time remove_begin,
723 const Time remove_end) {
[email protected]6cade212008-12-03 00:32:22724 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29725 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
726 if (hs)
727 hs->RemoveDownloadsBetween(remove_begin, remove_end);
728}
729
730void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
731 DownloadMap::iterator it = in_progress_.find(download_id);
732 if (it != in_progress_.end()) {
733 DownloadItem* download = it->second;
734 download->Update(size);
735 UpdateHistoryForDownload(download);
736 }
737}
738
739void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
740 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32741 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29742 // The download is done, but the user hasn't selected a final location for
743 // it yet (the Save As dialog box is probably still showing), so just keep
744 // track of the fact that this download id is complete, when the
745 // DownloadItem is constructed later we'll notify its completion then.
746 PendingFinishedMap::iterator erase_it =
747 pending_finished_downloads_.find(download_id);
748 DCHECK(erase_it == pending_finished_downloads_.end());
749 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32750 return;
initial.commit09911bf2008-07-26 23:55:29751 }
[email protected]9ccbb372008-10-10 18:50:32752
753 // Remove the id from the list of pending ids.
754 PendingFinishedMap::iterator erase_it =
755 pending_finished_downloads_.find(download_id);
756 if (erase_it != pending_finished_downloads_.end())
757 pending_finished_downloads_.erase(erase_it);
758
759 DownloadItem* download = it->second;
760 download->Finished(size);
761
762 // Clean up will happen when the history system create callback runs if we
763 // don't have a valid db_handle yet.
764 if (download->db_handle() != kUninitializedHandle) {
765 in_progress_.erase(it);
766 NotifyAboutDownloadStop();
767 UpdateHistoryForDownload(download);
768 }
769
770 // If this a dangerous download not yet validated by the user, don't do
771 // anything. When the user notifies us, it will trigger a call to
772 // ProceedWithFinishedDangerousDownload.
773 if (download->safety_state() == DownloadItem::DANGEROUS) {
774 dangerous_finished_[download_id] = download;
775 return;
776 }
777
778 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22779 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32780 // its final name before we can continue.
781 file_loop_->PostTask(FROM_HERE,
782 NewRunnableMethod(
783 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
784 download->db_handle(),
785 download->full_path(), download->original_name()));
786 return;
787 }
788 ContinueDownloadFinished(download);
789}
790
791void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
792 // If this was a dangerous download, it has now been approved and must be
793 // removed from dangerous_finished_ so it does not get deleted on shutdown.
794 DownloadMap::iterator it = dangerous_finished_.find(download->id());
795 if (it != dangerous_finished_.end())
796 dangerous_finished_.erase(it);
797
798 // Notify our observers that we are complete (the call to Finished() set the
799 // state to complete but did not notify).
800 download->UpdateObservers();
801
802 // Open the download if the user or user prefs indicate it should be.
803 const std::wstring extension =
804 file_util::GetFileExtensionFromPath(download->full_path());
805 if (download->open_when_complete() || ShouldOpenFileExtension(extension))
806 OpenDownloadInShell(download, NULL);
807}
808
809// Called on the file thread. Renames the downloaded file to its original name.
810void DownloadManager::ProceedWithFinishedDangerousDownload(
811 int64 download_handle,
812 const std::wstring& path,
813 const std::wstring& original_name) {
814 bool success = false;
815 std::wstring new_path = path;
[email protected]7a256ea2008-10-17 17:34:16816 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32817 if (file_util::PathExists(path)) {
818 new_path = file_util::GetDirectoryFromPath(new_path);
819 file_util::AppendToPath(&new_path, original_name);
[email protected]7a256ea2008-10-17 17:34:16820 // Make our name unique at this point, as if a dangerous file is downloading
821 // and a 2nd download is started for a file with the same name, they would
822 // have the same path. This is because we uniquify the name on download
823 // start, and at that time the first file does not exists yet, so the second
824 // file gets the same name.
825 uniquifier = GetUniquePathNumber(new_path);
826 if (uniquifier > 0)
827 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32828 success = file_util::Move(path, new_path);
829 } else {
830 NOTREACHED();
831 }
[email protected]6cade212008-12-03 00:32:22832
[email protected]9ccbb372008-10-10 18:50:32833 ui_loop_->PostTask(FROM_HERE,
834 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16835 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32836}
837
838// Call from the file thread when the finished dangerous download was renamed.
839void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
840 bool success,
[email protected]7a256ea2008-10-17 17:34:16841 const std::wstring& new_path,
842 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32843 DownloadMap::iterator it = downloads_.find(download_handle);
844 if (it == downloads_.end()) {
845 NOTREACHED();
846 return;
847 }
848
849 DownloadItem* download = it->second;
850 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16851 if (success) {
852 // We need to update the path uniquifier so that the UI shows the right
853 // name when calling GetFileName().
854 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32855 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16856 }
[email protected]9ccbb372008-10-10 18:50:32857
858 // Continue the download finished sequence.
859 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29860}
861
862// static
863// We have to tell the ResourceDispatcherHost to cancel the download from this
[email protected]6cade212008-12-03 00:32:22864// thread, since we can't forward tasks from the file thread to the IO thread
initial.commit09911bf2008-07-26 23:55:29865// reliably (crash on shutdown race condition).
866void DownloadManager::CancelDownloadRequest(int render_process_id,
867 int request_id) {
868 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]ab820df2008-08-26 05:55:10869 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29870 if (!io_thread || !rdh)
871 return;
872 io_thread->message_loop()->PostTask(FROM_HERE,
873 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
874 rdh,
875 render_process_id,
876 request_id));
877}
878
879// static
880void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
881 int render_process_id,
882 int request_id) {
883 rdh->CancelRequest(render_process_id, request_id, false);
884}
885
886void DownloadManager::DownloadCancelled(int32 download_id) {
887 DownloadMap::iterator it = in_progress_.find(download_id);
888 if (it == in_progress_.end())
889 return;
890 DownloadItem* download = it->second;
891
892 CancelDownloadRequest(download->render_process_id(), download->request_id());
893
894 // Clean up will happen when the history system create callback runs if we
895 // don't have a valid db_handle yet.
896 if (download->db_handle() != kUninitializedHandle) {
897 in_progress_.erase(it);
898 NotifyAboutDownloadStop();
899 UpdateHistoryForDownload(download);
900 }
901
902 // Tell the file manager to cancel the download.
903 file_manager_->RemoveDownload(download->id(), this); // On the UI thread
904 file_loop_->PostTask(FROM_HERE,
905 NewRunnableMethod(file_manager_,
906 &DownloadFileManager::CancelDownload,
907 download->id()));
908}
909
910void DownloadManager::PauseDownload(int32 download_id, bool pause) {
911 DownloadMap::iterator it = in_progress_.find(download_id);
912 if (it != in_progress_.end()) {
913 DownloadItem* download = it->second;
914 if (pause == download->is_paused())
915 return;
916
917 // Inform the ResourceDispatcherHost of the new pause state.
[email protected]ab820df2008-08-26 05:55:10918 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29919 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
920 if (!io_thread || !rdh)
921 return;
922
923 io_thread->message_loop()->PostTask(FROM_HERE,
924 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
925 rdh,
926 download->render_process_id(),
927 download->request_id(),
928 pause));
929 }
930}
931
932// static
933void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
934 int render_process_id,
935 int request_id,
936 bool pause) {
937 rdh->PauseRequest(render_process_id, request_id, pause);
938}
939
[email protected]9ccbb372008-10-10 18:50:32940bool DownloadManager::IsDangerous(const std::wstring& file_name) {
941 // TODO(jcampan): Improve me.
942 return IsExecutable(file_util::GetFileExtensionFromPath(file_name));
943}
944
945void DownloadManager::RenameDownload(DownloadItem* download,
946 const std::wstring& new_path) {
947 download->Rename(new_path);
948
949 // Update the history.
950
951 // No update necessary if the download was initiated while in incognito mode.
952 if (download->db_handle() <= kUninitializedHandle)
953 return;
954
[email protected]6cade212008-12-03 00:32:22955 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:32956 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
957 if (hs)
958 hs->UpdateDownloadPath(new_path, download->db_handle());
959}
960
initial.commit09911bf2008-07-26 23:55:29961void DownloadManager::RemoveDownload(int64 download_handle) {
962 DownloadMap::iterator it = downloads_.find(download_handle);
963 if (it == downloads_.end())
964 return;
965
966 // Make history update.
967 DownloadItem* download = it->second;
968 RemoveDownloadFromHistory(download);
969
970 // Remove from our tables and delete.
971 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32972 it = dangerous_finished_.find(download->id());
973 if (it != dangerous_finished_.end())
974 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:29975
976 // Tell observers to refresh their views.
977 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:36978
979 delete download;
initial.commit09911bf2008-07-26 23:55:29980}
981
982int DownloadManager::RemoveDownloadsBetween(const Time remove_begin,
983 const Time remove_end) {
984 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
985
986 int num_deleted = 0;
987 DownloadMap::iterator it = downloads_.begin();
988 while (it != downloads_.end()) {
989 DownloadItem* download = it->second;
990 DownloadItem::DownloadState state = download->state();
991 if (download->start_time() >= remove_begin &&
992 (remove_end.is_null() || download->start_time() < remove_end) &&
993 (state == DownloadItem::COMPLETE ||
994 state == DownloadItem::CANCELLED)) {
995 // Remove from the map and move to the next in the list.
996 it = downloads_.erase(it);
[email protected]a6604d92008-10-30 00:58:58997
998 // Also remove it from any completed dangerous downloads.
999 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1000 if (dit != dangerous_finished_.end())
1001 dangerous_finished_.erase(dit);
1002
initial.commit09911bf2008-07-26 23:55:291003 delete download;
1004
1005 ++num_deleted;
1006 continue;
1007 }
1008
1009 ++it;
1010 }
1011
1012 // Tell observers to refresh their views.
1013 if (num_deleted > 0)
1014 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1015
1016 return num_deleted;
1017}
1018
1019int DownloadManager::RemoveDownloads(const Time remove_begin) {
1020 return RemoveDownloadsBetween(remove_begin, Time());
1021}
1022
1023// Initiate a download of a specific URL. We send the request to the
1024// ResourceDispatcherHost, and let it send us responses like a regular
1025// download.
1026void DownloadManager::DownloadUrl(const GURL& url,
1027 const GURL& referrer,
1028 WebContents* web_contents) {
1029 DCHECK(web_contents);
1030 file_manager_->DownloadUrl(url,
1031 referrer,
1032 web_contents->process()->host_id(),
1033 web_contents->render_view_host()->routing_id(),
1034 request_context_.get());
1035}
1036
1037void DownloadManager::NotifyAboutDownloadStart() {
1038 NotificationService::current()->
1039 Notify(NOTIFY_DOWNLOAD_START, NotificationService::AllSources(),
1040 NotificationService::NoDetails());
1041}
1042
1043void DownloadManager::NotifyAboutDownloadStop() {
1044 NotificationService::current()->
1045 Notify(NOTIFY_DOWNLOAD_STOP, NotificationService::AllSources(),
1046 NotificationService::NoDetails());
1047}
1048
1049void DownloadManager::GenerateExtension(const std::wstring& file_name,
1050 const std::string& mime_type,
1051 std::wstring* generated_extension) {
1052 // We're worried about three things here:
1053 //
1054 // 1) Security. Many sites let users upload content, such as buddy icons, to
1055 // their web sites. We want to mitigate the case where an attacker
1056 // supplies a malicious executable with an executable file extension but an
1057 // honest site serves the content with a benign content type, such as
1058 // image/jpeg.
1059 //
1060 // 2) Usability. If the site fails to provide a file extension, we want to
1061 // guess a reasonable file extension based on the content type.
1062 //
1063 // 3) Shell integration. Some file extensions automatically integrate with
1064 // the shell. We block these extensions to prevent a malicious web site
1065 // from integrating with the user's shell.
1066
1067 static const wchar_t default_extension[] = L"download";
1068
1069 // See if our file name already contains an extension.
1070 std::wstring extension(file_util::GetFileExtensionFromPath(file_name));
1071
1072 // Rename shell-integrated extensions.
1073 if (win_util::IsShellIntegratedExtension(extension))
1074 extension.assign(default_extension);
1075
1076 std::string mime_type_from_extension;
[email protected]a9bb6f692008-07-30 16:40:101077 net::GetMimeTypeFromFile(file_name, &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291078 if (mime_type == mime_type_from_extension) {
1079 // The hinted extension matches the mime type. It looks like a winner.
1080 generated_extension->swap(extension);
1081 return;
1082 }
1083
1084 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1085 // We want to be careful about executable extensions. The worry here is
1086 // that a trusted web site could be tricked into dropping an executable file
1087 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101088 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291089 // We couldn't find a good extension for this content type. Use a dummy
1090 // extension instead.
1091 extension.assign(default_extension);
1092 }
1093 }
1094
1095 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101096 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291097 } else {
[email protected]6cade212008-12-03 00:32:221098 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291099 // 1. New extension is not ".txt"
1100 // 2. New extension is not the same as the already existing extension.
1101 // 3. New extension is not executable. This action mitigates the case when
1102 // an execuatable is hidden in a benign file extension;
1103 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1104 // application/x-javascript.
1105 std::wstring append_extension;
[email protected]a9bb6f692008-07-30 16:40:101106 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
initial.commit09911bf2008-07-26 23:55:291107 if (append_extension != L".txt" && append_extension != extension &&
1108 !IsExecutable(append_extension))
1109 extension += append_extension;
1110 }
1111 }
1112
1113 generated_extension->swap(extension);
1114}
1115
1116void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
1117 std::wstring* generated_name) {
1118 std::wstring file_name =
[email protected]8ac1a752008-07-31 19:40:371119 net::GetSuggestedFilename(GURL(info->url),
1120 info->content_disposition,
1121 L"download");
initial.commit09911bf2008-07-26 23:55:291122 DCHECK(!file_name.empty());
1123
1124 // Make sure we get the right file extension.
1125 std::wstring extension;
1126 GenerateExtension(file_name, info->mime_type, &extension);
1127 file_util::ReplaceExtension(&file_name, extension);
1128
1129 // Prepend "_" to the file name if it's a reserved name
1130 if (win_util::IsReservedName(file_name))
1131 file_name = std::wstring(L"_") + file_name;
1132
1133 generated_name->assign(file_name);
1134}
1135
1136void DownloadManager::AddObserver(Observer* observer) {
1137 observers_.AddObserver(observer);
1138 observer->ModelChanged();
1139}
1140
1141void DownloadManager::RemoveObserver(Observer* observer) {
1142 observers_.RemoveObserver(observer);
1143}
1144
1145// Post Windows Shell operations to the Download thread, to avoid blocking the
1146// user interface.
1147void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1148 DCHECK(file_manager_);
1149 file_loop_->PostTask(FROM_HERE,
1150 NewRunnableMethod(file_manager_,
1151 &DownloadFileManager::OnShowDownloadInShell,
1152 download->full_path()));
1153}
1154
1155void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
1156 HWND parent_window) {
1157 DCHECK(file_manager_);
1158 file_loop_->PostTask(FROM_HERE,
1159 NewRunnableMethod(file_manager_,
1160 &DownloadFileManager::OnOpenDownloadInShell,
1161 download->full_path(), download->url(), parent_window));
1162}
1163
1164void DownloadManager::OpenFilesOfExtension(const std::wstring& extension,
1165 bool open) {
1166 if (open && !IsExecutable(extension))
1167 auto_open_.insert(extension);
1168 else
1169 auto_open_.erase(extension);
1170 SaveAutoOpens();
1171}
1172
1173bool DownloadManager::ShouldOpenFileExtension(const std::wstring& extension) {
1174 if (!IsExecutable(extension) &&
1175 auto_open_.find(extension) != auto_open_.end())
1176 return true;
1177 return false;
1178}
1179
[email protected]7b73d992008-12-15 20:56:461180static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291181 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461182 "text/javascript",
1183 "text/javascript;version=*",
[email protected]60ff8f912008-12-05 07:58:391184 // Some sites use binary/octet-stream to mean application/octet-stream.
1185 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461186 "binary/octet-stream"
1187};
initial.commit09911bf2008-07-26 23:55:291188
[email protected]7b73d992008-12-15 20:56:461189static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291190 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461191 "application/*+xml",
1192 "application/xml"
1193};
initial.commit09911bf2008-07-26 23:55:291194
[email protected]7b73d992008-12-15 20:56:461195// static
1196bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
1197 for (int i=0; i < arraysize(kExecutableWhiteList); ++i) {
1198 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1199 return true;
1200 }
1201 for (int i=0; i < arraysize(kExecutableBlackList); ++i) {
1202 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1203 return false;
1204 }
1205 // We consider only other application types to be executable.
1206 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291207}
1208
1209bool DownloadManager::IsExecutable(const std::wstring& extension) {
1210 return exe_types_.find(extension) != exe_types_.end();
1211}
1212
1213void DownloadManager::ResetAutoOpenFiles() {
1214 auto_open_.clear();
1215 SaveAutoOpens();
1216}
1217
1218bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1219 return !auto_open_.empty();
1220}
1221
1222void DownloadManager::SaveAutoOpens() {
1223 PrefService* prefs = profile_->GetPrefs();
1224 if (prefs) {
1225 std::wstring extensions;
1226 for (std::set<std::wstring>::iterator it = auto_open_.begin();
1227 it != auto_open_.end(); ++it) {
1228 extensions += *it + L":";
1229 }
1230 if (!extensions.empty())
1231 extensions.erase(extensions.size() - 1);
1232 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions);
1233 }
1234}
1235
1236void DownloadManager::FileSelected(const std::wstring& path, void* params) {
1237 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071238 if (info->save_as)
initial.commit09911bf2008-07-26 23:55:291239 last_download_path_ = file_util::GetDirectoryFromPath(path);
1240 ContinueStartDownload(info, path);
1241}
1242
1243void DownloadManager::FileSelectionCanceled(void* params) {
1244 // The user didn't pick a place to save the file, so need to cancel the
1245 // download that's already in progress to the temporary location.
1246 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
1247 file_loop_->PostTask(FROM_HERE,
1248 NewRunnableMethod(file_manager_, &DownloadFileManager::CancelDownload,
1249 info->download_id));
1250}
1251
[email protected]9ccbb372008-10-10 18:50:321252void DownloadManager::DeleteDownload(const std::wstring& path) {
1253 file_loop_->PostTask(FROM_HERE, NewRunnableMethod(
1254 file_manager_, &DownloadFileManager::DeleteFile, path));
1255}
1256
1257
1258void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1259 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1260 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1261 download->UpdateObservers();
1262
1263 // If the download is not complete, nothing to do. The required
1264 // post-processing will be performed when it does complete.
1265 if (download->state() != DownloadItem::COMPLETE)
1266 return;
1267
1268 file_loop_->PostTask(FROM_HERE,
1269 NewRunnableMethod(this,
1270 &DownloadManager::ProceedWithFinishedDangerousDownload,
1271 download->db_handle(), download->full_path(),
1272 download->original_name()));
1273}
1274
initial.commit09911bf2008-07-26 23:55:291275// Operations posted to us from the history service ----------------------------
1276
1277// The history service has retrieved all download entries. 'entries' contains
1278// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1279void DownloadManager::OnQueryDownloadEntriesComplete(
1280 std::vector<DownloadCreateInfo>* entries) {
1281 for (size_t i = 0; i < entries->size(); ++i) {
1282 DownloadItem* download = new DownloadItem(entries->at(i));
1283 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1284 downloads_[download->db_handle()] = download;
1285 download->set_manager(this);
1286 }
1287 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1288}
1289
1290
1291// Once the new DownloadItem's creation info has been committed to the history
1292// service, we associate the DownloadItem with the db handle, update our
1293// 'downloads_' map and inform observers.
1294void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1295 int64 db_handle) {
1296 DownloadMap::iterator it = in_progress_.find(info.download_id);
1297 DCHECK(it != in_progress_.end());
1298
1299 DownloadItem* download = it->second;
1300 DCHECK(download->db_handle() == kUninitializedHandle);
1301 download->set_db_handle(db_handle);
1302
1303 // Insert into our full map.
1304 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1305 downloads_[download->db_handle()] = download;
1306
1307 // The 'contents' may no longer exist if the user closed the tab before we get
1308 // this start completion event. If it does, tell the origin WebContents to
1309 // display its download shelf.
1310 TabContents* contents =
1311 tab_util::GetTabContentsByID(info.render_process_id, info.render_view_id);
1312
1313 // If the contents no longer exists or is no longer active, we start the
1314 // download in the last active browser. This is not ideal but better than
1315 // fully hiding the download from the user. Note: non active means that the
1316 // user navigated away from the tab contents. This has nothing to do with
1317 // tab selection.
1318 if (!contents || !contents->is_active()) {
1319 Browser* last_active = BrowserList::GetLastActive();
1320 if (last_active)
1321 contents = last_active->GetSelectedTabContents();
1322 }
1323
1324 if (contents)
1325 contents->OnStartDownload(download);
1326
1327 // Inform interested objects about the new download.
1328 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1329 NotifyAboutDownloadStart();
1330
1331 // If this download has been completed before we've received the db handle,
1332 // post one final message to the history service so that it can be properly
1333 // in sync with the DownloadItem's completion status, and also inform any
1334 // observers so that they get more than just the start notification.
1335 if (download->state() != DownloadItem::IN_PROGRESS) {
1336 in_progress_.erase(it);
1337 NotifyAboutDownloadStop();
1338 UpdateHistoryForDownload(download);
1339 download->UpdateObservers();
1340 }
1341}
1342
1343// Called when the history service has retrieved the list of downloads that
1344// match the search text.
1345void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1346 std::vector<int64>* results) {
1347 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1348 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1349 if (!requestor)
1350 return;
1351
1352 std::vector<DownloadItem*> searched_downloads;
1353 for (std::vector<int64>::iterator it = results->begin();
1354 it != results->end(); ++it) {
1355 DownloadMap::iterator dit = downloads_.find(*it);
1356 if (dit != downloads_.end())
1357 searched_downloads.push_back(dit->second);
1358 }
1359
1360 requestor->SetDownloads(searched_downloads);
1361}
[email protected]905a08d2008-11-19 07:24:121362
[email protected]6cade212008-12-03 00:32:221363// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121364void DownloadManager::ClearLastDownloadPath() {
1365 last_download_path_.clear();
1366}