diff options
author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2020-10-12 14:27:29 +0200 |
---|---|---|
committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2020-10-13 09:35:20 +0000 |
commit | c30a6232df03e1efbd9f3b226777b07e087a1122 (patch) | |
tree | e992f45784689f373bcc38d1b79a239ebe17ee23 /chromium/net/test | |
parent | 7b5b123ac58f58ffde0f4f6e488bcd09aa4decd3 (diff) | |
download | qtwebengine-chromium-85-based.tar.gz |
BASELINE: Update Chromium to 85.0.4183.14085-based
Change-Id: Iaa42f4680837c57725b1344f108c0196741f6057
Reviewed-by: Allan Sandfeld Jensen <allan.jensen@qt.io>
Diffstat (limited to 'chromium/net/test')
9 files changed, 115 insertions, 468 deletions
diff --git a/chromium/net/test/cert_test_util_nss.cc b/chromium/net/test/cert_test_util_nss.cc index 2b55ebc979c..096285d0963 100644 --- a/chromium/net/test/cert_test_util_nss.cc +++ b/chromium/net/test/cert_test_util_nss.cc @@ -12,6 +12,7 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" +#include "base/logging.h" #include "crypto/ec_private_key.h" #include "crypto/nss_key_util.h" #include "crypto/nss_util.h" diff --git a/chromium/net/test/embedded_test_server/embedded_test_server.cc b/chromium/net/test/embedded_test_server/embedded_test_server.cc index 36873f21b8a..d143a79ff94 100644 --- a/chromium/net/test/embedded_test_server/embedded_test_server.cc +++ b/chromium/net/test/embedded_test_server/embedded_test_server.cc @@ -219,6 +219,28 @@ bool MaybeCreateOCSPResponse(CertBuilder* target, } // namespace +EmbeddedTestServerHandle::EmbeddedTestServerHandle( + EmbeddedTestServerHandle&& other) { + operator=(std::move(other)); +} + +EmbeddedTestServerHandle& EmbeddedTestServerHandle::operator=( + EmbeddedTestServerHandle&& other) { + EmbeddedTestServerHandle temporary; + std::swap(other.test_server_, temporary.test_server_); + std::swap(temporary.test_server_, test_server_); + return *this; +} + +EmbeddedTestServerHandle::EmbeddedTestServerHandle( + EmbeddedTestServer* test_server) + : test_server_(test_server) {} + +EmbeddedTestServerHandle::~EmbeddedTestServerHandle() { + if (test_server_) + CHECK(test_server_->ShutdownAndWaitUntilComplete()); +} + EmbeddedTestServer::OCSPConfig::OCSPConfig() = default; EmbeddedTestServer::OCSPConfig::OCSPConfig(ResponseType response_type) : response_type(response_type) {} @@ -268,9 +290,8 @@ EmbeddedTestServer::EmbeddedTestServer(Type type) EmbeddedTestServer::~EmbeddedTestServer() { DCHECK(thread_checker_.CalledOnValidThread()); - if (Started() && !ShutdownAndWaitUntilComplete()) { - LOG(ERROR) << "EmbeddedTestServer failed to shut down."; - } + if (Started()) + CHECK(ShutdownAndWaitUntilComplete()); { base::ScopedAllowBaseSyncPrimitivesForTesting allow_wait_for_thread_join; @@ -288,23 +309,21 @@ void EmbeddedTestServer::RegisterTestCerts() { void EmbeddedTestServer::SetConnectionListener( EmbeddedTestServerConnectionListener* listener) { - DCHECK(!io_thread_.get()) + DCHECK(!io_thread_) << "ConnectionListener must be set before starting the server."; connection_listener_ = listener; } EmbeddedTestServerHandle EmbeddedTestServer::StartAndReturnHandle(int port) { - if (!Start(port)) - return EmbeddedTestServerHandle(); - return EmbeddedTestServerHandle(this); + bool result = Start(port); + return result ? EmbeddedTestServerHandle(this) : EmbeddedTestServerHandle(); } bool EmbeddedTestServer::Start(int port) { bool success = InitializeAndListen(port); - if (!success) - return false; - StartAcceptingConnections(); - return true; + if (success) + StartAcceptingConnections(); + return success; } bool EmbeddedTestServer::InitializeAndListen(int port) { @@ -543,7 +562,7 @@ bool EmbeddedTestServer::GenerateCertAndKey() { // StartAcceptingConnections so that this server and the AIA server start at // the same time. (If the test only called InitializeAndListen they expect no // threads to be created yet.) - if (io_thread_.get()) + if (io_thread_) aia_http_server_->StartAcceptingConnections(); return true; @@ -562,10 +581,14 @@ bool EmbeddedTestServer::InitializeSSLServerContext() { return true; } +EmbeddedTestServerHandle +EmbeddedTestServer::StartAcceptingConnectionsAndReturnHandle() { + return EmbeddedTestServerHandle(this); +} + void EmbeddedTestServer::StartAcceptingConnections() { DCHECK(Started()); - DCHECK(!io_thread_.get()) - << "Server must not be started while server is running"; + DCHECK(!io_thread_) << "Server must not be started while server is running"; if (aia_http_server_) aia_http_server_->StartAcceptingConnections(); @@ -584,8 +607,18 @@ void EmbeddedTestServer::StartAcceptingConnections() { bool EmbeddedTestServer::ShutdownAndWaitUntilComplete() { DCHECK(thread_checker_.CalledOnValidThread()); - return PostTaskToIOThreadAndWait(base::BindOnce( - &EmbeddedTestServer::ShutdownOnIOThread, base::Unretained(this))); + // Ensure that the AIA HTTP server is no longer Started(). + bool aia_http_server_not_started = true; + if (aia_http_server_ && aia_http_server_->Started()) { + aia_http_server_not_started = + aia_http_server_->ShutdownAndWaitUntilComplete(); + } + + // Return false if either this or the AIA HTTP server are still Started(). + return PostTaskToIOThreadAndWait( + base::BindOnce(&EmbeddedTestServer::ShutdownOnIOThread, + base::Unretained(this))) && + aia_http_server_not_started; } // static @@ -793,21 +826,21 @@ void EmbeddedTestServer::AddDefaultHandlers(const base::FilePath& directory) { void EmbeddedTestServer::RegisterRequestHandler( const HandleRequestCallback& callback) { - DCHECK(!io_thread_.get()) + DCHECK(!io_thread_) << "Handlers must be registered before starting the server."; request_handlers_.push_back(callback); } void EmbeddedTestServer::RegisterRequestMonitor( const MonitorRequestCallback& callback) { - DCHECK(!io_thread_.get()) + DCHECK(!io_thread_) << "Monitors must be registered before starting the server."; request_monitors_.push_back(callback); } void EmbeddedTestServer::RegisterDefaultHandler( const HandleRequestCallback& callback) { - DCHECK(!io_thread_.get()) + DCHECK(!io_thread_) << "Handlers must be registered before starting the server."; default_request_handlers_.push_back(callback); } @@ -1008,27 +1041,5 @@ bool EmbeddedTestServer::PostTaskToIOThreadAndWaitWithResult( return task_result; } -EmbeddedTestServerHandle::EmbeddedTestServerHandle( - EmbeddedTestServerHandle&& other) { - operator=(std::move(other)); -} - -EmbeddedTestServerHandle& EmbeddedTestServerHandle::operator=( - EmbeddedTestServerHandle&& other) { - EmbeddedTestServerHandle temporary; - std::swap(other.test_server_, temporary.test_server_); - std::swap(temporary.test_server_, test_server_); - return *this; -} - -EmbeddedTestServerHandle::EmbeddedTestServerHandle( - EmbeddedTestServer* test_server) - : test_server_(test_server) {} - -EmbeddedTestServerHandle::~EmbeddedTestServerHandle() { - if (test_server_) - EXPECT_TRUE(test_server_->ShutdownAndWaitUntilComplete()); -} - } // namespace test_server } // namespace net diff --git a/chromium/net/test/embedded_test_server/embedded_test_server.h b/chromium/net/test/embedded_test_server/embedded_test_server.h index 699e64f6a4c..b296db0223f 100644 --- a/chromium/net/test/embedded_test_server/embedded_test_server.h +++ b/chromium/net/test/embedded_test_server/embedded_test_server.h @@ -39,11 +39,33 @@ class TCPServerSocket; namespace test_server { class EmbeddedTestServerConnectionListener; -class EmbeddedTestServerHandle; class HttpConnection; class HttpResponse; struct HttpRequest; +class EmbeddedTestServer; + +// Returned by the Start[AcceptingConnections]WithHandle() APIs, to simplify +// correct shutdown ordering of the EmbeddedTestServer. Shutdown() is invoked +// on the associated test server when the handle goes out of scope. The handle +// must therefore be destroyed before the test server. +class EmbeddedTestServerHandle { + public: + EmbeddedTestServerHandle() = default; + EmbeddedTestServerHandle(EmbeddedTestServerHandle&& other); + EmbeddedTestServerHandle& operator=(EmbeddedTestServerHandle&& other); + ~EmbeddedTestServerHandle(); + + bool is_valid() const { return test_server_; } + explicit operator bool() const { return test_server_; } + + private: + friend class EmbeddedTestServer; + + explicit EmbeddedTestServerHandle(EmbeddedTestServer* test_server); + EmbeddedTestServer* test_server_ = nullptr; +}; + // Class providing an HTTP server for testing purpose. This is a basic server // providing only an essential subset of HTTP/1.1 protocol. Especially, // it assumes that the request syntax is correct. It *does not* support @@ -61,7 +83,7 @@ struct HttpRequest; // std::unique_ptr<HttpResponse> HandleRequest(const HttpRequest& request) { // GURL absolute_url = test_server_->GetURL(request.relative_url); // if (absolute_url.path() != "/test") -// return std::unique_ptr<HttpResponse>(); +// return nullptr; // // auto http_response = std::make_unique<BasicHttpResponse>(); // http_response->set_code(net::HTTP_OK); @@ -274,7 +296,8 @@ class EmbeddedTestServer { typedef base::RepeatingCallback<void(const HttpRequest& request)> MonitorRequestCallback; - // Creates a http test server. Start() must be called to start the server. + // Creates a http test server. StartAndReturnHandle() must be called to start + // the server. // |type| indicates the protocol type of the server (HTTP/HTTPS). // // When a TYPE_HTTPS server is created, EmbeddedTestServer will call @@ -299,13 +322,14 @@ class EmbeddedTestServer { // Initializes and waits until the server is ready to accept requests. // This is the equivalent of calling InitializeAndListen() followed by - // StartAcceptingConnections(). + // StartAcceptingConnectionsAndReturnHandle(). // Returns a "handle" which will ShutdownAndWaitUntilComplete() when // destroyed, or null if the listening socket could not be created. EmbeddedTestServerHandle StartAndReturnHandle(int port = 0) WARN_UNUSED_RESULT; - // Deprecated equivalent of StartAndReturnHandle(). + // Equivalent of StartAndReturnHandle(), but requires manual Shutdown() by + // the caller. bool Start(int port = 0) WARN_UNUSED_RESULT; // Starts listening for incoming connections but will not yet accept them. @@ -313,9 +337,16 @@ class EmbeddedTestServer { bool InitializeAndListen(int port = 0) WARN_UNUSED_RESULT; // Starts the Accept IO Thread and begins accepting connections. + EmbeddedTestServerHandle StartAcceptingConnectionsAndReturnHandle() + WARN_UNUSED_RESULT; + + // Equivalent of StartAcceptingConnectionsAndReturnHandle(), but requires + // manual Shutdown() by the caller. void StartAcceptingConnections(); // Shuts down the http server and waits until the shutdown is complete. + // Prefer to use the Start*AndReturnHandle() APIs to manage shutdown, if + // possible. bool ShutdownAndWaitUntilComplete() WARN_UNUSED_RESULT; // Checks if the server has started listening for incoming connections. @@ -386,23 +417,22 @@ class EmbeddedTestServer { // |directory| directory, relative to DIR_SOURCE_ROOT. void AddDefaultHandlers(const base::FilePath& directory); - // The most general purpose method. Any request processing can be added using - // this method. Takes ownership of the object. The |callback| is called - // on the server's IO thread so all handlers must be registered before the - // server is started. + // Adds a request handler that can perform any general-purpose processing. + // |callback| will be invoked on the server's IO thread. Note that: + // 1. All handlers must be registered before the server is Start()ed. + // 2. The server should be Shutdown() before any variables referred to by + // |callback| (e.g. via base::Unretained(&local)) are deleted. Using the + // Start*WithHandle() API variants is recommended for this reason. void RegisterRequestHandler(const HandleRequestCallback& callback); - // Adds request monitors. The |callback| is called before any handlers are - // called, but can not respond it. This is useful to monitor requests that - // will be handled by other request handlers. The |callback| is called - // on the server's IO thread so all monitors must be registered before the - // server is started. + // Adds a request monitor that will be called before any handlers. Monitors + // can be used to observe requests, but not to respond to them. + // See RegisterRequestHandler() for notes on usage. void RegisterRequestMonitor(const MonitorRequestCallback& callback); - // Adds default handlers, including those added by AddDefaultHandlers, to be - // tried after all other user-specified handlers have been tried. The - // |callback| is called on the server's IO thread so all handlers must be - // registered before the server is started. + // Adds a default request handler, to be called if no user-specified handler + // handles the request. + // See RegisterRequestHandler() for notes on usage. void RegisterDefaultHandler(const HandleRequestCallback& callback); bool FlushAllSocketsAndConnectionsOnUIThread(); @@ -525,23 +555,6 @@ class EmbeddedTestServer { DISALLOW_COPY_AND_ASSIGN(EmbeddedTestServer); }; -class EmbeddedTestServerHandle { - public: - EmbeddedTestServerHandle() = default; - EmbeddedTestServerHandle(EmbeddedTestServerHandle&& other); - EmbeddedTestServerHandle& operator=(EmbeddedTestServerHandle&& other); - - ~EmbeddedTestServerHandle(); - - explicit operator bool() const { return test_server_; } - - private: - friend class EmbeddedTestServer; - - explicit EmbeddedTestServerHandle(EmbeddedTestServer* test_server); - EmbeddedTestServer* test_server_ = nullptr; -}; - } // namespace test_server // TODO(svaldez): Refactor EmbeddedTestServer to be in the net namespace. diff --git a/chromium/net/test/embedded_test_server/request_handler_util.cc b/chromium/net/test/embedded_test_server/request_handler_util.cc index 91d4275f94b..f08d3c34a0b 100644 --- a/chromium/net/test/embedded_test_server/request_handler_util.cc +++ b/chromium/net/test/embedded_test_server/request_handler_util.cc @@ -60,6 +60,10 @@ std::string GetContentType(const base::FilePath& path) { return "audio/wav"; if (path.MatchesExtension(FILE_PATH_LITERAL(".webp"))) return "image/webp"; + if (path.MatchesExtension(FILE_PATH_LITERAL(".mp4"))) + return "video/mp4"; + if (path.MatchesExtension(FILE_PATH_LITERAL(".webm"))) + return "video/webm"; if (path.MatchesExtension(FILE_PATH_LITERAL(".xml"))) return "text/xml"; if (path.MatchesExtension(FILE_PATH_LITERAL(".mhtml"))) diff --git a/chromium/net/test/spawned_test_server/base_test_server.cc b/chromium/net/test/spawned_test_server/base_test_server.cc index 22fd960a7f3..8330ccda5d2 100644 --- a/chromium/net/test/spawned_test_server/base_test_server.cc +++ b/chromium/net/test/spawned_test_server/base_test_server.cc @@ -19,6 +19,7 @@ #include "net/base/address_list.h" #include "net/base/host_port_pair.h" #include "net/base/net_errors.h" +#include "net/base/network_isolation_key.h" #include "net/base/port_util.h" #include "net/base/test_completion_callback.h" #include "net/cert/test_root_certs.h" @@ -221,7 +222,8 @@ bool BaseTestServer::GetAddressList(AddressList* address_list) const { parameters.dns_query_type = DnsQueryType::A; std::unique_ptr<HostResolver::ResolveHostRequest> request = - resolver->CreateRequest(host_port_pair_, NetLogWithSource(), parameters); + resolver->CreateRequest(host_port_pair_, NetworkIsolationKey(), + NetLogWithSource(), parameters); TestCompletionCallback callback; int rv = request->Start(callback.callback()); @@ -361,15 +363,14 @@ void BaseTestServer::SetResourcePath(const base::FilePath& document_root, bool BaseTestServer::SetAndParseServerData(const std::string& server_data, int* port) { VLOG(1) << "Server data: " << server_data; - base::JSONReader json_reader; - base::Optional<base::Value> value(json_reader.ReadToValue(server_data)); - if (!value || !value->is_dict()) { - LOG(ERROR) << "Could not parse server data: " - << json_reader.GetErrorMessage(); + base::JSONReader::ValueWithError parsed_json = + base::JSONReader::ReadAndReturnValueWithError(server_data); + if (!parsed_json.value || !parsed_json.value->is_dict()) { + LOG(ERROR) << "Could not parse server data: " << parsed_json.error_message; return false; } - server_data_ = std::move(value); + server_data_ = std::move(parsed_json.value); base::Optional<int> port_value = server_data_->FindIntKey("port"); if (!port_value) { diff --git a/chromium/net/test/spawned_test_server/local_test_server.cc b/chromium/net/test/spawned_test_server/local_test_server.cc index 3f46015d4fc..eb5016bd805 100644 --- a/chromium/net/test/spawned_test_server/local_test_server.cc +++ b/chromium/net/test/spawned_test_server/local_test_server.cc @@ -7,6 +7,7 @@ #include "base/command_line.h" #include "base/json/json_reader.h" #include "base/logging.h" +#include "base/notreached.h" #include "base/path_service.h" #include "base/strings/string_number_conversions.h" #include "base/threading/thread_restrictions.h" diff --git a/chromium/net/test/spawned_test_server/local_test_server_win.cc b/chromium/net/test/spawned_test_server/local_test_server_win.cc index 085a3f8cd59..319eee0789e 100644 --- a/chromium/net/test/spawned_test_server/local_test_server_win.cc +++ b/chromium/net/test/spawned_test_server/local_test_server_win.cc @@ -11,6 +11,7 @@ #include "base/command_line.h" #include "base/environment.h" #include "base/files/file_path.h" +#include "base/logging.h" #include "base/path_service.h" #include "base/process/launch.h" #include "base/strings/string_number_conversions.h" diff --git a/chromium/net/test/url_request/url_request_slow_download_job.cc b/chromium/net/test/url_request/url_request_slow_download_job.cc deleted file mode 100644 index 2195db86e6f..00000000000 --- a/chromium/net/test/url_request/url_request_slow_download_job.cc +++ /dev/null @@ -1,283 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "net/test/url_request/url_request_slow_download_job.h" - -#include "base/bind.h" -#include "base/compiler_specific.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/macros.h" -#include "base/single_thread_task_runner.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" -#include "base/threading/thread_task_runner_handle.h" -#include "net/base/io_buffer.h" -#include "net/base/net_errors.h" -#include "net/http/http_response_headers.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_filter.h" -#include "net/url_request/url_request_interceptor.h" -#include "url/gurl.h" - -namespace net { - -const char URLRequestSlowDownloadJob::kUnknownSizeUrl[] = - "http://url.handled.by.slow.download/download-unknown-size"; -const char URLRequestSlowDownloadJob::kKnownSizeUrl[] = - "http://url.handled.by.slow.download/download-known-size"; -const char URLRequestSlowDownloadJob::kFinishDownloadUrl[] = - "http://url.handled.by.slow.download/download-finish"; -const char URLRequestSlowDownloadJob::kErrorDownloadUrl[] = - "http://url.handled.by.slow.download/download-error"; - -const int URLRequestSlowDownloadJob::kFirstDownloadSize = 1024 * 35; -const int URLRequestSlowDownloadJob::kSecondDownloadSize = 1024 * 10; - -class URLRequestSlowDownloadJob::Interceptor : public URLRequestInterceptor { - public: - Interceptor() = default; - ~Interceptor() override = default; - - // URLRequestInterceptor implementation: - URLRequestJob* MaybeInterceptRequest( - URLRequest* request, - NetworkDelegate* network_delegate) const override { - URLRequestSlowDownloadJob* job = - new URLRequestSlowDownloadJob(request, network_delegate); - if (request->url().spec() != kFinishDownloadUrl && - request->url().spec() != kErrorDownloadUrl) { - pending_requests_.Get().insert(job); - } - return job; - } - - private: - DISALLOW_COPY_AND_ASSIGN(Interceptor); -}; - -// static -base::LazyInstance<URLRequestSlowDownloadJob::SlowJobsSet>::Leaky - URLRequestSlowDownloadJob::pending_requests_ = LAZY_INSTANCE_INITIALIZER; - -void URLRequestSlowDownloadJob::Start() { - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(&URLRequestSlowDownloadJob::StartAsync, - weak_factory_.GetWeakPtr())); -} - -int64_t URLRequestSlowDownloadJob::GetTotalReceivedBytes() const { - return bytes_already_sent_; -} - -// static -void URLRequestSlowDownloadJob::AddUrlHandler() { - URLRequestFilter* filter = URLRequestFilter::GetInstance(); - filter->AddUrlInterceptor( - GURL(kUnknownSizeUrl), - std::unique_ptr<URLRequestInterceptor>(new Interceptor())); - filter->AddUrlInterceptor( - GURL(kKnownSizeUrl), - std::unique_ptr<URLRequestInterceptor>(new Interceptor())); - filter->AddUrlInterceptor( - GURL(kFinishDownloadUrl), - std::unique_ptr<URLRequestInterceptor>(new Interceptor())); - filter->AddUrlInterceptor( - GURL(kErrorDownloadUrl), - std::unique_ptr<URLRequestInterceptor>(new Interceptor())); -} - -// static -size_t URLRequestSlowDownloadJob::NumberOutstandingRequests() { - return pending_requests_.Get().size(); -} - -// static -void URLRequestSlowDownloadJob::FinishPendingRequests() { - for (auto it = pending_requests_.Get().begin(); - it != pending_requests_.Get().end(); ++it) { - (*it)->set_should_finish_download(); - } -} - -void URLRequestSlowDownloadJob::ErrorPendingRequests() { - for (auto it = pending_requests_.Get().begin(); - it != pending_requests_.Get().end(); ++it) { - (*it)->set_should_error_download(); - } -} - -URLRequestSlowDownloadJob::URLRequestSlowDownloadJob( - URLRequest* request, - NetworkDelegate* network_delegate) - : URLRequestJob(request, network_delegate), - bytes_already_sent_(0), - should_error_download_(false), - should_finish_download_(false), - buffer_size_(0) {} - -void URLRequestSlowDownloadJob::StartAsync() { - if (base::LowerCaseEqualsASCII(kFinishDownloadUrl, - request_->url().spec().c_str())) - URLRequestSlowDownloadJob::FinishPendingRequests(); - if (base::LowerCaseEqualsASCII(kErrorDownloadUrl, - request_->url().spec().c_str())) - URLRequestSlowDownloadJob::ErrorPendingRequests(); - - NotifyHeadersComplete(); -} - -// ReadRawData and CheckDoneStatus together implement a state -// machine. ReadRawData may be called arbitrarily by the network stack. -// It responds by: -// * If there are bytes remaining in the first chunk, they are -// returned. -// [No bytes remaining in first chunk. ] -// * If should_finish_download_ is not set, it returns IO_PENDING, -// and starts calling CheckDoneStatus on a regular timer. -// [should_finish_download_ set.] -// * If there are bytes remaining in the second chunk, they are filled. -// * Otherwise, return *bytes_read = 0 to indicate end of request. -// CheckDoneStatus is called on a regular basis, in the specific -// case where we have transmitted all of the first chunk and none of the -// second. If should_finish_download_ becomes set, it will "complete" -// the ReadRawData call that spawned off the CheckDoneStatus() repeated call. -// -// FillBufferHelper is a helper function that does the actual work of figuring -// out where in the state machine we are and how we should fill the buffer. -// It returns an enum indicating the state of the read. -URLRequestSlowDownloadJob::ReadStatus -URLRequestSlowDownloadJob::FillBufferHelper(IOBuffer* buf, - int buf_size, - int* bytes_written) { - if (bytes_already_sent_ < kFirstDownloadSize) { - int bytes_to_write = - std::min(kFirstDownloadSize - bytes_already_sent_, buf_size); - for (int i = 0; i < bytes_to_write; ++i) { - buf->data()[i] = '*'; - } - *bytes_written = bytes_to_write; - bytes_already_sent_ += bytes_to_write; - return BUFFER_FILLED; - } - - if (!should_finish_download_) - return REQUEST_BLOCKED; - - if (bytes_already_sent_ < kFirstDownloadSize + kSecondDownloadSize) { - int bytes_to_write = - std::min(kFirstDownloadSize + kSecondDownloadSize - bytes_already_sent_, - buf_size); - for (int i = 0; i < bytes_to_write; ++i) { - buf->data()[i] = '*'; - } - *bytes_written = bytes_to_write; - bytes_already_sent_ += bytes_to_write; - return BUFFER_FILLED; - } - - return REQUEST_COMPLETE; -} - -int URLRequestSlowDownloadJob::ReadRawData(IOBuffer* buf, int buf_size) { - if (base::LowerCaseEqualsASCII(kFinishDownloadUrl, - request_->url().spec().c_str()) || - base::LowerCaseEqualsASCII(kErrorDownloadUrl, - request_->url().spec().c_str())) { - VLOG(10) << __FUNCTION__ << " called w/ kFinish/ErrorDownloadUrl."; - return 0; - } - - VLOG(10) << __FUNCTION__ << " called at position " << bytes_already_sent_ - << " in the stream."; - int bytes_read = 0; - ReadStatus status = FillBufferHelper(buf, buf_size, &bytes_read); - switch (status) { - case BUFFER_FILLED: - case REQUEST_COMPLETE: - return bytes_read; - case REQUEST_BLOCKED: - buffer_ = buf; - buffer_size_ = buf_size; - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&URLRequestSlowDownloadJob::CheckDoneStatus, - weak_factory_.GetWeakPtr()), - base::TimeDelta::FromMilliseconds(100)); - return ERR_IO_PENDING; - } - NOTREACHED(); - return OK; -} - -void URLRequestSlowDownloadJob::CheckDoneStatus() { - if (should_finish_download_) { - VLOG(10) << __FUNCTION__ << " called w/ should_finish_download_ set."; - DCHECK(nullptr != buffer_.get()); - int bytes_written = 0; - ReadStatus status = - FillBufferHelper(buffer_.get(), buffer_size_, &bytes_written); - DCHECK_EQ(BUFFER_FILLED, status); - buffer_ = nullptr; // Release the reference. - ReadRawDataComplete(bytes_written); - } else if (should_error_download_) { - VLOG(10) << __FUNCTION__ << " called w/ should_finish_ownload_ set."; - ReadRawDataComplete(ERR_CONNECTION_RESET); - } else { - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&URLRequestSlowDownloadJob::CheckDoneStatus, - weak_factory_.GetWeakPtr()), - base::TimeDelta::FromMilliseconds(100)); - } -} - -// Public virtual version. -void URLRequestSlowDownloadJob::GetResponseInfo(HttpResponseInfo* info) { - // Forward to private const version. - GetResponseInfoConst(info); -} - -URLRequestSlowDownloadJob::~URLRequestSlowDownloadJob() { - pending_requests_.Get().erase(this); -} - -// Private const version. -void URLRequestSlowDownloadJob::GetResponseInfoConst( - HttpResponseInfo* info) const { - // Send back mock headers. - std::string raw_headers; - if (base::LowerCaseEqualsASCII(kFinishDownloadUrl, - request_->url().spec().c_str()) || - base::LowerCaseEqualsASCII(kErrorDownloadUrl, - request_->url().spec().c_str())) { - raw_headers.append( - "HTTP/1.1 200 OK\n" - "Content-type: text/plain\n"); - } else { - raw_headers.append( - "HTTP/1.1 200 OK\n" - "Content-type: application/octet-stream\n" - "Cache-Control: max-age=0\n"); - - if (base::LowerCaseEqualsASCII(kKnownSizeUrl, - request_->url().spec().c_str())) { - raw_headers.append(base::StringPrintf( - "Content-Length: %d\n", kFirstDownloadSize + kSecondDownloadSize)); - } - } - - // ParseRawHeaders expects \0 to end each header line. - base::ReplaceSubstringsAfterOffset( - &raw_headers, 0, "\n", base::StringPiece("\0", 1)); - info->headers = new HttpResponseHeaders(raw_headers); -} - -bool URLRequestSlowDownloadJob::GetMimeType(std::string* mime_type) const { - HttpResponseInfo info; - GetResponseInfoConst(&info); - return info.headers.get() && info.headers->GetMimeType(mime_type); -} - -} // namespace net diff --git a/chromium/net/test/url_request/url_request_slow_download_job.h b/chromium/net/test/url_request/url_request_slow_download_job.h deleted file mode 100644 index c7302c9074c..00000000000 --- a/chromium/net/test/url_request/url_request_slow_download_job.h +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// This class simulates a slow download. Requests to |kUnknownSizeUrl| and -// |kKnownSizeUrl| start downloads that pause after the first N bytes, to be -// completed by sending a request to |kFinishDownloadUrl|. - -#ifndef NET_TEST_URL_REQUEST_URL_REQUEST_SLOW_DOWNLOAD_JOB_H_ -#define NET_TEST_URL_REQUEST_URL_REQUEST_SLOW_DOWNLOAD_JOB_H_ - -#include <stddef.h> -#include <stdint.h> - -#include <set> -#include <string> - -#include "base/lazy_instance.h" -#include "base/memory/weak_ptr.h" -#include "net/url_request/url_request_job.h" - -namespace net { - -class URLRequestSlowDownloadJob : public URLRequestJob { - public: - // Test URLs. - static const char kUnknownSizeUrl[]; - static const char kKnownSizeUrl[]; - static const char kFinishDownloadUrl[]; - static const char kErrorDownloadUrl[]; - - // Download sizes. - static const int kFirstDownloadSize; - static const int kSecondDownloadSize; - - // Timer callback, used to check to see if we should finish our download and - // send the second chunk. - void CheckDoneStatus(); - - // URLRequestJob methods - void Start() override; - int64_t GetTotalReceivedBytes() const override; - bool GetMimeType(std::string* mime_type) const override; - void GetResponseInfo(HttpResponseInfo* info) override; - int ReadRawData(IOBuffer* buf, int buf_size) override; - - // Returns the current number of URLRequestSlowDownloadJobs that have - // not yet completed. - static size_t NumberOutstandingRequests(); - - // Adds the testing URLs to the URLRequestFilter. - static void AddUrlHandler(); - - private: - class Interceptor; - - // Enum indicating where we are in the read after a call to - // FillBufferHelper. - enum ReadStatus { - // The buffer was filled with data and may be returned. - BUFFER_FILLED, - - // No data was added to the buffer because kFinishDownloadUrl has - // not yet been seen and we've already returned the first chunk. - REQUEST_BLOCKED, - - // No data was added to the buffer because we've already returned - // all the data. - REQUEST_COMPLETE - }; - - URLRequestSlowDownloadJob(URLRequest* request, - NetworkDelegate* network_delegate); - ~URLRequestSlowDownloadJob() override; - - ReadStatus FillBufferHelper(IOBuffer* buf, int buf_size, int* bytes_written); - - void GetResponseInfoConst(HttpResponseInfo* info) const; - - // Mark all pending requests to be finished. We keep track of pending - // requests in |pending_requests_|. - static void FinishPendingRequests(); - static void ErrorPendingRequests(); - typedef std::set<URLRequestSlowDownloadJob*> SlowJobsSet; - static base::LazyInstance<SlowJobsSet>::Leaky pending_requests_; - - void StartAsync(); - - void set_should_finish_download() { should_finish_download_ = true; } - void set_should_error_download() { should_error_download_ = true; } - - int bytes_already_sent_; - bool should_error_download_; - bool should_finish_download_; - scoped_refptr<IOBuffer> buffer_; - int buffer_size_; - - base::WeakPtrFactory<URLRequestSlowDownloadJob> weak_factory_{this}; -}; - -} // namespace net - -#endif // NET_TEST_URL_REQUEST_URL_REQUEST_SLOW_DOWNLOAD_JOB_H_ |