1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/test/url_request/url_request_slow_download_job.h"
8 #include "base/compiler_specific.h"
9 #include "base/logging.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/strings/string_util.h"
12 #include "base/strings/stringprintf.h"
13 #include "net/base/io_buffer.h"
14 #include "net/base/net_errors.h"
15 #include "net/http/http_response_headers.h"
16 #include "net/url_request/url_request.h"
17 #include "net/url_request/url_request_filter.h"
18 #include "net/url_request/url_request_interceptor.h"
23 const char URLRequestSlowDownloadJob::kUnknownSizeUrl
[] =
24 "http://url.handled.by.slow.download/download-unknown-size";
25 const char URLRequestSlowDownloadJob::kKnownSizeUrl
[] =
26 "http://url.handled.by.slow.download/download-known-size";
27 const char URLRequestSlowDownloadJob::kFinishDownloadUrl
[] =
28 "http://url.handled.by.slow.download/download-finish";
29 const char URLRequestSlowDownloadJob::kErrorDownloadUrl
[] =
30 "http://url.handled.by.slow.download/download-error";
32 const int URLRequestSlowDownloadJob::kFirstDownloadSize
= 1024 * 35;
33 const int URLRequestSlowDownloadJob::kSecondDownloadSize
= 1024 * 10;
35 class URLRequestSlowDownloadJob::Interceptor
: public URLRequestInterceptor
{
38 ~Interceptor() override
{}
40 // URLRequestInterceptor implementation:
41 URLRequestJob
* MaybeInterceptRequest(
43 NetworkDelegate
* network_delegate
) const override
{
44 URLRequestSlowDownloadJob
* job
=
45 new URLRequestSlowDownloadJob(request
, network_delegate
);
46 if (request
->url().spec() != kFinishDownloadUrl
&&
47 request
->url().spec() != kErrorDownloadUrl
) {
48 pending_requests_
.Get().insert(job
);
54 DISALLOW_COPY_AND_ASSIGN(Interceptor
);
58 base::LazyInstance
<URLRequestSlowDownloadJob::SlowJobsSet
>::Leaky
59 URLRequestSlowDownloadJob::pending_requests_
= LAZY_INSTANCE_INITIALIZER
;
61 void URLRequestSlowDownloadJob::Start() {
62 base::MessageLoop::current()->PostTask(
63 FROM_HERE
, base::Bind(&URLRequestSlowDownloadJob::StartAsync
,
64 weak_factory_
.GetWeakPtr()));
68 void URLRequestSlowDownloadJob::AddUrlHandler() {
69 URLRequestFilter
* filter
= URLRequestFilter::GetInstance();
70 filter
->AddUrlInterceptor(
71 GURL(kUnknownSizeUrl
),
72 scoped_ptr
<URLRequestInterceptor
>(new Interceptor()));
73 filter
->AddUrlInterceptor(
75 scoped_ptr
<URLRequestInterceptor
>(new Interceptor()));
76 filter
->AddUrlInterceptor(
77 GURL(kFinishDownloadUrl
),
78 scoped_ptr
<URLRequestInterceptor
>(new Interceptor()));
79 filter
->AddUrlInterceptor(
80 GURL(kErrorDownloadUrl
),
81 scoped_ptr
<URLRequestInterceptor
>(new Interceptor()));
85 size_t URLRequestSlowDownloadJob::NumberOutstandingRequests() {
86 return pending_requests_
.Get().size();
90 void URLRequestSlowDownloadJob::FinishPendingRequests() {
91 typedef std::set
<URLRequestSlowDownloadJob
*> JobList
;
92 for (JobList::iterator it
= pending_requests_
.Get().begin();
93 it
!= pending_requests_
.Get().end(); ++it
) {
94 (*it
)->set_should_finish_download();
98 void URLRequestSlowDownloadJob::ErrorPendingRequests() {
99 typedef std::set
<URLRequestSlowDownloadJob
*> JobList
;
100 for (JobList::iterator it
= pending_requests_
.Get().begin();
101 it
!= pending_requests_
.Get().end(); ++it
) {
102 (*it
)->set_should_error_download();
106 URLRequestSlowDownloadJob::URLRequestSlowDownloadJob(
108 NetworkDelegate
* network_delegate
)
109 : URLRequestJob(request
, network_delegate
),
110 bytes_already_sent_(0),
111 should_error_download_(false),
112 should_finish_download_(false),
114 weak_factory_(this) {
117 void URLRequestSlowDownloadJob::StartAsync() {
118 if (base::LowerCaseEqualsASCII(kFinishDownloadUrl
,
119 request_
->url().spec().c_str()))
120 URLRequestSlowDownloadJob::FinishPendingRequests();
121 if (base::LowerCaseEqualsASCII(kErrorDownloadUrl
,
122 request_
->url().spec().c_str()))
123 URLRequestSlowDownloadJob::ErrorPendingRequests();
125 NotifyHeadersComplete();
128 // ReadRawData and CheckDoneStatus together implement a state
129 // machine. ReadRawData may be called arbitrarily by the network stack.
131 // * If there are bytes remaining in the first chunk, they are
133 // [No bytes remaining in first chunk. ]
134 // * If should_finish_download_ is not set, it returns IO_PENDING,
135 // and starts calling CheckDoneStatus on a regular timer.
136 // [should_finish_download_ set.]
137 // * If there are bytes remaining in the second chunk, they are filled.
138 // * Otherwise, return *bytes_read = 0 to indicate end of request.
139 // CheckDoneStatus is called on a regular basis, in the specific
140 // case where we have transmitted all of the first chunk and none of the
141 // second. If should_finish_download_ becomes set, it will "complete"
142 // the ReadRawData call that spawned off the CheckDoneStatus() repeated call.
144 // FillBufferHelper is a helper function that does the actual work of figuring
145 // out where in the state machine we are and how we should fill the buffer.
146 // It returns an enum indicating the state of the read.
147 URLRequestSlowDownloadJob::ReadStatus
148 URLRequestSlowDownloadJob::FillBufferHelper(IOBuffer
* buf
,
150 int* bytes_written
) {
151 if (bytes_already_sent_
< kFirstDownloadSize
) {
153 std::min(kFirstDownloadSize
- bytes_already_sent_
, buf_size
);
154 for (int i
= 0; i
< bytes_to_write
; ++i
) {
155 buf
->data()[i
] = '*';
157 *bytes_written
= bytes_to_write
;
158 bytes_already_sent_
+= bytes_to_write
;
159 return BUFFER_FILLED
;
162 if (!should_finish_download_
)
163 return REQUEST_BLOCKED
;
165 if (bytes_already_sent_
< kFirstDownloadSize
+ kSecondDownloadSize
) {
167 std::min(kFirstDownloadSize
+ kSecondDownloadSize
- bytes_already_sent_
,
169 for (int i
= 0; i
< bytes_to_write
; ++i
) {
170 buf
->data()[i
] = '*';
172 *bytes_written
= bytes_to_write
;
173 bytes_already_sent_
+= bytes_to_write
;
174 return BUFFER_FILLED
;
177 return REQUEST_COMPLETE
;
180 bool URLRequestSlowDownloadJob::ReadRawData(IOBuffer
* buf
,
183 if (base::LowerCaseEqualsASCII(kFinishDownloadUrl
,
184 request_
->url().spec().c_str()) ||
185 base::LowerCaseEqualsASCII(kErrorDownloadUrl
,
186 request_
->url().spec().c_str())) {
187 VLOG(10) << __FUNCTION__
<< " called w/ kFinish/ErrorDownloadUrl.";
192 VLOG(10) << __FUNCTION__
<< " called at position " << bytes_already_sent_
193 << " in the stream.";
194 ReadStatus status
= FillBufferHelper(buf
, buf_size
, bytes_read
);
198 case REQUEST_BLOCKED
:
200 buffer_size_
= buf_size
;
201 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING
, 0));
202 base::MessageLoop::current()->PostDelayedTask(
203 FROM_HERE
, base::Bind(&URLRequestSlowDownloadJob::CheckDoneStatus
,
204 weak_factory_
.GetWeakPtr()),
205 base::TimeDelta::FromMilliseconds(100));
207 case REQUEST_COMPLETE
:
215 void URLRequestSlowDownloadJob::CheckDoneStatus() {
216 if (should_finish_download_
) {
217 VLOG(10) << __FUNCTION__
<< " called w/ should_finish_download_ set.";
218 DCHECK(NULL
!= buffer_
.get());
219 int bytes_written
= 0;
221 FillBufferHelper(buffer_
.get(), buffer_size_
, &bytes_written
);
222 DCHECK_EQ(BUFFER_FILLED
, status
);
223 buffer_
= NULL
; // Release the reference.
224 SetStatus(URLRequestStatus());
225 NotifyReadComplete(bytes_written
);
226 } else if (should_error_download_
) {
227 VLOG(10) << __FUNCTION__
<< " called w/ should_finish_ownload_ set.";
229 URLRequestStatus(URLRequestStatus::FAILED
, ERR_CONNECTION_RESET
));
231 base::MessageLoop::current()->PostDelayedTask(
232 FROM_HERE
, base::Bind(&URLRequestSlowDownloadJob::CheckDoneStatus
,
233 weak_factory_
.GetWeakPtr()),
234 base::TimeDelta::FromMilliseconds(100));
238 // Public virtual version.
239 void URLRequestSlowDownloadJob::GetResponseInfo(HttpResponseInfo
* info
) {
240 // Forward to private const version.
241 GetResponseInfoConst(info
);
244 URLRequestSlowDownloadJob::~URLRequestSlowDownloadJob() {
245 pending_requests_
.Get().erase(this);
248 // Private const version.
249 void URLRequestSlowDownloadJob::GetResponseInfoConst(
250 HttpResponseInfo
* info
) const {
251 // Send back mock headers.
252 std::string raw_headers
;
253 if (base::LowerCaseEqualsASCII(kFinishDownloadUrl
,
254 request_
->url().spec().c_str()) ||
255 base::LowerCaseEqualsASCII(kErrorDownloadUrl
,
256 request_
->url().spec().c_str())) {
259 "Content-type: text/plain\n");
263 "Content-type: application/octet-stream\n"
264 "Cache-Control: max-age=0\n");
266 if (base::LowerCaseEqualsASCII(kKnownSizeUrl
,
267 request_
->url().spec().c_str())) {
268 raw_headers
.append(base::StringPrintf(
269 "Content-Length: %d\n", kFirstDownloadSize
+ kSecondDownloadSize
));
273 // ParseRawHeaders expects \0 to end each header line.
274 ReplaceSubstringsAfterOffset(&raw_headers
, 0, "\n", std::string("\0", 1));
275 info
->headers
= new HttpResponseHeaders(raw_headers
);
278 bool URLRequestSlowDownloadJob::GetMimeType(std::string
* mime_type
) const {
279 HttpResponseInfo info
;
280 GetResponseInfoConst(&info
);
281 return info
.headers
.get() && info
.headers
->GetMimeType(mime_type
);