diff options
author | Zeno Albisser <zeno.albisser@theqtcompany.com> | 2014-12-05 15:04:29 +0100 |
---|---|---|
committer | Andras Becsi <andras.becsi@theqtcompany.com> | 2014-12-09 10:49:28 +0100 |
commit | af6588f8d723931a298c995fa97259bb7f7deb55 (patch) | |
tree | 060ca707847ba1735f01af2372e0d5e494dc0366 /chromium/content/browser/download | |
parent | 2fff84d821cc7b1c785f6404e0f8091333283e74 (diff) | |
download | qtwebengine-chromium-af6588f8d723931a298c995fa97259bb7f7deb55.tar.gz |
BASELINE: Update chromium to 40.0.2214.28 and ninja to 1.5.3.
Change-Id: I759465284fd64d59ad120219cbe257f7402c4181
Reviewed-by: Andras Becsi <andras.becsi@theqtcompany.com>
Diffstat (limited to 'chromium/content/browser/download')
40 files changed, 923 insertions, 523 deletions
diff --git a/chromium/content/browser/download/base_file.cc b/chromium/content/browser/download/base_file.cc index 362f64ea1e0..5bca7831a44 100644 --- a/chromium/content/browser/download/base_file.cc +++ b/chromium/content/browser/download/base_file.cc @@ -5,8 +5,8 @@ #include "content/browser/download/base_file.h" #include "base/bind.h" -#include "base/file_util.h" #include "base/files/file.h" +#include "base/files/file_util.h" #include "base/format_macros.h" #include "base/logging.h" #include "base/pickle.h" @@ -159,15 +159,18 @@ DownloadInterruptReason BaseFile::Rename(const base::FilePath& new_path) { // permissions / security descriptors that makes sense in the new directory. rename_result = MoveFileAndAdjustPermissions(new_path); - if (rename_result == DOWNLOAD_INTERRUPT_REASON_NONE) { + if (rename_result == DOWNLOAD_INTERRUPT_REASON_NONE) full_path_ = new_path; - // Re-open the file if we were still using it. - if (was_in_progress) - rename_result = Open(); - } + + // Re-open the file if we were still using it regardless of the interrupt + // reason. + DownloadInterruptReason open_result = DOWNLOAD_INTERRUPT_REASON_NONE; + if (was_in_progress) + open_result = Open(); bound_net_log_.EndEvent(net::NetLog::TYPE_DOWNLOAD_FILE_RENAMED); - return rename_result; + return rename_result == DOWNLOAD_INTERRUPT_REASON_NONE ? open_result + : rename_result; } void BaseFile::Detach() { @@ -326,11 +329,10 @@ DownloadInterruptReason BaseFile::LogSystemError( const char* operation, logging::SystemErrorCode os_error) { // There's no direct conversion from a system error to an interrupt reason. - net::Error net_error = net::MapSystemError(os_error); + base::File::Error file_error = base::File::OSErrorToFileError(os_error); return LogInterruptReason( operation, os_error, - ConvertNetErrorToInterruptReason( - net_error, DOWNLOAD_INTERRUPT_FROM_DISK)); + ConvertFileErrorToInterruptReason(file_error)); } DownloadInterruptReason BaseFile::LogInterruptReason( diff --git a/chromium/content/browser/download/base_file.h b/chromium/content/browser/download/base_file.h index a14c5daef31..037aecca3b5 100644 --- a/chromium/content/browser/download/base_file.h +++ b/chromium/content/browser/download/base_file.h @@ -56,7 +56,10 @@ class CONTENT_EXPORT BaseFile { DownloadInterruptReason AppendDataToFile(const char* data, size_t data_len); // Rename the download file. Returns a DownloadInterruptReason indicating the - // result of the operation. + // result of the operation. A return code of NONE indicates that the rename + // was successful. After a failure, the full_path() and in_progress() can be + // used to determine the last known filename and whether the file is available + // for writing or retrying the rename. virtual DownloadInterruptReason Rename(const base::FilePath& full_path); // Detach the file so it is not deleted on destruction. @@ -79,8 +82,15 @@ class CONTENT_EXPORT BaseFile { // Windows to ensure the correct app client ID is available. DownloadInterruptReason AnnotateWithSourceInformation(); - base::FilePath full_path() const { return full_path_; } + // Returns the last known path to the download file. Can be empty if there's + // no file. + const base::FilePath& full_path() const { return full_path_; } + + // Returns true if the file is open. If true, the file can be written to or + // renamed. bool in_progress() const { return file_.IsValid(); } + + // Returns the number of bytes in the file pointed to by full_path(). int64 bytes_so_far() const { return bytes_so_far_; } // Fills |hash| with the hash digest for the file. diff --git a/chromium/content/browser/download/base_file_posix.cc b/chromium/content/browser/download/base_file_posix.cc index 4cf987c8b20..b5d8e014422 100644 --- a/chromium/content/browser/download/base_file_posix.cc +++ b/chromium/content/browser/download/base_file_posix.cc @@ -4,7 +4,7 @@ #include "content/browser/download/base_file.h" -#include "base/file_util.h" +#include "base/files/file_util.h" #include "content/public/browser/download_interrupt_reasons.h" namespace content { @@ -27,8 +27,6 @@ DownloadInterruptReason BaseFile::MoveFileAndAdjustPermissions( if (!stat_succeeded) LogSystemError("stat", errno); - // TODO(estade): Move() falls back to copying and deleting when a simple - // rename fails. Copying sucks for large downloads. crbug.com/8737 if (!base::Move(full_path_, new_path)) return LogSystemError("Move", errno); diff --git a/chromium/content/browser/download/base_file_unittest.cc b/chromium/content/browser/download/base_file_unittest.cc index 8b45ce9ca0f..7e27ffe0969 100644 --- a/chromium/content/browser/download/base_file_unittest.cc +++ b/chromium/content/browser/download/base_file_unittest.cc @@ -4,8 +4,8 @@ #include "content/browser/download/base_file.h" -#include "base/file_util.h" #include "base/files/file.h" +#include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/logging.h" #include "base/message_loop/message_loop.h" @@ -45,7 +45,7 @@ class BaseFileTest : public testing::Test { file_thread_(BrowserThread::FILE, &message_loop_) { } - virtual void SetUp() { + void SetUp() override { ResetHash(); ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); base_file_.reset(new BaseFile(base::FilePath(), @@ -58,7 +58,7 @@ class BaseFileTest : public testing::Test { net::BoundNetLog())); } - virtual void TearDown() { + void TearDown() override { EXPECT_FALSE(base_file_->in_progress()); if (!expected_error_) { EXPECT_EQ(static_cast<int64>(expected_data_.size()), @@ -195,6 +195,12 @@ class BaseFileTest : public testing::Test { expected_error_ = err; } + void ExpectPermissionError(DownloadInterruptReason err) { + EXPECT_TRUE(err == DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR || + err == DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED) + << "Interrupt reason = " << err; + } + protected: // BaseClass instance we are testing. scoped_ptr<BaseFile> base_file_; @@ -467,15 +473,63 @@ TEST_F(BaseFileTest, RenameWithError) { EXPECT_FALSE(base::PathExists(new_path)); { - file_util::PermissionRestorer restore_permissions_for(test_dir); - ASSERT_TRUE(file_util::MakeFileUnwritable(test_dir)); - EXPECT_EQ(DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED, - base_file_->Rename(new_path)); + base::FilePermissionRestorer restore_permissions_for(test_dir); + ASSERT_TRUE(base::MakeFileUnwritable(test_dir)); + ExpectPermissionError(base_file_->Rename(new_path)); } base_file_->Finish(); } +// Test that if a rename fails for an in-progress BaseFile, it remains writeable +// and renameable. +TEST_F(BaseFileTest, RenameWithErrorInProgress) { + ASSERT_TRUE(InitializeFile()); + + base::FilePath test_dir(temp_dir_.path().AppendASCII("TestDir")); + ASSERT_TRUE(base::CreateDirectory(test_dir)); + + base::FilePath new_path(test_dir.AppendASCII("TestFile")); + EXPECT_FALSE(base::PathExists(new_path)); + + // Write some data to start with. + ASSERT_TRUE(AppendDataToFile(kTestData1)); + ASSERT_TRUE(base_file_->in_progress()); + + base::FilePath old_path = base_file_->full_path(); + + { + base::FilePermissionRestorer restore_permissions_for(test_dir); + ASSERT_TRUE(base::MakeFileUnwritable(test_dir)); + ExpectPermissionError(base_file_->Rename(new_path)); + + // The file should still be open and we should be able to continue writing + // to it. + ASSERT_TRUE(base_file_->in_progress()); + ASSERT_TRUE(AppendDataToFile(kTestData2)); + ASSERT_EQ(old_path.value(), base_file_->full_path().value()); + + // Try to rename again, just for kicks. It should still fail. + ExpectPermissionError(base_file_->Rename(new_path)); + } + + // Now that TestDir is writeable again, we should be able to successfully + // rename the file. + EXPECT_EQ(DOWNLOAD_INTERRUPT_REASON_NONE, base_file_->Rename(new_path)); + ASSERT_EQ(new_path.value(), base_file_->full_path().value()); + ASSERT_TRUE(AppendDataToFile(kTestData3)); + + base_file_->Finish(); + + // The contents of the file should be intact. + std::string file_contents; + std::string expected_contents(kTestData1); + expected_contents += kTestData2; + expected_contents += kTestData3; + ASSERT_TRUE(base::ReadFileToString(new_path, &file_contents)); + EXPECT_EQ(expected_contents, file_contents); +} + // Test that a failed write reports an error. TEST_F(BaseFileTest, WriteWithError) { base::FilePath path; @@ -558,10 +612,10 @@ TEST_F(BaseFileTest, ReadonlyBaseFile) { base::FilePath readonly_file_name = CreateTestFile(); // Restore permissions to the file when we are done with this test. - file_util::PermissionRestorer restore_permissions(readonly_file_name); + base::FilePermissionRestorer restore_permissions(readonly_file_name); // Make it read-only. - EXPECT_TRUE(file_util::MakeFileUnwritable(readonly_file_name)); + EXPECT_TRUE(base::MakeFileUnwritable(readonly_file_name)); // Try to overwrite it. base_file_.reset(new BaseFile(readonly_file_name, diff --git a/chromium/content/browser/download/base_file_win.cc b/chromium/content/browser/download/base_file_win.cc index 252f0495d7d..fec1454d57b 100644 --- a/chromium/content/browser/download/base_file_win.cc +++ b/chromium/content/browser/download/base_file_win.cc @@ -9,7 +9,8 @@ #include <objbase.h> #include <shellapi.h> -#include "base/file_util.h" +#include "base/files/file.h" +#include "base/files/file_util.h" #include "base/guid.h" #include "base/metrics/histogram.h" #include "base/strings/utf_string_conversions.h" @@ -25,6 +26,8 @@ namespace { const int kAllSpecialShFileOperationCodes[] = { // Should be kept in sync with the case statement below. ERROR_ACCESS_DENIED, + ERROR_SHARING_VIOLATION, + ERROR_INVALID_PARAMETER, 0x71, 0x72, 0x73, @@ -68,11 +71,28 @@ DownloadInterruptReason MapShFileOperationCodes(int code) { // This switch statement should be kept in sync with the list of codes // above. switch (code) { - // Not a pre-Win32 error code; here so that this particular - // case shows up in our histograms. This is redundant with the - // mapping function net::MapSystemError used later. + // Not a pre-Win32 error code; here so that this particular case shows up in + // our histograms. Unfortunately, it is used not just to signal actual + // ACCESS_DENIED errors, but many other errors as well. So we treat it as a + // transient error. case ERROR_ACCESS_DENIED: // Access is denied. - result = DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED; + result = DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR; + break; + + // This isn't documented but returned from SHFileOperation. Sharing + // violations indicate that another process had the file open while we were + // trying to rename. Anti-virus is believed to be the cause of this error in + // the wild. Treated as a transient error on the assumption that the file + // will be made available for renaming at a later time. + case ERROR_SHARING_VIOLATION: + result = DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR; + break; + + // This is also not a documented return value of SHFileOperation, but has + // been observed in the wild. We are treating it as a transient error based + // on the cases we have seen so far. See http://crbug.com/368455. + case ERROR_INVALID_PARAMETER: + result = DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR; break; // The source and destination files are the same file. @@ -250,12 +270,20 @@ DownloadInterruptReason MapShFileOperationCodes(int code) { arraysize(kAllSpecialShFileOperationCodes))); } + if (result == DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR) { + UMA_HISTOGRAM_CUSTOM_ENUMERATION( + "Download.MapWinShErrorTransientError", code, + base::CustomHistogram::ArrayToCustomRanges( + kAllSpecialShFileOperationCodes, + arraysize(kAllSpecialShFileOperationCodes))); + } + if (result != DOWNLOAD_INTERRUPT_REASON_NONE) return result; // If not one of the above codes, it should be a standard Windows error code. - return ConvertNetErrorToInterruptReason( - net::MapSystemError(code), DOWNLOAD_INTERRUPT_FROM_DISK); + return ConvertFileErrorToInterruptReason( + base::File::OSErrorToFileError(code)); } // Maps a return code from ScanAndSaveDownloadedFile() to a @@ -310,6 +338,7 @@ DownloadInterruptReason BaseFile::MoveFileAndAdjustPermissions( move_info.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR | FOF_NOCOPYSECURITYATTRIBS; + base::TimeTicks now = base::TimeTicks::Now(); int result = SHFileOperation(&move_info); DownloadInterruptReason interrupt_reason = DOWNLOAD_INTERRUPT_REASON_NONE; diff --git a/chromium/content/browser/download/download_browsertest.cc b/chromium/content/browser/download/download_browsertest.cc index 8f35b63e576..a011fc90015 100644 --- a/chromium/content/browser/download/download_browsertest.cc +++ b/chromium/content/browser/download/download_browsertest.cc @@ -6,9 +6,10 @@ // in a pure content context. Over time tests should be migrated here. #include "base/command_line.h" -#include "base/file_util.h" #include "base/files/file_path.h" +#include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" +#include "base/memory/ref_counted.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/platform_thread.h" @@ -19,7 +20,6 @@ #include "content/browser/download/download_item_impl.h" #include "content/browser/download/download_manager_impl.h" #include "content/browser/download/download_resource_handler.h" -#include "content/browser/plugin_service_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/power_save_blocker.h" #include "content/public/common/content_switches.h" @@ -34,16 +34,20 @@ #include "content/shell/browser/shell_browser_context.h" #include "content/shell/browser/shell_download_manager_delegate.h" #include "content/shell/browser/shell_network_delegate.h" -#include "content/test/net/url_request_mock_http_job.h" #include "content/test/net/url_request_slow_download_job.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" #include "net/test/spawned_test_server/spawned_test_server.h" +#include "net/test/url_request/url_request_mock_http_job.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" +#if defined(ENABLE_PLUGINS) +#include "content/browser/plugin_service_impl.h" +#endif + using ::net::test_server::EmbeddedTestServer; using ::testing::AllOf; using ::testing::Field; @@ -118,17 +122,15 @@ class DownloadFileWithDelay : public DownloadFileImpl { base::WeakPtr<DownloadDestinationObserver> observer, base::WeakPtr<DownloadFileWithDelayFactory> owner); - virtual ~DownloadFileWithDelay(); + ~DownloadFileWithDelay() override; // Wraps DownloadFileImpl::Rename* and intercepts the return callback, // storing it in the factory that produced this object for later // retrieval. - virtual void RenameAndUniquify( - const base::FilePath& full_path, - const RenameCompletionCallback& callback) OVERRIDE; - virtual void RenameAndAnnotate( - const base::FilePath& full_path, - const RenameCompletionCallback& callback) OVERRIDE; + void RenameAndUniquify(const base::FilePath& full_path, + const RenameCompletionCallback& callback) override; + void RenameAndAnnotate(const base::FilePath& full_path, + const RenameCompletionCallback& callback) override; private: static void RenameCallbackWrapper( @@ -151,10 +153,10 @@ class DownloadFileWithDelay : public DownloadFileImpl { class DownloadFileWithDelayFactory : public DownloadFileFactory { public: DownloadFileWithDelayFactory(); - virtual ~DownloadFileWithDelayFactory(); + ~DownloadFileWithDelayFactory() override; // DownloadFileFactory interface. - virtual DownloadFile* CreateFile( + DownloadFile* CreateFile( scoped_ptr<DownloadSaveInfo> save_info, const base::FilePath& default_download_directory, const GURL& url, @@ -162,7 +164,7 @@ class DownloadFileWithDelayFactory : public DownloadFileFactory { bool calculate_hash, scoped_ptr<ByteStreamReader> stream, const net::BoundNetLog& bound_net_log, - base::WeakPtr<DownloadDestinationObserver> observer) OVERRIDE; + base::WeakPtr<DownloadDestinationObserver> observer) override; void AddRenameCallback(base::Closure callback); void GetAllRenameCallbacks(std::vector<base::Closure>* results); @@ -288,12 +290,12 @@ class CountingDownloadFile : public DownloadFileImpl { url, referrer_url, calculate_hash, stream.Pass(), bound_net_log, observer) {} - virtual ~CountingDownloadFile() { + ~CountingDownloadFile() override { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); active_files_--; } - virtual void Initialize(const InitializeCallback& callback) OVERRIDE { + void Initialize(const InitializeCallback& callback) override { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); active_files_++; return DownloadFileImpl::Initialize(callback); @@ -327,18 +329,18 @@ int CountingDownloadFile::active_files_ = 0; class CountingDownloadFileFactory : public DownloadFileFactory { public: CountingDownloadFileFactory() {} - virtual ~CountingDownloadFileFactory() {} + ~CountingDownloadFileFactory() override {} // DownloadFileFactory interface. - virtual DownloadFile* CreateFile( - scoped_ptr<DownloadSaveInfo> save_info, - const base::FilePath& default_downloads_directory, - const GURL& url, - const GURL& referrer_url, - bool calculate_hash, - scoped_ptr<ByteStreamReader> stream, - const net::BoundNetLog& bound_net_log, - base::WeakPtr<DownloadDestinationObserver> observer) OVERRIDE { + DownloadFile* CreateFile( + scoped_ptr<DownloadSaveInfo> save_info, + const base::FilePath& default_downloads_directory, + const GURL& url, + const GURL& referrer_url, + bool calculate_hash, + scoped_ptr<ByteStreamReader> stream, + const net::BoundNetLog& bound_net_log, + base::WeakPtr<DownloadDestinationObserver> observer) override { scoped_ptr<PowerSaveBlocker> psb( PowerSaveBlocker::Create( PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension, @@ -354,11 +356,11 @@ class TestShellDownloadManagerDelegate : public ShellDownloadManagerDelegate { public: TestShellDownloadManagerDelegate() : delay_download_open_(false) {} - virtual ~TestShellDownloadManagerDelegate() {} + ~TestShellDownloadManagerDelegate() override {} - virtual bool ShouldOpenDownload( + bool ShouldOpenDownload( DownloadItem* item, - const DownloadOpenDelayedCallback& callback) OVERRIDE { + const DownloadOpenDelayedCallback& callback) override { if (delay_download_open_) { delayed_callbacks_.push_back(callback); return false; @@ -396,9 +398,7 @@ class RecordingDownloadObserver : DownloadItem::Observer { download_->AddObserver(this); } - virtual ~RecordingDownloadObserver() { - RemoveObserver(); - } + ~RecordingDownloadObserver() override { RemoveObserver(); } void CompareToExpectedRecord(const RecordStruct expected[], size_t size) { EXPECT_EQ(size, record_.size()); @@ -411,7 +411,7 @@ class RecordingDownloadObserver : DownloadItem::Observer { } private: - virtual void OnDownloadUpdated(DownloadItem* download) OVERRIDE { + void OnDownloadUpdated(DownloadItem* download) override { DCHECK_EQ(download_, download); DownloadItem::DownloadState state = download->GetState(); int bytes = download->GetReceivedBytes(); @@ -422,7 +422,7 @@ class RecordingDownloadObserver : DownloadItem::Observer { } } - virtual void OnDownloadDestroyed(DownloadItem* download) OVERRIDE { + void OnDownloadDestroyed(DownloadItem* download) override { DCHECK_EQ(download_, download); RemoveObserver(); } @@ -449,20 +449,20 @@ class DownloadCreateObserver : DownloadManager::Observer { manager_->AddObserver(this); } - virtual ~DownloadCreateObserver() { + ~DownloadCreateObserver() override { if (manager_) manager_->RemoveObserver(this); manager_ = NULL; } - virtual void ManagerGoingDown(DownloadManager* manager) OVERRIDE { + void ManagerGoingDown(DownloadManager* manager) override { DCHECK_EQ(manager_, manager); manager_->RemoveObserver(this); manager_ = NULL; } - virtual void OnDownloadCreated(DownloadManager* manager, - DownloadItem* download) OVERRIDE { + void OnDownloadCreated(DownloadManager* manager, + DownloadItem* download) override { if (!item_) item_ = download; @@ -518,7 +518,7 @@ scoped_ptr<net::test_server::HttpResponse> HandleRequestAndSendRedirectResponse( response->set_code(net::HTTP_FOUND); response->AddCustomHeader("Location", target_url.spec()); } - return response.PassAs<net::test_server::HttpResponse>(); + return response.Pass(); } // Creates a request handler for EmbeddedTestServer that responds with a HTTP @@ -542,7 +542,7 @@ scoped_ptr<net::test_server::HttpResponse> HandleRequestAndSendBasicResponse( response->set_content_type(content_type); response->set_content(body); } - return response.PassAs<net::test_server::HttpResponse>(); + return response.Pass(); } // Creates a request handler for an EmbeddedTestServer that response with an @@ -570,7 +570,7 @@ class DownloadContentTest : public ContentBrowserTest { ByteStreamWriter::kFractionBufferBeforeSending) + 1; } - virtual void SetUpOnMainThread() OVERRIDE { + void SetUpOnMainThread() override { ASSERT_TRUE(downloads_directory_.CreateUniqueTempDir()); test_delegate_.reset(new TestShellDownloadManagerDelegate()); @@ -585,8 +585,12 @@ class DownloadContentTest : public ContentBrowserTest { base::Bind(&URLRequestSlowDownloadJob::AddUrlHandler)); base::FilePath mock_base(GetTestFilePath("download", "")); BrowserThread::PostTask( - BrowserThread::IO, FROM_HERE, - base::Bind(&URLRequestMockHTTPJob::AddUrlHandler, mock_base)); + BrowserThread::IO, + FROM_HERE, + base::Bind( + &net::URLRequestMockHTTPJob::AddUrlHandler, + mock_base, + make_scoped_refptr(content::BrowserThread::GetBlockingPool()))); } TestShellDownloadManagerDelegate* GetDownloadManagerDelegate() { @@ -798,7 +802,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, MultiDownload) { // Start the second download and wait until it's done. base::FilePath file(FILE_PATH_LITERAL("download-test.lib")); - GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); + GURL url(net::URLRequestMockHTTPJob::GetMockUrl(file)); // Download the file and wait. NavigateToURLAndWaitForDownload(shell(), url, DownloadItem::COMPLETE); @@ -853,7 +857,8 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, DownloadOctetStream) { PluginServiceImpl::GetInstance()->RegisterInternalPlugin(plugin_info, false); // The following is served with a Content-Type of application/octet-stream. - GURL url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(kTestFilePath))); + GURL url( + net::URLRequestMockHTTPJob::GetMockUrl(base::FilePath(kTestFilePath))); NavigateToURLAndWaitForDownload(shell(), url, DownloadItem::COMPLETE); } #endif @@ -870,7 +875,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, CancelAtFinalRename) { // Create a download base::FilePath file(FILE_PATH_LITERAL("download-test.lib")); - NavigateToURL(shell(), URLRequestMockHTTPJob::GetMockUrl(file)); + NavigateToURL(shell(), net::URLRequestMockHTTPJob::GetMockUrl(file)); // Wait until the first (intermediate file) rename and execute the callback. file_factory->WaitForSomeCallback(); @@ -919,7 +924,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, CancelAtRelease) { // Create a download base::FilePath file(FILE_PATH_LITERAL("download-test.lib")); - NavigateToURL(shell(), URLRequestMockHTTPJob::GetMockUrl(file)); + NavigateToURL(shell(), net::URLRequestMockHTTPJob::GetMockUrl(file)); // Wait until the first (intermediate file) rename and execute the callback. file_factory->WaitForSomeCallback(); @@ -1029,7 +1034,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, ShutdownAtRelease) { // Create a download base::FilePath file(FILE_PATH_LITERAL("download-test.lib")); - NavigateToURL(shell(), URLRequestMockHTTPJob::GetMockUrl(file)); + NavigateToURL(shell(), net::URLRequestMockHTTPJob::GetMockUrl(file)); // Wait until the first (intermediate file) rename and execute the callback. file_factory->WaitForSomeCallback(); @@ -1070,7 +1075,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, ShutdownAtRelease) { } IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeInterruptedDownload) { - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); ASSERT_TRUE(test_server()->Start()); @@ -1137,7 +1142,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeInterruptedDownload) { // Confirm restart fallback happens if a range request is bounced. IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeInterruptedDownloadNoRange) { - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); ASSERT_TRUE(test_server()->Start()); @@ -1186,7 +1191,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeInterruptedDownloadNoRange) { // Confirm restart fallback happens if a precondition is failed. IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeInterruptedDownloadBadPrecondition) { - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); ASSERT_TRUE(test_server()->Start()); @@ -1238,7 +1243,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, // Confirm we don't try to resume if we don't have a verifier. IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeInterruptedDownloadNoVerifiers) { - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); ASSERT_TRUE(test_server()->Start()); @@ -1282,7 +1287,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, } IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeWithDeletedFile) { - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); ASSERT_TRUE(test_server()->Start()); @@ -1333,10 +1338,10 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeWithDeletedFile) { } IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeWithFileInitError) { - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); base::FilePath file(FILE_PATH_LITERAL("download-test.lib")); - GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); + GURL url(net::URLRequestMockHTTPJob::GetMockUrl(file)); // Setup the error injector. scoped_refptr<TestFileErrorInjector> injector( @@ -1384,10 +1389,10 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeWithFileInitError) { IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeWithFileIntermediateRenameError) { - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); base::FilePath file(FILE_PATH_LITERAL("download-test.lib")); - GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); + GURL url(net::URLRequestMockHTTPJob::GetMockUrl(file)); // Setup the error injector. scoped_refptr<TestFileErrorInjector> injector( @@ -1436,10 +1441,10 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, } IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeWithFileFinalRenameError) { - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); base::FilePath file(FILE_PATH_LITERAL("download-test.lib")); - GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); + GURL url(net::URLRequestMockHTTPJob::GetMockUrl(file)); // Setup the error injector. scoped_refptr<TestFileErrorInjector> injector( @@ -1489,7 +1494,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, ResumeWithFileFinalRenameError) { // An interrupted download should remove the intermediate file when it is // cancelled. IN_PROC_BROWSER_TEST_F(DownloadContentTest, CancelInterruptedDownload) { - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); ASSERT_TRUE(test_server()->Start()); @@ -1519,7 +1524,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, CancelInterruptedDownload) { } IN_PROC_BROWSER_TEST_F(DownloadContentTest, RemoveDownload) { - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); ASSERT_TRUE(test_server()->Start()); @@ -1554,7 +1559,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, RemoveDownload) { { // Start the second download and wait until it's done. base::FilePath file2(FILE_PATH_LITERAL("download-test.lib")); - GURL url2(URLRequestMockHTTPJob::GetMockUrl(file2)); + GURL url2(net::URLRequestMockHTTPJob::GetMockUrl(file2)); scoped_ptr<DownloadTestObserver> completion_observer( CreateWaiter(shell(), 1)); DownloadItem* download(StartDownloadAndReturnItem(url2)); @@ -1574,7 +1579,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, RemoveDownload) { IN_PROC_BROWSER_TEST_F(DownloadContentTest, RemoveResumingDownload) { SetupEnsureNoPendingDownloads(); - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); ASSERT_TRUE(test_server()->Start()); @@ -1621,7 +1626,7 @@ IN_PROC_BROWSER_TEST_F(DownloadContentTest, RemoveResumingDownload) { IN_PROC_BROWSER_TEST_F(DownloadContentTest, CancelResumingDownload) { SetupEnsureNoPendingDownloads(); - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); ASSERT_TRUE(test_server()->Start()); diff --git a/chromium/content/browser/download/download_create_info.cc b/chromium/content/browser/download/download_create_info.cc index e381fa854bd..05b0992a26d 100644 --- a/chromium/content/browser/download/download_create_info.cc +++ b/chromium/content/browser/download/download_create_info.cc @@ -15,7 +15,7 @@ DownloadCreateInfo::DownloadCreateInfo(const base::Time& start_time, int64 total_bytes, const net::BoundNetLog& bound_net_log, bool has_user_gesture, - PageTransition transition_type, + ui::PageTransition transition_type, scoped_ptr<DownloadSaveInfo> save_info) : start_time(start_time), total_bytes(total_bytes), @@ -29,7 +29,7 @@ DownloadCreateInfo::DownloadCreateInfo() : total_bytes(0), download_id(DownloadItem::kInvalidId), has_user_gesture(false), - transition_type(PAGE_TRANSITION_LINK), + transition_type(ui::PAGE_TRANSITION_LINK), save_info(new DownloadSaveInfo()) { } diff --git a/chromium/content/browser/download/download_create_info.h b/chromium/content/browser/download/download_create_info.h index e8e1443b93a..cbf87119aa2 100644 --- a/chromium/content/browser/download/download_create_info.h +++ b/chromium/content/browser/download/download_create_info.h @@ -15,8 +15,8 @@ #include "content/browser/download/download_request_handle.h" #include "content/common/content_export.h" #include "content/public/browser/download_save_info.h" -#include "content/public/common/page_transition_types.h" #include "net/base/net_log.h" +#include "ui/base/page_transition_types.h" #include "url/gurl.h" namespace content { @@ -28,7 +28,7 @@ struct CONTENT_EXPORT DownloadCreateInfo { int64 total_bytes, const net::BoundNetLog& bound_net_log, bool has_user_gesture, - PageTransition transition_type, + ui::PageTransition transition_type, scoped_ptr<DownloadSaveInfo> save_info); DownloadCreateInfo(); ~DownloadCreateInfo(); @@ -63,7 +63,7 @@ struct CONTENT_EXPORT DownloadCreateInfo { // True if the download was initiated by user action. bool has_user_gesture; - PageTransition transition_type; + ui::PageTransition transition_type; // The content-disposition string from the response header. std::string content_disposition; diff --git a/chromium/content/browser/download/download_file_impl.cc b/chromium/content/browser/download/download_file_impl.cc index 11e98cb726b..91b25dac35b 100644 --- a/chromium/content/browser/download/download_file_impl.cc +++ b/chromium/content/browser/download/download_file_impl.cc @@ -7,7 +7,7 @@ #include <string> #include "base/bind.h" -#include "base/file_util.h" +#include "base/files/file_util.h" #include "base/message_loop/message_loop_proxy.h" #include "base/strings/stringprintf.h" #include "base/time/time.h" @@ -25,6 +25,12 @@ namespace content { const int kUpdatePeriodMs = 500; const int kMaxTimeBlockingFileThreadMs = 1000; +// These constants control the default retry behavior for failing renames. Each +// retry is performed after a delay that is twice the previous delay. The +// initial delay is specified by kInitialRenameRetryDelayMs. +const int kMaxRenameRetries = 3; +const int kInitialRenameRetryDelayMs = 200; + int DownloadFile::number_active_objects_ = 0; DownloadFileImpl::DownloadFileImpl( @@ -36,20 +42,20 @@ DownloadFileImpl::DownloadFileImpl( scoped_ptr<ByteStreamReader> stream, const net::BoundNetLog& bound_net_log, base::WeakPtr<DownloadDestinationObserver> observer) - : file_(save_info->file_path, - url, - referrer_url, - save_info->offset, - calculate_hash, - save_info->hash_state, - save_info->file.Pass(), - bound_net_log), - default_download_directory_(default_download_directory), - stream_reader_(stream.Pass()), - bytes_seen_(0), - bound_net_log_(bound_net_log), - observer_(observer), - weak_factory_(this) { + : file_(save_info->file_path, + url, + referrer_url, + save_info->offset, + calculate_hash, + save_info->hash_state, + save_info->file.Pass(), + bound_net_log), + default_download_directory_(default_download_directory), + stream_reader_(stream.Pass()), + bytes_seen_(0), + bound_net_log_(bound_net_log), + observer_(observer), + weak_factory_(this) { } DownloadFileImpl::~DownloadFileImpl() { @@ -103,47 +109,84 @@ DownloadInterruptReason DownloadFileImpl::AppendDataToFile( void DownloadFileImpl::RenameAndUniquify( const base::FilePath& full_path, const RenameCompletionCallback& callback) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - - base::FilePath new_path(full_path); - - int uniquifier = base::GetUniquePathNumber( - new_path, base::FilePath::StringType()); - if (uniquifier > 0) { - new_path = new_path.InsertBeforeExtensionASCII( - base::StringPrintf(" (%d)", uniquifier)); - } - - DownloadInterruptReason reason = file_.Rename(new_path); - if (reason != DOWNLOAD_INTERRUPT_REASON_NONE) { - // Make sure our information is updated, since we're about to - // error out. - SendUpdate(); + RenameWithRetryInternal( + full_path, UNIQUIFY, kMaxRenameRetries, base::TimeTicks(), callback); +} - // Null out callback so that we don't do any more stream processing. - stream_reader_->RegisterCallback(base::Closure()); +void DownloadFileImpl::RenameAndAnnotate( + const base::FilePath& full_path, + const RenameCompletionCallback& callback) { + RenameWithRetryInternal(full_path, + ANNOTATE_WITH_SOURCE_INFORMATION, + kMaxRenameRetries, + base::TimeTicks(), + callback); +} - new_path.clear(); - } +base::TimeDelta DownloadFileImpl::GetRetryDelayForFailedRename( + int attempt_number) { + DCHECK_GE(attempt_number, 0); + // |delay| starts at kInitialRenameRetryDelayMs and increases by a factor of + // 2 at each subsequent retry. Assumes that |retries_left| starts at + // kMaxRenameRetries. Also assumes that kMaxRenameRetries is less than the + // number of bits in an int. + return base::TimeDelta::FromMilliseconds(kInitialRenameRetryDelayMs) * + (1 << attempt_number); +} - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - base::Bind(callback, reason, new_path)); +bool DownloadFileImpl::ShouldRetryFailedRename(DownloadInterruptReason reason) { + return reason == DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR; } -void DownloadFileImpl::RenameAndAnnotate( +void DownloadFileImpl::RenameWithRetryInternal( const base::FilePath& full_path, + RenameOption option, + int retries_left, + base::TimeTicks time_of_first_failure, const RenameCompletionCallback& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); base::FilePath new_path(full_path); - DownloadInterruptReason reason = DOWNLOAD_INTERRUPT_REASON_NONE; - // Short circuit null rename. - if (full_path != file_.full_path()) - reason = file_.Rename(new_path); + if ((option & UNIQUIFY) && full_path != file_.full_path()) { + int uniquifier = + base::GetUniquePathNumber(new_path, base::FilePath::StringType()); + if (uniquifier > 0) + new_path = new_path.InsertBeforeExtensionASCII( + base::StringPrintf(" (%d)", uniquifier)); + } + + DownloadInterruptReason reason = file_.Rename(new_path); + + // Attempt to retry the rename if possible. If the rename failed and the + // subsequent open also failed, then in_progress() would be false. We don't + // try to retry renames if the in_progress() was false to begin with since we + // have less assurance that the file at file_.full_path() was the one we were + // working with. + if (ShouldRetryFailedRename(reason) && file_.in_progress() && + retries_left > 0) { + int attempt_number = kMaxRenameRetries - retries_left; + BrowserThread::PostDelayedTask( + BrowserThread::FILE, + FROM_HERE, + base::Bind(&DownloadFileImpl::RenameWithRetryInternal, + weak_factory_.GetWeakPtr(), + full_path, + option, + --retries_left, + time_of_first_failure.is_null() ? base::TimeTicks::Now() + : time_of_first_failure, + callback), + GetRetryDelayForFailedRename(attempt_number)); + return; + } + + if (!time_of_first_failure.is_null()) + RecordDownloadFileRenameResultAfterRetry( + base::TimeTicks::Now() - time_of_first_failure, reason); - if (reason == DOWNLOAD_INTERRUPT_REASON_NONE) { + if (reason == DOWNLOAD_INTERRUPT_REASON_NONE && + (option & ANNOTATE_WITH_SOURCE_INFORMATION)) { // Doing the annotation after the rename rather than before leaves // a very small window during which the file has the final name but // hasn't been marked with the Mark Of The Web. However, it allows diff --git a/chromium/content/browser/download/download_file_impl.h b/chromium/content/browser/download/download_file_impl.h index 2ba3d8d058e..9ff3f8583db 100644 --- a/chromium/content/browser/download/download_file_impl.h +++ b/chromium/content/browser/download/download_file_impl.h @@ -44,31 +44,58 @@ class CONTENT_EXPORT DownloadFileImpl : virtual public DownloadFile { const net::BoundNetLog& bound_net_log, base::WeakPtr<DownloadDestinationObserver> observer); - virtual ~DownloadFileImpl(); + ~DownloadFileImpl() override; // DownloadFile functions. - virtual void Initialize(const InitializeCallback& callback) OVERRIDE; - virtual void RenameAndUniquify( - const base::FilePath& full_path, - const RenameCompletionCallback& callback) OVERRIDE; - virtual void RenameAndAnnotate( - const base::FilePath& full_path, - const RenameCompletionCallback& callback) OVERRIDE; - virtual void Detach() OVERRIDE; - virtual void Cancel() OVERRIDE; - virtual base::FilePath FullPath() const OVERRIDE; - virtual bool InProgress() const OVERRIDE; - virtual int64 CurrentSpeed() const OVERRIDE; - virtual bool GetHash(std::string* hash) OVERRIDE; - virtual std::string GetHashState() OVERRIDE; - virtual void SetClientGuid(const std::string& guid) OVERRIDE; + void Initialize(const InitializeCallback& callback) override; + void RenameAndUniquify(const base::FilePath& full_path, + const RenameCompletionCallback& callback) override; + void RenameAndAnnotate(const base::FilePath& full_path, + const RenameCompletionCallback& callback) override; + void Detach() override; + void Cancel() override; + base::FilePath FullPath() const override; + bool InProgress() const override; + int64 CurrentSpeed() const override; + bool GetHash(std::string* hash) override; + std::string GetHashState() override; + void SetClientGuid(const std::string& guid) override; protected: // For test class overrides. virtual DownloadInterruptReason AppendDataToFile( const char* data, size_t data_len); + virtual base::TimeDelta GetRetryDelayForFailedRename(int attempt_number); + + virtual bool ShouldRetryFailedRename(DownloadInterruptReason reason); + private: + friend class DownloadFileTest; + + // Options for RenameWithRetryInternal. + enum RenameOption { + UNIQUIFY = 1 << 0, // If there's already a file on disk that conflicts with + // |new_path|, try to create a unique file by appending + // a uniquifier. + ANNOTATE_WITH_SOURCE_INFORMATION = 1 << 1 + }; + + // Rename file_ to |new_path|. + // |option| specifies additional operations to be performed during the rename. + // See RenameOption above. + // |retries_left| indicates how many times to retry the operation if the + // rename fails with a transient error. + // |time_of_first_failure| Set to an empty base::TimeTicks during the first + // call. Once the first failure is seen, subsequent calls of + // RenameWithRetryInternal will have a non-empty value keeping track of + // the time of first observed failure. Used for UMA. + void RenameWithRetryInternal(const base::FilePath& new_path, + RenameOption option, + int retries_left, + base::TimeTicks time_of_first_failure, + const RenameCompletionCallback& callback); + // Send an update on our progress. void SendUpdate(); diff --git a/chromium/content/browser/download/download_file_unittest.cc b/chromium/content/browser/download/download_file_unittest.cc index 1127908c260..620efa36ff0 100644 --- a/chromium/content/browser/download/download_file_unittest.cc +++ b/chromium/content/browser/download/download_file_unittest.cc @@ -2,8 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/file_util.h" +#include "base/files/file.h" +#include "base/files/file_util.h" #include "base/message_loop/message_loop.h" +#include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/test/test_file_util.h" #include "content/browser/browser_thread_impl.h" @@ -59,6 +61,46 @@ class MockDownloadDestinationObserver : public DownloadDestinationObserver { MATCHER(IsNullCallback, "") { return (arg.is_null()); } +typedef void (DownloadFile::*DownloadFileRenameMethodType)( + const base::FilePath&, + const DownloadFile::RenameCompletionCallback&); + +// This is a test DownloadFileImpl that has no retry delay and, on Posix, +// retries renames failed due to ACCESS_DENIED. +class TestDownloadFileImpl : public DownloadFileImpl { + public: + TestDownloadFileImpl(scoped_ptr<DownloadSaveInfo> save_info, + const base::FilePath& default_downloads_directory, + const GURL& url, + const GURL& referrer_url, + bool calculate_hash, + scoped_ptr<ByteStreamReader> stream, + const net::BoundNetLog& bound_net_log, + base::WeakPtr<DownloadDestinationObserver> observer) + : DownloadFileImpl(save_info.Pass(), + default_downloads_directory, + url, + referrer_url, + calculate_hash, + stream.Pass(), + bound_net_log, + observer) {} + + protected: + base::TimeDelta GetRetryDelayForFailedRename(int attempt_count) override { + return base::TimeDelta::FromMilliseconds(0); + } + +#if !defined(OS_WIN) + // On Posix, we don't encounter transient errors during renames, except + // possibly EAGAIN, which is difficult to replicate reliably. So we resort to + // simulating a transient error using ACCESS_DENIED instead. + bool ShouldRetryFailedRename(DownloadInterruptReason reason) override { + return reason == DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED; + } +#endif +}; + } // namespace class DownloadFileTest : public testing::Test { @@ -83,8 +125,7 @@ class DownloadFileTest : public testing::Test { file_thread_(BrowserThread::FILE, &loop_) { } - virtual ~DownloadFileTest() { - } + ~DownloadFileTest() override {} void SetUpdateDownloadInfo(int64 bytes, int64 bytes_per_sec, const std::string& hash_state) { @@ -97,22 +138,22 @@ class DownloadFileTest : public testing::Test { observer_->CurrentUpdateStatus(bytes_, bytes_per_sec_, hash_state_); } - virtual void SetUp() { + void SetUp() override { EXPECT_CALL(*(observer_.get()), DestinationUpdate(_, _, _)) .Times(AnyNumber()) .WillRepeatedly(Invoke(this, &DownloadFileTest::SetUpdateDownloadInfo)); } // Mock calls to this function are forwarded here. - void RegisterCallback(base::Closure sink_callback) { + void RegisterCallback(const base::Closure& sink_callback) { sink_callback_ = sink_callback; } - void SetInterruptReasonCallback(bool* was_called, + void SetInterruptReasonCallback(const base::Closure& closure, DownloadInterruptReason* reason_p, DownloadInterruptReason reason) { - *was_called = true; *reason_p = reason; + closure.Run(); } bool CreateDownloadFile(int offset, bool calculate_hash) { @@ -128,30 +169,29 @@ class DownloadFileTest : public testing::Test { .RetiresOnSaturation(); scoped_ptr<DownloadSaveInfo> save_info(new DownloadSaveInfo()); - download_file_.reset( - new DownloadFileImpl(save_info.Pass(), - base::FilePath(), - GURL(), // Source - GURL(), // Referrer - calculate_hash, - scoped_ptr<ByteStreamReader>(input_stream_), - net::BoundNetLog(), - observer_factory_.GetWeakPtr())); - download_file_->SetClientGuid( - "12345678-ABCD-1234-DCBA-123456789ABC"); + scoped_ptr<TestDownloadFileImpl> download_file_impl( + new TestDownloadFileImpl(save_info.Pass(), + base::FilePath(), + GURL(), // Source + GURL(), // Referrer + calculate_hash, + scoped_ptr<ByteStreamReader>(input_stream_), + net::BoundNetLog(), + observer_factory_.GetWeakPtr())); + download_file_impl->SetClientGuid("12345678-ABCD-1234-DCBA-123456789ABC"); + download_file_ = download_file_impl.Pass(); EXPECT_CALL(*input_stream_, Read(_, _)) .WillOnce(Return(ByteStreamReader::STREAM_EMPTY)) .RetiresOnSaturation(); base::WeakPtrFactory<DownloadFileTest> weak_ptr_factory(this); - bool called = false; - DownloadInterruptReason result; + DownloadInterruptReason result = DOWNLOAD_INTERRUPT_REASON_NONE; + base::RunLoop loop_runner; download_file_->Initialize(base::Bind( &DownloadFileTest::SetInterruptReasonCallback, - weak_ptr_factory.GetWeakPtr(), &called, &result)); - loop_.RunUntilIdle(); - EXPECT_TRUE(called); + weak_ptr_factory.GetWeakPtr(), loop_runner.QuitClosure(), &result)); + loop_runner.Run(); ::testing::Mock::VerifyAndClearExpectations(input_stream_); return result == DOWNLOAD_INTERRUPT_REASON_NONE; @@ -243,42 +283,42 @@ class DownloadFileTest : public testing::Test { DownloadInterruptReason RenameAndUniquify( const base::FilePath& full_path, base::FilePath* result_path_p) { - base::WeakPtrFactory<DownloadFileTest> weak_ptr_factory(this); - DownloadInterruptReason result_reason(DOWNLOAD_INTERRUPT_REASON_NONE); - bool callback_was_called(false); - base::FilePath result_path; + return InvokeRenameMethodAndWaitForCallback( + &DownloadFile::RenameAndUniquify, full_path, result_path_p); + } - download_file_->RenameAndUniquify( - full_path, base::Bind(&DownloadFileTest::SetRenameResult, - weak_ptr_factory.GetWeakPtr(), - &callback_was_called, - &result_reason, result_path_p)); - loop_.RunUntilIdle(); + DownloadInterruptReason RenameAndAnnotate( + const base::FilePath& full_path, + base::FilePath* result_path_p) { + return InvokeRenameMethodAndWaitForCallback( + &DownloadFile::RenameAndAnnotate, full_path, result_path_p); + } - EXPECT_TRUE(callback_was_called); - return result_reason; + void ExpectPermissionError(DownloadInterruptReason err) { + EXPECT_TRUE(err == DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR || + err == DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED) + << "Interrupt reason = " << err; } - DownloadInterruptReason RenameAndAnnotate( + protected: + DownloadInterruptReason InvokeRenameMethodAndWaitForCallback( + DownloadFileRenameMethodType method, const base::FilePath& full_path, base::FilePath* result_path_p) { - base::WeakPtrFactory<DownloadFileTest> weak_ptr_factory(this); DownloadInterruptReason result_reason(DOWNLOAD_INTERRUPT_REASON_NONE); - bool callback_was_called(false); base::FilePath result_path; - download_file_->RenameAndAnnotate( - full_path, base::Bind(&DownloadFileTest::SetRenameResult, - weak_ptr_factory.GetWeakPtr(), - &callback_was_called, - &result_reason, result_path_p)); - loop_.RunUntilIdle(); - - EXPECT_TRUE(callback_was_called); + base::RunLoop loop_runner; + ((*download_file_).*method)(full_path, + base::Bind(&DownloadFileTest::SetRenameResult, + base::Unretained(this), + loop_runner.QuitClosure(), + &result_reason, + result_path_p)); + loop_runner.Run(); return result_reason; } - protected: scoped_ptr<StrictMock<MockDownloadDestinationObserver> > observer_; base::WeakPtrFactory<DownloadDestinationObserver> observer_factory_; @@ -300,17 +340,16 @@ class DownloadFileTest : public testing::Test { base::MessageLoop loop_; private: - void SetRenameResult(bool* called_p, + void SetRenameResult(const base::Closure& closure, DownloadInterruptReason* reason_p, base::FilePath* result_path_p, DownloadInterruptReason reason, const base::FilePath& result_path) { - if (called_p) - *called_p = true; if (reason_p) *reason_p = reason; if (result_path_p) *result_path_p = result_path; + closure.Run(); } // UI thread. @@ -322,6 +361,33 @@ class DownloadFileTest : public testing::Test { std::string expected_data_; }; +// DownloadFile::RenameAndAnnotate and DownloadFile::RenameAndUniquify have a +// considerable amount of functional overlap. In order to re-use test logic, we +// are going to introduce this value parameterized test fixture. It will take a +// DownloadFileRenameMethodType value which can be either of the two rename +// methods. +class DownloadFileTestWithRename + : public DownloadFileTest, + public ::testing::WithParamInterface<DownloadFileRenameMethodType> { + protected: + DownloadInterruptReason InvokeSelectedRenameMethod( + const base::FilePath& full_path, + base::FilePath* result_path_p) { + return InvokeRenameMethodAndWaitForCallback( + GetParam(), full_path, result_path_p); + } +}; + +// And now instantiate all DownloadFileTestWithRename tests using both +// DownloadFile rename methods. Each test of the form +// DownloadFileTestWithRename.<FooTest> will be instantiated once with +// RenameAndAnnotate as the value parameter and once with RenameAndUniquify as +// the value parameter. +INSTANTIATE_TEST_CASE_P(DownloadFile, + DownloadFileTestWithRename, + ::testing::Values(&DownloadFile::RenameAndAnnotate, + &DownloadFile::RenameAndUniquify)); + const char* DownloadFileTest::kTestData1 = "Let's write some data to the file!\n"; const char* DownloadFileTest::kTestData2 = "Writing more data.\n"; @@ -335,7 +401,7 @@ const int DownloadFileTest::kDummyRequestId = 67; // Rename the file before any data is downloaded, after some has, after it all // has, and after it's closed. -TEST_F(DownloadFileTest, RenameFileFinal) { +TEST_P(DownloadFileTestWithRename, RenameFileFinal) { ASSERT_TRUE(CreateDownloadFile(0, true)); base::FilePath initial_path(download_file_->FullPath()); EXPECT_TRUE(base::PathExists(initial_path)); @@ -343,12 +409,11 @@ TEST_F(DownloadFileTest, RenameFileFinal) { base::FilePath path_2(initial_path.InsertBeforeExtensionASCII("_2")); base::FilePath path_3(initial_path.InsertBeforeExtensionASCII("_3")); base::FilePath path_4(initial_path.InsertBeforeExtensionASCII("_4")); - base::FilePath path_5(initial_path.InsertBeforeExtensionASCII("_5")); base::FilePath output_path; // Rename the file before downloading any data. EXPECT_EQ(DOWNLOAD_INTERRUPT_REASON_NONE, - RenameAndUniquify(path_1, &output_path)); + InvokeSelectedRenameMethod(path_1, &output_path)); base::FilePath renamed_path = download_file_->FullPath(); EXPECT_EQ(path_1, renamed_path); EXPECT_EQ(path_1, output_path); @@ -363,7 +428,7 @@ TEST_F(DownloadFileTest, RenameFileFinal) { // Rename the file after downloading some data. EXPECT_EQ(DOWNLOAD_INTERRUPT_REASON_NONE, - RenameAndUniquify(path_2, &output_path)); + InvokeSelectedRenameMethod(path_2, &output_path)); renamed_path = download_file_->FullPath(); EXPECT_EQ(path_2, renamed_path); EXPECT_EQ(path_2, output_path); @@ -377,7 +442,7 @@ TEST_F(DownloadFileTest, RenameFileFinal) { // Rename the file after downloading all the data. EXPECT_EQ(DOWNLOAD_INTERRUPT_REASON_NONE, - RenameAndUniquify(path_3, &output_path)); + InvokeSelectedRenameMethod(path_3, &output_path)); renamed_path = download_file_->FullPath(); EXPECT_EQ(path_3, renamed_path); EXPECT_EQ(path_3, output_path); @@ -394,7 +459,7 @@ TEST_F(DownloadFileTest, RenameFileFinal) { // Rename the file after downloading all the data and closing the file. EXPECT_EQ(DOWNLOAD_INTERRUPT_REASON_NONE, - RenameAndUniquify(path_4, &output_path)); + InvokeSelectedRenameMethod(path_4, &output_path)); renamed_path = download_file_->FullPath(); EXPECT_EQ(path_4, renamed_path); EXPECT_EQ(path_4, output_path); @@ -407,29 +472,42 @@ TEST_F(DownloadFileTest, RenameFileFinal) { EXPECT_TRUE(download_file_->GetHash(&hash)); EXPECT_EQ(kDataHash, base::HexEncode(hash.data(), hash.size())); - // Check that a rename with overwrite to an existing file succeeds. - std::string file_contents; - ASSERT_FALSE(base::PathExists(path_5)); + DestroyDownloadFile(0); +} + +// Test to make sure the rename overwrites when requested. This is separate from +// the above test because it only applies to RenameAndAnnotate(). +// RenameAndUniquify() doesn't overwrite by design. +TEST_F(DownloadFileTest, RenameOverwrites) { + ASSERT_TRUE(CreateDownloadFile(0, true)); + base::FilePath initial_path(download_file_->FullPath()); + EXPECT_TRUE(base::PathExists(initial_path)); + base::FilePath path_1(initial_path.InsertBeforeExtensionASCII("_1")); + + ASSERT_FALSE(base::PathExists(path_1)); static const char file_data[] = "xyzzy"; - ASSERT_EQ(static_cast<int>(sizeof(file_data) - 1), - base::WriteFile(path_5, file_data, sizeof(file_data) - 1)); - ASSERT_TRUE(base::PathExists(path_5)); - EXPECT_TRUE(base::ReadFileToString(path_5, &file_contents)); - EXPECT_EQ(std::string(file_data), file_contents); + ASSERT_EQ(static_cast<int>(sizeof(file_data)), + base::WriteFile(path_1, file_data, sizeof(file_data))); + ASSERT_TRUE(base::PathExists(path_1)); + base::FilePath new_path; EXPECT_EQ(DOWNLOAD_INTERRUPT_REASON_NONE, - RenameAndAnnotate(path_5, &output_path)); - EXPECT_EQ(path_5, output_path); + RenameAndAnnotate(path_1, &new_path)); + EXPECT_EQ(path_1.value(), new_path.value()); - file_contents = ""; - EXPECT_TRUE(base::ReadFileToString(path_5, &file_contents)); + std::string file_contents; + ASSERT_TRUE(base::ReadFileToString(new_path, &file_contents)); EXPECT_NE(std::string(file_data), file_contents); + FinishStream(DOWNLOAD_INTERRUPT_REASON_NONE, true); + loop_.RunUntilIdle(); DestroyDownloadFile(0); } // Test to make sure the rename uniquifies if we aren't overwriting -// and there's a file where we're aiming. +// and there's a file where we're aiming. As above, not a +// DownloadFileTestWithRename test because this only applies to +// RenameAndUniquify(). TEST_F(DownloadFileTest, RenameUniquifies) { ASSERT_TRUE(CreateDownloadFile(0, true)); base::FilePath initial_path(download_file_->FullPath()); @@ -451,16 +529,35 @@ TEST_F(DownloadFileTest, RenameUniquifies) { DestroyDownloadFile(0); } +// Test that RenameAndUniquify doesn't try to uniquify in the case where the +// target filename is the same as the current filename. +TEST_F(DownloadFileTest, RenameRecognizesSelfConflict) { + ASSERT_TRUE(CreateDownloadFile(0, true)); + base::FilePath initial_path(download_file_->FullPath()); + EXPECT_TRUE(base::PathExists(initial_path)); + + base::FilePath new_path; + EXPECT_EQ(DOWNLOAD_INTERRUPT_REASON_NONE, + RenameAndUniquify(initial_path, &new_path)); + EXPECT_TRUE(base::PathExists(initial_path)); + + FinishStream(DOWNLOAD_INTERRUPT_REASON_NONE, true); + loop_.RunUntilIdle(); + DestroyDownloadFile(0); + EXPECT_EQ(initial_path.value(), new_path.value()); +} + // Test to make sure we get the proper error on failure. -TEST_F(DownloadFileTest, RenameError) { +TEST_P(DownloadFileTestWithRename, RenameError) { ASSERT_TRUE(CreateDownloadFile(0, true)); base::FilePath initial_path(download_file_->FullPath()); // Create a subdirectory. - base::FilePath tempdir( - initial_path.DirName().Append(FILE_PATH_LITERAL("tempdir"))); - ASSERT_TRUE(base::CreateDirectory(tempdir)); - base::FilePath target_path(tempdir.Append(initial_path.BaseName())); + base::FilePath target_dir( + initial_path.DirName().Append(FILE_PATH_LITERAL("TargetDir"))); + ASSERT_FALSE(base::DirectoryExists(target_dir)); + ASSERT_TRUE(base::CreateDirectory(target_dir)); + base::FilePath target_path(target_dir.Append(initial_path.BaseName())); // Targets base::FilePath target_path_suffixed( @@ -470,13 +567,12 @@ TEST_F(DownloadFileTest, RenameError) { // Make the directory unwritable and try to rename within it. { - file_util::PermissionRestorer restorer(tempdir); - ASSERT_TRUE(file_util::MakeFileUnwritable(tempdir)); + base::FilePermissionRestorer restorer(target_dir); + ASSERT_TRUE(base::MakeFileUnwritable(target_dir)); // Expect nulling out of further processing. EXPECT_CALL(*input_stream_, RegisterCallback(IsNullCallback())); - EXPECT_EQ(DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED, - RenameAndAnnotate(target_path, NULL)); + ExpectPermissionError(InvokeSelectedRenameMethod(target_path, NULL)); EXPECT_FALSE(base::PathExists(target_path_suffixed)); } @@ -485,6 +581,98 @@ TEST_F(DownloadFileTest, RenameError) { DestroyDownloadFile(0); } +namespace { + +void TestRenameCompletionCallback(const base::Closure& closure, + bool* did_run_callback, + DownloadInterruptReason interrupt_reason, + const base::FilePath& new_path) { + EXPECT_EQ(DOWNLOAD_INTERRUPT_REASON_NONE, interrupt_reason); + *did_run_callback = true; + closure.Run(); +} + +} // namespace + +// Test that the retry logic works. This test assumes that DownloadFileImpl will +// post tasks to the current message loop (acting as the FILE thread) +// asynchronously to retry the renames. We will stuff RunLoop::QuitClosures() +// in between the retry tasks to stagger them and then allow the rename to +// succeed. +// +// Note that there is only one queue of tasks to run, and that is in the tests' +// base::MessageLoop::current(). Each RunLoop processes that queue until it sees +// a QuitClosure() targeted at itself, at which point it stops processing. +TEST_P(DownloadFileTestWithRename, RenameWithErrorRetry) { + ASSERT_TRUE(CreateDownloadFile(0, true)); + base::FilePath initial_path(download_file_->FullPath()); + + // Create a subdirectory. + base::FilePath target_dir( + initial_path.DirName().Append(FILE_PATH_LITERAL("TargetDir"))); + ASSERT_FALSE(base::DirectoryExists(target_dir)); + ASSERT_TRUE(base::CreateDirectory(target_dir)); + base::FilePath target_path(target_dir.Append(initial_path.BaseName())); + + bool did_run_callback = false; + + // Each RunLoop can be used the run the MessageLoop until the corresponding + // QuitClosure() is run. This one is used to produce the QuitClosure() that + // will be run when the entire rename operation is complete. + base::RunLoop succeeding_run; + { + // (Scope for the base::File or base::FilePermissionRestorer below.) +#if defined(OS_WIN) + // On Windows we test with an actual transient error, a sharing violation. + // The rename will fail because we are holding the file open for READ. On + // Posix this doesn't cause a failure. + base::File locked_file(initial_path, + base::File::FLAG_OPEN | base::File::FLAG_READ); + ASSERT_TRUE(locked_file.IsValid()); +#else + // Simulate a transient failure by revoking write permission for target_dir. + // The TestDownloadFileImpl class treats this error as transient even though + // DownloadFileImpl itself doesn't. + base::FilePermissionRestorer restore_permissions_for(target_dir); + ASSERT_TRUE(base::MakeFileUnwritable(target_dir)); +#endif + + // The Rename() should fail here and enqueue a retry task without invoking + // the completion callback. + ((*download_file_).*GetParam())(target_path, + base::Bind(&TestRenameCompletionCallback, + succeeding_run.QuitClosure(), + &did_run_callback)); + EXPECT_FALSE(did_run_callback); + + base::RunLoop first_failing_run; + // Queue the QuitClosure() on the MessageLoop now. Any tasks queued by the + // Rename() will be in front of the QuitClosure(). Running the message loop + // now causes the just the first retry task to be run. The rename still + // fails, so another retry task would get queued behind the QuitClosure(). + base::MessageLoop::current()->PostTask(FROM_HERE, + first_failing_run.QuitClosure()); + first_failing_run.Run(); + EXPECT_FALSE(did_run_callback); + + // Running another loop should have the same effect as the above as long as + // kMaxRenameRetries is greater than 2. + base::RunLoop second_failing_run; + base::MessageLoop::current()->PostTask(FROM_HERE, + second_failing_run.QuitClosure()); + second_failing_run.Run(); + EXPECT_FALSE(did_run_callback); + } + + // This time the QuitClosure from succeeding_run should get executed. + succeeding_run.Run(); + EXPECT_TRUE(did_run_callback); + + FinishStream(DOWNLOAD_INTERRUPT_REASON_NONE, true); + loop_.RunUntilIdle(); + DestroyDownloadFile(0); +} + // Various tests of the StreamActive method. TEST_F(DownloadFileTest, StreamEmptySuccess) { ASSERT_TRUE(CreateDownloadFile(0, true)); diff --git a/chromium/content/browser/download/download_interrupt_reasons_impl.cc b/chromium/content/browser/download/download_interrupt_reasons_impl.cc index 9a01f484f1d..2ed8f147ee0 100644 --- a/chromium/content/browser/download/download_interrupt_reasons_impl.cc +++ b/chromium/content/browser/download/download_interrupt_reasons_impl.cc @@ -8,6 +8,35 @@ namespace content { +DownloadInterruptReason ConvertFileErrorToInterruptReason( + base::File::Error file_error) { + switch (file_error) { + case base::File::FILE_OK: + return DOWNLOAD_INTERRUPT_REASON_NONE; + + case base::File::FILE_ERROR_IN_USE: + return DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR; + + case base::File::FILE_ERROR_ACCESS_DENIED: + return DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED; + + case base::File::FILE_ERROR_TOO_MANY_OPENED: + return DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR; + + case base::File::FILE_ERROR_NO_MEMORY: + return DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR; + + case base::File::FILE_ERROR_NO_SPACE: + return DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE; + + case base::File::FILE_ERROR_SECURITY: + return DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED; + + default: + return DOWNLOAD_INTERRUPT_REASON_FILE_FAILED; + } +} + DownloadInterruptReason ConvertNetErrorToInterruptReason( net::Error net_error, DownloadInterruptSource source) { switch (net_error) { diff --git a/chromium/content/browser/download/download_interrupt_reasons_impl.h b/chromium/content/browser/download/download_interrupt_reasons_impl.h index 137dcb2abc5..61ccae1a441 100644 --- a/chromium/content/browser/download/download_interrupt_reasons_impl.h +++ b/chromium/content/browser/download/download_interrupt_reasons_impl.h @@ -5,6 +5,7 @@ #ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_INTERRUPT_REASONS_IMPL_H_ #define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_INTERRUPT_REASONS_IMPL_H_ +#include "base/files/file.h" #include "content/public/browser/download_interrupt_reasons.h" #include "net/base/net_errors.h" @@ -22,6 +23,10 @@ enum DownloadInterruptSource { DownloadInterruptReason CONTENT_EXPORT ConvertNetErrorToInterruptReason( net::Error file_error, DownloadInterruptSource source); +// Safe to call from any thread. +DownloadInterruptReason CONTENT_EXPORT ConvertFileErrorToInterruptReason( + base::File::Error file_error); + } // namespace content #endif // CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_INTERRUPT_REASONS_IMPL_H_ diff --git a/chromium/content/browser/download/download_item_impl.cc b/chromium/content/browser/download/download_item_impl.cc index 433ac78f48b..f681486cdcb 100644 --- a/chromium/content/browser/download/download_item_impl.cc +++ b/chromium/content/browser/download/download_item_impl.cc @@ -28,7 +28,7 @@ #include "base/basictypes.h" #include "base/bind.h" #include "base/command_line.h" -#include "base/file_util.h" +#include "base/files/file_util.h" #include "base/format_macros.h" #include "base/logging.h" #include "base/metrics/histogram.h" @@ -93,7 +93,7 @@ static void DownloadFileCancel(scoped_ptr<DownloadFile> download_file) { } bool IsDownloadResumptionEnabled() { - return CommandLine::ForCurrentProcess()->HasSwitch( + return base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableDownloadResumption); } @@ -133,7 +133,7 @@ DownloadItemImpl::DownloadItemImpl(DownloadItemImplDelegate* delegate, target_disposition_(TARGET_DISPOSITION_OVERWRITE), url_chain_(url_chain), referrer_url_(referrer_url), - transition_type_(PAGE_TRANSITION_LINK), + transition_type_(ui::PAGE_TRANSITION_LINK), has_user_gesture_(false), mime_type_(mime_type), original_mime_type_(original_mime_type), @@ -242,7 +242,7 @@ DownloadItemImpl::DownloadItemImpl( target_disposition_(TARGET_DISPOSITION_OVERWRITE), url_chain_(1, url), referrer_url_(GURL()), - transition_type_(PAGE_TRANSITION_LINK), + transition_type_(ui::PAGE_TRANSITION_LINK), has_user_gesture_(false), mime_type_(mime_type), original_mime_type_(mime_type), @@ -588,7 +588,7 @@ bool DownloadItemImpl::HasUserGesture() const { return has_user_gesture_; }; -PageTransition DownloadItemImpl::GetTransitionType() const { +ui::PageTransition DownloadItemImpl::GetTransitionType() const { return transition_type_; }; @@ -927,6 +927,8 @@ DownloadItemImpl::ResumeMode DownloadItemImpl::GetResumeMode() const { case DOWNLOAD_INTERRUPT_REASON_USER_CANCELED: case DOWNLOAD_INTERRUPT_REASON_FILE_BLOCKED: case DOWNLOAD_INTERRUPT_REASON_FILE_SECURITY_CHECK_FAILED: + case DOWNLOAD_INTERRUPT_REASON_SERVER_UNAUTHORIZED: + case DOWNLOAD_INTERRUPT_REASON_SERVER_CERT_PROBLEM: mode = RESUME_MODE_INVALID; break; } @@ -1680,7 +1682,8 @@ void DownloadItemImpl::ResumeInterruptedDownload() { // If the flag for downloads resumption isn't enabled, ignore // this request. - const CommandLine& command_line = *CommandLine::ForCurrentProcess(); + const base::CommandLine& command_line = + *base::CommandLine::ForCurrentProcess(); if (!command_line.HasSwitch(switches::kEnableDownloadResumption)) return; diff --git a/chromium/content/browser/download/download_item_impl.h b/chromium/content/browser/download/download_item_impl.h index 34916ff6fd9..b6394f7469d 100644 --- a/chromium/content/browser/download/download_item_impl.h +++ b/chromium/content/browser/download/download_item_impl.h @@ -14,7 +14,6 @@ #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/time/time.h" -#include "base/timer/timer.h" #include "content/browser/download/download_net_log_parameters.h" #include "content/browser/download/download_request_handle.h" #include "content/common/content_export.h" @@ -87,77 +86,76 @@ class CONTENT_EXPORT DownloadItemImpl scoped_ptr<DownloadRequestHandleInterface> request_handle, const net::BoundNetLog& bound_net_log); - virtual ~DownloadItemImpl(); + ~DownloadItemImpl() override; // DownloadItem - virtual void AddObserver(DownloadItem::Observer* observer) OVERRIDE; - virtual void RemoveObserver(DownloadItem::Observer* observer) OVERRIDE; - virtual void UpdateObservers() OVERRIDE; - virtual void ValidateDangerousDownload() OVERRIDE; - virtual void StealDangerousDownload(const AcquireFileCallback& callback) - OVERRIDE; - virtual void Pause() OVERRIDE; - virtual void Resume() OVERRIDE; - virtual void Cancel(bool user_cancel) OVERRIDE; - virtual void Remove() OVERRIDE; - virtual void OpenDownload() OVERRIDE; - virtual void ShowDownloadInShell() OVERRIDE; - virtual uint32 GetId() const OVERRIDE; - virtual DownloadState GetState() const OVERRIDE; - virtual DownloadInterruptReason GetLastReason() const OVERRIDE; - virtual bool IsPaused() const OVERRIDE; - virtual bool IsTemporary() const OVERRIDE; - virtual bool CanResume() const OVERRIDE; - virtual bool IsDone() const OVERRIDE; - virtual const GURL& GetURL() const OVERRIDE; - virtual const std::vector<GURL>& GetUrlChain() const OVERRIDE; - virtual const GURL& GetOriginalUrl() const OVERRIDE; - virtual const GURL& GetReferrerUrl() const OVERRIDE; - virtual const GURL& GetTabUrl() const OVERRIDE; - virtual const GURL& GetTabReferrerUrl() const OVERRIDE; - virtual std::string GetSuggestedFilename() const OVERRIDE; - virtual std::string GetContentDisposition() const OVERRIDE; - virtual std::string GetMimeType() const OVERRIDE; - virtual std::string GetOriginalMimeType() const OVERRIDE; - virtual std::string GetRemoteAddress() const OVERRIDE; - virtual bool HasUserGesture() const OVERRIDE; - virtual PageTransition GetTransitionType() const OVERRIDE; - virtual const std::string& GetLastModifiedTime() const OVERRIDE; - virtual const std::string& GetETag() const OVERRIDE; - virtual bool IsSavePackageDownload() const OVERRIDE; - virtual const base::FilePath& GetFullPath() const OVERRIDE; - virtual const base::FilePath& GetTargetFilePath() const OVERRIDE; - virtual const base::FilePath& GetForcedFilePath() const OVERRIDE; - virtual base::FilePath GetFileNameToReportUser() const OVERRIDE; - virtual TargetDisposition GetTargetDisposition() const OVERRIDE; - virtual const std::string& GetHash() const OVERRIDE; - virtual const std::string& GetHashState() const OVERRIDE; - virtual bool GetFileExternallyRemoved() const OVERRIDE; - virtual void DeleteFile(const base::Callback<void(bool)>& callback) OVERRIDE; - virtual bool IsDangerous() const OVERRIDE; - virtual DownloadDangerType GetDangerType() const OVERRIDE; - virtual bool TimeRemaining(base::TimeDelta* remaining) const OVERRIDE; - virtual int64 CurrentSpeed() const OVERRIDE; - virtual int PercentComplete() const OVERRIDE; - virtual bool AllDataSaved() const OVERRIDE; - virtual int64 GetTotalBytes() const OVERRIDE; - virtual int64 GetReceivedBytes() const OVERRIDE; - virtual base::Time GetStartTime() const OVERRIDE; - virtual base::Time GetEndTime() const OVERRIDE; - virtual bool CanShowInFolder() OVERRIDE; - virtual bool CanOpenDownload() OVERRIDE; - virtual bool ShouldOpenFileBasedOnExtension() OVERRIDE; - virtual bool GetOpenWhenComplete() const OVERRIDE; - virtual bool GetAutoOpened() OVERRIDE; - virtual bool GetOpened() const OVERRIDE; - virtual BrowserContext* GetBrowserContext() const OVERRIDE; - virtual WebContents* GetWebContents() const OVERRIDE; - virtual void OnContentCheckCompleted(DownloadDangerType danger_type) OVERRIDE; - virtual void SetOpenWhenComplete(bool open) OVERRIDE; - virtual void SetIsTemporary(bool temporary) OVERRIDE; - virtual void SetOpened(bool opened) OVERRIDE; - virtual void SetDisplayName(const base::FilePath& name) OVERRIDE; - virtual std::string DebugString(bool verbose) const OVERRIDE; + void AddObserver(DownloadItem::Observer* observer) override; + void RemoveObserver(DownloadItem::Observer* observer) override; + void UpdateObservers() override; + void ValidateDangerousDownload() override; + void StealDangerousDownload(const AcquireFileCallback& callback) override; + void Pause() override; + void Resume() override; + void Cancel(bool user_cancel) override; + void Remove() override; + void OpenDownload() override; + void ShowDownloadInShell() override; + uint32 GetId() const override; + DownloadState GetState() const override; + DownloadInterruptReason GetLastReason() const override; + bool IsPaused() const override; + bool IsTemporary() const override; + bool CanResume() const override; + bool IsDone() const override; + const GURL& GetURL() const override; + const std::vector<GURL>& GetUrlChain() const override; + const GURL& GetOriginalUrl() const override; + const GURL& GetReferrerUrl() const override; + const GURL& GetTabUrl() const override; + const GURL& GetTabReferrerUrl() const override; + std::string GetSuggestedFilename() const override; + std::string GetContentDisposition() const override; + std::string GetMimeType() const override; + std::string GetOriginalMimeType() const override; + std::string GetRemoteAddress() const override; + bool HasUserGesture() const override; + ui::PageTransition GetTransitionType() const override; + const std::string& GetLastModifiedTime() const override; + const std::string& GetETag() const override; + bool IsSavePackageDownload() const override; + const base::FilePath& GetFullPath() const override; + const base::FilePath& GetTargetFilePath() const override; + const base::FilePath& GetForcedFilePath() const override; + base::FilePath GetFileNameToReportUser() const override; + TargetDisposition GetTargetDisposition() const override; + const std::string& GetHash() const override; + const std::string& GetHashState() const override; + bool GetFileExternallyRemoved() const override; + void DeleteFile(const base::Callback<void(bool)>& callback) override; + bool IsDangerous() const override; + DownloadDangerType GetDangerType() const override; + bool TimeRemaining(base::TimeDelta* remaining) const override; + int64 CurrentSpeed() const override; + int PercentComplete() const override; + bool AllDataSaved() const override; + int64 GetTotalBytes() const override; + int64 GetReceivedBytes() const override; + base::Time GetStartTime() const override; + base::Time GetEndTime() const override; + bool CanShowInFolder() override; + bool CanOpenDownload() override; + bool ShouldOpenFileBasedOnExtension() override; + bool GetOpenWhenComplete() const override; + bool GetAutoOpened() override; + bool GetOpened() const override; + BrowserContext* GetBrowserContext() const override; + WebContents* GetWebContents() const override; + void OnContentCheckCompleted(DownloadDangerType danger_type) override; + void SetOpenWhenComplete(bool open) override; + void SetIsTemporary(bool temporary) override; + void SetOpened(bool opened) override; + void SetDisplayName(const base::FilePath& name) override; + std::string DebugString(bool verbose) const override; // All remaining public interfaces virtual to allow for DownloadItemImpl // mocks. @@ -210,11 +208,11 @@ class CONTENT_EXPORT DownloadItemImpl virtual void MarkAsComplete(); // DownloadDestinationObserver - virtual void DestinationUpdate(int64 bytes_so_far, - int64 bytes_per_sec, - const std::string& hash_state) OVERRIDE; - virtual void DestinationError(DownloadInterruptReason reason) OVERRIDE; - virtual void DestinationCompleted(const std::string& final_hash) OVERRIDE; + void DestinationUpdate(int64 bytes_so_far, + int64 bytes_per_sec, + const std::string& hash_state) override; + void DestinationError(DownloadInterruptReason reason) override; + void DestinationCompleted(const std::string& final_hash) override; private: // Fine grained states of a download. Note that active downloads are created @@ -437,7 +435,7 @@ class CONTENT_EXPORT DownloadItemImpl base::FilePath forced_file_path_; // Page transition that triggerred the download. - PageTransition transition_type_; + ui::PageTransition transition_type_; // Whether the download was triggered with a user gesture. bool has_user_gesture_; diff --git a/chromium/content/browser/download/download_item_impl_unittest.cc b/chromium/content/browser/download/download_item_impl_unittest.cc index 1291ce11350..acbc55e2ef8 100644 --- a/chromium/content/browser/download/download_item_impl_unittest.cc +++ b/chromium/content/browser/download/download_item_impl_unittest.cc @@ -54,7 +54,7 @@ class MockDelegate : public DownloadItemImplDelegate { MOCK_METHOD1(CheckForFileRemoval, void(DownloadItemImpl*)); virtual void ResumeInterruptedDownload( - scoped_ptr<DownloadUrlParameters> params, uint32 id) OVERRIDE { + scoped_ptr<DownloadUrlParameters> params, uint32 id) override { MockResumeInterruptedDownload(params.get(), id); } MOCK_METHOD2(MockResumeInterruptedDownload, @@ -121,17 +121,17 @@ class DownloadItemTest : public testing::Test { item_->AddObserver(this); } - virtual ~MockObserver() { + ~MockObserver() override { if (item_) item_->RemoveObserver(this); } - virtual void OnDownloadRemoved(DownloadItem* download) OVERRIDE { + void OnDownloadRemoved(DownloadItem* download) override { DVLOG(20) << " " << __FUNCTION__ << " download = " << download->DebugString(false); removed_ = true; } - virtual void OnDownloadUpdated(DownloadItem* download) OVERRIDE { + void OnDownloadUpdated(DownloadItem* download) override { DVLOG(20) << " " << __FUNCTION__ << " download = " << download->DebugString(false); updated_ = true; @@ -147,12 +147,12 @@ class DownloadItemTest : public testing::Test { last_state_ = new_state; } - virtual void OnDownloadOpened(DownloadItem* download) OVERRIDE { + void OnDownloadOpened(DownloadItem* download) override { DVLOG(20) << " " << __FUNCTION__ << " download = " << download->DebugString(false); } - virtual void OnDownloadDestroyed(DownloadItem* download) OVERRIDE { + void OnDownloadDestroyed(DownloadItem* download) override { DVLOG(20) << " " << __FUNCTION__ << " download = " << download->DebugString(false); destroyed_ = true; @@ -409,7 +409,7 @@ TEST_F(DownloadItemTest, NotificationAfterDestroyed) { } TEST_F(DownloadItemTest, ContinueAfterInterrupted) { - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); DownloadItemImpl* item = CreateDownloadItem(); @@ -437,7 +437,7 @@ TEST_F(DownloadItemTest, ContinueAfterInterrupted) { // Same as above, but with a non-continuable interrupt. TEST_F(DownloadItemTest, RestartAfterInterrupted) { - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); DownloadItemImpl* item = CreateDownloadItem(); @@ -461,7 +461,7 @@ TEST_F(DownloadItemTest, RestartAfterInterrupted) { // Check we do correct cleanup for RESUME_MODE_INVALID interrupts. TEST_F(DownloadItemTest, UnresumableInterrupt) { - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); DownloadItemImpl* item = CreateDownloadItem(); @@ -491,7 +491,7 @@ TEST_F(DownloadItemTest, UnresumableInterrupt) { } TEST_F(DownloadItemTest, LimitRestartsAfterInterrupted) { - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); DownloadItemImpl* item = CreateDownloadItem(); @@ -813,7 +813,7 @@ TEST_F(DownloadItemTest, InterruptedBeforeIntermediateRename_Restart) { // intermediate path should be retained when the download is interrupted after // the intermediate rename succeeds. TEST_F(DownloadItemTest, InterruptedBeforeIntermediateRename_Continue) { - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); DownloadItemImpl* item = CreateDownloadItem(); DownloadItemImplDelegate::DownloadTargetCallback callback; @@ -848,7 +848,7 @@ TEST_F(DownloadItemTest, InterruptedBeforeIntermediateRename_Continue) { // As above. If the intermediate rename fails, then the interrupt reason should // be set to the destination error and the intermediate path should be empty. TEST_F(DownloadItemTest, InterruptedBeforeIntermediateRename_Failed) { - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); DownloadItemImpl* item = CreateDownloadItem(); DownloadItemImplDelegate::DownloadTargetCallback callback; @@ -1248,7 +1248,7 @@ TEST_F(DownloadItemTest, StealDangerousDownload) { } TEST_F(DownloadItemTest, StealInterruptedDangerousDownload) { - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); base::FilePath returned_path; DownloadItemImpl* item = CreateDownloadItem(); @@ -1274,7 +1274,7 @@ TEST_F(DownloadItemTest, StealInterruptedDangerousDownload) { } TEST_F(DownloadItemTest, StealInterruptedNonResumableDangerousDownload) { - CommandLine::ForCurrentProcess()->AppendSwitch( + base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableDownloadResumption); base::FilePath returned_path; DownloadItemImpl* item = CreateDownloadItem(); diff --git a/chromium/content/browser/download/download_manager_impl.cc b/chromium/content/browser/download/download_manager_impl.cc index 2bd747d5595..30296cb82e7 100644 --- a/chromium/content/browser/download/download_manager_impl.cc +++ b/chromium/content/browser/download/download_manager_impl.cc @@ -39,10 +39,10 @@ #include "content/public/browser/resource_context.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/common/referrer.h" +#include "net/base/elements_upload_data_stream.h" #include "net/base/load_flags.h" #include "net/base/request_priority.h" #include "net/base/upload_bytes_element_reader.h" -#include "net/base/upload_data_stream.h" #include "net/url_request/url_request_context.h" namespace content { @@ -63,8 +63,8 @@ void BeginDownload(scoped_ptr<DownloadUrlParameters> params, const std::string& body = params->post_body(); scoped_ptr<net::UploadElementReader> reader( net::UploadOwnedBytesElementReader::CreateWithString(body)); - request->set_upload(make_scoped_ptr( - net::UploadDataStream::CreateWithReader(reader.Pass(), 0))); + request->set_upload( + net::ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0)); } if (params->post_id() >= 0) { // The POST in this case does not have an actual body, and only works @@ -75,7 +75,8 @@ void BeginDownload(scoped_ptr<DownloadUrlParameters> params, DCHECK_EQ("POST", params->method()); ScopedVector<net::UploadElementReader> element_readers; request->set_upload(make_scoped_ptr( - new net::UploadDataStream(element_readers.Pass(), params->post_id()))); + new net::ElementsUploadDataStream(element_readers.Pass(), + params->post_id()))); } // If we're not at the beginning of the file, retrieve only the remaining @@ -160,9 +161,9 @@ class MapValueIteratorAdapter { class DownloadItemFactoryImpl : public DownloadItemFactory { public: DownloadItemFactoryImpl() {} - virtual ~DownloadItemFactoryImpl() {} + ~DownloadItemFactoryImpl() override {} - virtual DownloadItemImpl* CreatePersistedItem( + DownloadItemImpl* CreatePersistedItem( DownloadItemImplDelegate* delegate, uint32 download_id, const base::FilePath& current_path, @@ -181,7 +182,7 @@ class DownloadItemFactoryImpl : public DownloadItemFactory { DownloadDangerType danger_type, DownloadInterruptReason interrupt_reason, bool opened, - const net::BoundNetLog& bound_net_log) OVERRIDE { + const net::BoundNetLog& bound_net_log) override { return new DownloadItemImpl( delegate, download_id, @@ -204,22 +205,22 @@ class DownloadItemFactoryImpl : public DownloadItemFactory { bound_net_log); } - virtual DownloadItemImpl* CreateActiveItem( + DownloadItemImpl* CreateActiveItem( DownloadItemImplDelegate* delegate, uint32 download_id, const DownloadCreateInfo& info, - const net::BoundNetLog& bound_net_log) OVERRIDE { + const net::BoundNetLog& bound_net_log) override { return new DownloadItemImpl(delegate, download_id, info, bound_net_log); } - virtual DownloadItemImpl* CreateSavePageItem( + DownloadItemImpl* CreateSavePageItem( DownloadItemImplDelegate* delegate, uint32 download_id, const base::FilePath& path, const GURL& url, const std::string& mime_type, scoped_ptr<DownloadRequestHandleInterface> request_handle, - const net::BoundNetLog& bound_net_log) OVERRIDE { + const net::BoundNetLog& bound_net_log) override { return new DownloadItemImpl(delegate, download_id, path, url, mime_type, request_handle.Pass(), bound_net_log); diff --git a/chromium/content/browser/download/download_manager_impl.h b/chromium/content/browser/download/download_manager_impl.h index 630c83252a8..0c9c33bbbad 100644 --- a/chromium/content/browser/download/download_manager_impl.h +++ b/chromium/content/browser/download/download_manager_impl.h @@ -40,7 +40,7 @@ class CONTENT_EXPORT DownloadManagerImpl : public DownloadManager, // Caller guarantees that |net_log| will remain valid // for the lifetime of DownloadManagerImpl (until Shutdown() is called). DownloadManagerImpl(net::NetLog* net_log, BrowserContext* browser_context); - virtual ~DownloadManagerImpl(); + ~DownloadManagerImpl() override; // Implementation functions (not part of the DownloadManager interface). @@ -58,22 +58,22 @@ class CONTENT_EXPORT DownloadManagerImpl : public DownloadManager, void OnSavePackageSuccessfullyFinished(DownloadItem* download_item); // DownloadManager functions. - virtual void SetDelegate(DownloadManagerDelegate* delegate) OVERRIDE; - virtual DownloadManagerDelegate* GetDelegate() const OVERRIDE; - virtual void Shutdown() OVERRIDE; - virtual void GetAllDownloads(DownloadVector* result) OVERRIDE; - virtual void StartDownload( + void SetDelegate(DownloadManagerDelegate* delegate) override; + DownloadManagerDelegate* GetDelegate() const override; + void Shutdown() override; + void GetAllDownloads(DownloadVector* result) override; + void StartDownload( scoped_ptr<DownloadCreateInfo> info, scoped_ptr<ByteStreamReader> stream, - const DownloadUrlParameters::OnStartedCallback& on_started) OVERRIDE; - virtual int RemoveDownloadsBetween(base::Time remove_begin, - base::Time remove_end) OVERRIDE; - virtual int RemoveDownloads(base::Time remove_begin) OVERRIDE; - virtual int RemoveAllDownloads() OVERRIDE; - virtual void DownloadUrl(scoped_ptr<DownloadUrlParameters> params) OVERRIDE; - virtual void AddObserver(Observer* observer) OVERRIDE; - virtual void RemoveObserver(Observer* observer) OVERRIDE; - virtual content::DownloadItem* CreateDownloadItem( + const DownloadUrlParameters::OnStartedCallback& on_started) override; + int RemoveDownloadsBetween(base::Time remove_begin, + base::Time remove_end) override; + int RemoveDownloads(base::Time remove_begin) override; + int RemoveAllDownloads() override; + void DownloadUrl(scoped_ptr<DownloadUrlParameters> params) override; + void AddObserver(Observer* observer) override; + void RemoveObserver(Observer* observer) override; + content::DownloadItem* CreateDownloadItem( uint32 id, const base::FilePath& current_path, const base::FilePath& target_path, @@ -90,12 +90,12 @@ class CONTENT_EXPORT DownloadManagerImpl : public DownloadManager, content::DownloadItem::DownloadState state, DownloadDangerType danger_type, DownloadInterruptReason interrupt_reason, - bool opened) OVERRIDE; - virtual int InProgressCount() const OVERRIDE; - virtual int NonMaliciousInProgressCount() const OVERRIDE; - virtual BrowserContext* GetBrowserContext() const OVERRIDE; - virtual void CheckForHistoryFilesRemoval() OVERRIDE; - virtual DownloadItem* GetDownload(uint32 id) OVERRIDE; + bool opened) override; + int InProgressCount() const override; + int NonMaliciousInProgressCount() const override; + BrowserContext* GetBrowserContext() const override; + void CheckForHistoryFilesRemoval() override; + DownloadItem* GetDownload(uint32 id) override; // For testing; specifically, accessed from TestFileErrorInjector. void SetDownloadItemFactoryForTesting( @@ -144,22 +144,20 @@ class CONTENT_EXPORT DownloadManagerImpl : public DownloadManager, // Overridden from DownloadItemImplDelegate // (Note that |GetBrowserContext| are present in both interfaces.) - virtual void DetermineDownloadTarget( - DownloadItemImpl* item, const DownloadTargetCallback& callback) OVERRIDE; - virtual bool ShouldCompleteDownload( - DownloadItemImpl* item, const base::Closure& complete_callback) OVERRIDE; - virtual bool ShouldOpenFileBasedOnExtension( - const base::FilePath& path) OVERRIDE; - virtual bool ShouldOpenDownload( - DownloadItemImpl* item, - const ShouldOpenDownloadCallback& callback) OVERRIDE; - virtual void CheckForFileRemoval(DownloadItemImpl* download_item) OVERRIDE; - virtual void ResumeInterruptedDownload( + void DetermineDownloadTarget(DownloadItemImpl* item, + const DownloadTargetCallback& callback) override; + bool ShouldCompleteDownload(DownloadItemImpl* item, + const base::Closure& complete_callback) override; + bool ShouldOpenFileBasedOnExtension(const base::FilePath& path) override; + bool ShouldOpenDownload(DownloadItemImpl* item, + const ShouldOpenDownloadCallback& callback) override; + void CheckForFileRemoval(DownloadItemImpl* download_item) override; + void ResumeInterruptedDownload( scoped_ptr<content::DownloadUrlParameters> params, - uint32 id) OVERRIDE; - virtual void OpenDownload(DownloadItemImpl* download) OVERRIDE; - virtual void ShowDownloadInShell(DownloadItemImpl* download) OVERRIDE; - virtual void DownloadRemoved(DownloadItemImpl* download) OVERRIDE; + uint32 id) override; + void OpenDownload(DownloadItemImpl* download) override; + void ShowDownloadInShell(DownloadItemImpl* download) override; + void DownloadRemoved(DownloadItemImpl* download) override; // Factory for creation of downloads items. scoped_ptr<DownloadItemFactory> item_factory_; diff --git a/chromium/content/browser/download/download_manager_impl_unittest.cc b/chromium/content/browser/download/download_manager_impl_unittest.cc index 66430b4443a..0c5eb523966 100644 --- a/chromium/content/browser/download/download_manager_impl_unittest.cc +++ b/chromium/content/browser/download/download_manager_impl_unittest.cc @@ -111,7 +111,7 @@ class MockDownloadItemImpl : public DownloadItemImpl { MOCK_METHOD0(OnDownloadedFileRemoved, void()); virtual void Start( scoped_ptr<DownloadFile> download_file, - scoped_ptr<DownloadRequestHandleInterface> req_handle) OVERRIDE { + scoped_ptr<DownloadRequestHandleInterface> req_handle) override { MockStart(download_file.get(), req_handle.get()); } @@ -159,7 +159,7 @@ class MockDownloadItemImpl : public DownloadItemImpl { MOCK_METHOD0(GetAutoOpened, bool()); MOCK_CONST_METHOD0(GetForcedFilePath, const base::FilePath&()); MOCK_CONST_METHOD0(HasUserGesture, bool()); - MOCK_CONST_METHOD0(GetTransitionType, PageTransition()); + MOCK_CONST_METHOD0(GetTransitionType, ui::PageTransition()); MOCK_CONST_METHOD0(IsTemporary, bool()); MOCK_METHOD1(SetIsTemporary, void(bool)); MOCK_METHOD1(SetOpened, void(bool)); @@ -173,7 +173,7 @@ class MockDownloadItemImpl : public DownloadItemImpl { MOCK_METHOD1(SetDisplayName, void(const base::FilePath&)); MOCK_METHOD0(NotifyRemoved, void()); // May be called when vlog is on. - virtual std::string DebugString(bool verbose) const OVERRIDE { + virtual std::string DebugString(bool verbose) const override { return std::string(); } }; @@ -211,7 +211,7 @@ class MockDownloadItemFactory public base::SupportsWeakPtr<MockDownloadItemFactory> { public: MockDownloadItemFactory(); - virtual ~MockDownloadItemFactory(); + ~MockDownloadItemFactory() override; // Access to map of created items. // TODO(rdsmith): Could add type (save page, persisted, etc.) @@ -229,7 +229,7 @@ class MockDownloadItemFactory void RemoveItem(int id); // Overridden methods from DownloadItemFactory. - virtual DownloadItemImpl* CreatePersistedItem( + DownloadItemImpl* CreatePersistedItem( DownloadItemImplDelegate* delegate, uint32 download_id, const base::FilePath& current_path, @@ -248,20 +248,20 @@ class MockDownloadItemFactory DownloadDangerType danger_type, DownloadInterruptReason interrupt_reason, bool opened, - const net::BoundNetLog& bound_net_log) OVERRIDE; - virtual DownloadItemImpl* CreateActiveItem( + const net::BoundNetLog& bound_net_log) override; + DownloadItemImpl* CreateActiveItem( DownloadItemImplDelegate* delegate, uint32 download_id, const DownloadCreateInfo& info, - const net::BoundNetLog& bound_net_log) OVERRIDE; - virtual DownloadItemImpl* CreateSavePageItem( + const net::BoundNetLog& bound_net_log) override; + DownloadItemImpl* CreateSavePageItem( DownloadItemImplDelegate* delegate, uint32 download_id, const base::FilePath& path, const GURL& url, - const std::string& mime_type, + const std::string& mime_type, scoped_ptr<DownloadRequestHandleInterface> request_handle, - const net::BoundNetLog& bound_net_log) OVERRIDE; + const net::BoundNetLog& bound_net_log) override; private: std::map<uint32, MockDownloadItemImpl*> items_; @@ -415,8 +415,9 @@ class MockBrowserContext : public BrowserContext { MOCK_METHOD0(GetResourceContext, ResourceContext*()); MOCK_METHOD0(GetDownloadManagerDelegate, DownloadManagerDelegate*()); MOCK_METHOD0(GetGuestManager, BrowserPluginGuestManager* ()); - MOCK_METHOD0(GetSpecialStoragePolicy, quota::SpecialStoragePolicy*()); + MOCK_METHOD0(GetSpecialStoragePolicy, storage::SpecialStoragePolicy*()); MOCK_METHOD0(GetPushMessagingService, PushMessagingService*()); + MOCK_METHOD0(GetSSLHostStateDelegate, SSLHostStateDelegate*()); }; class MockDownloadManagerObserver : public DownloadManager::Observer { @@ -445,12 +446,12 @@ class DownloadManagerTest : public testing::Test { } // We tear down everything in TearDown(). - virtual ~DownloadManagerTest() {} + ~DownloadManagerTest() override {} // Create a MockDownloadItemFactory and MockDownloadManagerDelegate, // then create a DownloadManager that points // at all of those. - virtual void SetUp() { + void SetUp() override { DCHECK(!download_manager_); mock_download_item_factory_ = (new MockDownloadItemFactory())->AsWeakPtr(); @@ -476,7 +477,7 @@ class DownloadManagerTest : public testing::Test { download_manager_->SetDelegate(mock_download_manager_delegate_.get()); } - virtual void TearDown() { + void TearDown() override { while (MockDownloadItemImpl* item = mock_download_item_factory_->PopItem()) { EXPECT_CALL(*item, GetState()) diff --git a/chromium/content/browser/download/download_net_log_parameters.cc b/chromium/content/browser/download/download_net_log_parameters.cc index 45321362273..36e7e1e2210 100644 --- a/chromium/content/browser/download/download_net_log_parameters.cc +++ b/chromium/content/browser/download/download_net_log_parameters.cc @@ -34,10 +34,9 @@ static const char* download_danger_names[] = { "POTENTIALLY_UNWANTED" }; -COMPILE_ASSERT(ARRAYSIZE_UNSAFE(download_type_names) == SRC_SAVE_PAGE_AS + 1, +COMPILE_ASSERT(arraysize(download_type_names) == SRC_SAVE_PAGE_AS + 1, download_type_enum_has_changed); -COMPILE_ASSERT(ARRAYSIZE_UNSAFE(download_danger_names) == - DOWNLOAD_DANGER_TYPE_MAX, +COMPILE_ASSERT(arraysize(download_danger_names) == DOWNLOAD_DANGER_TYPE_MAX, download_danger_enum_has_changed); } // namespace diff --git a/chromium/content/browser/download/download_request_handle.h b/chromium/content/browser/download/download_request_handle.h index de1d8ae83d1..76affae249e 100644 --- a/chromium/content/browser/download/download_request_handle.h +++ b/chromium/content/browser/download/download_request_handle.h @@ -45,7 +45,7 @@ class CONTENT_EXPORT DownloadRequestHandleInterface { class CONTENT_EXPORT DownloadRequestHandle : public DownloadRequestHandleInterface { public: - virtual ~DownloadRequestHandle(); + ~DownloadRequestHandle() override; // Create a null DownloadRequestHandle: getters will return null, and // all actions are no-ops. @@ -63,12 +63,12 @@ class CONTENT_EXPORT DownloadRequestHandle int request_id); // Implement DownloadRequestHandleInterface interface. - virtual WebContents* GetWebContents() const OVERRIDE; - virtual DownloadManager* GetDownloadManager() const OVERRIDE; - virtual void PauseRequest() const OVERRIDE; - virtual void ResumeRequest() const OVERRIDE; - virtual void CancelRequest() const OVERRIDE; - virtual std::string DebugString() const OVERRIDE; + WebContents* GetWebContents() const override; + DownloadManager* GetDownloadManager() const override; + void PauseRequest() const override; + void ResumeRequest() const override; + void CancelRequest() const override; + std::string DebugString() const override; private: base::WeakPtr<DownloadResourceHandler> handler_; diff --git a/chromium/content/browser/download/download_resource_handler.cc b/chromium/content/browser/download/download_resource_handler.cc index 0a19163c9c3..f2fb2a5b267 100644 --- a/chromium/content/browser/download/download_resource_handler.cc +++ b/chromium/content/browser/download/download_resource_handler.cc @@ -141,12 +141,9 @@ bool DownloadResourceHandler::OnUploadProgress(uint64 position, } bool DownloadResourceHandler::OnRequestRedirected( - const GURL& url, + const net::RedirectInfo& redirect_info, ResourceResponse* response, bool* defer) { - // We treat a download as a main frame load, and thus update the policy URL - // on redirects. - request()->set_first_party_for_cookies(url); return true; } @@ -383,7 +380,10 @@ void DownloadResourceHandler::OnResponseCompleted( // to a user action. // TODO(ahendrickson) -- Find a better set of codes to use here, as // CANCELED/ERR_ABORTED can occur for reasons other than user cancel. - reason = DOWNLOAD_INTERRUPT_REASON_USER_CANCELED; + if (net::IsCertStatusError(request()->ssl_info().cert_status)) + reason = DOWNLOAD_INTERRUPT_REASON_SERVER_CERT_PROBLEM; + else + reason = DOWNLOAD_INTERRUPT_REASON_USER_CANCELED; } if (status.is_success() && @@ -414,6 +414,10 @@ void DownloadResourceHandler::OnResponseCompleted( // If we haven't received data when we get this error, we won't. reason = DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE; break; + case net::HTTP_UNAUTHORIZED: + // Server didn't authorize this request. + reason = DOWNLOAD_INTERRUPT_REASON_SERVER_UNAUTHORIZED; + break; default: // All other errors. // Redirection and informational codes should have been handled earlier // in the stack. diff --git a/chromium/content/browser/download/download_resource_handler.h b/chromium/content/browser/download/download_resource_handler.h index de6efef2fe6..89587831496 100644 --- a/chromium/content/browser/download/download_resource_handler.h +++ b/chromium/content/browser/download/download_resource_handler.h @@ -9,7 +9,6 @@ #include "base/callback.h" #include "base/memory/scoped_ptr.h" -#include "base/timer/timer.h" #include "content/browser/loader/resource_handler.h" #include "content/public/browser/download_interrupt_reasons.h" #include "content/public/browser/download_manager.h" @@ -46,36 +45,35 @@ class CONTENT_EXPORT DownloadResourceHandler const DownloadUrlParameters::OnStartedCallback& started_cb, scoped_ptr<DownloadSaveInfo> save_info); - virtual bool OnUploadProgress(uint64 position, uint64 size) OVERRIDE; + bool OnUploadProgress(uint64 position, uint64 size) override; - virtual bool OnRequestRedirected(const GURL& url, - ResourceResponse* response, - bool* defer) OVERRIDE; + bool OnRequestRedirected(const net::RedirectInfo& redirect_info, + ResourceResponse* response, + bool* defer) override; // Send the download creation information to the download thread. - virtual bool OnResponseStarted(ResourceResponse* response, - bool* defer) OVERRIDE; + bool OnResponseStarted(ResourceResponse* response, bool* defer) override; // Pass-through implementation. - virtual bool OnWillStart(const GURL& url, bool* defer) OVERRIDE; + bool OnWillStart(const GURL& url, bool* defer) override; // Pass-through implementation. - virtual bool OnBeforeNetworkStart(const GURL& url, bool* defer) OVERRIDE; + bool OnBeforeNetworkStart(const GURL& url, bool* defer) override; // Create a new buffer, which will be handed to the download thread for file // writing and deletion. - virtual bool OnWillRead(scoped_refptr<net::IOBuffer>* buf, - int* buf_size, - int min_size) OVERRIDE; + bool OnWillRead(scoped_refptr<net::IOBuffer>* buf, + int* buf_size, + int min_size) override; - virtual bool OnReadCompleted(int bytes_read, bool* defer) OVERRIDE; + bool OnReadCompleted(int bytes_read, bool* defer) override; - virtual void OnResponseCompleted(const net::URLRequestStatus& status, - const std::string& security_info, - bool* defer) OVERRIDE; + void OnResponseCompleted(const net::URLRequestStatus& status, + const std::string& security_info, + bool* defer) override; // N/A to this flavor of DownloadHandler. - virtual void OnDataDownloaded(int bytes_downloaded) OVERRIDE; + void OnDataDownloaded(int bytes_downloaded) override; void PauseRequest(); void ResumeRequest(); @@ -86,7 +84,7 @@ class CONTENT_EXPORT DownloadResourceHandler std::string DebugString() const; private: - virtual ~DownloadResourceHandler(); + ~DownloadResourceHandler() override; // Arrange for started_cb_ to be called on the UI thread with the // below values, nulling out started_cb_. Should only be called diff --git a/chromium/content/browser/download/download_stats.cc b/chromium/content/browser/download/download_stats.cc index 66716cac415..d88eef2c4e2 100644 --- a/chromium/content/browser/download/download_stats.cc +++ b/chromium/content/browser/download/download_stats.cc @@ -611,6 +611,18 @@ void RecordFileBandwidth(size_t length, disk_write_time_ms * 100 / elapsed_time_ms); } +void RecordDownloadFileRenameResultAfterRetry( + base::TimeDelta time_since_first_failure, + DownloadInterruptReason interrupt_reason) { + if (interrupt_reason == DOWNLOAD_INTERRUPT_REASON_NONE) { + UMA_HISTOGRAM_TIMES("Download.TimeToRenameSuccessAfterInitialFailure", + time_since_first_failure); + } else { + UMA_HISTOGRAM_TIMES("Download.TimeToRenameFailureAfterInitialFailure", + time_since_first_failure); + } +} + void RecordSavePackageEvent(SavePackageEvent event) { UMA_HISTOGRAM_ENUMERATION("Download.SavePackage", event, diff --git a/chromium/content/browser/download/download_stats.h b/chromium/content/browser/download/download_stats.h index 65fad8d6b4a..3ae2612f8ea 100644 --- a/chromium/content/browser/download/download_stats.h +++ b/chromium/content/browser/download/download_stats.h @@ -200,6 +200,11 @@ void RecordFileBandwidth(size_t length, base::TimeDelta disk_write_time, base::TimeDelta elapsed_time); +// Record the result of a download file rename. +void RecordDownloadFileRenameResultAfterRetry( + base::TimeDelta time_since_first_failure, + DownloadInterruptReason interrupt_reason); + enum SavePackageEvent { // The user has started to save a page as a package. SAVE_PACKAGE_STARTED, diff --git a/chromium/content/browser/download/drag_download_file.cc b/chromium/content/browser/download/drag_download_file.cc index 29b8b5caa5c..ca68740a257 100644 --- a/chromium/content/browser/download/drag_download_file.cc +++ b/chromium/content/browser/download/drag_download_file.cc @@ -83,7 +83,7 @@ class DragDownloadFile::DragDownloadFileUI : public DownloadItem::Observer { } private: - virtual ~DragDownloadFileUI() { + ~DragDownloadFileUI() override { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (download_item_) download_item_->RemoveObserver(this); @@ -103,7 +103,7 @@ class DragDownloadFile::DragDownloadFileUI : public DownloadItem::Observer { } // DownloadItem::Observer: - virtual void OnDownloadUpdated(DownloadItem* item) OVERRIDE { + void OnDownloadUpdated(DownloadItem* item) override { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK_EQ(download_item_, item); DownloadItem::DownloadState state = download_item_->GetState(); @@ -121,7 +121,7 @@ class DragDownloadFile::DragDownloadFileUI : public DownloadItem::Observer { // Ignore other states. } - virtual void OnDownloadDestroyed(DownloadItem* item) OVERRIDE { + void OnDownloadDestroyed(DownloadItem* item) override { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK_EQ(download_item_, item); if (!on_completed_.is_null()) { diff --git a/chromium/content/browser/download/drag_download_file.h b/chromium/content/browser/download/drag_download_file.h index 62e4ec2aa28..825f73668aa 100644 --- a/chromium/content/browser/download/drag_download_file.h +++ b/chromium/content/browser/download/drag_download_file.h @@ -42,15 +42,15 @@ class CONTENT_EXPORT DragDownloadFile : public ui::DownloadFileProvider { WebContents* web_contents); // DownloadFileProvider methods. - virtual void Start(ui::DownloadFileObserver* observer) OVERRIDE; - virtual bool Wait() OVERRIDE; - virtual void Stop() OVERRIDE; + void Start(ui::DownloadFileObserver* observer) override; + bool Wait() override; + void Stop() override; private: class DragDownloadFileUI; enum State {INITIALIZED, STARTED, SUCCESS, FAILURE}; - virtual ~DragDownloadFile(); + ~DragDownloadFile() override; void DownloadCompleted(bool is_successful); void CheckThread(); diff --git a/chromium/content/browser/download/drag_download_file_browsertest.cc b/chromium/content/browser/download/drag_download_file_browsertest.cc index 136fac3cf32..0b1de7d6fcd 100644 --- a/chromium/content/browser/download/drag_download_file_browsertest.cc +++ b/chromium/content/browser/download/drag_download_file_browsertest.cc @@ -4,6 +4,7 @@ #include "base/files/file_path.h" #include "base/files/scoped_temp_dir.h" +#include "base/memory/ref_counted.h" #include "content/browser/download/download_file_factory.h" #include "content/browser/download/download_file_impl.h" #include "content/browser/download/download_item_impl.h" @@ -21,8 +22,8 @@ #include "content/shell/browser/shell.h" #include "content/shell/browser/shell_browser_context.h" #include "content/shell/browser/shell_download_manager_delegate.h" -#include "content/test/net/url_request_mock_http_job.h" #include "content/test/net/url_request_slow_download_job.h" +#include "net/test/url_request/url_request_mock_http_job.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -48,7 +49,7 @@ class MockDownloadFileObserver : public ui::DownloadFileObserver { class DragDownloadFileTest : public ContentBrowserTest { public: DragDownloadFileTest() {} - virtual ~DragDownloadFileTest() {} + ~DragDownloadFileTest() override {} void Succeed() { BrowserThread::PostTask(BrowserThread::UI, @@ -61,7 +62,7 @@ class DragDownloadFileTest : public ContentBrowserTest { } protected: - virtual void SetUpOnMainThread() OVERRIDE { + void SetUpOnMainThread() override { ASSERT_TRUE(downloads_directory_.CreateUniqueTempDir()); ShellDownloadManagerDelegate* delegate = static_cast<ShellDownloadManagerDelegate*>( @@ -73,8 +74,12 @@ class DragDownloadFileTest : public ContentBrowserTest { void SetUpServer() { base::FilePath mock_base(GetTestFilePath("download", "")); BrowserThread::PostTask( - BrowserThread::IO, FROM_HERE, - base::Bind(&URLRequestMockHTTPJob::AddUrlHandler, mock_base)); + BrowserThread::IO, + FROM_HERE, + base::Bind( + &net::URLRequestMockHTTPJob::AddUrlHandler, + mock_base, + make_scoped_refptr(content::BrowserThread::GetBlockingPool()))); } const base::FilePath& downloads_directory() const { @@ -90,8 +95,8 @@ class DragDownloadFileTest : public ContentBrowserTest { IN_PROC_BROWSER_TEST_F(DragDownloadFileTest, DragDownloadFileTest_NetError) { base::FilePath name(downloads_directory().AppendASCII( "DragDownloadFileTest_NetError.txt")); - GURL url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(FILE_PATH_LITERAL( - "download-test.lib")))); + GURL url(net::URLRequestMockHTTPJob::GetMockUrl( + base::FilePath(FILE_PATH_LITERAL("download-test.lib")))); Referrer referrer; std::string referrer_encoding; scoped_refptr<DragDownloadFile> file( @@ -110,8 +115,8 @@ IN_PROC_BROWSER_TEST_F(DragDownloadFileTest, DragDownloadFileTest_NetError) { IN_PROC_BROWSER_TEST_F(DragDownloadFileTest, DragDownloadFileTest_Complete) { base::FilePath name(downloads_directory().AppendASCII( "DragDownloadFileTest_Complete.txt")); - GURL url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(FILE_PATH_LITERAL( - "download-test.lib")))); + GURL url(net::URLRequestMockHTTPJob::GetMockUrl( + base::FilePath(FILE_PATH_LITERAL("download-test.lib")))); Referrer referrer; std::string referrer_encoding; SetUpServer(); diff --git a/chromium/content/browser/download/drag_download_util.h b/chromium/content/browser/download/drag_download_util.h index 76b4e61068c..38b516c5854 100644 --- a/chromium/content/browser/download/drag_download_util.h +++ b/chromium/content/browser/download/drag_download_util.h @@ -45,11 +45,11 @@ class PromiseFileFinalizer : public ui::DownloadFileObserver { explicit PromiseFileFinalizer(DragDownloadFile* drag_file_downloader); // DownloadFileObserver methods. - virtual void OnDownloadCompleted(const base::FilePath& file_path) OVERRIDE; - virtual void OnDownloadAborted() OVERRIDE; + void OnDownloadCompleted(const base::FilePath& file_path) override; + void OnDownloadAborted() override; protected: - virtual ~PromiseFileFinalizer(); + ~PromiseFileFinalizer() override; private: void Cleanup(); diff --git a/chromium/content/browser/download/file_metadata_linux.cc b/chromium/content/browser/download/file_metadata_linux.cc index c06d3f1a90f..1864d29a717 100644 --- a/chromium/content/browser/download/file_metadata_linux.cc +++ b/chromium/content/browser/download/file_metadata_linux.cc @@ -7,8 +7,8 @@ #include <sys/types.h> #include <sys/xattr.h> -#include "base/file_util.h" #include "base/files/file_path.h" +#include "base/files/file_util.h" #include "base/logging.h" #include "url/gurl.h" diff --git a/chromium/content/browser/download/file_metadata_unittest_linux.cc b/chromium/content/browser/download/file_metadata_unittest_linux.cc index 96db2646470..ab7eb3c8044 100644 --- a/chromium/content/browser/download/file_metadata_unittest_linux.cc +++ b/chromium/content/browser/download/file_metadata_unittest_linux.cc @@ -10,8 +10,8 @@ #include <sstream> #include <string> -#include "base/file_util.h" #include "base/files/file_path.h" +#include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/logging.h" #include "base/strings/string_split.h" @@ -50,7 +50,7 @@ class FileMetadataLinuxTest : public testing::Test { } protected: - virtual void SetUp() OVERRIDE { + void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.path(), &test_file_)); int result = setxattr(test_file_.value().c_str(), diff --git a/chromium/content/browser/download/mhtml_generation_browsertest.cc b/chromium/content/browser/download/mhtml_generation_browsertest.cc index 283e53ac1e0..fbe9a1f6db9 100644 --- a/chromium/content/browser/download/mhtml_generation_browsertest.cc +++ b/chromium/content/browser/download/mhtml_generation_browsertest.cc @@ -3,8 +3,8 @@ // found in the LICENSE file. #include "base/bind.h" -#include "base/file_util.h" #include "base/files/file_path.h" +#include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/run_loop.h" #include "content/public/browser/web_contents.h" @@ -28,7 +28,7 @@ class MHTMLGenerationTest : public ContentBrowserTest { } protected: - virtual void SetUp() { + void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); ContentBrowserTest::SetUp(); } diff --git a/chromium/content/browser/download/mhtml_generation_manager.cc b/chromium/content/browser/download/mhtml_generation_manager.cc index db4ba30533f..d02d509996a 100644 --- a/chromium/content/browser/download/mhtml_generation_manager.cc +++ b/chromium/content/browser/download/mhtml_generation_manager.cc @@ -19,7 +19,7 @@ namespace content { class MHTMLGenerationManager::Job : public RenderProcessHostObserver { public: Job(); - virtual ~Job(); + ~Job() override; void SetWebContents(WebContents* web_contents); @@ -33,12 +33,10 @@ class MHTMLGenerationManager::Job : public RenderProcessHostObserver { void set_callback(GenerateMHTMLCallback callback) { callback_ = callback; } // RenderProcessHostObserver: - virtual void RenderProcessExited(RenderProcessHost* host, - base::ProcessHandle handle, - base::TerminationStatus status, - int exit_code) OVERRIDE; - virtual void RenderProcessHostDestroyed(RenderProcessHost* host) OVERRIDE; - + void RenderProcessExited(RenderProcessHost* host, + base::TerminationStatus status, + int exit_code) override; + void RenderProcessHostDestroyed(RenderProcessHost* host) override; private: // The handle to the file the MHTML is saved to for the browser process. @@ -76,7 +74,6 @@ void MHTMLGenerationManager::Job::SetWebContents(WebContents* web_contents) { void MHTMLGenerationManager::Job::RenderProcessExited( RenderProcessHost* host, - base::ProcessHandle handle, base::TerminationStatus status, int exit_code) { MHTMLGenerationManager::GetInstance()->RenderProcessExited(this); diff --git a/chromium/content/browser/download/save_file_manager.cc b/chromium/content/browser/download/save_file_manager.cc index 80ab95eefd0..e9c03f484ff 100644 --- a/chromium/content/browser/download/save_file_manager.cc +++ b/chromium/content/browser/download/save_file_manager.cc @@ -7,7 +7,7 @@ #include "content/browser/download/save_file_manager.h" #include "base/bind.h" -#include "base/file_util.h" +#include "base/files/file_util.h" #include "base/logging.h" #include "base/stl_util.h" #include "base/strings/string_util.h" diff --git a/chromium/content/browser/download/save_file_resource_handler.cc b/chromium/content/browser/download/save_file_resource_handler.cc index e1fc32b7fc4..17c29ed6593 100644 --- a/chromium/content/browser/download/save_file_resource_handler.cc +++ b/chromium/content/browser/download/save_file_resource_handler.cc @@ -11,6 +11,7 @@ #include "content/browser/download/save_file_manager.h" #include "content/public/browser/browser_thread.h" #include "net/base/io_buffer.h" +#include "net/url_request/redirect_info.h" #include "net/url_request/url_request_status.h" namespace content { @@ -37,10 +38,10 @@ bool SaveFileResourceHandler::OnUploadProgress(uint64 position, uint64 size) { } bool SaveFileResourceHandler::OnRequestRedirected( - const GURL& url, + const net::RedirectInfo& redirect_info, ResourceResponse* response, bool* defer) { - final_url_ = url; + final_url_ = redirect_info.new_url; return true; } diff --git a/chromium/content/browser/download/save_file_resource_handler.h b/chromium/content/browser/download/save_file_resource_handler.h index 5adbc5c229a..b7425b49b01 100644 --- a/chromium/content/browser/download/save_file_resource_handler.h +++ b/chromium/content/browser/download/save_file_resource_handler.h @@ -26,42 +26,41 @@ class SaveFileResourceHandler : public ResourceHandler { int render_view_id, const GURL& url, SaveFileManager* manager); - virtual ~SaveFileResourceHandler(); + ~SaveFileResourceHandler() override; // ResourceHandler Implementation: - virtual bool OnUploadProgress(uint64 position, uint64 size) OVERRIDE; + bool OnUploadProgress(uint64 position, uint64 size) override; // Saves the redirected URL to final_url_, we need to use the original // URL to match original request. - virtual bool OnRequestRedirected(const GURL& url, - ResourceResponse* response, - bool* defer) OVERRIDE; + bool OnRequestRedirected(const net::RedirectInfo& redirect_info, + ResourceResponse* response, + bool* defer) override; // Sends the download creation information to the download thread. - virtual bool OnResponseStarted(ResourceResponse* response, - bool* defer) OVERRIDE; + bool OnResponseStarted(ResourceResponse* response, bool* defer) override; // Pass-through implementation. - virtual bool OnWillStart(const GURL& url, bool* defer) OVERRIDE; + bool OnWillStart(const GURL& url, bool* defer) override; // Pass-through implementation. - virtual bool OnBeforeNetworkStart(const GURL& url, bool* defer) OVERRIDE; + bool OnBeforeNetworkStart(const GURL& url, bool* defer) override; // Creates a new buffer, which will be handed to the download thread for file // writing and deletion. - virtual bool OnWillRead(scoped_refptr<net::IOBuffer>* buf, - int* buf_size, - int min_size) OVERRIDE; + bool OnWillRead(scoped_refptr<net::IOBuffer>* buf, + int* buf_size, + int min_size) override; // Passes the buffer to the download file writer. - virtual bool OnReadCompleted(int bytes_read, bool* defer) OVERRIDE; + bool OnReadCompleted(int bytes_read, bool* defer) override; - virtual void OnResponseCompleted(const net::URLRequestStatus& status, - const std::string& security_info, - bool* defer) OVERRIDE; + void OnResponseCompleted(const net::URLRequestStatus& status, + const std::string& security_info, + bool* defer) override; // N/A to this flavor of SaveFileResourceHandler. - virtual void OnDataDownloaded(int bytes_downloaded) OVERRIDE; + void OnDataDownloaded(int bytes_downloaded) override; // If the content-length header is not present (or contains something other // than numbers), StringToInt64 returns 0, which indicates 'unknown size' and diff --git a/chromium/content/browser/download/save_package.cc b/chromium/content/browser/download/save_package.cc index 90ab2a5056d..486cb1057d1 100644 --- a/chromium/content/browser/download/save_package.cc +++ b/chromium/content/browser/download/save_package.cc @@ -7,8 +7,8 @@ #include <algorithm> #include "base/bind.h" -#include "base/file_util.h" #include "base/files/file_path.h" +#include "base/files/file_util.h" #include "base/i18n/file_util_icu.h" #include "base/logging.h" #include "base/message_loop/message_loop.h" @@ -113,16 +113,14 @@ class SavePackageRequestHandle : public DownloadRequestHandleInterface { : save_package_(save_package) {} // DownloadRequestHandleInterface - virtual WebContents* GetWebContents() const OVERRIDE { + WebContents* GetWebContents() const override { return save_package_.get() ? save_package_->web_contents() : NULL; } - virtual DownloadManager* GetDownloadManager() const OVERRIDE { - return NULL; - } - virtual void PauseRequest() const OVERRIDE {} - virtual void ResumeRequest() const OVERRIDE {} - virtual void CancelRequest() const OVERRIDE {} - virtual std::string DebugString() const OVERRIDE { + DownloadManager* GetDownloadManager() const override { return NULL; } + void PauseRequest() const override {} + void ResumeRequest() const override {} + void CancelRequest() const override {} + std::string DebugString() const override { return "SavePackage DownloadRequestHandle"; } @@ -133,11 +131,7 @@ class SavePackageRequestHandle : public DownloadRequestHandleInterface { } // namespace const base::FilePath::CharType SavePackage::kDefaultHtmlExtension[] = -#if defined(OS_WIN) - FILE_PATH_LITERAL("htm"); -#else FILE_PATH_LITERAL("html"); -#endif SavePackage::SavePackage(WebContents* web_contents, SavePageType save_type, @@ -471,7 +465,7 @@ bool SavePackage::GenerateFileName(const std::string& disposition, file_path.RemoveExtension().BaseName().value(); base::FilePath::StringType file_name_ext = file_path.Extension(); - // If it is HTML resource, use ".htm{l,}" as its extension. + // If it is HTML resource, use ".html" as its extension. if (need_html_ext) { file_name_ext = FILE_PATH_LITERAL("."); file_name_ext.append(kDefaultHtmlExtension); @@ -1248,7 +1242,7 @@ base::FilePath SavePackage::GetSuggestedNameForSaveAs( name_with_proper_ext = EnsureHtmlExtension(name_with_proper_ext); base::FilePath::StringType file_name = name_with_proper_ext.value(); - file_util::ReplaceIllegalCharactersInPath(&file_name, ' '); + base::i18n::ReplaceIllegalCharactersInPath(&file_name, ' '); return base::FilePath(file_name); } @@ -1301,17 +1295,13 @@ const base::FilePath::CharType* SavePackage::ExtensionForMimeType( #elif defined(OS_WIN) base::FilePath::StringType mime_type(base::UTF8ToWide(contents_mime_type)); #endif // OS_WIN - for (uint32 i = 0; i < ARRAYSIZE_UNSAFE(extensions); ++i) { + for (uint32 i = 0; i < arraysize(extensions); ++i) { if (mime_type == extensions[i].mime_type) return extensions[i].suggested_extension; } return FILE_PATH_LITERAL(""); } -WebContents* SavePackage::web_contents() const { - return WebContentsObserver::web_contents(); -} - void SavePackage::GetSaveInfo() { // Can't use web_contents_ in the file thread, so get the data that we need // before calling to it. diff --git a/chromium/content/browser/download/save_package.h b/chromium/content/browser/download/save_package.h index 1ab429e16b9..3507b1760b4 100644 --- a/chromium/content/browser/download/save_package.h +++ b/chromium/content/browser/download/save_package.h @@ -117,7 +117,6 @@ class CONTENT_EXPORT SavePackage SavePageType save_type() const { return save_type_; } int contents_id() const { return contents_id_; } int id() const { return unique_id_; } - WebContents* web_contents() const; void GetSaveInfo(); @@ -136,7 +135,7 @@ class CONTENT_EXPORT SavePackage const base::FilePath& file_full_path, const base::FilePath& directory_full_path); - virtual ~SavePackage(); + ~SavePackage() override; // Notes from Init() above applies here as well. void InternalInit(); @@ -147,10 +146,10 @@ class CONTENT_EXPORT SavePackage void DoSavingProcess(); // WebContentsObserver implementation. - virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE; + bool OnMessageReceived(const IPC::Message& message) override; // DownloadItem::Observer implementation. - virtual void OnDownloadDestroyed(DownloadItem* download) OVERRIDE; + void OnDownloadDestroyed(DownloadItem* download) override; // Update the download history of this item upon completion. void FinalizeDownloadEntry(); diff --git a/chromium/content/browser/download/save_package_browsertest.cc b/chromium/content/browser/download/save_package_browsertest.cc index 2c7a652dd0d..5b3bc173634 100644 --- a/chromium/content/browser/download/save_package_browsertest.cc +++ b/chromium/content/browser/download/save_package_browsertest.cc @@ -14,7 +14,7 @@ const char kTestFile[] = "files/simple_page.html"; class SavePackageBrowserTest : public ContentBrowserTest { protected: - virtual void SetUp() OVERRIDE { + void SetUp() override { ASSERT_TRUE(save_dir_.CreateUniqueTempDir()); ContentBrowserTest::SetUp(); } diff --git a/chromium/content/browser/download/save_package_unittest.cc b/chromium/content/browser/download/save_package_unittest.cc index b0e38c0f18d..c0dcbf0a7eb 100644 --- a/chromium/content/browser/download/save_package_unittest.cc +++ b/chromium/content/browser/download/save_package_unittest.cc @@ -6,25 +6,23 @@ #include "base/files/file_path.h" #include "base/files/scoped_temp_dir.h" -#include "base/path_service.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "content/browser/download/save_package.h" -#include "content/test/net/url_request_mock_http_job.h" +#include "content/public/common/url_constants.h" #include "content/test/test_render_view_host.h" #include "content/test/test_web_contents.h" +#include "net/test/url_request/url_request_mock_http_job.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace content { #define FPL FILE_PATH_LITERAL +#define HTML_EXTENSION ".html" #if defined(OS_WIN) -#define HTML_EXTENSION ".htm" -// This second define is needed because MSVC is broken. -#define FPL_HTML_EXTENSION L".htm" +#define FPL_HTML_EXTENSION L".html" #else -#define HTML_EXTENSION ".html" #define FPL_HTML_EXTENSION ".html" #endif @@ -95,7 +93,7 @@ class SavePackageTest : public RenderViewHostImplTestHarness { } protected: - virtual void SetUp() { + void SetUp() override { RenderViewHostImplTestHarness::SetUp(); // Do the initialization in SetUp so contents() is initialized by @@ -176,7 +174,7 @@ static const struct { }; TEST_F(SavePackageTest, TestSuccessfullyGenerateSavePackageFilename) { - for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kGeneratedFiles); ++i) { + for (size_t i = 0; i < arraysize(kGeneratedFiles); ++i) { base::FilePath::StringType file_name; bool ok = GetGeneratedFilename(true, kGeneratedFiles[i].disposition, @@ -189,7 +187,7 @@ TEST_F(SavePackageTest, TestSuccessfullyGenerateSavePackageFilename) { } TEST_F(SavePackageTest, TestUnSuccessfullyGenerateSavePackageFilename) { - for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kGeneratedFiles); ++i) { + for (size_t i = 0; i < arraysize(kGeneratedFiles); ++i) { base::FilePath::StringType file_name; bool ok = GetGeneratedFilename(false, kGeneratedFiles[i].disposition, @@ -244,7 +242,7 @@ TEST_F(SavePackageTest, MAYBE_TestLongSafePureFilename) { const base::FilePath::StringType ext(FPL_HTML_EXTENSION); base::FilePath::StringType filename = #if defined(OS_WIN) - base::ASCIIToWide(long_file_name); + base::ASCIIToUTF16(long_file_name); #else long_file_name; #endif @@ -282,7 +280,7 @@ static const struct { #define MAYBE_TestEnsureHtmlExtension TestEnsureHtmlExtension #endif TEST_F(SavePackageTest, MAYBE_TestEnsureHtmlExtension) { - for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kExtensionTestCases); ++i) { + for (size_t i = 0; i < arraysize(kExtensionTestCases); ++i) { base::FilePath original = base::FilePath(kExtensionTestCases[i].page_title); base::FilePath expected = base::FilePath(kExtensionTestCases[i].expected_name); @@ -327,7 +325,7 @@ TEST_F(SavePackageTest, MAYBE_TestEnsureMimeExtension) { { FPL("filename.abc"), FPL("filename.abc"), "unknown/unknown" }, { FPL("filename"), FPL("filename"), "unknown/unknown" }, }; - for (uint32 i = 0; i < ARRAYSIZE_UNSAFE(kExtensionTests); ++i) { + for (uint32 i = 0; i < arraysize(kExtensionTests); ++i) { base::FilePath original = base::FilePath(kExtensionTests[i].page_title); base::FilePath expected = base::FilePath(kExtensionTests[i].expected_name); std::string mime_type(kExtensionTests[i].contents_mime_type); @@ -416,8 +414,8 @@ static const base::FilePath::CharType* kTestDir = // GetUrlToBeSaved method should return correct url to be saved. TEST_F(SavePackageTest, TestGetUrlToBeSaved) { base::FilePath file_name(FILE_PATH_LITERAL("a.htm")); - GURL url = URLRequestMockHTTPJob::GetMockUrl( - base::FilePath(kTestDir).Append(file_name)); + GURL url = net::URLRequestMockHTTPJob::GetMockUrl( + base::FilePath(kTestDir).Append(file_name)); NavigateAndCommit(url); EXPECT_EQ(url, GetUrlToBeSaved()); } @@ -428,10 +426,12 @@ TEST_F(SavePackageTest, TestGetUrlToBeSaved) { // when user types view-source:http://www.google.com TEST_F(SavePackageTest, TestGetUrlToBeSavedViewSource) { base::FilePath file_name(FILE_PATH_LITERAL("a.htm")); - GURL view_source_url = URLRequestMockHTTPJob::GetMockViewSourceUrl( - base::FilePath(kTestDir).Append(file_name)); - GURL actual_url = URLRequestMockHTTPJob::GetMockUrl( - base::FilePath(kTestDir).Append(file_name)); + GURL mock_url = net::URLRequestMockHTTPJob::GetMockUrl( + base::FilePath(kTestDir).Append(file_name)); + GURL view_source_url = + GURL(kViewSourceScheme + std::string(":") + mock_url.spec()); + GURL actual_url = net::URLRequestMockHTTPJob::GetMockUrl( + base::FilePath(kTestDir).Append(file_name)); NavigateAndCommit(view_source_url); EXPECT_EQ(actual_url, GetUrlToBeSaved()); EXPECT_EQ(view_source_url, contents()->GetLastCommittedURL()); |