blob: 97dc7ac86bee5ef11a7d579ce746a55e2e8f6f10 [file] [log] [blame]
[email protected]21ca982c2010-01-26 22:49:551// Copyright (c) 2010 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]cdaa8652008-09-13 02:48:595#include "chrome/browser/download/download_manager.h"
initial.commit09911bf2008-07-26 23:55:296
[email protected]a92b8642009-05-05 23:38:567#include "app/l10n_util.h"
[email protected]21ca982c2010-01-26 22:49:558#include "app/resource_bundle.h"
[email protected]2041cf342010-02-19 03:15:599#include "base/callback.h"
initial.commit09911bf2008-07-26 23:55:2910#include "base/file_util.h"
11#include "base/logging.h"
initial.commit09911bf2008-07-26 23:55:2912#include "base/path_service.h"
[email protected]1b5044d2009-02-24 00:04:1413#include "base/rand_util.h"
[email protected]1b5044d2009-02-24 00:04:1414#include "base/sys_string_conversions.h"
initial.commit09911bf2008-07-26 23:55:2915#include "base/task.h"
[email protected]d2a8fb72010-01-21 05:31:4216#include "build/build_config.h"
[email protected]6c69796d2010-07-16 21:41:1617#include "chrome/browser/browser.h"
initial.commit09911bf2008-07-26 23:55:2918#include "chrome/browser/browser_list.h"
19#include "chrome/browser/browser_process.h"
[email protected]d83d03aa2009-11-02 21:44:3720#include "chrome/browser/chrome_thread.h"
[email protected]6c69796d2010-07-16 21:41:1621#include "chrome/browser/download/download_file_manager.h"
22#include "chrome/browser/download/download_item.h"
[email protected]e9ef0a62009-08-11 22:50:1323#include "chrome/browser/download/download_util.h"
[email protected]866930682009-08-18 22:53:4724#include "chrome/browser/extensions/crx_installer.h"
[email protected]2a464a92009-08-01 17:58:3525#include "chrome/browser/extensions/extension_install_ui.h"
[email protected]8f783752009-04-01 23:33:4526#include "chrome/browser/extensions/extensions_service.h"
[email protected]6c69796d2010-07-16 21:41:1627#include "chrome/browser/history/download_types.h"
[email protected]be180c802009-10-23 06:33:3128#include "chrome/browser/net/chrome_url_request_context.h"
[email protected]14a000d2010-04-29 21:44:2429#include "chrome/browser/platform_util.h"
initial.commit09911bf2008-07-26 23:55:2930#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:2631#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2532#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]21ca982c2010-01-26 22:49:5533#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]57c6a652009-05-04 07:58:3434#include "chrome/browser/tab_contents/tab_contents.h"
[email protected]d2a8fb72010-01-21 05:31:4235#include "chrome/browser/tab_contents/tab_util.h"
initial.commit09911bf2008-07-26 23:55:2936#include "chrome/common/chrome_paths.h"
[email protected]91e1bd82009-09-03 22:04:4037#include "chrome/common/notification_service.h"
38#include "chrome/common/notification_type.h"
initial.commit09911bf2008-07-26 23:55:2939#include "chrome/common/pref_names.h"
[email protected]46072d42008-07-28 14:49:3540#include "googleurl/src/gurl.h"
[email protected]34ac8f32009-02-22 23:03:2741#include "grit/generated_resources.h"
[email protected]21ca982c2010-01-26 22:49:5542#include "grit/theme_resources.h"
initial.commit09911bf2008-07-26 23:55:2943#include "net/base/mime_util.h"
44#include "net/base/net_util.h"
initial.commit09911bf2008-07-26 23:55:2945
[email protected]b7f05882009-02-22 01:21:5646#if defined(OS_WIN)
[email protected]4a0765a2009-05-08 23:12:2547#include "app/win_util.h"
[email protected]b7f05882009-02-22 01:21:5648#include "base/registry.h"
49#include "base/win_util.h"
[email protected]a0a9577b2009-05-27 23:52:3250#endif
51
[email protected]21ca982c2010-01-26 22:49:5552namespace {
53
[email protected]b0ab1d42010-02-24 19:29:2854// Used to sort download items based on descending start time.
55bool CompareStartTime(DownloadItem* first, DownloadItem* second) {
56 return first->start_time() > second->start_time();
57}
58
[email protected]da74e5ae22010-07-14 16:12:3759void DeleteDownloadedFile(const FilePath& path) {
60 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));
61
62 // Make sure we only delete files.
63 if (!file_util::DirectoryExists(path))
64 file_util::Delete(path, false);
65}
66
[email protected]21ca982c2010-01-26 22:49:5567} // namespace
68
[email protected]6c69796d2010-07-16 21:41:1669// Our download table ID starts at 1, so we use 0 to represent a download that
70// has started, but has not yet had its data persisted in the table. We use fake
71// database handles in incognito mode starting at -1 and progressively getting
72// more negative.
73// static
74const int DownloadManager::kUninitializedHandle = 0;
initial.commit09911bf2008-07-26 23:55:2975
76// static
77void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
78 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
[email protected]20ce516d2010-06-18 02:20:0479 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, "");
[email protected]f052118e2008-09-05 02:25:3280 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
81
82 // The default download path is userprofile\download.
[email protected]290c9702010-03-09 04:01:3683 const FilePath& default_download_path =
84 download_util::GetDefaultDownloadDirectory();
[email protected]b9636002009-03-04 00:05:2585 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
86 default_download_path);
[email protected]f052118e2008-09-05 02:25:3287
88 // If the download path is dangerous we forcefully reset it. But if we do
89 // so we set a flag to make sure we only do it once, to avoid fighting
90 // the user if he really wants it on an unsafe place such as the desktop.
91
92 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]38233e62010-04-26 04:43:3693 FilePath current_download_dir = prefs->GetFilePath(
94 prefs::kDownloadDefaultDirectory);
[email protected]290c9702010-03-09 04:01:3695 if (download_util::DownloadPathIsDangerous(current_download_dir)) {
[email protected]38233e62010-04-26 04:43:3696 prefs->SetFilePath(prefs::kDownloadDefaultDirectory,
97 default_download_path);
[email protected]f052118e2008-09-05 02:25:3298 }
99 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
100 }
initial.commit09911bf2008-07-26 23:55:29101}
102
103DownloadManager::DownloadManager()
104 : shutdown_needed_(false),
105 profile_(NULL),
[email protected]d2a8fb72010-01-21 05:31:42106 file_manager_(NULL),
107 fake_db_handle_(kUninitializedHandle - 1) {
initial.commit09911bf2008-07-26 23:55:29108}
109
110DownloadManager::~DownloadManager() {
[email protected]b0ab1d42010-02-24 19:29:28111 FOR_EACH_OBSERVER(Observer, observers_, ManagerGoingDown());
112
initial.commit09911bf2008-07-26 23:55:29113 if (shutdown_needed_)
114 Shutdown();
115}
116
117void DownloadManager::Shutdown() {
118 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
119
120 // Stop receiving download updates
[email protected]2941c2392010-07-15 22:54:30121 if (file_manager_)
122 file_manager_->RemoveDownloadManager(this);
initial.commit09911bf2008-07-26 23:55:29123
124 // Stop making history service requests
125 cancelable_consumer_.CancelAllRequests();
126
127 // 'in_progress_' may contain DownloadItems that have not finished the start
128 // complete (from the history service) and thus aren't in downloads_.
129 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32130 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29131 for (; it != in_progress_.end(); ++it) {
132 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32133 if (download->safety_state() == DownloadItem::DANGEROUS) {
134 // Forget about any download that the user did not approve.
135 // Note that we cannot call download->Remove() this would invalidate our
136 // iterator.
137 to_remove.insert(download);
138 continue;
initial.commit09911bf2008-07-26 23:55:29139 }
[email protected]9ccbb372008-10-10 18:50:32140 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
141 download->Cancel(false);
142 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29143 if (download->db_handle() == kUninitializedHandle) {
144 // An invalid handle means that 'download' does not yet exist in
145 // 'downloads_', so we have to delete it here.
146 delete download;
147 }
148 }
149
[email protected]9ccbb372008-10-10 18:50:32150 // 'dangerous_finished_' contains all complete downloads that have not been
151 // approved. They should be removed.
152 it = dangerous_finished_.begin();
153 for (; it != dangerous_finished_.end(); ++it)
154 to_remove.insert(it->second);
155
156 // Remove the dangerous download that are not approved.
157 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
158 rm_it != to_remove.end(); ++rm_it) {
159 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32160 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32161 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32162 // Same as above, delete the download if it is not in 'downloads_' (as the
163 // Remove() call above won't have deleted it).
164 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32165 delete download;
166 }
167 to_remove.clear();
168
initial.commit09911bf2008-07-26 23:55:29169 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32170 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29171 STLDeleteValues(&downloads_);
172
173 file_manager_ = NULL;
174
175 // Save our file extensions to auto open.
176 SaveAutoOpens();
177
178 // Make sure the save as dialog doesn't notify us back if we're gone before
179 // it returns.
180 if (select_file_dialog_.get())
181 select_file_dialog_->ListenerDestroyed();
182
183 shutdown_needed_ = false;
184}
185
186// Issue a history query for downloads matching 'search_text'. If 'search_text'
187// is empty, return all downloads that we know about.
188void DownloadManager::GetDownloads(Observer* observer,
189 const std::wstring& search_text) {
[email protected]b0ab1d42010-02-24 19:29:28190 std::vector<DownloadItem*> otr_downloads;
191
192 if (profile_->IsOffTheRecord() && search_text.empty()) {
193 // List all incognito downloads and add that to the downloads the parent
194 // profile lists.
195 otr_downloads.reserve(downloads_.size());
196 for (DownloadMap::iterator it = downloads_.begin();
197 it != downloads_.end(); ++it) {
198 DownloadItem* download = it->second;
199 if (download->is_otr() && !download->is_extension_install() &&
200 !download->is_temporary()) {
201 otr_downloads.push_back(download);
202 }
203 }
204 }
205
206 profile_->GetOriginalProfile()->GetDownloadManager()->
207 DoGetDownloads(observer, search_text, otr_downloads);
208}
209
210void DownloadManager::DoGetDownloads(
211 Observer* observer,
212 const std::wstring& search_text,
213 std::vector<DownloadItem*>& otr_downloads) {
initial.commit09911bf2008-07-26 23:55:29214 DCHECK(observer);
215
216 // Return a empty list if we've not yet received the set of downloads from the
217 // history system (we'll update all observers once we get that list in
218 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
initial.commit09911bf2008-07-26 23:55:29219 if (downloads_.empty()) {
[email protected]b0ab1d42010-02-24 19:29:28220 observer->SetDownloads(otr_downloads);
initial.commit09911bf2008-07-26 23:55:29221 return;
222 }
223
[email protected]b0ab1d42010-02-24 19:29:28224 std::vector<DownloadItem*> download_copy;
initial.commit09911bf2008-07-26 23:55:29225 // We already know all the downloads and there is no filter, so just return a
226 // copy to the observer.
227 if (search_text.empty()) {
228 download_copy.reserve(downloads_.size());
229 for (DownloadMap::iterator it = downloads_.begin();
230 it != downloads_.end(); ++it) {
[email protected]67f373a2009-09-22 02:44:51231 if (it->second->db_handle() > kUninitializedHandle)
232 download_copy.push_back(it->second);
initial.commit09911bf2008-07-26 23:55:29233 }
234
[email protected]b0ab1d42010-02-24 19:29:28235 // Merge sort based on start time.
236 std::vector<DownloadItem*> merged_downloads;
237 std::merge(otr_downloads.begin(), otr_downloads.end(),
238 download_copy.begin(), download_copy.end(),
239 std::back_inserter(merged_downloads),
240 CompareStartTime);
241
initial.commit09911bf2008-07-26 23:55:29242 // We retain ownership of the DownloadItems.
[email protected]b0ab1d42010-02-24 19:29:28243 observer->SetDownloads(merged_downloads);
initial.commit09911bf2008-07-26 23:55:29244 return;
245 }
246
[email protected]b0ab1d42010-02-24 19:29:28247 DCHECK(otr_downloads.empty());
248
initial.commit09911bf2008-07-26 23:55:29249 // Issue a request to the history service for a list of downloads matching
250 // our search text.
251 HistoryService* hs =
252 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
253 if (hs) {
254 HistoryService::Handle h =
[email protected]e53668962010-06-23 15:35:25255 hs->SearchDownloads(WideToUTF16(search_text),
initial.commit09911bf2008-07-26 23:55:29256 &cancelable_consumer_,
257 NewCallback(this,
258 &DownloadManager::OnSearchComplete));
259 cancelable_consumer_.SetClientData(hs, h, observer);
260 }
261}
262
[email protected]6aa4a1c02010-01-15 18:49:58263void DownloadManager::GetTemporaryDownloads(Observer* observer,
264 const FilePath& dir_path) {
265 DCHECK(observer);
266
267 std::vector<DownloadItem*> download_copy;
268
269 for (DownloadMap::iterator it = downloads_.begin();
270 it != downloads_.end(); ++it) {
271 if (it->second->is_temporary() &&
272 it->second->full_path().DirName() == dir_path)
273 download_copy.push_back(it->second);
274 }
275
276 observer->SetDownloads(download_copy);
277}
278
[email protected]8ddbd66a2010-05-21 16:38:34279void DownloadManager::GetAllDownloads(Observer* observer,
280 const FilePath& dir_path) {
281 DCHECK(observer);
282
283 std::vector<DownloadItem*> download_copy;
284
285 for (DownloadMap::iterator it = downloads_.begin();
286 it != downloads_.end(); ++it) {
287 if (!it->second->is_temporary() &&
288 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
289 download_copy.push_back(it->second);
290 }
291
292 observer->SetDownloads(download_copy);
293}
294
[email protected]c4a530b2010-03-08 17:33:03295void DownloadManager::GetCurrentDownloads(Observer* observer,
296 const FilePath& dir_path) {
297 DCHECK(observer);
298
299 std::vector<DownloadItem*> download_copy;
300
301 for (DownloadMap::iterator it = downloads_.begin();
302 it != downloads_.end(); ++it) {
303 if (!it->second->is_temporary() &&
304 (it->second->state() == DownloadItem::IN_PROGRESS ||
305 it->second->safety_state() == DownloadItem::DANGEROUS) &&
306 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
307 download_copy.push_back(it->second);
308 }
309
310 observer->SetDownloads(download_copy);
311}
312
initial.commit09911bf2008-07-26 23:55:29313// Query the history service for information about all persisted downloads.
314bool DownloadManager::Init(Profile* profile) {
315 DCHECK(profile);
316 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
317 shutdown_needed_ = true;
318
319 profile_ = profile;
[email protected]be180c802009-10-23 06:33:31320 request_context_getter_ = profile_->GetRequestContext();
initial.commit09911bf2008-07-26 23:55:29321
322 // 'incognito mode' will have access to past downloads, but we won't store
323 // information about new downloads while in that mode.
324 QueryHistoryForDownloads();
325
[email protected]024f2f02010-04-30 22:51:46326 // Cleans up entries only when called for the first time. Subsequent calls are
327 // a no op.
328 CleanUpInProgressHistoryEntries();
329
[email protected]2941c2392010-07-15 22:54:30330 // In test mode, there may be no ResourceDispatcherHost. In this case it's
331 // safe to avoid setting |file_manager_| because we only call a small set of
332 // functions, none of which need it.
initial.commit09911bf2008-07-26 23:55:29333 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]2941c2392010-07-15 22:54:30334 if (rdh) {
335 file_manager_ = rdh->download_file_manager();
336 DCHECK(file_manager_);
initial.commit09911bf2008-07-26 23:55:29337 }
338
initial.commit09911bf2008-07-26 23:55:29339 // Get our user preference state.
340 PrefService* prefs = profile_->GetPrefs();
341 DCHECK(prefs);
342 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
343
initial.commit09911bf2008-07-26 23:55:29344 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
345
[email protected]bb69e9b32008-08-14 23:08:14346 // Ensure that the download directory specified in the preferences exists.
[email protected]d83d03aa2009-11-02 21:44:37347 ChromeThread::PostTask(
348 ChromeThread::FILE, FROM_HERE,
[email protected]309b7642009-12-09 03:08:50349 NewRunnableFunction(&file_util::CreateDirectory, download_path()));
initial.commit09911bf2008-07-26 23:55:29350
[email protected]2b2f8f72009-02-24 22:42:05351 // We store any file extension that should be opened automatically at
352 // download completion in this pref.
[email protected]ddd231e2010-06-29 20:35:19353 std::string extensions_to_open =
initial.commit09911bf2008-07-26 23:55:29354 prefs->GetString(prefs::kDownloadExtensionsToOpen);
[email protected]ddd231e2010-06-29 20:35:19355 std::vector<std::string> extensions;
356 SplitString(extensions_to_open, ':', &extensions);
357
initial.commit09911bf2008-07-26 23:55:29358 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]ddd231e2010-06-29 20:35:19359#if defined(OS_POSIX)
360 FilePath path(extensions[i]);
361#elif defined(OS_WIN)
362 FilePath path(UTF8ToWide(extensions[i]));
363#endif
364 if (!extensions[i].empty() && !IsExecutableFile(path))
365 auto_open_.insert(path.value());
initial.commit09911bf2008-07-26 23:55:29366 }
367
[email protected]b0ab1d42010-02-24 19:29:28368 other_download_manager_observer_.reset(
369 new OtherDownloadManagerObserver(this));
370
initial.commit09911bf2008-07-26 23:55:29371 return true;
372}
373
374void DownloadManager::QueryHistoryForDownloads() {
375 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
376 if (hs) {
377 hs->QueryDownloads(
378 &cancelable_consumer_,
379 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
380 }
381}
382
[email protected]024f2f02010-04-30 22:51:46383void DownloadManager::CleanUpInProgressHistoryEntries() {
384 static bool already_cleaned_up = false;
385
386 if (!already_cleaned_up) {
387 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
388 if (hs) {
389 hs->CleanUpInProgressEntries();
390 already_cleaned_up = true;
391 }
392 }
393}
394
initial.commit09911bf2008-07-26 23:55:29395// We have received a message from DownloadFileManager about a new download. We
396// create a download item and store it in our download map, and inform the
397// history system of a new download. Since this method can be called while the
398// history service thread is still reading the persistent state, we do not
399// insert the new DownloadItem into 'downloads_' or inform our observers at this
400// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
401// download creation as a callback from the history thread.
402void DownloadManager::StartDownload(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37403 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29404 DCHECK(info);
405
[email protected]a60c8ae2009-12-25 06:50:57406 // Check whether this download is for an extension install or not.
[email protected]e6875c12010-07-18 11:14:13407 // Allow extensions to be explicitly saved.
408 if (!info->prompt_user_for_save_location) {
[email protected]a60c8ae2009-12-25 06:50:57409 if (UserScript::HasUserScriptFileExtension(info->url) ||
410 info->mime_type == Extension::kMimeType)
411 info->is_extension_install = true;
412 }
413
[email protected]8af9d032010-02-10 00:00:32414 if (info->save_info.file_path.empty()) {
[email protected]2941c2392010-07-15 22:54:30415 FilePath generated_name;
416 GenerateFileNameFromInfo(info, &generated_name);
417
418 // Freeze the user's preference for showing a Save As dialog. We're going
419 // to bounce around a bunch of threads and we don't want to worry about race
420 // conditions where the user changes this pref out from under us.
421 if (*prompt_for_download_) {
422 // But ignore the user's preference for the following scenarios:
423 // 1) Extension installation. Note that we only care here about the case
424 // where an extension is installed, not when one is downloaded with
425 // "save as...".
426 // 2) Filetypes marked "always open." If the user just wants this file
427 // opened, don't bother asking where to keep it.
428 if (!info->is_extension_install &&
429 !ShouldOpenFileBasedOnExtension(generated_name))
[email protected]e6875c12010-07-18 11:14:13430 info->prompt_user_for_save_location = true;
[email protected]2941c2392010-07-15 22:54:30431 }
432
[email protected]8af9d032010-02-10 00:00:32433 // Determine the proper path for a download, by either one of the following:
434 // 1) using the default download directory.
435 // 2) prompting the user.
[email protected]e6875c12010-07-18 11:14:13436 if (info->prompt_user_for_save_location && !last_download_path_.empty())
[email protected]8af9d032010-02-10 00:00:32437 info->suggested_path = last_download_path_;
438 else
439 info->suggested_path = download_path();
440 info->suggested_path = info->suggested_path.Append(generated_name);
441 } else {
442 info->suggested_path = info->save_info.file_path;
443 }
initial.commit09911bf2008-07-26 23:55:29444
[email protected]e6875c12010-07-18 11:14:13445 if (!info->prompt_user_for_save_location &&
446 info->save_info.file_path.empty()) {
[email protected]4289d9b2009-07-25 21:17:34447 // Downloads can be marked as dangerous for two reasons:
448 // a) They have a dangerous-looking filename
449 // b) They are an extension that is not from the gallery
450 if (IsDangerous(info->suggested_path.BaseName()))
451 info->is_dangerous = true;
[email protected]a60c8ae2009-12-25 06:50:57452 else if (info->is_extension_install &&
[email protected]b7c2f252009-12-08 00:47:23453 !ExtensionsService::IsDownloadFromGallery(info->url,
454 info->referrer_url)) {
[email protected]4289d9b2009-07-25 21:17:34455 info->is_dangerous = true;
456 }
[email protected]e9ebf3fc2008-10-17 22:06:58457 }
458
initial.commit09911bf2008-07-26 23:55:29459 // We need to move over to the download thread because we don't want to stat
460 // the suggested path on the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37461 ChromeThread::PostTask(
462 ChromeThread::FILE, FROM_HERE,
463 NewRunnableMethod(
464 this, &DownloadManager::CheckIfSuggestedPathExists, info));
initial.commit09911bf2008-07-26 23:55:29465}
466
467void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
468 DCHECK(info);
469
470 // Check writability of the suggested path. If we can't write to it, default
471 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41472 FilePath dir = info->suggested_path.DirName();
473 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32474 if (!file_util::PathIsWritable(dir)) {
[email protected]e6875c12010-07-18 11:14:13475 info->prompt_user_for_save_location = true;
initial.commit09911bf2008-07-26 23:55:29476 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41477 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29478 }
479
[email protected]8af9d032010-02-10 00:00:32480 // Do not add the path uniquifier if we are saving to a specific path as in
481 // the drag-out case.
[email protected]5a2388a2010-03-26 16:13:39482 if (info->save_info.file_path.empty()) {
483 info->path_uniquifier = download_util::GetUniquePathNumber(
484 info->suggested_path);
485 }
initial.commit09911bf2008-07-26 23:55:29486
[email protected]6cade212008-12-03 00:32:22487 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58488 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41489 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32490 // Create a temporary file to hold the file until the user approves its
491 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41492 FilePath::StringType file_name;
493 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32494 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41495 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32496 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41497 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07498 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41499 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32500 }
501 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16502 } else {
503 // We know the final path, build it if necessary.
504 if (info->path_uniquifier > 0) {
[email protected]5a2388a2010-03-26 16:13:39505 download_util::AppendNumberToPath(&(info->suggested_path),
506 info->path_uniquifier);
[email protected]7a256ea2008-10-17 17:34:16507 // Setting path_uniquifier to 0 to make sure we don't try to unique it
508 // later on.
509 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07510 } else if (info->path_uniquifier == -1) {
511 // We failed to find a unique path. We have to prompt the user.
[email protected]e6875c12010-07-18 11:14:13512 info->prompt_user_for_save_location = true;
[email protected]7a256ea2008-10-17 17:34:16513 }
[email protected]9ccbb372008-10-10 18:50:32514 }
515
[email protected]e6875c12010-07-18 11:14:13516 if (!info->prompt_user_for_save_location &&
517 info->save_info.file_path.empty()) {
[email protected]7d3851d82008-12-12 03:26:07518 // Create an empty file at the suggested path so that we don't allocate the
519 // same "non-existant" path to multiple downloads.
520 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ff3f632009-10-13 18:43:35521 file_util::WriteFile(info->suggested_path, "", 0);
[email protected]7d3851d82008-12-12 03:26:07522 }
523
initial.commit09911bf2008-07-26 23:55:29524 // Now we return to the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37525 ChromeThread::PostTask(
526 ChromeThread::UI, FROM_HERE,
initial.commit09911bf2008-07-26 23:55:29527 NewRunnableMethod(this,
528 &DownloadManager::OnPathExistenceAvailable,
529 info));
530}
531
532void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37533 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29534 DCHECK(info);
535
[email protected]e6875c12010-07-18 11:14:13536 if (info->prompt_user_for_save_location) {
initial.commit09911bf2008-07-26 23:55:29537 // We must ask the user for the place to put the download.
538 if (!select_file_dialog_.get())
539 select_file_dialog_ = SelectFileDialog::Create(this);
540
[email protected]76543b92009-08-31 17:27:45541 TabContents* contents = tab_util::GetTabContentsByID(info->child_id,
542 info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08543 SelectFileDialog::FileTypeInfo file_type_info;
544 file_type_info.extensions.resize(1);
545 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24546 if (!file_type_info.extensions[0][0].empty())
547 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08548 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23549 gfx::NativeWindow owning_window =
550 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29551 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34552 string16(),
553 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08554 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30555 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29556 } else {
557 // No prompting for download, just continue with the suggested name.
558 ContinueStartDownload(info, info->suggested_path);
559 }
560}
561
562void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41563 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29564 scoped_ptr<DownloadCreateInfo> infop(info);
565 info->path = target_path;
566
567 DownloadItem* download = NULL;
568 DownloadMap::iterator it = in_progress_.find(info->download_id);
569 if (it == in_progress_.end()) {
570 download = new DownloadItem(info->download_id,
571 info->path,
[email protected]7a256ea2008-10-17 17:34:16572 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29573 info->url,
[email protected]494c06e2009-07-25 01:06:42574 info->referrer_url,
[email protected]e435d6b72009-07-25 03:15:58575 info->mime_type,
[email protected]d4a71882010-06-25 16:36:41576 info->original_mime_type,
[email protected]9ccbb372008-10-10 18:50:32577 info->original_name,
initial.commit09911bf2008-07-26 23:55:29578 info->start_time,
579 info->total_bytes,
[email protected]76543b92009-08-31 17:27:45580 info->child_id,
[email protected]9ccbb372008-10-10 18:50:32581 info->request_id,
[email protected]67f373a2009-09-22 02:44:51582 info->is_dangerous,
[email protected]e6875c12010-07-18 11:14:13583 info->prompt_user_for_save_location,
[email protected]b0ab1d42010-02-24 19:29:28584 profile_->IsOffTheRecord(),
[email protected]6aa4a1c02010-01-15 18:49:58585 info->is_extension_install,
[email protected]8af9d032010-02-10 00:00:32586 !info->save_info.file_path.empty());
initial.commit09911bf2008-07-26 23:55:29587 download->set_manager(this);
588 in_progress_[info->download_id] = download;
589 } else {
590 NOTREACHED(); // Should not exist!
591 return;
592 }
593
[email protected]6b323782009-03-27 18:43:08594 // Called before DownloadFinished in order to avoid a race condition where we
595 // attempt to open a completed download before it has been renamed.
[email protected]d83d03aa2009-11-02 21:44:37596 ChromeThread::PostTask(
597 ChromeThread::FILE, FROM_HERE,
598 NewRunnableMethod(
599 file_manager_, &DownloadFileManager::OnFinalDownloadName,
600 download->id(), target_path, this));
[email protected]6b323782009-03-27 18:43:08601
initial.commit09911bf2008-07-26 23:55:29602 // If the download already completed by the time we reached this point, then
603 // notify observers that it did.
604 PendingFinishedMap::iterator pending_it =
605 pending_finished_downloads_.find(info->download_id);
606 if (pending_it != pending_finished_downloads_.end())
607 DownloadFinished(pending_it->first, pending_it->second);
608
609 download->Rename(target_path);
610
[email protected]67f373a2009-09-22 02:44:51611 // Do not store the download in the history database for a few special cases:
612 // - incognito mode (that is the point of this mode)
613 // - extensions (users don't think of extension installation as 'downloading')
[email protected]6aa4a1c02010-01-15 18:49:58614 // - temporary download, like in drag-and-drop
[email protected]67f373a2009-09-22 02:44:51615 // We have to make sure that these handles don't collide with normal db
616 // handles, so we use a negative value. Eventually, they could overlap, but
617 // you'd have to do enough downloading that your ISP would likely stab you in
618 // the neck first. YMMV.
[email protected]b0ab1d42010-02-24 19:29:28619 if (download->is_otr() || download->is_extension_install() ||
[email protected]6aa4a1c02010-01-15 18:49:58620 download->is_temporary()) {
[email protected]d2a8fb72010-01-21 05:31:42621 OnCreateDownloadEntryComplete(*info, fake_db_handle_.GetNext());
initial.commit09911bf2008-07-26 23:55:29622 } else {
623 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22624 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29625 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
626 if (hs) {
627 hs->CreateDownload(
628 *info, &cancelable_consumer_,
629 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
630 }
631 }
[email protected]6a7fb042010-02-01 16:30:47632
633 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:29634}
635
636// Convenience function for updating the history service for a download.
637void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
638 DCHECK(download);
639
640 // Don't store info in the database if the download was initiated while in
641 // incognito mode or if it hasn't been initialized in our database table.
642 if (download->db_handle() <= kUninitializedHandle)
643 return;
644
[email protected]6cade212008-12-03 00:32:22645 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29646 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
647 if (hs) {
648 hs->UpdateDownload(download->received_bytes(),
649 download->state(),
650 download->db_handle());
651 }
652}
653
654void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
655 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22656 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29657 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
658 if (download->db_handle() > kUninitializedHandle && hs)
659 hs->RemoveDownload(download->db_handle());
660}
661
[email protected]e93d2822009-01-30 05:59:59662void DownloadManager::RemoveDownloadsFromHistoryBetween(
663 const base::Time remove_begin,
664 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22665 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29666 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
667 if (hs)
668 hs->RemoveDownloadsBetween(remove_begin, remove_end);
669}
670
671void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
672 DownloadMap::iterator it = in_progress_.find(download_id);
673 if (it != in_progress_.end()) {
674 DownloadItem* download = it->second;
675 download->Update(size);
676 UpdateHistoryForDownload(download);
677 }
[email protected]6a7fb042010-02-01 16:30:47678 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:29679}
680
681void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
682 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32683 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29684 // The download is done, but the user hasn't selected a final location for
685 // it yet (the Save As dialog box is probably still showing), so just keep
686 // track of the fact that this download id is complete, when the
687 // DownloadItem is constructed later we'll notify its completion then.
688 PendingFinishedMap::iterator erase_it =
689 pending_finished_downloads_.find(download_id);
690 DCHECK(erase_it == pending_finished_downloads_.end());
691 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32692 return;
initial.commit09911bf2008-07-26 23:55:29693 }
[email protected]9ccbb372008-10-10 18:50:32694
695 // Remove the id from the list of pending ids.
696 PendingFinishedMap::iterator erase_it =
697 pending_finished_downloads_.find(download_id);
698 if (erase_it != pending_finished_downloads_.end())
699 pending_finished_downloads_.erase(erase_it);
700
701 DownloadItem* download = it->second;
702 download->Finished(size);
703
704 // Clean up will happen when the history system create callback runs if we
705 // don't have a valid db_handle yet.
706 if (download->db_handle() != kUninitializedHandle) {
707 in_progress_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32708 UpdateHistoryForDownload(download);
709 }
710
[email protected]6a7fb042010-02-01 16:30:47711 UpdateAppIcon();
712
[email protected]9ccbb372008-10-10 18:50:32713 // If this a dangerous download not yet validated by the user, don't do
714 // anything. When the user notifies us, it will trigger a call to
715 // ProceedWithFinishedDangerousDownload.
716 if (download->safety_state() == DownloadItem::DANGEROUS) {
717 dangerous_finished_[download_id] = download;
718 return;
719 }
720
721 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22722 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32723 // its final name before we can continue.
[email protected]d83d03aa2009-11-02 21:44:37724 ChromeThread::PostTask(
725 ChromeThread::FILE, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32726 NewRunnableMethod(
727 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
728 download->db_handle(),
729 download->full_path(), download->original_name()));
730 return;
731 }
732 ContinueDownloadFinished(download);
733}
734
[email protected]8f783752009-04-01 23:33:45735void DownloadManager::DownloadRenamedToFinalName(int download_id,
736 const FilePath& full_path) {
[email protected]6aa4a1c02010-01-15 18:49:58737 DownloadMap::iterator it = downloads_.begin();
738 while (it != downloads_.end()) {
739 DownloadItem* download = it->second;
740 if (download->id() == download_id) {
741 // The download file is meant to be completed if both the filename is
742 // finalized and the file data is downloaded. The ordering of these two
743 // actions is indeterministic. Thus, if we are still in downloading the
744 // file, delay the notification.
745 download->set_name_finalized(true);
746 if (download->state() == DownloadItem::COMPLETE)
747 download->NotifyObserversDownloadFileCompleted();
748 return;
749 }
750 it++;
751 }
[email protected]8f783752009-04-01 23:33:45752}
753
[email protected]9ccbb372008-10-10 18:50:32754void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
755 // If this was a dangerous download, it has now been approved and must be
756 // removed from dangerous_finished_ so it does not get deleted on shutdown.
757 DownloadMap::iterator it = dangerous_finished_.find(download->id());
758 if (it != dangerous_finished_.end())
759 dangerous_finished_.erase(it);
760
[email protected]0aad67b2009-07-15 20:34:28761 // Handle chrome extensions explicitly and skip the shell execute.
[email protected]a60c8ae2009-12-25 06:50:57762 if (download->is_extension_install()) {
[email protected]d4a71882010-06-25 16:36:41763 OpenChromeExtension(download->full_path(),
764 download->url(),
765 download->referrer_url(),
766 download->original_mime_type());
[email protected]0aad67b2009-07-15 20:34:28767 download->set_auto_opened(true);
768 } else if (download->open_when_complete() ||
[email protected]6aa4a1c02010-01-15 18:49:58769 ShouldOpenFileBasedOnExtension(download->full_path()) ||
770 download->is_temporary()) {
771 // If the download is temporary, like in drag-and-drop, do not open it but
772 // we still need to set it auto-opened so that it can be removed from the
773 // download shelf.
774 if (!download->is_temporary())
775 OpenDownloadInShell(download, NULL);
[email protected]0aad67b2009-07-15 20:34:28776 download->set_auto_opened(true);
777 }
[email protected]9ccbb372008-10-10 18:50:32778
[email protected]0aad67b2009-07-15 20:34:28779 // Notify our observers that we are complete (the call to Finished() set the
780 // state to complete but did not notify).
781 download->UpdateObservers();
[email protected]6aa4a1c02010-01-15 18:49:58782
783 // The download file is meant to be completed if both the filename is
784 // finalized and the file data is downloaded. The ordering of these two
785 // actions is indeterministic. Thus, if the filename is not finalized yet,
786 // delay the notification.
787 if (download->name_finalized())
788 download->NotifyObserversDownloadFileCompleted();
[email protected]0aad67b2009-07-15 20:34:28789}
[email protected]eccb9d12009-10-28 05:40:09790
[email protected]9ccbb372008-10-10 18:50:32791// Called on the file thread. Renames the downloaded file to its original name.
792void DownloadManager::ProceedWithFinishedDangerousDownload(
793 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41794 const FilePath& path,
795 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32796 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41797 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16798 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32799 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24800 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16801 // Make our name unique at this point, as if a dangerous file is downloading
802 // and a 2nd download is started for a file with the same name, they would
803 // have the same path. This is because we uniquify the name on download
804 // start, and at that time the first file does not exists yet, so the second
805 // file gets the same name.
[email protected]5a2388a2010-03-26 16:13:39806 uniquifier = download_util::GetUniquePathNumber(new_path);
[email protected]7a256ea2008-10-17 17:34:16807 if (uniquifier > 0)
[email protected]5a2388a2010-03-26 16:13:39808 download_util::AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32809 success = file_util::Move(path, new_path);
810 } else {
811 NOTREACHED();
812 }
[email protected]6cade212008-12-03 00:32:22813
[email protected]d83d03aa2009-11-02 21:44:37814 ChromeThread::PostTask(
815 ChromeThread::UI, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32816 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16817 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32818}
819
820// Call from the file thread when the finished dangerous download was renamed.
821void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
822 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41823 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16824 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32825 DownloadMap::iterator it = downloads_.find(download_handle);
826 if (it == downloads_.end()) {
827 NOTREACHED();
828 return;
829 }
830
831 DownloadItem* download = it->second;
832 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16833 if (success) {
834 // We need to update the path uniquifier so that the UI shows the right
835 // name when calling GetFileName().
836 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32837 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16838 }
[email protected]9ccbb372008-10-10 18:50:32839
840 // Continue the download finished sequence.
841 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29842}
843
initial.commit09911bf2008-07-26 23:55:29844void DownloadManager::DownloadCancelled(int32 download_id) {
845 DownloadMap::iterator it = in_progress_.find(download_id);
846 if (it == in_progress_.end())
847 return;
848 DownloadItem* download = it->second;
849
initial.commit09911bf2008-07-26 23:55:29850 // Clean up will happen when the history system create callback runs if we
851 // don't have a valid db_handle yet.
852 if (download->db_handle() != kUninitializedHandle) {
853 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:29854 UpdateHistoryForDownload(download);
855 }
856
[email protected]d7d1c5c2009-08-05 23:52:50857 DownloadCancelledInternal(download_id,
858 download->render_process_id(),
859 download->request_id());
[email protected]6a7fb042010-02-01 16:30:47860 UpdateAppIcon();
[email protected]d7d1c5c2009-08-05 23:52:50861}
862
863void DownloadManager::DownloadCancelledInternal(int download_id,
864 int render_process_id,
865 int request_id) {
[email protected]d85cf072009-10-27 03:59:31866 // Cancel the network request. RDH is guaranteed to outlive the IO thread.
867 ChromeThread::PostTask(
868 ChromeThread::IO, FROM_HERE,
[email protected]ae8945192010-07-20 16:56:26869 NewRunnableFunction(&download_util::CancelDownloadRequest,
[email protected]d85cf072009-10-27 03:59:31870 g_browser_process->resource_dispatcher_host(),
871 render_process_id,
872 request_id));
[email protected]d7d1c5c2009-08-05 23:52:50873
initial.commit09911bf2008-07-26 23:55:29874 // Tell the file manager to cancel the download.
[email protected]d7d1c5c2009-08-05 23:52:50875 file_manager_->RemoveDownload(download_id, this); // On the UI thread
[email protected]d83d03aa2009-11-02 21:44:37876 ChromeThread::PostTask(
877 ChromeThread::FILE, FROM_HERE,
878 NewRunnableMethod(
879 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:29880}
881
882void DownloadManager::PauseDownload(int32 download_id, bool pause) {
883 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]d85cf072009-10-27 03:59:31884 if (it == in_progress_.end())
885 return;
initial.commit09911bf2008-07-26 23:55:29886
[email protected]d85cf072009-10-27 03:59:31887 DownloadItem* download = it->second;
888 if (pause == download->is_paused())
889 return;
initial.commit09911bf2008-07-26 23:55:29890
[email protected]d85cf072009-10-27 03:59:31891 // Inform the ResourceDispatcherHost of the new pause state.
892 ChromeThread::PostTask(
893 ChromeThread::IO, FROM_HERE,
894 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
895 g_browser_process->resource_dispatcher_host(),
896 download->render_process_id(),
897 download->request_id(),
898 pause));
initial.commit09911bf2008-07-26 23:55:29899}
900
901// static
902void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
903 int render_process_id,
904 int request_id,
905 bool pause) {
906 rdh->PauseRequest(render_process_id, request_id, pause);
907}
908
[email protected]7ae7c2cb2009-01-06 23:31:41909bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:32910 // TODO(jcampan): Improve me.
[email protected]eccb9d12009-10-28 05:40:09911 return IsExecutableFile(file_name);
[email protected]9ccbb372008-10-10 18:50:32912}
913
[email protected]6a7fb042010-02-01 16:30:47914void DownloadManager::UpdateAppIcon() {
915 int64 total_bytes = 0;
916 int64 received_bytes = 0;
917 int download_count = 0;
918 bool progress_known = true;
919
920 for (DownloadMap::iterator i = in_progress_.begin();
921 i != in_progress_.end();
922 ++i) {
923 ++download_count;
924 const DownloadItem* item = i->second;
925 if (item->total_bytes() > 0) {
926 total_bytes += item->total_bytes();
927 received_bytes += item->received_bytes();
928 } else {
929 // This download didn't specify a Content-Length, so the combined progress
930 // bar neeeds to be indeterminate.
931 progress_known = false;
932 }
933 }
934
935 float progress = 0;
936 if (progress_known && download_count)
937 progress = (float)received_bytes / total_bytes;
938
939 download_util::UpdateAppIconDownloadProgress(download_count,
940 progress_known,
941 progress);
942}
943
[email protected]9ccbb372008-10-10 18:50:32944void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:41945 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:32946 download->Rename(new_path);
947
948 // Update the history.
949
950 // No update necessary if the download was initiated while in incognito mode.
951 if (download->db_handle() <= kUninitializedHandle)
952 return;
953
[email protected]6cade212008-12-03 00:32:22954 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:32955 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
956 if (hs)
[email protected]e53668962010-06-23 15:35:25957 hs->UpdateDownloadPath(new_path, download->db_handle());
[email protected]9ccbb372008-10-10 18:50:32958}
959
initial.commit09911bf2008-07-26 23:55:29960void DownloadManager::RemoveDownload(int64 download_handle) {
961 DownloadMap::iterator it = downloads_.find(download_handle);
962 if (it == downloads_.end())
963 return;
964
965 // Make history update.
966 DownloadItem* download = it->second;
967 RemoveDownloadFromHistory(download);
968
969 // Remove from our tables and delete.
970 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32971 it = dangerous_finished_.find(download->id());
972 if (it != dangerous_finished_.end())
973 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:29974
975 // Tell observers to refresh their views.
[email protected]b0ab1d42010-02-24 19:29:28976 NotifyModelChanged();
[email protected]6f712872008-11-07 00:35:36977
978 delete download;
initial.commit09911bf2008-07-26 23:55:29979}
980
[email protected]e93d2822009-01-30 05:59:59981int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
982 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:29983 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
984
initial.commit09911bf2008-07-26 23:55:29985 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:28986 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:29987 while (it != downloads_.end()) {
988 DownloadItem* download = it->second;
989 DownloadItem::DownloadState state = download->state();
990 if (download->start_time() >= remove_begin &&
991 (remove_end.is_null() || download->start_time() < remove_end) &&
992 (state == DownloadItem::COMPLETE ||
993 state == DownloadItem::CANCELLED)) {
994 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:56995 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:58996
997 // Also remove it from any completed dangerous downloads.
998 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
999 if (dit != dangerous_finished_.end())
1000 dangerous_finished_.erase(dit);
1001
[email protected]78b8fcc92009-03-31 17:36:281002 pending_deletes.push_back(download);
[email protected]b0ab1d42010-02-24 19:29:281003 // Observer interface.
initial.commit09911bf2008-07-26 23:55:291004
initial.commit09911bf2008-07-26 23:55:291005 continue;
1006 }
1007
1008 ++it;
1009 }
1010
1011 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281012 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291013 if (num_deleted > 0)
[email protected]b0ab1d42010-02-24 19:29:281014 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291015
[email protected]78b8fcc92009-03-31 17:36:281016 // Delete the download items after updating the observers.
1017 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1018 pending_deletes.clear();
1019
initial.commit09911bf2008-07-26 23:55:291020 return num_deleted;
1021}
1022
[email protected]e93d2822009-01-30 05:59:591023int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1024 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291025}
1026
[email protected]d41355e6f2009-04-07 21:21:121027int DownloadManager::RemoveAllDownloads() {
[email protected]024f2f02010-04-30 22:51:461028 if (this != profile_->GetOriginalProfile()->GetDownloadManager()) {
1029 // This is an incognito downloader. Clear All should clear main download
1030 // manager as well.
1031 profile_->GetOriginalProfile()->GetDownloadManager()->RemoveAllDownloads();
1032 }
[email protected]d41355e6f2009-04-07 21:21:121033 // The null times make the date range unbounded.
1034 return RemoveDownloadsBetween(base::Time(), base::Time());
1035}
1036
initial.commit09911bf2008-07-26 23:55:291037// Initiate a download of a specific URL. We send the request to the
1038// ResourceDispatcherHost, and let it send us responses like a regular
1039// download.
1040void DownloadManager::DownloadUrl(const GURL& url,
1041 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:501042 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:341043 TabContents* tab_contents) {
[email protected]ae8945192010-07-20 16:56:261044 DownloadUrlToFile(url, referrer, referrer_charset, DownloadSaveInfo(),
1045 tab_contents);
[email protected]6aa4a1c02010-01-15 18:49:581046}
1047
1048void DownloadManager::DownloadUrlToFile(const GURL& url,
1049 const GURL& referrer,
1050 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:321051 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:581052 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:341053 DCHECK(tab_contents);
[email protected]ae8945192010-07-20 16:56:261054 ChromeThread::PostTask(ChromeThread::IO, FROM_HERE,
1055 NewRunnableFunction(&download_util::DownloadUrl,
1056 url,
1057 referrer,
1058 referrer_charset,
1059 save_info,
1060 g_browser_process->resource_dispatcher_host(),
1061 tab_contents->GetRenderProcessHost()->id(),
1062 tab_contents->render_view_host()->routing_id(),
1063 request_context_getter_));
initial.commit09911bf2008-07-26 23:55:291064}
1065
[email protected]7ae7c2cb2009-01-06 23:31:411066void DownloadManager::GenerateExtension(
1067 const FilePath& file_name,
1068 const std::string& mime_type,
1069 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291070 // We're worried about three things here:
1071 //
1072 // 1) Security. Many sites let users upload content, such as buddy icons, to
1073 // their web sites. We want to mitigate the case where an attacker
1074 // supplies a malicious executable with an executable file extension but an
1075 // honest site serves the content with a benign content type, such as
1076 // image/jpeg.
1077 //
1078 // 2) Usability. If the site fails to provide a file extension, we want to
1079 // guess a reasonable file extension based on the content type.
1080 //
1081 // 3) Shell integration. Some file extensions automatically integrate with
1082 // the shell. We block these extensions to prevent a malicious web site
1083 // from integrating with the user's shell.
1084
[email protected]7ae7c2cb2009-01-06 23:31:411085 static const FilePath::CharType default_extension[] =
1086 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291087
1088 // See if our file name already contains an extension.
[email protected]63597e4e2010-07-08 17:49:051089 FilePath::StringType extension = file_name.Extension();
1090 if (!extension.empty())
1091 extension.erase(extension.begin()); // Erase preceding '.'.
initial.commit09911bf2008-07-26 23:55:291092
[email protected]b7f05882009-02-22 01:21:561093#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291094 // Rename shell-integrated extensions.
1095 if (win_util::IsShellIntegratedExtension(extension))
1096 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561097#endif
initial.commit09911bf2008-07-26 23:55:291098
1099 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411100 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411101 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291102 if (mime_type == mime_type_from_extension) {
1103 // The hinted extension matches the mime type. It looks like a winner.
1104 generated_extension->swap(extension);
1105 return;
1106 }
1107
[email protected]eccb9d12009-10-28 05:40:091108 if (IsExecutableExtension(extension) && !IsExecutableMimeType(mime_type)) {
initial.commit09911bf2008-07-26 23:55:291109 // We want to be careful about executable extensions. The worry here is
1110 // that a trusted web site could be tricked into dropping an executable file
1111 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101112 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291113 // We couldn't find a good extension for this content type. Use a dummy
1114 // extension instead.
1115 extension.assign(default_extension);
1116 }
1117 }
1118
1119 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101120 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291121 } else {
[email protected]6cade212008-12-03 00:32:221122 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291123 // 1. New extension is not ".txt"
1124 // 2. New extension is not the same as the already existing extension.
1125 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411126 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291127 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1128 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371129 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1130 // servers, i.e. bug 5772.
[email protected]e32642f62009-09-11 21:58:291131 // 5. The original extension is not ".tgz" & the new extension is not "gz".
[email protected]7ae7c2cb2009-01-06 23:31:411132 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101133 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171134 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411135 append_extension != extension &&
[email protected]eccb9d12009-10-28 05:40:091136 !IsExecutableExtension(append_extension) &&
[email protected]e32642f62009-09-11 21:58:291137 !(append_extension == FILE_PATH_LITERAL("gz") &&
1138 extension == FILE_PATH_LITERAL("tgz")) &&
[email protected]e106457b2009-03-25 22:43:371139 (append_extension != FILE_PATH_LITERAL("tar") ||
1140 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171141 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291142 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171143 }
initial.commit09911bf2008-07-26 23:55:291144 }
1145 }
1146
1147 generated_extension->swap(extension);
1148}
1149
[email protected]6aa4a1c02010-01-15 18:49:581150void DownloadManager::GenerateFileNameFromInfo(DownloadCreateInfo* info,
1151 FilePath* generated_name) {
1152 GenerateFileName(GURL(info->url),
1153 info->content_disposition,
1154 info->referrer_charset,
1155 info->mime_type,
1156 generated_name);
1157}
1158
1159void DownloadManager::GenerateFileName(const GURL& url,
1160 const std::string& content_disposition,
1161 const std::string& referrer_charset,
1162 const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411163 FilePath* generated_name) {
[email protected]630947c2009-11-04 18:37:311164 std::wstring default_name =
1165 l10n_util::GetString(IDS_DEFAULT_DOWNLOAD_FILENAME);
1166#if defined(OS_WIN)
1167 FilePath default_file_path(default_name);
1168#elif defined(OS_POSIX)
1169 FilePath default_file_path(base::SysWideToNativeMB(default_name));
1170#endif
1171
[email protected]6aa4a1c02010-01-15 18:49:581172 *generated_name = net::GetSuggestedFilename(GURL(url),
1173 content_disposition,
1174 referrer_charset,
[email protected]630947c2009-11-04 18:37:311175 default_file_path);
1176
[email protected]7ae7c2cb2009-01-06 23:31:411177 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291178
[email protected]6aa4a1c02010-01-15 18:49:581179 GenerateSafeFileName(mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291180}
1181
1182void DownloadManager::AddObserver(Observer* observer) {
1183 observers_.AddObserver(observer);
1184 observer->ModelChanged();
1185}
1186
1187void DownloadManager::RemoveObserver(Observer* observer) {
1188 observers_.RemoveObserver(observer);
1189}
1190
1191// Post Windows Shell operations to the Download thread, to avoid blocking the
1192// user interface.
1193void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1194 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:371195 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:581196#if defined(OS_MACOSX)
1197 // Mac needs to run this operation on the UI thread.
1198 platform_util::ShowItemInFolder(download->full_path());
1199#else
[email protected]d83d03aa2009-11-02 21:44:371200 ChromeThread::PostTask(
1201 ChromeThread::FILE, FROM_HERE,
1202 NewRunnableMethod(
1203 file_manager_, &DownloadFileManager::OnShowDownloadInShell,
1204 FilePath(download->full_path())));
[email protected]8b6ff012009-08-18 22:29:581205#endif
initial.commit09911bf2008-07-26 23:55:291206}
1207
[email protected]8f783752009-04-01 23:33:451208void DownloadManager::OpenDownload(const DownloadItem* download,
1209 gfx::NativeView parent_window) {
[email protected]0e34d7892009-06-05 19:17:401210 // Open Chrome extensions with ExtensionsService. For everything else do shell
[email protected]8f783752009-04-01 23:33:451211 // execute.
[email protected]a60c8ae2009-12-25 06:50:571212 if (download->is_extension_install()) {
[email protected]d4a71882010-06-25 16:36:411213 OpenChromeExtension(download->full_path(),
1214 download->url(),
1215 download->referrer_url(),
1216 download->original_mime_type());
[email protected]8f783752009-04-01 23:33:451217 } else {
1218 OpenDownloadInShell(download, parent_window);
1219 }
1220}
1221
[email protected]d4a71882010-06-25 16:36:411222void DownloadManager::OpenChromeExtension(
1223 const FilePath& full_path,
1224 const GURL& download_url,
1225 const GURL& referrer_url,
1226 const std::string& original_mime_type) {
[email protected]6ef635e42009-07-26 06:16:121227 // We don't support extensions in OTR mode.
[email protected]2a464a92009-08-01 17:58:351228 ExtensionsService* service = profile_->GetExtensionsService();
1229 if (service) {
[email protected]91e1bd82009-09-03 22:04:401230 NotificationService* nservice = NotificationService::current();
[email protected]6dfbbf82010-03-12 23:09:161231 GURL nonconst_download_url = download_url;
1232 nservice->Notify(NotificationType::EXTENSION_READY_FOR_INSTALL,
1233 Source<DownloadManager>(this),
1234 Details<GURL>(&nonconst_download_url));
1235
1236 scoped_refptr<CrxInstaller> installer(
1237 new CrxInstaller(service->install_directory(),
1238 service,
1239 new ExtensionInstallUI(profile_)));
1240 installer->set_delete_source(true);
1241
[email protected]a050d712009-11-06 00:40:101242 if (UserScript::HasUserScriptFileExtension(download_url)) {
[email protected]6dfbbf82010-03-12 23:09:161243 installer->InstallUserScript(full_path, download_url);
[email protected]6657afa62009-11-04 02:15:201244 } else {
[email protected]be18e1582010-06-03 21:50:421245 bool is_gallery_download =
1246 ExtensionsService::IsDownloadFromGallery(download_url, referrer_url);
[email protected]d4a71882010-06-25 16:36:411247 installer->set_original_mime_type(original_mime_type);
1248 installer->set_apps_require_extension_mime_type(true);
[email protected]6dfbbf82010-03-12 23:09:161249 installer->set_allow_privilege_increase(true);
1250 installer->set_original_url(download_url);
[email protected]9f72aa02010-06-25 10:01:051251 installer->set_limit_web_extent_to_download_host(!is_gallery_download);
[email protected]6dfbbf82010-03-12 23:09:161252 installer->InstallCrx(full_path);
[email protected]6657afa62009-11-04 02:15:201253 }
[email protected]21ca982c2010-01-26 22:49:551254 } else {
1255 TabContents* contents = NULL;
[email protected]a65bce4e2010-06-09 16:00:151256 // Get last active normal browser of profile.
1257 Browser* last_active = BrowserList::FindBrowserWithType(profile_,
[email protected]074e4f42010-06-23 16:12:061258 Browser::TYPE_NORMAL, true);
[email protected]21ca982c2010-01-26 22:49:551259 if (last_active)
1260 contents = last_active->GetSelectedTabContents();
1261 if (contents) {
1262 contents->AddInfoBar(
1263 new SimpleAlertInfoBarDelegate(contents,
1264 l10n_util::GetString(
1265 IDS_EXTENSION_INCOGNITO_INSTALL_INFOBAR_LABEL),
1266 ResourceBundle::GetSharedInstance().GetBitmapNamed(
[email protected]938e1f92010-04-01 18:09:421267 IDR_INFOBAR_PLUGIN_INSTALL),
1268 true));
[email protected]21ca982c2010-01-26 22:49:551269 }
[email protected]2a464a92009-08-01 17:58:351270 }
[email protected]8f783752009-04-01 23:33:451271}
1272
initial.commit09911bf2008-07-26 23:55:291273void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591274 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291275 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:371276 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:581277#if defined(OS_MACOSX)
1278 // Mac OS X requires opening downloads on the UI thread.
1279 platform_util::OpenItem(download->full_path());
1280#else
[email protected]d83d03aa2009-11-02 21:44:371281 ChromeThread::PostTask(
1282 ChromeThread::FILE, FROM_HERE,
1283 NewRunnableMethod(
1284 file_manager_, &DownloadFileManager::OnOpenDownloadInShell,
1285 download->full_path(), download->url(), parent_window));
[email protected]8b6ff012009-08-18 22:29:581286#endif
initial.commit09911bf2008-07-26 23:55:291287}
1288
[email protected]eccb9d12009-10-28 05:40:091289void DownloadManager::OpenFilesBasedOnExtension(
1290 const FilePath& path, bool open) {
1291 FilePath::StringType extension = path.Extension();
1292 if (extension.empty())
1293 return;
1294 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1295 extension.erase(0, 1);
1296 if (open && !IsExecutableExtension(extension))
initial.commit09911bf2008-07-26 23:55:291297 auto_open_.insert(extension);
1298 else
1299 auto_open_.erase(extension);
1300 SaveAutoOpens();
1301}
1302
[email protected]eccb9d12009-10-28 05:40:091303bool DownloadManager::ShouldOpenFileBasedOnExtension(
1304 const FilePath& path) const {
[email protected]eccb9d12009-10-28 05:40:091305 FilePath::StringType extension = path.Extension();
1306 if (extension.empty())
1307 return false;
1308 if (IsExecutableExtension(extension))
1309 return false;
[email protected]92e11c82010-01-13 06:39:561310 if (Extension::IsExtension(path))
1311 return false;
[email protected]eccb9d12009-10-28 05:40:091312 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1313 extension.erase(0, 1);
[email protected]92e11c82010-01-13 06:39:561314 if (auto_open_.find(extension) != auto_open_.end())
[email protected]8c756ac2009-01-30 23:36:411315 return true;
initial.commit09911bf2008-07-26 23:55:291316 return false;
1317}
1318
[email protected]7b73d992008-12-15 20:56:461319static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291320 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461321 "text/javascript",
1322 "text/javascript;version=*",
[email protected]54d8d452009-04-08 17:29:241323 // Registry files can cause critical changes to the MS OS behavior.
1324 // Addition of this mimetype also addresses bug 7337.
1325 "text/x-registry",
[email protected]60ff8f912008-12-05 07:58:391326 // Some sites use binary/octet-stream to mean application/octet-stream.
1327 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461328 "binary/octet-stream"
1329};
initial.commit09911bf2008-07-26 23:55:291330
[email protected]7b73d992008-12-15 20:56:461331static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291332 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461333 "application/*+xml",
1334 "application/xml"
1335};
initial.commit09911bf2008-07-26 23:55:291336
[email protected]7b73d992008-12-15 20:56:461337// static
1338bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411339 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461340 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1341 return true;
1342 }
[email protected]bae0ea12009-02-14 01:20:411343 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461344 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1345 return false;
1346 }
1347 // We consider only other application types to be executable.
1348 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291349}
1350
[email protected]eccb9d12009-10-28 05:40:091351bool DownloadManager::IsExecutableFile(const FilePath& path) const {
1352 return IsExecutableExtension(path.Extension());
1353}
1354
1355bool DownloadManager::IsExecutableExtension(
[email protected]6aa4a1c02010-01-15 18:49:581356 const FilePath::StringType& extension) {
[email protected]eccb9d12009-10-28 05:40:091357 if (extension.empty())
1358 return false;
[email protected]64da0b932009-02-24 02:30:041359 if (!IsStringASCII(extension))
1360 return false;
[email protected]a0a9577b2009-05-27 23:52:321361#if defined(OS_WIN)
[email protected]64da0b932009-02-24 02:30:041362 std::string ascii_extension = WideToASCII(extension);
[email protected]e9ef0a62009-08-11 22:50:131363#elif defined(OS_POSIX)
[email protected]a0a9577b2009-05-27 23:52:321364 std::string ascii_extension = extension;
1365#endif
[email protected]64da0b932009-02-24 02:30:041366
[email protected]eccb9d12009-10-28 05:40:091367 // Strip out leading dot if it's still there
1368 if (ascii_extension[0] == FilePath::kExtensionSeparator)
1369 ascii_extension.erase(0, 1);
1370
[email protected]6aa4a1c02010-01-15 18:49:581371 return download_util::IsExecutableExtension(ascii_extension);
initial.commit09911bf2008-07-26 23:55:291372}
1373
1374void DownloadManager::ResetAutoOpenFiles() {
1375 auto_open_.clear();
1376 SaveAutoOpens();
1377}
1378
1379bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1380 return !auto_open_.empty();
1381}
1382
1383void DownloadManager::SaveAutoOpens() {
1384 PrefService* prefs = profile_->GetPrefs();
1385 if (prefs) {
[email protected]ddd231e2010-06-29 20:35:191386 std::string extensions;
[email protected]eccb9d12009-10-28 05:40:091387 for (AutoOpenSet::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291388 it != auto_open_.end(); ++it) {
[email protected]ddd231e2010-06-29 20:35:191389#if defined(OS_POSIX)
1390 std::string this_extension = *it;
1391#elif defined(OS_WIN)
1392 std::string this_extension = base::SysWideToUTF8(*it);
1393#endif
1394 extensions += this_extension + ":";
initial.commit09911bf2008-07-26 23:55:291395 }
1396 if (!extensions.empty())
1397 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561398
[email protected]ddd231e2010-06-29 20:35:191399 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions);
initial.commit09911bf2008-07-26 23:55:291400 }
1401}
1402
[email protected]561abe62009-04-06 18:08:341403void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361404 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291405 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]e6875c12010-07-18 11:14:131406 if (info->prompt_user_for_save_location)
[email protected]7ae7c2cb2009-01-06 23:31:411407 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291408 ContinueStartDownload(info, path);
1409}
1410
1411void DownloadManager::FileSelectionCanceled(void* params) {
1412 // The user didn't pick a place to save the file, so need to cancel the
1413 // download that's already in progress to the temporary location.
1414 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]d7d1c5c2009-08-05 23:52:501415 DownloadCancelledInternal(info->download_id,
[email protected]76543b92009-08-31 17:27:451416 info->child_id,
[email protected]d7d1c5c2009-08-05 23:52:501417 info->request_id);
initial.commit09911bf2008-07-26 23:55:291418}
1419
[email protected]7ae7c2cb2009-01-06 23:31:411420void DownloadManager::DeleteDownload(const FilePath& path) {
[email protected]d83d03aa2009-11-02 21:44:371421 ChromeThread::PostTask(
1422 ChromeThread::FILE, FROM_HERE,
[email protected]da74e5ae22010-07-14 16:12:371423 NewRunnableFunction(&DeleteDownloadedFile, path));
[email protected]9ccbb372008-10-10 18:50:321424}
1425
[email protected]9ccbb372008-10-10 18:50:321426void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1427 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1428 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1429 download->UpdateObservers();
1430
1431 // If the download is not complete, nothing to do. The required
1432 // post-processing will be performed when it does complete.
1433 if (download->state() != DownloadItem::COMPLETE)
1434 return;
1435
[email protected]d83d03aa2009-11-02 21:44:371436 ChromeThread::PostTask(
1437 ChromeThread::FILE, FROM_HERE,
1438 NewRunnableMethod(
1439 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
1440 download->db_handle(), download->full_path(),
1441 download->original_name()));
[email protected]9ccbb372008-10-10 18:50:321442}
1443
[email protected]6aa4a1c02010-01-15 18:49:581444void DownloadManager::GenerateSafeFileName(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411445 FilePath* file_name) {
1446 // Make sure we get the right file extension
1447 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391448 GenerateExtension(*file_name, mime_type, &extension);
[email protected]1bdaa60c2010-06-01 01:57:431449 *file_name = file_name->ReplaceExtension(extension);
[email protected]763f946a2009-01-06 19:04:391450
[email protected]2b2f8f72009-02-24 22:42:051451#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391452 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411453 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391454 DCHECK(!leaf_name.empty());
1455 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411456 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1457 *file_name = file_name->DirName();
1458 if (file_name->value() == FilePath::kCurrentDirectory) {
1459 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391460 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411461 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391462 }
1463 }
[email protected]b7f05882009-02-22 01:21:561464#endif
[email protected]763f946a2009-01-06 19:04:391465}
1466
initial.commit09911bf2008-07-26 23:55:291467// Operations posted to us from the history service ----------------------------
1468
1469// The history service has retrieved all download entries. 'entries' contains
1470// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1471void DownloadManager::OnQueryDownloadEntriesComplete(
1472 std::vector<DownloadCreateInfo>* entries) {
1473 for (size_t i = 0; i < entries->size(); ++i) {
1474 DownloadItem* download = new DownloadItem(entries->at(i));
1475 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1476 downloads_[download->db_handle()] = download;
1477 download->set_manager(this);
1478 }
[email protected]b0ab1d42010-02-24 19:29:281479 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291480}
1481
initial.commit09911bf2008-07-26 23:55:291482// Once the new DownloadItem's creation info has been committed to the history
1483// service, we associate the DownloadItem with the db handle, update our
1484// 'downloads_' map and inform observers.
1485void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1486 int64 db_handle) {
1487 DownloadMap::iterator it = in_progress_.find(info.download_id);
1488 DCHECK(it != in_progress_.end());
1489
1490 DownloadItem* download = it->second;
[email protected]d2a8fb72010-01-21 05:31:421491
1492 // It's not immediately obvious, but HistoryBackend::CreateDownload() can
1493 // call this function with an invalid |db_handle|. For instance, this can
1494 // happen when the history database is offline. We cannot have multiple
1495 // DownloadItems with the same invalid db_handle, so we need to assign a
1496 // unique |db_handle| here.
1497 if (db_handle == kUninitializedHandle)
1498 db_handle = fake_db_handle_.GetNext();
1499
initial.commit09911bf2008-07-26 23:55:291500 DCHECK(download->db_handle() == kUninitializedHandle);
1501 download->set_db_handle(db_handle);
1502
1503 // Insert into our full map.
1504 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1505 downloads_[download->db_handle()] = download;
1506
[email protected]5e595482009-05-06 20:16:531507 // Show in the appropropriate browser UI.
1508 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291509
1510 // Inform interested objects about the new download.
[email protected]b0ab1d42010-02-24 19:29:281511 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291512
1513 // If this download has been completed before we've received the db handle,
1514 // post one final message to the history service so that it can be properly
1515 // in sync with the DownloadItem's completion status, and also inform any
1516 // observers so that they get more than just the start notification.
1517 if (download->state() != DownloadItem::IN_PROGRESS) {
1518 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291519 UpdateHistoryForDownload(download);
1520 download->UpdateObservers();
1521 }
[email protected]6a7fb042010-02-01 16:30:471522
1523 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:291524}
1525
1526// Called when the history service has retrieved the list of downloads that
1527// match the search text.
1528void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1529 std::vector<int64>* results) {
1530 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1531 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1532 if (!requestor)
1533 return;
1534
1535 std::vector<DownloadItem*> searched_downloads;
1536 for (std::vector<int64>::iterator it = results->begin();
1537 it != results->end(); ++it) {
1538 DownloadMap::iterator dit = downloads_.find(*it);
1539 if (dit != downloads_.end())
1540 searched_downloads.push_back(dit->second);
1541 }
1542
1543 requestor->SetDownloads(searched_downloads);
1544}
[email protected]905a08d2008-11-19 07:24:121545
[email protected]5e595482009-05-06 20:16:531546void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1547 DownloadItem* download) {
[email protected]8ddbd66a2010-05-21 16:38:341548 // The 'contents' may no longer exist if the user closed the tab before we
1549 // get this start completion event. If it does, tell the origin TabContents
1550 // to display its download shelf.
[email protected]76543b92009-08-31 17:27:451551 TabContents* contents = tab_util::GetTabContentsByID(info.child_id,
1552 info.render_view_id);
[email protected]5e595482009-05-06 20:16:531553
1554 // If the contents no longer exists, we start the download in the last active
1555 // browser. This is not ideal but better than fully hiding the download from
1556 // the user.
1557 if (!contents) {
1558 Browser* last_active = BrowserList::GetLastActive();
1559 if (last_active)
1560 contents = last_active->GetSelectedTabContents();
1561 }
1562
1563 if (contents)
1564 contents->OnStartDownload(download);
1565}
1566
[email protected]6cade212008-12-03 00:32:221567// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121568void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411569 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381570}
[email protected]b0ab1d42010-02-24 19:29:281571
1572void DownloadManager::NotifyModelChanged() {
1573 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1574}
1575
1576// DownloadManager::OtherDownloadManagerObserver implementation ----------------
1577
1578DownloadManager::OtherDownloadManagerObserver::OtherDownloadManagerObserver(
1579 DownloadManager* observing_download_manager)
1580 : observing_download_manager_(observing_download_manager),
1581 observed_download_manager_(NULL) {
1582 if (observing_download_manager->profile_->GetOriginalProfile() ==
1583 observing_download_manager->profile_) {
1584 return;
1585 }
1586
1587 observed_download_manager_ = observing_download_manager_->
1588 profile_->GetOriginalProfile()->GetDownloadManager();
1589 observed_download_manager_->AddObserver(this);
1590}
1591
1592DownloadManager::OtherDownloadManagerObserver::~OtherDownloadManagerObserver() {
1593 if (observed_download_manager_)
1594 observed_download_manager_->RemoveObserver(this);
1595}
1596
1597void DownloadManager::OtherDownloadManagerObserver::ModelChanged() {
1598 observing_download_manager_->NotifyModelChanged();
1599}
1600
1601void DownloadManager::OtherDownloadManagerObserver::SetDownloads(
1602 std::vector<DownloadItem*>& downloads) {
1603}
1604
1605void DownloadManager::OtherDownloadManagerObserver::ManagerGoingDown() {
1606 observed_download_manager_ = NULL;
1607}