1 //
2 // Copyright (C) 2012 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 #include <netinet/in.h>
18 #include <netinet/ip.h>
19 #include <sys/socket.h>
20 #include <unistd.h>
21
22 #include <algorithm>
23 #include <deque>
24 #include <memory>
25 #include <string>
26 #include <utility>
27 #include <vector>
28
29 #include <base/bind.h>
30 #include <base/location.h>
31 #include <base/logging.h>
32 #if BASE_VER < 780000 // Android
33 #include <base/message_loop/message_loop.h>
34 #endif // BASE_VER < 780000
35 #include <base/stl_util.h>
36 #include <base/strings/string_number_conversions.h>
37 #include <base/strings/string_util.h>
38 #include <base/strings/stringprintf.h>
39 #if BASE_VER >= 780000 // CrOS
40 #include <base/task/single_thread_task_executor.h>
41 #endif // BASE_VER >= 780000
42 #include <base/time/time.h>
43 #include <brillo/message_loops/base_message_loop.h>
44 #include <brillo/message_loops/message_loop.h>
45 #include <brillo/message_loops/message_loop_utils.h>
46 #ifdef __CHROMEOS__
47 #include <brillo/process/process.h>
48 #else
49 #include <brillo/process.h>
50 #endif // __CHROMEOS__
51 #include <brillo/streams/file_stream.h>
52 #include <brillo/streams/stream.h>
53 #include <gmock/gmock.h>
54 #include <gtest/gtest.h>
55
56 #include "update_engine/common/fake_hardware.h"
57 #include "update_engine/common/file_fetcher.h"
58 #include "update_engine/common/http_common.h"
59 #include "update_engine/common/mock_http_fetcher.h"
60 #include "update_engine/common/multi_range_http_fetcher.h"
61 #include "update_engine/common/test_utils.h"
62 #include "update_engine/common/utils.h"
63 #include "update_engine/libcurl_http_fetcher.h"
64
65 using brillo::MessageLoop;
66 using std::make_pair;
67 using std::pair;
68 using std::string;
69 using std::unique_ptr;
70 using std::vector;
71 using testing::_;
72 using testing::DoAll;
73 using testing::Return;
74 using testing::SaveArg;
75
76 namespace {
77
78 const int kBigLength = 100000;
79 const int kMediumLength = 1000;
80 const int kFlakyTruncateLength = 29000;
81 const int kFlakySleepEvery = 3;
82 const int kFlakySleepSecs = 10;
83
84 } // namespace
85
86 namespace chromeos_update_engine {
87
88 static const char* kUnusedUrl = "unused://unused";
89
LocalServerUrlForPath(in_port_t port,const string & path)90 static inline string LocalServerUrlForPath(in_port_t port, const string& path) {
91 string port_str = (port ? base::StringPrintf(":%hu", port) : "");
92 return base::StringPrintf(
93 "http://127.0.0.1%s%s", port_str.c_str(), path.c_str());
94 }
95
96 //
97 // Class hierarchy for HTTP server implementations.
98 //
99
100 namespace {
101
102 class HttpServer {
103 public:
104 // This makes it an abstract class (dirty but works).
105 virtual ~HttpServer() = 0;
106
GetPort() const107 virtual in_port_t GetPort() const { return 0; }
108
109 bool started_;
110 };
111
~HttpServer()112 HttpServer::~HttpServer() {}
113
114 class NullHttpServer : public HttpServer {
115 public:
NullHttpServer()116 NullHttpServer() { started_ = true; }
117 };
118
119 class PythonHttpServer : public HttpServer {
120 public:
PythonHttpServer()121 PythonHttpServer() : port_(0) {
122 started_ = false;
123
124 // Spawn the server process.
125 unique_ptr<brillo::Process> http_server(new brillo::ProcessImpl());
126 http_server->AddArg(test_utils::GetBuildArtifactsPath("test_http_server"));
127 http_server->RedirectUsingPipe(STDOUT_FILENO, false);
128
129 if (!http_server->Start()) {
130 ADD_FAILURE() << "failed to spawn http server process";
131 return;
132 }
133 LOG(INFO) << "started http server with pid " << http_server->pid();
134
135 // Wait for server to begin accepting connections, obtain its port.
136 brillo::StreamPtr stdout = brillo::FileStream::FromFileDescriptor(
137 http_server->GetPipe(STDOUT_FILENO), false /* own */, nullptr);
138 if (!stdout)
139 return;
140
141 vector<char> buf(128);
142 string line;
143 while (line.find('\n') == string::npos) {
144 size_t read{};
145 if (!stdout->ReadBlocking(buf.data(), buf.size(), &read, nullptr)) {
146 ADD_FAILURE() << "error reading http server stdout";
147 return;
148 }
149 line.append(buf.data(), read);
150 if (read == 0)
151 break;
152 }
153 // Parse the port from the output line.
154 const size_t listening_msg_prefix_len = strlen(kServerListeningMsgPrefix);
155 if (line.size() < listening_msg_prefix_len) {
156 ADD_FAILURE() << "server output too short";
157 return;
158 }
159
160 EXPECT_EQ(kServerListeningMsgPrefix,
161 line.substr(0, listening_msg_prefix_len));
162 string port_str = line.substr(listening_msg_prefix_len);
163 port_str.resize(port_str.find('\n'));
164 EXPECT_TRUE(base::StringToUint(port_str, &port_));
165
166 started_ = true;
167 LOG(INFO) << "server running, listening on port " << port_;
168
169 // Any failure before this point will SIGKILL the test server if started
170 // when the |http_server| goes out of scope.
171 http_server_ = std::move(http_server);
172 }
173
~PythonHttpServer()174 ~PythonHttpServer() {
175 // If there's no process, do nothing.
176 if (!http_server_)
177 return;
178 // Wait up to 10 seconds for the process to finish. Destroying the process
179 // will kill it with a SIGKILL otherwise.
180 http_server_->Kill(SIGTERM, 10);
181 }
182
GetPort() const183 in_port_t GetPort() const override { return port_; }
184
185 private:
186 static const char* kServerListeningMsgPrefix;
187
188 unique_ptr<brillo::Process> http_server_;
189 unsigned int port_;
190 };
191
192 const char* PythonHttpServer::kServerListeningMsgPrefix = "listening on port ";
193
194 //
195 // Class hierarchy for HTTP fetcher test wrappers.
196 //
197
198 class AnyHttpFetcherFactory {
199 public:
AnyHttpFetcherFactory()200 AnyHttpFetcherFactory() {}
~AnyHttpFetcherFactory()201 virtual ~AnyHttpFetcherFactory() {}
202
203 virtual HttpFetcher* NewLargeFetcher() = 0;
NewLargeFetcher(size_t num_proxies)204 HttpFetcher* NewLargeFetcher(size_t num_proxies) {
205 auto res = NewLargeFetcher();
206
207 res->SetProxies(std::deque<std::string>(num_proxies, kNoProxy));
208 return res;
209 }
210
211 virtual HttpFetcher* NewSmallFetcher() = 0;
212
BigUrl(in_port_t port) const213 virtual string BigUrl(in_port_t port) const { return kUnusedUrl; }
SmallUrl(in_port_t port) const214 virtual string SmallUrl(in_port_t port) const { return kUnusedUrl; }
ErrorUrl(in_port_t port) const215 virtual string ErrorUrl(in_port_t port) const { return kUnusedUrl; }
216
217 virtual bool IsMock() const = 0;
218 virtual bool IsMulti() const = 0;
219 virtual bool IsHttpSupported() const = 0;
220 virtual bool IsFileFetcher() const = 0;
221
IgnoreServerAborting(HttpServer * server) const222 virtual void IgnoreServerAborting(HttpServer* server) const {}
223
224 virtual HttpServer* CreateServer() = 0;
225
fake_hardware()226 FakeHardware* fake_hardware() { return &fake_hardware_; }
227
228 protected:
229 FakeHardware fake_hardware_;
230 };
231
232 class MockHttpFetcherFactory : public AnyHttpFetcherFactory {
233 public:
234 // Necessary to unhide the definition in the base class.
235 using AnyHttpFetcherFactory::NewLargeFetcher;
NewLargeFetcher()236 HttpFetcher* NewLargeFetcher() override {
237 brillo::Blob big_data(1000000);
238 return new MockHttpFetcher(big_data.data(), big_data.size());
239 }
240
241 // Necessary to unhide the definition in the base class.
242 using AnyHttpFetcherFactory::NewSmallFetcher;
NewSmallFetcher()243 HttpFetcher* NewSmallFetcher() override {
244 return new MockHttpFetcher("x", 1);
245 }
246
IsMock() const247 bool IsMock() const override { return true; }
IsMulti() const248 bool IsMulti() const override { return false; }
IsHttpSupported() const249 bool IsHttpSupported() const override { return true; }
IsFileFetcher() const250 bool IsFileFetcher() const override { return false; }
251
CreateServer()252 HttpServer* CreateServer() override { return new NullHttpServer; }
253 };
254
255 class LibcurlHttpFetcherFactory : public AnyHttpFetcherFactory {
256 public:
257 // Necessary to unhide the definition in the base class.
258 using AnyHttpFetcherFactory::NewLargeFetcher;
NewLargeFetcher()259 HttpFetcher* NewLargeFetcher() override {
260 LibcurlHttpFetcher* ret = new LibcurlHttpFetcher(&fake_hardware_);
261 // Speed up test execution.
262 ret->set_idle_seconds(1);
263 ret->set_retry_seconds(1);
264 fake_hardware_.SetIsOfficialBuild(false);
265 return ret;
266 }
267
268 // Necessary to unhide the definition in the base class.
269 using AnyHttpFetcherFactory::NewSmallFetcher;
270
NewSmallFetcher()271 HttpFetcher* NewSmallFetcher() override { return NewLargeFetcher(); }
272
BigUrl(in_port_t port) const273 string BigUrl(in_port_t port) const override {
274 return LocalServerUrlForPath(
275 port, base::StringPrintf("/download/%d", kBigLength));
276 }
SmallUrl(in_port_t port) const277 string SmallUrl(in_port_t port) const override {
278 return LocalServerUrlForPath(port, "/foo");
279 }
ErrorUrl(in_port_t port) const280 string ErrorUrl(in_port_t port) const override {
281 return LocalServerUrlForPath(port, "/error");
282 }
283
IsMock() const284 bool IsMock() const override { return false; }
IsMulti() const285 bool IsMulti() const override { return false; }
IsHttpSupported() const286 bool IsHttpSupported() const override { return true; }
IsFileFetcher() const287 bool IsFileFetcher() const override { return false; }
288
IgnoreServerAborting(HttpServer * server) const289 void IgnoreServerAborting(HttpServer* server) const override {
290 // Nothing to do.
291 }
292
CreateServer()293 HttpServer* CreateServer() override { return new PythonHttpServer; }
294 };
295
296 class MultiRangeHttpFetcherFactory : public LibcurlHttpFetcherFactory {
297 public:
298 // Necessary to unhide the definition in the base class.
299 using AnyHttpFetcherFactory::NewLargeFetcher;
NewLargeFetcher()300 HttpFetcher* NewLargeFetcher() override {
301 MultiRangeHttpFetcher* ret =
302 new MultiRangeHttpFetcher(new LibcurlHttpFetcher(&fake_hardware_));
303 ret->ClearRanges();
304 ret->AddRange(0);
305 // Speed up test execution.
306 ret->set_idle_seconds(1);
307 ret->set_retry_seconds(1);
308 fake_hardware_.SetIsOfficialBuild(false);
309 return ret;
310 }
311
312 // Necessary to unhide the definition in the base class.
313 using AnyHttpFetcherFactory::NewSmallFetcher;
NewSmallFetcher()314 HttpFetcher* NewSmallFetcher() override { return NewLargeFetcher(); }
315
IsMulti() const316 bool IsMulti() const override { return true; }
317 };
318
319 class FileFetcherFactory : public AnyHttpFetcherFactory {
320 public:
321 // Necessary to unhide the definition in the base class.
322 using AnyHttpFetcherFactory::NewLargeFetcher;
NewLargeFetcher()323 HttpFetcher* NewLargeFetcher() override { return new FileFetcher(); }
324
325 // Necessary to unhide the definition in the base class.
326 using AnyHttpFetcherFactory::NewSmallFetcher;
NewSmallFetcher()327 HttpFetcher* NewSmallFetcher() override { return NewLargeFetcher(); }
328
BigUrl(in_port_t port) const329 string BigUrl(in_port_t port) const override {
330 static string big_contents = []() {
331 string buf;
332 buf.reserve(kBigLength);
333 constexpr const char* kBigUrlContent = "abcdefghij";
334 for (size_t i = 0; i < kBigLength; i += strlen(kBigUrlContent)) {
335 buf.append(kBigUrlContent,
336 std::min(kBigLength - i, strlen(kBigUrlContent)));
337 }
338 return buf;
339 }();
340 test_utils::WriteFileString(temp_file_.path(), big_contents);
341 return "file://" + temp_file_.path();
342 }
SmallUrl(in_port_t port) const343 string SmallUrl(in_port_t port) const override {
344 test_utils::WriteFileString(temp_file_.path(), "small contents");
345 return "file://" + temp_file_.path();
346 }
ErrorUrl(in_port_t port) const347 string ErrorUrl(in_port_t port) const override {
348 return "file:///path/to/non-existing-file";
349 }
350
IsMock() const351 bool IsMock() const override { return false; }
IsMulti() const352 bool IsMulti() const override { return false; }
IsHttpSupported() const353 bool IsHttpSupported() const override { return false; }
IsFileFetcher() const354 bool IsFileFetcher() const override { return true; }
355
IgnoreServerAborting(HttpServer * server) const356 void IgnoreServerAborting(HttpServer* server) const override {}
357
CreateServer()358 HttpServer* CreateServer() override { return new NullHttpServer; }
359
360 private:
361 ScopedTempFile temp_file_{"ue_file_fetcher.XXXXXX"};
362 };
363
364 class MultiRangeHttpFetcherOverFileFetcherFactory : public FileFetcherFactory {
365 public:
366 // Necessary to unhide the definition in the base class.
367 using AnyHttpFetcherFactory::NewLargeFetcher;
NewLargeFetcher()368 HttpFetcher* NewLargeFetcher() override {
369 MultiRangeHttpFetcher* ret = new MultiRangeHttpFetcher(new FileFetcher());
370 ret->ClearRanges();
371 // FileFetcher doesn't support range with unspecified length.
372 ret->AddRange(0, 1);
373 // Speed up test execution.
374 ret->set_idle_seconds(1);
375 ret->set_retry_seconds(1);
376 fake_hardware_.SetIsOfficialBuild(false);
377 return ret;
378 }
379
380 // Necessary to unhide the definition in the base class.
381 using AnyHttpFetcherFactory::NewSmallFetcher;
NewSmallFetcher()382 HttpFetcher* NewSmallFetcher() override { return NewLargeFetcher(); }
383
IsMulti() const384 bool IsMulti() const override { return true; }
385 };
386
387 //
388 // Infrastructure for type tests of HTTP fetcher.
389 // See: http://code.google.com/p/googletest/wiki/AdvancedGuide#Typed_Tests
390 //
391
392 // Fixture class template. We use an explicit constraint to guarantee that it
393 // can only be instantiated with an AnyHttpFetcherTest type, see:
394 // http://www2.research.att.com/~bs/bs_faq2.html#constraints
395 template <typename T>
396 class HttpFetcherTest : public ::testing::Test {
397 public:
398 #if BASE_VER < 780000 // Android
399 base::MessageLoopForIO base_loop_;
400 brillo::BaseMessageLoop loop_{&base_loop_};
401 #else // Chrome OS
402 base::SingleThreadTaskExecutor base_loop_{base::MessagePumpType::IO};
403 brillo::BaseMessageLoop loop_{base_loop_.task_runner()};
404 #endif // BASE_VER < 780000
405
406 T test_;
407
408 protected:
HttpFetcherTest()409 HttpFetcherTest() { loop_.SetAsCurrent(); }
410
TearDown()411 void TearDown() override {
412 EXPECT_EQ(0, brillo::MessageLoopRunMaxIterations(&loop_, 1));
413 }
414
415 private:
TypeConstraint(T * a)416 static void TypeConstraint(T* a) {
417 AnyHttpFetcherFactory* b = a;
418 if (b == 0) // Silence compiler warning of unused variable.
419 *b = a;
420 }
421 };
422
423 // Test case types list.
424 typedef ::testing::Types<LibcurlHttpFetcherFactory,
425 MockHttpFetcherFactory,
426 MultiRangeHttpFetcherFactory,
427 FileFetcherFactory,
428 MultiRangeHttpFetcherOverFileFetcherFactory>
429 HttpFetcherTestTypes;
430 TYPED_TEST_CASE(HttpFetcherTest, HttpFetcherTestTypes);
431
432 class HttpFetcherTestDelegate : public HttpFetcherDelegate {
433 public:
434 HttpFetcherTestDelegate() = default;
435
ReceivedBytes(HttpFetcher *,const void * bytes,size_t length)436 bool ReceivedBytes(HttpFetcher* /* fetcher */,
437 const void* bytes,
438 size_t length) override {
439 data.append(reinterpret_cast<const char*>(bytes), length);
440 // Update counters
441 times_received_bytes_called_++;
442 return true;
443 }
444
TransferComplete(HttpFetcher * fetcher,bool successful)445 void TransferComplete(HttpFetcher* fetcher, bool successful) override {
446 if (is_expect_error_)
447 EXPECT_EQ(kHttpResponseNotFound, fetcher->http_response_code());
448 else
449 EXPECT_EQ(kHttpResponseOk, fetcher->http_response_code());
450 MessageLoop::current()->BreakLoop();
451
452 // Update counter
453 times_transfer_complete_called_++;
454 }
455
TransferTerminated(HttpFetcher * fetcher)456 void TransferTerminated(HttpFetcher* fetcher) override {
457 times_transfer_terminated_called_++;
458 MessageLoop::current()->BreakLoop();
459 }
460
461 // Are we expecting an error response? (default: no)
462 bool is_expect_error_{false};
463
464 // Counters for callback invocations.
465 int times_transfer_complete_called_{0};
466 int times_transfer_terminated_called_{0};
467 int times_received_bytes_called_{0};
468
469 // The received data bytes.
470 string data;
471 };
472
StartTransfer(HttpFetcher * http_fetcher,const string & url)473 void StartTransfer(HttpFetcher* http_fetcher, const string& url) {
474 http_fetcher->BeginTransfer(url);
475 }
476
TYPED_TEST(HttpFetcherTest,SimpleTest)477 TYPED_TEST(HttpFetcherTest, SimpleTest) {
478 HttpFetcherTestDelegate delegate;
479 unique_ptr<HttpFetcher> fetcher(this->test_.NewSmallFetcher());
480 fetcher->set_delegate(&delegate);
481
482 unique_ptr<HttpServer> server(this->test_.CreateServer());
483 ASSERT_TRUE(server->started_);
484
485 this->loop_.PostTask(FROM_HERE,
486 base::Bind(StartTransfer,
487 fetcher.get(),
488 this->test_.SmallUrl(server->GetPort())));
489 this->loop_.Run();
490 EXPECT_EQ(0, delegate.times_transfer_terminated_called_);
491 }
492
TYPED_TEST(HttpFetcherTest,SimpleBigTest)493 TYPED_TEST(HttpFetcherTest, SimpleBigTest) {
494 HttpFetcherTestDelegate delegate;
495 unique_ptr<HttpFetcher> fetcher(this->test_.NewLargeFetcher());
496 fetcher->set_delegate(&delegate);
497
498 unique_ptr<HttpServer> server(this->test_.CreateServer());
499 ASSERT_TRUE(server->started_);
500
501 this->loop_.PostTask(
502 FROM_HERE,
503 base::Bind(
504 StartTransfer, fetcher.get(), this->test_.BigUrl(server->GetPort())));
505 this->loop_.Run();
506 EXPECT_EQ(0, delegate.times_transfer_terminated_called_);
507 }
508
509 // Issue #9648: when server returns an error HTTP response, the fetcher needs to
510 // terminate transfer prematurely, rather than try to process the error payload.
TYPED_TEST(HttpFetcherTest,ErrorTest)511 TYPED_TEST(HttpFetcherTest, ErrorTest) {
512 if (this->test_.IsMock() || this->test_.IsMulti())
513 return;
514 HttpFetcherTestDelegate delegate;
515
516 // Delegate should expect an error response.
517 delegate.is_expect_error_ = true;
518
519 unique_ptr<HttpFetcher> fetcher(this->test_.NewSmallFetcher());
520 fetcher->set_delegate(&delegate);
521
522 unique_ptr<HttpServer> server(this->test_.CreateServer());
523 ASSERT_TRUE(server->started_);
524
525 this->loop_.PostTask(FROM_HERE,
526 base::Bind(StartTransfer,
527 fetcher.get(),
528 this->test_.ErrorUrl(server->GetPort())));
529 this->loop_.Run();
530
531 // Make sure that no bytes were received.
532 EXPECT_EQ(0, delegate.times_received_bytes_called_);
533 EXPECT_EQ(0U, fetcher->GetBytesDownloaded());
534
535 // Make sure that transfer completion was signaled once, and no termination
536 // was signaled.
537 EXPECT_EQ(1, delegate.times_transfer_complete_called_);
538 EXPECT_EQ(0, delegate.times_transfer_terminated_called_);
539 }
540
TYPED_TEST(HttpFetcherTest,ExtraHeadersInRequestTest)541 TYPED_TEST(HttpFetcherTest, ExtraHeadersInRequestTest) {
542 if (this->test_.IsMock() || !this->test_.IsHttpSupported())
543 return;
544
545 HttpFetcherTestDelegate delegate;
546 unique_ptr<HttpFetcher> fetcher(this->test_.NewSmallFetcher());
547 fetcher->set_delegate(&delegate);
548 fetcher->SetHeader("User-Agent", "MyTest");
549 fetcher->SetHeader("user-agent", "Override that header");
550 fetcher->SetHeader("Authorization", "Basic user:passwd");
551
552 // Invalid headers.
553 fetcher->SetHeader("X-Foo", "Invalid\nHeader\nIgnored");
554 fetcher->SetHeader("X-Bar: ", "I do not know how to parse");
555
556 // Hide Accept header normally added by default.
557 fetcher->SetHeader("Accept", "");
558
559 PythonHttpServer server;
560 int port = server.GetPort();
561 ASSERT_TRUE(server.started_);
562
563 this->loop_.PostTask(
564 FROM_HERE,
565 base::Bind(StartTransfer,
566 fetcher.get(),
567 LocalServerUrlForPath(port, "/echo-headers")));
568 this->loop_.Run();
569
570 EXPECT_NE(string::npos,
571 delegate.data.find("user-agent: Override that header\r\n"));
572 EXPECT_NE(string::npos,
573 delegate.data.find("Authorization: Basic user:passwd\r\n"));
574
575 EXPECT_EQ(string::npos, delegate.data.find("\nAccept:"));
576 EXPECT_EQ(string::npos, delegate.data.find("X-Foo: Invalid"));
577 EXPECT_EQ(string::npos, delegate.data.find("X-Bar: I do not"));
578 }
579
580 class PausingHttpFetcherTestDelegate : public HttpFetcherDelegate {
581 public:
ReceivedBytes(HttpFetcher * fetcher,const void *,size_t)582 bool ReceivedBytes(HttpFetcher* fetcher,
583 const void* /* bytes */,
584 size_t /* length */) override {
585 CHECK(!paused_);
586 paused_ = true;
587 fetcher->Pause();
588 return true;
589 }
TransferComplete(HttpFetcher * fetcher,bool successful)590 void TransferComplete(HttpFetcher* fetcher, bool successful) override {
591 MessageLoop::current()->BreakLoop();
592 }
TransferTerminated(HttpFetcher * fetcher)593 void TransferTerminated(HttpFetcher* fetcher) override { ADD_FAILURE(); }
Unpause()594 void Unpause() {
595 CHECK(paused_);
596 paused_ = false;
597 fetcher_->Unpause();
598 }
599 bool paused_;
600 HttpFetcher* fetcher_;
601 };
602
UnpausingTimeoutCallback(PausingHttpFetcherTestDelegate * delegate,MessageLoop::TaskId * my_id)603 void UnpausingTimeoutCallback(PausingHttpFetcherTestDelegate* delegate,
604 MessageLoop::TaskId* my_id) {
605 if (delegate->paused_)
606 delegate->Unpause();
607 // Update the task id with the new scheduled callback.
608 *my_id = MessageLoop::current()->PostDelayedTask(
609 FROM_HERE,
610 base::Bind(&UnpausingTimeoutCallback, delegate, my_id),
611 base::TimeDelta::FromMilliseconds(200));
612 }
613
TYPED_TEST(HttpFetcherTest,PauseTest)614 TYPED_TEST(HttpFetcherTest, PauseTest) {
615 PausingHttpFetcherTestDelegate delegate;
616 unique_ptr<HttpFetcher> fetcher(this->test_.NewLargeFetcher());
617 delegate.paused_ = false;
618 delegate.fetcher_ = fetcher.get();
619 fetcher->set_delegate(&delegate);
620
621 unique_ptr<HttpServer> server(this->test_.CreateServer());
622 ASSERT_TRUE(server->started_);
623
624 MessageLoop::TaskId callback_id{};
625 callback_id = this->loop_.PostDelayedTask(
626 FROM_HERE,
627 base::Bind(&UnpausingTimeoutCallback, &delegate, &callback_id),
628 base::TimeDelta::FromMilliseconds(200));
629 fetcher->BeginTransfer(this->test_.BigUrl(server->GetPort()));
630
631 this->loop_.Run();
632 EXPECT_TRUE(this->loop_.CancelTask(callback_id));
633 }
634
635 // This test will pause the fetcher while the download is not yet started
636 // because it is waiting for the proxy to be resolved.
TYPED_TEST(HttpFetcherTest,PauseWhileResolvingProxyTest)637 TYPED_TEST(HttpFetcherTest, PauseWhileResolvingProxyTest) {
638 if (this->test_.IsMock() || !this->test_.IsHttpSupported())
639 return;
640 unique_ptr<HttpFetcher> fetcher(this->test_.NewLargeFetcher());
641
642 // Saved arguments from the proxy call.
643 fetcher->BeginTransfer("http://fake_url");
644
645 // Pausing and unpausing while resolving the proxy should not affect anything.
646 fetcher->Pause();
647 fetcher->Unpause();
648 fetcher->Pause();
649 // Proxy resolver comes back after we paused the fetcher.
650 }
651
652 class AbortingHttpFetcherTestDelegate : public HttpFetcherDelegate {
653 public:
ReceivedBytes(HttpFetcher * fetcher,const void * bytes,size_t length)654 bool ReceivedBytes(HttpFetcher* fetcher,
655 const void* bytes,
656 size_t length) override {
657 return true;
658 }
TransferComplete(HttpFetcher * fetcher,bool successful)659 void TransferComplete(HttpFetcher* fetcher, bool successful) override {
660 ADD_FAILURE(); // We should never get here
661 MessageLoop::current()->BreakLoop();
662 }
TransferTerminated(HttpFetcher * fetcher)663 void TransferTerminated(HttpFetcher* fetcher) override {
664 EXPECT_EQ(fetcher, fetcher_.get());
665 EXPECT_FALSE(once_);
666 EXPECT_TRUE(callback_once_);
667 callback_once_ = false;
668 // The fetcher could have a callback scheduled on the ProxyResolver that
669 // can fire after this callback. We wait until the end of the test to
670 // delete the fetcher.
671 }
TerminateTransfer()672 void TerminateTransfer() {
673 CHECK(once_);
674 once_ = false;
675 fetcher_->TerminateTransfer();
676 }
EndLoop()677 void EndLoop() { MessageLoop::current()->BreakLoop(); }
678 bool once_;
679 bool callback_once_;
680 unique_ptr<HttpFetcher> fetcher_;
681 };
682
AbortingTimeoutCallback(AbortingHttpFetcherTestDelegate * delegate,MessageLoop::TaskId * my_id)683 void AbortingTimeoutCallback(AbortingHttpFetcherTestDelegate* delegate,
684 MessageLoop::TaskId* my_id) {
685 if (delegate->once_) {
686 delegate->TerminateTransfer();
687 *my_id = MessageLoop::current()->PostTask(
688 FROM_HERE, base::Bind(AbortingTimeoutCallback, delegate, my_id));
689 } else {
690 delegate->EndLoop();
691 *my_id = MessageLoop::kTaskIdNull;
692 }
693 }
694
TYPED_TEST(HttpFetcherTest,AbortTest)695 TYPED_TEST(HttpFetcherTest, AbortTest) {
696 AbortingHttpFetcherTestDelegate delegate;
697 delegate.fetcher_.reset(this->test_.NewLargeFetcher());
698 delegate.once_ = true;
699 delegate.callback_once_ = true;
700 delegate.fetcher_->set_delegate(&delegate);
701
702 unique_ptr<HttpServer> server(this->test_.CreateServer());
703 this->test_.IgnoreServerAborting(server.get());
704 ASSERT_TRUE(server->started_);
705
706 MessageLoop::TaskId task_id = MessageLoop::kTaskIdNull;
707
708 task_id = this->loop_.PostTask(
709 FROM_HERE, base::Bind(AbortingTimeoutCallback, &delegate, &task_id));
710 delegate.fetcher_->BeginTransfer(this->test_.BigUrl(server->GetPort()));
711
712 this->loop_.Run();
713 CHECK(!delegate.once_);
714 CHECK(!delegate.callback_once_);
715 this->loop_.CancelTask(task_id);
716 }
717
TYPED_TEST(HttpFetcherTest,TerminateTransferWhileResolvingProxyTest)718 TYPED_TEST(HttpFetcherTest, TerminateTransferWhileResolvingProxyTest) {
719 if (this->test_.IsMock() || !this->test_.IsHttpSupported())
720 return;
721 unique_ptr<HttpFetcher> fetcher(this->test_.NewLargeFetcher());
722
723 HttpFetcherTestDelegate delegate;
724 fetcher->set_delegate(&delegate);
725
726 fetcher->BeginTransfer("http://fake_url");
727 // Run the message loop until idle. This must call the MockProxyResolver with
728 // the request.
729 while (this->loop_.RunOnce(false)) {
730 }
731
732 // Terminate the transfer right before the proxy resolution response.
733 fetcher->TerminateTransfer();
734 EXPECT_EQ(0, delegate.times_received_bytes_called_);
735 EXPECT_EQ(0, delegate.times_transfer_complete_called_);
736 EXPECT_EQ(1, delegate.times_transfer_terminated_called_);
737 }
738
739 class FlakyHttpFetcherTestDelegate : public HttpFetcherDelegate {
740 public:
ReceivedBytes(HttpFetcher * fetcher,const void * bytes,size_t length)741 bool ReceivedBytes(HttpFetcher* fetcher,
742 const void* bytes,
743 size_t length) override {
744 data.append(reinterpret_cast<const char*>(bytes), length);
745 return true;
746 }
TransferComplete(HttpFetcher * fetcher,bool successful)747 void TransferComplete(HttpFetcher* fetcher, bool successful) override {
748 EXPECT_TRUE(successful);
749 EXPECT_EQ(kHttpResponsePartialContent, fetcher->http_response_code());
750 MessageLoop::current()->BreakLoop();
751 }
TransferTerminated(HttpFetcher * fetcher)752 void TransferTerminated(HttpFetcher* fetcher) override { ADD_FAILURE(); }
753 string data;
754 };
755
TYPED_TEST(HttpFetcherTest,FlakyTest)756 TYPED_TEST(HttpFetcherTest, FlakyTest) {
757 if (this->test_.IsMock() || !this->test_.IsHttpSupported())
758 return;
759 {
760 FlakyHttpFetcherTestDelegate delegate;
761 unique_ptr<HttpFetcher> fetcher(this->test_.NewSmallFetcher());
762 fetcher->set_delegate(&delegate);
763
764 unique_ptr<HttpServer> server(this->test_.CreateServer());
765 ASSERT_TRUE(server->started_);
766
767 this->loop_.PostTask(FROM_HERE,
768 base::Bind(&StartTransfer,
769 fetcher.get(),
770 LocalServerUrlForPath(
771 server->GetPort(),
772 base::StringPrintf("/flaky/%d/%d/%d/%d",
773 kBigLength,
774 kFlakyTruncateLength,
775 kFlakySleepEvery,
776 kFlakySleepSecs))));
777 this->loop_.Run();
778
779 // verify the data we get back
780 ASSERT_EQ(kBigLength, static_cast<int>(delegate.data.size()));
781 for (int i = 0; i < kBigLength; i += 10) {
782 // Assert so that we don't flood the screen w/ EXPECT errors on failure.
783 ASSERT_EQ(delegate.data.substr(i, 10), "abcdefghij");
784 }
785 }
786 }
787
788 // This delegate kills the server attached to it after receiving any bytes.
789 // This can be used for testing what happens when you try to fetch data and
790 // the server dies.
791 class FailureHttpFetcherTestDelegate : public HttpFetcherDelegate {
792 public:
FailureHttpFetcherTestDelegate(PythonHttpServer * server)793 explicit FailureHttpFetcherTestDelegate(PythonHttpServer* server)
794 : server_(server) {}
795
~FailureHttpFetcherTestDelegate()796 ~FailureHttpFetcherTestDelegate() override {
797 if (server_) {
798 LOG(INFO) << "Stopping server in destructor";
799 server_.reset();
800 LOG(INFO) << "server stopped";
801 }
802 }
803
ReceivedBytes(HttpFetcher * fetcher,const void * bytes,size_t length)804 bool ReceivedBytes(HttpFetcher* fetcher,
805 const void* bytes,
806 size_t length) override {
807 if (server_) {
808 LOG(INFO) << "Stopping server in ReceivedBytes";
809 server_.reset();
810 LOG(INFO) << "server stopped";
811 }
812 return true;
813 }
TransferComplete(HttpFetcher * fetcher,bool successful)814 void TransferComplete(HttpFetcher* fetcher, bool successful) override {
815 EXPECT_FALSE(successful);
816 EXPECT_EQ(0, fetcher->http_response_code());
817 times_transfer_complete_called_++;
818 MessageLoop::current()->BreakLoop();
819 }
TransferTerminated(HttpFetcher * fetcher)820 void TransferTerminated(HttpFetcher* fetcher) override {
821 times_transfer_terminated_called_++;
822 MessageLoop::current()->BreakLoop();
823 }
824 unique_ptr<PythonHttpServer> server_;
825 int times_transfer_terminated_called_{0};
826 int times_transfer_complete_called_{0};
827 };
828
TYPED_TEST(HttpFetcherTest,FailureTest)829 TYPED_TEST(HttpFetcherTest, FailureTest) {
830 // This test ensures that a fetcher responds correctly when a server isn't
831 // available at all.
832 if (this->test_.IsMock())
833 return;
834 FailureHttpFetcherTestDelegate delegate(nullptr);
835 unique_ptr<HttpFetcher> fetcher(this->test_.NewSmallFetcher());
836 fetcher->set_delegate(&delegate);
837
838 this->loop_.PostTask(
839 FROM_HERE,
840 base::Bind(
841 StartTransfer, fetcher.get(), "http://host_doesnt_exist99999999"));
842 this->loop_.Run();
843 EXPECT_EQ(1, delegate.times_transfer_complete_called_);
844 EXPECT_EQ(0, delegate.times_transfer_terminated_called_);
845
846 // Exiting and testing happens in the delegate
847 }
848
TYPED_TEST(HttpFetcherTest,NoResponseTest)849 TYPED_TEST(HttpFetcherTest, NoResponseTest) {
850 // This test starts a new http server but the server doesn't respond and just
851 // closes the connection.
852 if (this->test_.IsMock())
853 return;
854
855 PythonHttpServer* server = new PythonHttpServer();
856 int port = server->GetPort();
857 ASSERT_TRUE(server->started_);
858
859 // Handles destruction and claims ownership.
860 FailureHttpFetcherTestDelegate delegate(server);
861 unique_ptr<HttpFetcher> fetcher(this->test_.NewSmallFetcher());
862 fetcher->set_delegate(&delegate);
863 // The server will not reply at all, so we can limit the execution time of the
864 // test by reducing the low-speed timeout to something small. The test will
865 // finish once the TimeoutCallback() triggers (every second) and the timeout
866 // expired.
867 fetcher->set_low_speed_limit(kDownloadLowSpeedLimitBps, 1);
868
869 this->loop_.PostTask(
870 FROM_HERE,
871 base::Bind(
872 StartTransfer, fetcher.get(), LocalServerUrlForPath(port, "/hang")));
873 this->loop_.Run();
874 EXPECT_EQ(1, delegate.times_transfer_complete_called_);
875 EXPECT_EQ(0, delegate.times_transfer_terminated_called_);
876
877 // Check that no other callback runs in the next two seconds. That would
878 // indicate a leaked callback.
879 bool timeout = false;
880 auto callback = base::Bind([](bool* timeout) { *timeout = true; },
881 base::Unretained(&timeout));
882 this->loop_.PostDelayedTask(
883 FROM_HERE, callback, base::TimeDelta::FromSeconds(2));
884 EXPECT_TRUE(this->loop_.RunOnce(true));
885 EXPECT_TRUE(timeout);
886 }
887
TYPED_TEST(HttpFetcherTest,ServerDiesTest)888 TYPED_TEST(HttpFetcherTest, ServerDiesTest) {
889 // This test starts a new http server and kills it after receiving its first
890 // set of bytes. It test whether or not our fetcher eventually gives up on
891 // retries and aborts correctly.
892 if (this->test_.IsMock())
893 return;
894 PythonHttpServer* server = new PythonHttpServer();
895 int port = server->GetPort();
896 ASSERT_TRUE(server->started_);
897
898 // Handles destruction and claims ownership.
899 FailureHttpFetcherTestDelegate delegate(server);
900 unique_ptr<HttpFetcher> fetcher(this->test_.NewSmallFetcher());
901 fetcher->set_delegate(&delegate);
902
903 this->loop_.PostTask(
904 FROM_HERE,
905 base::Bind(StartTransfer,
906 fetcher.get(),
907 LocalServerUrlForPath(port,
908 base::StringPrintf("/flaky/%d/%d/%d/%d",
909 kBigLength,
910 kFlakyTruncateLength,
911 kFlakySleepEvery,
912 kFlakySleepSecs))));
913 this->loop_.Run();
914 EXPECT_EQ(1, delegate.times_transfer_complete_called_);
915 EXPECT_EQ(0, delegate.times_transfer_terminated_called_);
916
917 // Exiting and testing happens in the delegate
918 }
919
920 // Test that we can cancel a transfer while it is still trying to connect to the
921 // server. This test kills the server after a few bytes are received.
TYPED_TEST(HttpFetcherTest,TerminateTransferWhenServerDiedTest)922 TYPED_TEST(HttpFetcherTest, TerminateTransferWhenServerDiedTest) {
923 if (this->test_.IsMock() || !this->test_.IsHttpSupported())
924 return;
925
926 PythonHttpServer* server = new PythonHttpServer();
927 int port = server->GetPort();
928 ASSERT_TRUE(server->started_);
929
930 // Handles destruction and claims ownership.
931 FailureHttpFetcherTestDelegate delegate(server);
932 unique_ptr<HttpFetcher> fetcher(this->test_.NewSmallFetcher());
933 fetcher->set_delegate(&delegate);
934
935 this->loop_.PostTask(
936 FROM_HERE,
937 base::Bind(StartTransfer,
938 fetcher.get(),
939 LocalServerUrlForPath(port,
940 base::StringPrintf("/flaky/%d/%d/%d/%d",
941 kBigLength,
942 kFlakyTruncateLength,
943 kFlakySleepEvery,
944 kFlakySleepSecs))));
945 // Terminating the transfer after 3 seconds gives it a chance to contact the
946 // server and enter the retry loop.
947 this->loop_.PostDelayedTask(FROM_HERE,
948 base::Bind(&HttpFetcher::TerminateTransfer,
949 base::Unretained(fetcher.get())),
950 base::TimeDelta::FromSeconds(3));
951
952 // Exiting and testing happens in the delegate.
953 this->loop_.Run();
954 EXPECT_EQ(0, delegate.times_transfer_complete_called_);
955 EXPECT_EQ(1, delegate.times_transfer_terminated_called_);
956
957 // Check that no other callback runs in the next two seconds. That would
958 // indicate a leaked callback.
959 bool timeout = false;
960 auto callback = base::Bind([](bool* timeout) { *timeout = true; },
961 base::Unretained(&timeout));
962 this->loop_.PostDelayedTask(
963 FROM_HERE, callback, base::TimeDelta::FromSeconds(2));
964 EXPECT_TRUE(this->loop_.RunOnce(true));
965 EXPECT_TRUE(timeout);
966 }
967
968 const HttpResponseCode kRedirectCodes[] = {kHttpResponseMovedPermanently,
969 kHttpResponseFound,
970 kHttpResponseSeeOther,
971 kHttpResponseTempRedirect};
972
973 class RedirectHttpFetcherTestDelegate : public HttpFetcherDelegate {
974 public:
RedirectHttpFetcherTestDelegate(bool expected_successful)975 explicit RedirectHttpFetcherTestDelegate(bool expected_successful)
976 : expected_successful_(expected_successful) {}
ReceivedBytes(HttpFetcher * fetcher,const void * bytes,size_t length)977 bool ReceivedBytes(HttpFetcher* fetcher,
978 const void* bytes,
979 size_t length) override {
980 data.append(reinterpret_cast<const char*>(bytes), length);
981 return true;
982 }
TransferComplete(HttpFetcher * fetcher,bool successful)983 void TransferComplete(HttpFetcher* fetcher, bool successful) override {
984 EXPECT_EQ(expected_successful_, successful);
985 if (expected_successful_) {
986 EXPECT_EQ(kHttpResponseOk, fetcher->http_response_code());
987 } else {
988 EXPECT_GE(fetcher->http_response_code(), kHttpResponseMovedPermanently);
989 EXPECT_LE(fetcher->http_response_code(), kHttpResponseTempRedirect);
990 }
991 MessageLoop::current()->BreakLoop();
992 }
TransferTerminated(HttpFetcher * fetcher)993 void TransferTerminated(HttpFetcher* fetcher) override { ADD_FAILURE(); }
994 bool expected_successful_;
995 string data;
996 };
997
998 // RedirectTest takes ownership of |http_fetcher|.
RedirectTest(const HttpServer * server,bool expected_successful,const string & url,HttpFetcher * http_fetcher)999 void RedirectTest(const HttpServer* server,
1000 bool expected_successful,
1001 const string& url,
1002 HttpFetcher* http_fetcher) {
1003 RedirectHttpFetcherTestDelegate delegate(expected_successful);
1004 unique_ptr<HttpFetcher> fetcher(http_fetcher);
1005 fetcher->set_delegate(&delegate);
1006
1007 MessageLoop::current()->PostTask(
1008 FROM_HERE,
1009 base::Bind(StartTransfer,
1010 fetcher.get(),
1011 LocalServerUrlForPath(server->GetPort(), url)));
1012 MessageLoop::current()->Run();
1013 if (expected_successful) {
1014 // verify the data we get back
1015 ASSERT_EQ(static_cast<size_t>(kMediumLength), delegate.data.size());
1016 for (int i = 0; i < kMediumLength; i += 10) {
1017 // Assert so that we don't flood the screen w/ EXPECT errors on failure.
1018 ASSERT_EQ(delegate.data.substr(i, 10), "abcdefghij");
1019 }
1020 }
1021 }
1022
TYPED_TEST(HttpFetcherTest,SimpleRedirectTest)1023 TYPED_TEST(HttpFetcherTest, SimpleRedirectTest) {
1024 if (this->test_.IsMock() || !this->test_.IsHttpSupported())
1025 return;
1026
1027 unique_ptr<HttpServer> server(this->test_.CreateServer());
1028 ASSERT_TRUE(server->started_);
1029
1030 for (size_t c = 0; c < base::size(kRedirectCodes); ++c) {
1031 const string url = base::StringPrintf(
1032 "/redirect/%d/download/%d", kRedirectCodes[c], kMediumLength);
1033 RedirectTest(server.get(), true, url, this->test_.NewLargeFetcher());
1034 }
1035 }
1036
TYPED_TEST(HttpFetcherTest,MaxRedirectTest)1037 TYPED_TEST(HttpFetcherTest, MaxRedirectTest) {
1038 if (this->test_.IsMock() || !this->test_.IsHttpSupported())
1039 return;
1040
1041 unique_ptr<HttpServer> server(this->test_.CreateServer());
1042 ASSERT_TRUE(server->started_);
1043
1044 string url;
1045 for (int r = 0; r < kDownloadMaxRedirects; r++) {
1046 url += base::StringPrintf("/redirect/%d",
1047 kRedirectCodes[r % base::size(kRedirectCodes)]);
1048 }
1049 url += base::StringPrintf("/download/%d", kMediumLength);
1050 RedirectTest(server.get(), true, url, this->test_.NewLargeFetcher());
1051 }
1052
TYPED_TEST(HttpFetcherTest,BeyondMaxRedirectTest)1053 TYPED_TEST(HttpFetcherTest, BeyondMaxRedirectTest) {
1054 if (this->test_.IsMock() || !this->test_.IsHttpSupported())
1055 return;
1056
1057 unique_ptr<HttpServer> server(this->test_.CreateServer());
1058 ASSERT_TRUE(server->started_);
1059
1060 string url;
1061 for (int r = 0; r < kDownloadMaxRedirects + 1; r++) {
1062 url += base::StringPrintf("/redirect/%d",
1063 kRedirectCodes[r % base::size(kRedirectCodes)]);
1064 }
1065 url += base::StringPrintf("/download/%d", kMediumLength);
1066 RedirectTest(server.get(), false, url, this->test_.NewLargeFetcher());
1067 }
1068
1069 class MultiHttpFetcherTestDelegate : public HttpFetcherDelegate {
1070 public:
MultiHttpFetcherTestDelegate(int expected_response_code)1071 explicit MultiHttpFetcherTestDelegate(int expected_response_code)
1072 : expected_response_code_(expected_response_code) {}
1073
ReceivedBytes(HttpFetcher * fetcher,const void * bytes,size_t length)1074 bool ReceivedBytes(HttpFetcher* fetcher,
1075 const void* bytes,
1076 size_t length) override {
1077 EXPECT_EQ(fetcher, fetcher_.get());
1078 data.append(reinterpret_cast<const char*>(bytes), length);
1079 return true;
1080 }
1081
TransferComplete(HttpFetcher * fetcher,bool successful)1082 void TransferComplete(HttpFetcher* fetcher, bool successful) override {
1083 EXPECT_EQ(fetcher, fetcher_.get());
1084 EXPECT_EQ(expected_response_code_ != kHttpResponseUndefined, successful);
1085 if (expected_response_code_ != 0)
1086 EXPECT_EQ(expected_response_code_, fetcher->http_response_code());
1087 // Destroy the fetcher (because we're allowed to).
1088 fetcher_.reset(nullptr);
1089 MessageLoop::current()->BreakLoop();
1090 }
1091
TransferTerminated(HttpFetcher * fetcher)1092 void TransferTerminated(HttpFetcher* fetcher) override { ADD_FAILURE(); }
1093
1094 unique_ptr<HttpFetcher> fetcher_;
1095 int expected_response_code_;
1096 string data;
1097 };
1098
MultiTest(HttpFetcher * fetcher_in,FakeHardware * fake_hardware,const string & url,const vector<pair<off_t,off_t>> & ranges,const string & expected_prefix,size_t expected_size,HttpResponseCode expected_response_code)1099 void MultiTest(HttpFetcher* fetcher_in,
1100 FakeHardware* fake_hardware,
1101 const string& url,
1102 const vector<pair<off_t, off_t>>& ranges,
1103 const string& expected_prefix,
1104 size_t expected_size,
1105 HttpResponseCode expected_response_code) {
1106 MultiHttpFetcherTestDelegate delegate(expected_response_code);
1107 delegate.fetcher_.reset(fetcher_in);
1108
1109 MultiRangeHttpFetcher* multi_fetcher =
1110 static_cast<MultiRangeHttpFetcher*>(fetcher_in);
1111 ASSERT_TRUE(multi_fetcher);
1112 multi_fetcher->ClearRanges();
1113 for (vector<pair<off_t, off_t>>::const_iterator it = ranges.begin(),
1114 e = ranges.end();
1115 it != e;
1116 ++it) {
1117 string tmp_str = base::StringPrintf("%jd+", it->first);
1118 if (it->second > 0) {
1119 base::StringAppendF(&tmp_str, "%jd", it->second);
1120 multi_fetcher->AddRange(it->first, it->second);
1121 } else {
1122 base::StringAppendF(&tmp_str, "?");
1123 multi_fetcher->AddRange(it->first);
1124 }
1125 LOG(INFO) << "added range: " << tmp_str;
1126 }
1127 fake_hardware->SetIsOfficialBuild(false);
1128 multi_fetcher->set_delegate(&delegate);
1129
1130 MessageLoop::current()->PostTask(
1131 FROM_HERE, base::Bind(StartTransfer, multi_fetcher, url));
1132 MessageLoop::current()->Run();
1133
1134 EXPECT_EQ(expected_size, delegate.data.size());
1135 EXPECT_EQ(expected_prefix,
1136 string(delegate.data.data(), expected_prefix.size()));
1137 }
1138
TYPED_TEST(HttpFetcherTest,MultiHttpFetcherSimpleTest)1139 TYPED_TEST(HttpFetcherTest, MultiHttpFetcherSimpleTest) {
1140 if (!this->test_.IsMulti())
1141 return;
1142
1143 unique_ptr<HttpServer> server(this->test_.CreateServer());
1144 ASSERT_TRUE(server->started_);
1145
1146 vector<pair<off_t, off_t>> ranges;
1147 ranges.push_back(make_pair(0, 25));
1148 ranges.push_back(make_pair(99, 17));
1149 MultiTest(this->test_.NewLargeFetcher(),
1150 this->test_.fake_hardware(),
1151 this->test_.BigUrl(server->GetPort()),
1152 ranges,
1153 "abcdefghijabcdefghijabcdejabcdefghijabcdef",
1154 25 + 17,
1155 this->test_.IsFileFetcher() ? kHttpResponseOk
1156 : kHttpResponsePartialContent);
1157 }
1158
TYPED_TEST(HttpFetcherTest,MultiHttpFetcherUnspecifiedEndTest)1159 TYPED_TEST(HttpFetcherTest, MultiHttpFetcherUnspecifiedEndTest) {
1160 if (!this->test_.IsMulti() || this->test_.IsFileFetcher())
1161 return;
1162
1163 unique_ptr<HttpServer> server(this->test_.CreateServer());
1164 ASSERT_TRUE(server->started_);
1165
1166 vector<pair<off_t, off_t>> ranges;
1167 ranges.push_back(make_pair(0, 25));
1168 ranges.push_back(make_pair(99, 0));
1169 MultiTest(this->test_.NewLargeFetcher(),
1170 this->test_.fake_hardware(),
1171 this->test_.BigUrl(server->GetPort()),
1172 ranges,
1173 "abcdefghijabcdefghijabcdejabcdefghijabcdef",
1174 kBigLength - (99 - 25),
1175 kHttpResponsePartialContent);
1176 }
1177
TYPED_TEST(HttpFetcherTest,MultiHttpFetcherLengthLimitTest)1178 TYPED_TEST(HttpFetcherTest, MultiHttpFetcherLengthLimitTest) {
1179 if (!this->test_.IsMulti())
1180 return;
1181
1182 unique_ptr<HttpServer> server(this->test_.CreateServer());
1183 ASSERT_TRUE(server->started_);
1184
1185 vector<pair<off_t, off_t>> ranges;
1186 ranges.push_back(make_pair(0, 24));
1187 MultiTest(this->test_.NewLargeFetcher(),
1188 this->test_.fake_hardware(),
1189 this->test_.BigUrl(server->GetPort()),
1190 ranges,
1191 "abcdefghijabcdefghijabcd",
1192 24,
1193 this->test_.IsFileFetcher() ? kHttpResponseOk
1194 : kHttpResponsePartialContent);
1195 }
1196
TYPED_TEST(HttpFetcherTest,MultiHttpFetcherMultiEndTest)1197 TYPED_TEST(HttpFetcherTest, MultiHttpFetcherMultiEndTest) {
1198 if (!this->test_.IsMulti() || this->test_.IsFileFetcher())
1199 return;
1200
1201 unique_ptr<HttpServer> server(this->test_.CreateServer());
1202 ASSERT_TRUE(server->started_);
1203
1204 vector<pair<off_t, off_t>> ranges;
1205 ranges.push_back(make_pair(kBigLength - 2, 0));
1206 ranges.push_back(make_pair(kBigLength - 3, 0));
1207 MultiTest(this->test_.NewLargeFetcher(),
1208 this->test_.fake_hardware(),
1209 this->test_.BigUrl(server->GetPort()),
1210 ranges,
1211 "ijhij",
1212 5,
1213 kHttpResponsePartialContent);
1214 }
1215
TYPED_TEST(HttpFetcherTest,MultiHttpFetcherInsufficientTest)1216 TYPED_TEST(HttpFetcherTest, MultiHttpFetcherInsufficientTest) {
1217 if (!this->test_.IsMulti())
1218 return;
1219
1220 unique_ptr<HttpServer> server(this->test_.CreateServer());
1221 ASSERT_TRUE(server->started_);
1222
1223 vector<pair<off_t, off_t>> ranges;
1224 ranges.push_back(make_pair(kBigLength - 2, 4));
1225 for (int i = 0; i < 2; ++i) {
1226 LOG(INFO) << "i = " << i;
1227 MultiTest(this->test_.NewLargeFetcher(),
1228 this->test_.fake_hardware(),
1229 this->test_.BigUrl(server->GetPort()),
1230 ranges,
1231 "ij",
1232 2,
1233 kHttpResponseUndefined);
1234 ranges.push_back(make_pair(0, 5));
1235 }
1236 }
1237
1238 // Issue #18143: when a fetch of a secondary chunk out of a chain, then it
1239 // should retry with other proxies listed before giving up.
1240 //
1241 // (1) successful recovery: The offset fetch will fail twice but succeed with
1242 // the third proxy.
TYPED_TEST(HttpFetcherTest,MultiHttpFetcherErrorIfOffsetRecoverableTest)1243 TYPED_TEST(HttpFetcherTest, MultiHttpFetcherErrorIfOffsetRecoverableTest) {
1244 if (!this->test_.IsMulti() || this->test_.IsFileFetcher())
1245 return;
1246
1247 unique_ptr<HttpServer> server(this->test_.CreateServer());
1248 ASSERT_TRUE(server->started_);
1249
1250 vector<pair<off_t, off_t>> ranges;
1251 ranges.push_back(make_pair(0, 25));
1252 ranges.push_back(make_pair(99, 0));
1253 MultiTest(this->test_.NewLargeFetcher(3),
1254 this->test_.fake_hardware(),
1255 LocalServerUrlForPath(
1256 server->GetPort(),
1257 base::StringPrintf("/error-if-offset/%d/2", kBigLength)),
1258 ranges,
1259 "abcdefghijabcdefghijabcdejabcdefghijabcdef",
1260 kBigLength - (99 - 25),
1261 kHttpResponsePartialContent);
1262 }
1263
1264 // (2) unsuccessful recovery: The offset fetch will fail repeatedly. The
1265 // fetcher will signal a (failed) completed transfer to the delegate.
TYPED_TEST(HttpFetcherTest,MultiHttpFetcherErrorIfOffsetUnrecoverableTest)1266 TYPED_TEST(HttpFetcherTest, MultiHttpFetcherErrorIfOffsetUnrecoverableTest) {
1267 if (!this->test_.IsMulti() || this->test_.IsFileFetcher())
1268 return;
1269
1270 unique_ptr<HttpServer> server(this->test_.CreateServer());
1271 ASSERT_TRUE(server->started_);
1272
1273 vector<pair<off_t, off_t>> ranges;
1274 ranges.push_back(make_pair(0, 25));
1275 ranges.push_back(make_pair(99, 0));
1276 MultiTest(this->test_.NewLargeFetcher(),
1277 this->test_.fake_hardware(),
1278 LocalServerUrlForPath(
1279 server->GetPort(),
1280 base::StringPrintf("/error-if-offset/%d/3", kBigLength)),
1281 ranges,
1282 "abcdefghijabcdefghijabcde", // only received the first chunk
1283 25,
1284 kHttpResponseUndefined);
1285 }
1286
1287 // This HttpFetcherDelegate calls TerminateTransfer at a configurable point.
1288 class MultiHttpFetcherTerminateTestDelegate : public HttpFetcherDelegate {
1289 public:
MultiHttpFetcherTerminateTestDelegate(size_t terminate_trigger_bytes)1290 explicit MultiHttpFetcherTerminateTestDelegate(size_t terminate_trigger_bytes)
1291 : terminate_trigger_bytes_(terminate_trigger_bytes) {}
1292
ReceivedBytes(HttpFetcher * fetcher,const void * bytes,size_t length)1293 bool ReceivedBytes(HttpFetcher* fetcher,
1294 const void* bytes,
1295 size_t length) override {
1296 LOG(INFO) << "ReceivedBytes, " << length << " bytes.";
1297 EXPECT_EQ(fetcher, fetcher_.get());
1298 bool should_terminate = false;
1299 if (bytes_downloaded_ < terminate_trigger_bytes_ &&
1300 bytes_downloaded_ + length >= terminate_trigger_bytes_) {
1301 MessageLoop::current()->PostTask(
1302 FROM_HERE,
1303 base::Bind(&HttpFetcher::TerminateTransfer,
1304 base::Unretained(fetcher_.get())));
1305 should_terminate = true;
1306 }
1307 bytes_downloaded_ += length;
1308 return !should_terminate;
1309 }
1310
TransferComplete(HttpFetcher * fetcher,bool successful)1311 void TransferComplete(HttpFetcher* fetcher, bool successful) override {
1312 ADD_FAILURE() << "TransferComplete called but expected a failure";
1313 // Destroy the fetcher (because we're allowed to).
1314 fetcher_.reset(nullptr);
1315 MessageLoop::current()->BreakLoop();
1316 }
1317
TransferTerminated(HttpFetcher * fetcher)1318 void TransferTerminated(HttpFetcher* fetcher) override {
1319 // Destroy the fetcher (because we're allowed to).
1320 fetcher_.reset(nullptr);
1321 MessageLoop::current()->BreakLoop();
1322 }
1323
1324 unique_ptr<HttpFetcher> fetcher_;
1325 size_t bytes_downloaded_{0};
1326 size_t terminate_trigger_bytes_;
1327 };
1328
TYPED_TEST(HttpFetcherTest,MultiHttpFetcherTerminateBetweenRangesTest)1329 TYPED_TEST(HttpFetcherTest, MultiHttpFetcherTerminateBetweenRangesTest) {
1330 if (!this->test_.IsMulti())
1331 return;
1332 const size_t kRangeTrigger = 1000;
1333 MultiHttpFetcherTerminateTestDelegate delegate(kRangeTrigger);
1334
1335 unique_ptr<HttpServer> server(this->test_.CreateServer());
1336 ASSERT_TRUE(server->started_);
1337
1338 MultiRangeHttpFetcher* multi_fetcher =
1339 static_cast<MultiRangeHttpFetcher*>(this->test_.NewLargeFetcher());
1340 ASSERT_TRUE(multi_fetcher);
1341 // Transfer ownership of the fetcher to the delegate.
1342 delegate.fetcher_.reset(multi_fetcher);
1343 multi_fetcher->set_delegate(&delegate);
1344
1345 multi_fetcher->ClearRanges();
1346 multi_fetcher->AddRange(45, kRangeTrigger);
1347 multi_fetcher->AddRange(2000, 100);
1348
1349 this->test_.fake_hardware()->SetIsOfficialBuild(false);
1350
1351 StartTransfer(multi_fetcher, this->test_.BigUrl(server->GetPort()));
1352 MessageLoop::current()->Run();
1353
1354 // Check that the delegate made it to the trigger point.
1355 EXPECT_EQ(kRangeTrigger, delegate.bytes_downloaded_);
1356 }
1357
1358 class BlockedTransferTestDelegate : public HttpFetcherDelegate {
1359 public:
ReceivedBytes(HttpFetcher * fetcher,const void * bytes,size_t length)1360 bool ReceivedBytes(HttpFetcher* fetcher,
1361 const void* bytes,
1362 size_t length) override {
1363 ADD_FAILURE();
1364 return true;
1365 }
TransferComplete(HttpFetcher * fetcher,bool successful)1366 void TransferComplete(HttpFetcher* fetcher, bool successful) override {
1367 EXPECT_FALSE(successful);
1368 MessageLoop::current()->BreakLoop();
1369 }
TransferTerminated(HttpFetcher * fetcher)1370 void TransferTerminated(HttpFetcher* fetcher) override { ADD_FAILURE(); }
1371 };
1372
BlockedTransferTestHelper(AnyHttpFetcherFactory * fetcher_test,bool is_official_build)1373 void BlockedTransferTestHelper(AnyHttpFetcherFactory* fetcher_test,
1374 bool is_official_build) {
1375 if (fetcher_test->IsMock() || fetcher_test->IsMulti())
1376 return;
1377
1378 unique_ptr<HttpServer> server(fetcher_test->CreateServer());
1379 ASSERT_TRUE(server->started_);
1380
1381 BlockedTransferTestDelegate delegate;
1382 unique_ptr<HttpFetcher> fetcher(fetcher_test->NewLargeFetcher());
1383 LOG(INFO) << "is_official_build: " << is_official_build;
1384 // NewLargeFetcher creates the HttpFetcher* with a FakeSystemState.
1385 fetcher_test->fake_hardware()->SetIsOfficialBuild(is_official_build);
1386 fetcher->set_delegate(&delegate);
1387
1388 MessageLoop::current()->PostTask(
1389 FROM_HERE,
1390 base::Bind(
1391 StartTransfer,
1392 fetcher.get(),
1393 LocalServerUrlForPath(server->GetPort(),
1394 fetcher_test->SmallUrl(server->GetPort()))));
1395 MessageLoop::current()->Run();
1396 }
1397
TYPED_TEST(HttpFetcherTest,BlockedTransferTest)1398 TYPED_TEST(HttpFetcherTest, BlockedTransferTest) {
1399 BlockedTransferTestHelper(&this->test_, false);
1400 }
1401
TYPED_TEST(HttpFetcherTest,BlockedTransferOfficialBuildTest)1402 TYPED_TEST(HttpFetcherTest, BlockedTransferOfficialBuildTest) {
1403 BlockedTransferTestHelper(&this->test_, true);
1404 }
1405
1406 } // namespace
1407
1408 } // namespace chromeos_update_engine
1409