blob: 5510dd7b1c614fdea1ea518f440ba9952abccd81 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
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//
David Zeuthen27a48bc2013-08-06 12:06:29 -070016
Alex Deymo8427b4a2014-11-05 14:00:32 -080017#include "update_engine/p2p_manager.h"
18
David Zeuthen27a48bc2013-08-06 12:06:29 -070019#include <dirent.h>
Alex Vakulenko44cab302014-07-23 13:12:15 -070020#include <fcntl.h>
21#include <sys/stat.h>
Alex Deymo6f20dd42015-08-18 16:42:46 -070022#include <sys/types.h>
23#include <sys/xattr.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070024#include <unistd.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070025
Ben Chan02f7c1d2014-10-18 15:18:02 -070026#include <memory>
Alex Deymob3391552015-07-10 10:48:06 -070027#include <string>
28#include <vector>
Ben Chan02f7c1d2014-10-18 15:18:02 -070029
Alex Deymo8427b4a2014-11-05 14:00:32 -080030#include <base/bind.h>
31#include <base/callback.h>
Alex Deymo454b7982015-07-10 10:49:29 -070032#include <base/files/file_util.h>
Qijiang Fanb0b6cc22020-10-15 21:54:11 +090033#if BASE_VER < 780000 // Android
Alex Deymo0b3db6b2015-08-10 15:19:37 -070034#include <base/message_loop/message_loop.h>
Qijiang Fanb0b6cc22020-10-15 21:54:11 +090035#endif // BASE_VER < 780000
Alex Vakulenko75039d72014-03-25 12:36:28 -070036#include <base/strings/stringprintf.h>
Qijiang Fanb0b6cc22020-10-15 21:54:11 +090037#if BASE_VER >= 780000 // CrOS
38#include <base/task/single_thread_task_executor.h>
39#endif // BASE_VER >= 780000
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070040#include <brillo/asynchronous_signal_handler.h>
41#include <brillo/message_loops/base_message_loop.h>
42#include <brillo/message_loops/message_loop.h>
43#include <brillo/message_loops/message_loop_utils.h>
Alex Deymo8427b4a2014-11-05 14:00:32 -080044#include <gmock/gmock.h>
45#include <gtest/gtest.h>
David Zeuthen92d9c8b2013-09-11 10:58:11 -070046#include <policy/libpolicy.h>
47#include <policy/mock_device_policy.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070048
Alex Deymo39910dc2015-11-09 17:04:30 -080049#include "update_engine/common/fake_clock.h"
50#include "update_engine/common/prefs.h"
Sen Jiangab6bda92019-01-09 16:33:51 -080051#include "update_engine/common/subprocess.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080052#include "update_engine/common/test_utils.h"
53#include "update_engine/common/utils.h"
David Zeuthen27a48bc2013-08-06 12:06:29 -070054#include "update_engine/fake_p2p_manager_configuration.h"
Gilad Arnold4a0321b2014-10-28 15:57:30 -070055#include "update_engine/update_manager/fake_update_manager.h"
56#include "update_engine/update_manager/mock_policy.h"
David Zeuthen27a48bc2013-08-06 12:06:29 -070057
Alex Deymof329b932014-10-30 01:37:48 -070058using base::TimeDelta;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070059using brillo::MessageLoop;
David Zeuthen27a48bc2013-08-06 12:06:29 -070060using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070061using std::unique_ptr;
Alex Deymo454b7982015-07-10 10:49:29 -070062using std::vector;
Amin Hassani7cc8bb02019-01-14 16:29:47 -080063using testing::_;
Gilad Arnold4a0321b2014-10-28 15:57:30 -070064using testing::DoAll;
65using testing::Return;
66using testing::SetArgPointee;
David Zeuthen27a48bc2013-08-06 12:06:29 -070067
68namespace chromeos_update_engine {
69
70// Test fixture that sets up a testing configuration (with e.g. a
71// temporary p2p dir) for P2PManager and cleans up when the test is
72// done.
73class P2PManagerTest : public testing::Test {
Alex Vakulenkod2779df2014-06-16 13:19:00 -070074 protected:
Gilad Arnold4a0321b2014-10-28 15:57:30 -070075 P2PManagerTest() : fake_um_(&fake_clock_) {}
Alex Deymo610277e2014-11-11 21:18:11 -080076 ~P2PManagerTest() override {}
David Zeuthen27a48bc2013-08-06 12:06:29 -070077
78 // Derived from testing::Test.
Alex Deymo610277e2014-11-11 21:18:11 -080079 void SetUp() override {
Alex Deymo509dd532015-06-10 14:11:05 -070080 loop_.SetAsCurrent();
Alex Deymob7ca0962014-10-01 17:58:07 -070081 async_signal_handler_.Init();
82 subprocess_.Init(&async_signal_handler_);
David Zeuthen27a48bc2013-08-06 12:06:29 -070083 test_conf_ = new FakeP2PManagerConfiguration();
Gilad Arnold4a0321b2014-10-28 15:57:30 -070084
85 // Allocate and install a mock policy implementation in the fake Update
86 // Manager. Note that the FakeUpdateManager takes ownership of the policy
87 // object.
88 mock_policy_ = new chromeos_update_manager::MockPolicy(&fake_clock_);
89 fake_um_.set_policy(mock_policy_);
90
91 // Construct the P2P manager under test.
Amin Hassani7cc8bb02019-01-14 16:29:47 -080092 manager_.reset(P2PManager::Construct(test_conf_,
93 &fake_clock_,
94 &fake_um_,
95 "cros_au",
96 3,
Alex Deymo509dd532015-06-10 14:11:05 -070097 TimeDelta::FromDays(5)));
David Zeuthen27a48bc2013-08-06 12:06:29 -070098 }
Alex Deymo509dd532015-06-10 14:11:05 -070099
Qijiang Fanb0b6cc22020-10-15 21:54:11 +0900100#if BASE_VER < 780000 // Android
Alex Deymo0b3db6b2015-08-10 15:19:37 -0700101 base::MessageLoopForIO base_loop_;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700102 brillo::BaseMessageLoop loop_{&base_loop_};
Qijiang Fanb0b6cc22020-10-15 21:54:11 +0900103#else // CrOS
104 base::SingleThreadTaskExecutor base_loop_{base::MessagePumpType::IO};
105 brillo::BaseMessageLoop loop_{base_loop_.task_runner()};
106#endif // BASE_VER < 780000
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700107 brillo::AsynchronousSignalHandler async_signal_handler_;
Alex Deymo461b2592015-07-24 20:10:52 -0700108 Subprocess subprocess_;
Alex Deymo60ca1a72015-06-18 18:19:15 -0700109
David Zeuthen27a48bc2013-08-06 12:06:29 -0700110 // The P2PManager::Configuration instance used for testing.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800111 FakeP2PManagerConfiguration* test_conf_;
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700112
113 FakeClock fake_clock_;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800114 chromeos_update_manager::MockPolicy* mock_policy_ = nullptr;
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700115 chromeos_update_manager::FakeUpdateManager fake_um_;
116
117 unique_ptr<P2PManager> manager_;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700118};
119
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700120// Check that IsP2PEnabled() polls the policy correctly, with the value not
121// changing between calls.
122TEST_F(P2PManagerTest, P2PEnabledInitAndNotChanged) {
123 EXPECT_CALL(*mock_policy_, P2PEnabled(_, _, _, _));
124 EXPECT_CALL(*mock_policy_, P2PEnabledChanged(_, _, _, _, false));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700125
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700126 EXPECT_FALSE(manager_->IsP2PEnabled());
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700127 brillo::MessageLoopRunMaxIterations(MessageLoop::current(), 100);
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700128 EXPECT_FALSE(manager_->IsP2PEnabled());
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700129}
130
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700131// Check that IsP2PEnabled() polls the policy correctly, with the value changing
132// between calls.
133TEST_F(P2PManagerTest, P2PEnabledInitAndChanged) {
134 EXPECT_CALL(*mock_policy_, P2PEnabled(_, _, _, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800135 .WillOnce(DoAll(SetArgPointee<3>(true),
136 Return(chromeos_update_manager::EvalStatus::kSucceeded)));
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700137 EXPECT_CALL(*mock_policy_, P2PEnabledChanged(_, _, _, _, true));
138 EXPECT_CALL(*mock_policy_, P2PEnabledChanged(_, _, _, _, false));
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700139
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700140 EXPECT_TRUE(manager_->IsP2PEnabled());
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700141 brillo::MessageLoopRunMaxIterations(MessageLoop::current(), 100);
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700142 EXPECT_FALSE(manager_->IsP2PEnabled());
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400143}
144
David Zeuthen27a48bc2013-08-06 12:06:29 -0700145// Check that we keep the $N newest files with the .$EXT.p2p extension.
David Zeuthen41f2cf52014-11-05 12:29:45 -0500146TEST_F(P2PManagerTest, HousekeepingCountLimit) {
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700147 // Specifically pass 0 for |max_file_age| to allow files of any age. Note that
148 // we need to reallocate the test_conf_ member, whose currently aliased object
149 // will be freed.
150 test_conf_ = new FakeP2PManagerConfiguration();
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800151 manager_.reset(P2PManager::Construct(test_conf_,
152 &fake_clock_,
153 &fake_um_,
154 "cros_au",
155 3,
156 TimeDelta() /* max_file_age */));
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700157 EXPECT_EQ(manager_->CountSharedFiles(), 0);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700158
Alex Deymo454b7982015-07-10 10:49:29 -0700159 base::Time start_time = base::Time::FromDoubleT(1246996800.);
Alex Deymo0f513512013-09-13 14:11:26 -0700160 // Generate files with different timestamps matching our pattern and generate
161 // other files not matching the pattern.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700162 for (int n = 0; n < 5; n++) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800163 base::FilePath path = test_conf_->GetP2PDir().Append(
164 base::StringPrintf("file_%d.cros_au.p2p", n));
Alex Deymo454b7982015-07-10 10:49:29 -0700165 base::Time file_time = start_time + TimeDelta::FromMinutes(n);
166 EXPECT_EQ(0, base::WriteFile(path, nullptr, 0));
167 EXPECT_TRUE(base::TouchFile(path, file_time, file_time));
David Zeuthen45e2ae22013-09-03 11:46:11 -0700168
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800169 path = test_conf_->GetP2PDir().Append(
170 base::StringPrintf("file_%d.OTHER.p2p", n));
Alex Deymo454b7982015-07-10 10:49:29 -0700171 EXPECT_EQ(0, base::WriteFile(path, nullptr, 0));
172 EXPECT_TRUE(base::TouchFile(path, file_time, file_time));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700173 }
174 // CountSharedFiles() only counts 'cros_au' files.
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700175 EXPECT_EQ(manager_->CountSharedFiles(), 5);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700176
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700177 EXPECT_TRUE(manager_->PerformHousekeeping());
David Zeuthen27a48bc2013-08-06 12:06:29 -0700178
179 // At this point - after HouseKeeping - we should only have
180 // eight files left.
181 for (int n = 0; n < 5; n++) {
182 string file_name;
183 bool expect;
184
185 expect = (n >= 2);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700186 file_name = base::StringPrintf(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800187 "%s/file_%d.cros_au.p2p", test_conf_->GetP2PDir().value().c_str(), n);
Alex Deymo454b7982015-07-10 10:49:29 -0700188 EXPECT_EQ(expect, utils::FileExists(file_name.c_str()));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700189
Alex Vakulenko75039d72014-03-25 12:36:28 -0700190 file_name = base::StringPrintf(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800191 "%s/file_%d.OTHER.p2p", test_conf_->GetP2PDir().value().c_str(), n);
Alex Deymo454b7982015-07-10 10:49:29 -0700192 EXPECT_TRUE(utils::FileExists(file_name.c_str()));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700193 }
194 // CountSharedFiles() only counts 'cros_au' files.
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700195 EXPECT_EQ(manager_->CountSharedFiles(), 3);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700196}
197
David Zeuthen41f2cf52014-11-05 12:29:45 -0500198// Check that we keep files with the .$EXT.p2p extension not older
Sen Jiang771f6482018-04-04 17:59:10 -0700199// than some specific age (5 days, in this test).
David Zeuthen41f2cf52014-11-05 12:29:45 -0500200TEST_F(P2PManagerTest, HousekeepingAgeLimit) {
201 // We set the cutoff time to be 1 billion seconds (01:46:40 UTC on 9
202 // September 2001 - arbitrary number, but constant to avoid test
203 // flakiness) since the epoch and then we put two files before that
204 // date and three files after.
Alex Deymo454b7982015-07-10 10:49:29 -0700205 base::Time cutoff_time = base::Time::FromTimeT(1000000000);
Alex Deymo10875d92014-11-10 21:52:57 -0800206 TimeDelta age_limit = TimeDelta::FromDays(5);
David Zeuthen41f2cf52014-11-05 12:29:45 -0500207
208 // Set the clock just so files with a timestamp before |cutoff_time|
209 // will be deleted at housekeeping.
Alex Deymo454b7982015-07-10 10:49:29 -0700210 fake_clock_.SetWallclockTime(cutoff_time + age_limit);
David Zeuthen41f2cf52014-11-05 12:29:45 -0500211
Alex Deymo454b7982015-07-10 10:49:29 -0700212 // Specifically pass 0 for |num_files_to_keep| to allow any number of files.
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700213 // Note that we need to reallocate the test_conf_ member, whose currently
214 // aliased object will be freed.
215 test_conf_ = new FakeP2PManagerConfiguration();
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800216 manager_.reset(P2PManager::Construct(test_conf_,
217 &fake_clock_,
218 &fake_um_,
219 "cros_au",
220 0 /* num_files_to_keep */,
221 age_limit));
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700222 EXPECT_EQ(manager_->CountSharedFiles(), 0);
David Zeuthen41f2cf52014-11-05 12:29:45 -0500223
224 // Generate files with different timestamps matching our pattern and generate
225 // other files not matching the pattern.
226 for (int n = 0; n < 5; n++) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800227 base::FilePath path = test_conf_->GetP2PDir().Append(
228 base::StringPrintf("file_%d.cros_au.p2p", n));
David Zeuthen41f2cf52014-11-05 12:29:45 -0500229
230 // With five files and aiming for two of them to be before
231 // |cutoff_time|, we distribute it like this:
232 //
233 // -------- 0 -------- 1 -------- 2 -------- 3 -------- 4 --------
234 // |
235 // cutoff_time
236 //
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800237 base::Time file_date = cutoff_time + (n - 2) * TimeDelta::FromDays(1) +
238 TimeDelta::FromHours(12);
David Zeuthen41f2cf52014-11-05 12:29:45 -0500239
Alex Deymo454b7982015-07-10 10:49:29 -0700240 EXPECT_EQ(0, base::WriteFile(path, nullptr, 0));
241 EXPECT_TRUE(base::TouchFile(path, file_date, file_date));
David Zeuthen41f2cf52014-11-05 12:29:45 -0500242
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800243 path = test_conf_->GetP2PDir().Append(
244 base::StringPrintf("file_%d.OTHER.p2p", n));
Alex Deymo454b7982015-07-10 10:49:29 -0700245 EXPECT_EQ(0, base::WriteFile(path, nullptr, 0));
246 EXPECT_TRUE(base::TouchFile(path, file_date, file_date));
David Zeuthen41f2cf52014-11-05 12:29:45 -0500247 }
248 // CountSharedFiles() only counts 'cros_au' files.
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700249 EXPECT_EQ(manager_->CountSharedFiles(), 5);
David Zeuthen41f2cf52014-11-05 12:29:45 -0500250
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700251 EXPECT_TRUE(manager_->PerformHousekeeping());
David Zeuthen41f2cf52014-11-05 12:29:45 -0500252
253 // At this point - after HouseKeeping - we should only have
254 // eight files left.
255 for (int n = 0; n < 5; n++) {
256 string file_name;
257 bool expect;
258
259 expect = (n >= 2);
260 file_name = base::StringPrintf(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800261 "%s/file_%d.cros_au.p2p", test_conf_->GetP2PDir().value().c_str(), n);
Alex Deymo454b7982015-07-10 10:49:29 -0700262 EXPECT_EQ(expect, utils::FileExists(file_name.c_str()));
David Zeuthen41f2cf52014-11-05 12:29:45 -0500263
264 file_name = base::StringPrintf(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800265 "%s/file_%d.OTHER.p2p", test_conf_->GetP2PDir().value().c_str(), n);
Alex Deymo454b7982015-07-10 10:49:29 -0700266 EXPECT_TRUE(utils::FileExists(file_name.c_str()));
David Zeuthen41f2cf52014-11-05 12:29:45 -0500267 }
268 // CountSharedFiles() only counts 'cros_au' files.
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700269 EXPECT_EQ(manager_->CountSharedFiles(), 3);
David Zeuthen41f2cf52014-11-05 12:29:45 -0500270}
271
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800272static bool CheckP2PFile(const string& p2p_dir,
273 const string& file_name,
274 ssize_t expected_size,
275 ssize_t expected_size_xattr) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700276 string path = p2p_dir + "/" + file_name;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800277 char ea_value[64] = {0};
David Zeuthen27a48bc2013-08-06 12:06:29 -0700278 ssize_t ea_size;
279
Gabe Blacka77939e2014-09-09 23:35:08 -0700280 off_t p2p_size = utils::FileSize(path);
281 if (p2p_size < 0) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700282 LOG(ERROR) << "File " << path << " does not exist";
283 return false;
284 }
285
286 if (expected_size != 0) {
Gabe Blacka77939e2014-09-09 23:35:08 -0700287 if (p2p_size != expected_size) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800288 LOG(ERROR) << "Expected size " << expected_size << " but size was "
289 << p2p_size;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700290 return false;
291 }
292 }
293
294 if (expected_size_xattr == 0) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800295 ea_size = getxattr(
296 path.c_str(), "user.cros-p2p-filesize", &ea_value, sizeof ea_value - 1);
Alex Deymo6f20dd42015-08-18 16:42:46 -0700297 if (ea_size == -1 && errno == ENODATA) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700298 // This is valid behavior as we support files without the xattr set.
299 } else {
Alex Deymo6f20dd42015-08-18 16:42:46 -0700300 PLOG(ERROR) << "getxattr() didn't fail with ENODATA as expected, "
David Zeuthen27a48bc2013-08-06 12:06:29 -0700301 << "ea_size=" << ea_size << ", errno=" << errno;
302 return false;
303 }
304 } else {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800305 ea_size = getxattr(
306 path.c_str(), "user.cros-p2p-filesize", &ea_value, sizeof ea_value - 1);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700307 if (ea_size < 0) {
308 LOG(ERROR) << "Error getting xattr attribute";
309 return false;
310 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700311 char* endp = nullptr;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700312 long long int val = strtoll(ea_value, &endp, 0); // NOLINT(runtime/int)
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700313 if (endp == nullptr || *endp != '\0') {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800314 LOG(ERROR) << "Error parsing xattr '" << ea_value << "' as an integer";
David Zeuthen27a48bc2013-08-06 12:06:29 -0700315 return false;
316 }
317 if (val != expected_size_xattr) {
318 LOG(ERROR) << "Expected xattr size " << expected_size_xattr
319 << " but size was " << val;
320 return false;
321 }
322 }
323
324 return true;
325}
326
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800327static bool CreateP2PFile(string p2p_dir,
328 string file_name,
329 size_t size,
330 size_t size_xattr) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700331 string path = p2p_dir + "/" + file_name;
332
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800333 int fd = open(path.c_str(), O_CREAT | O_RDWR, 0644);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700334 if (fd == -1) {
335 PLOG(ERROR) << "Error creating file with path " << path;
336 return false;
337 }
338 if (ftruncate(fd, size) != 0) {
339 PLOG(ERROR) << "Error truncating " << path << " to size " << size;
340 close(fd);
341 return false;
342 }
343
344 if (size_xattr != 0) {
Alex Deymoc00c98a2015-03-17 17:38:00 -0700345 string decimal_size = std::to_string(size_xattr);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800346 if (fsetxattr(fd,
347 "user.cros-p2p-filesize",
348 decimal_size.c_str(),
349 decimal_size.size(),
350 0) != 0) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700351 PLOG(ERROR) << "Error setting xattr on " << path;
352 close(fd);
353 return false;
354 }
355 }
356
357 close(fd);
358 return true;
359}
360
361// Check that sharing a *new* file works.
362TEST_F(P2PManagerTest, ShareFile) {
Alex Deymo3c3807c2015-01-30 09:32:41 -0800363 const int kP2PTestFileSize = 1000 * 1000; // 1 MB
David Zeuthen910ec5b2013-09-26 12:10:58 -0700364
Alex Deymo3c3807c2015-01-30 09:32:41 -0800365 EXPECT_TRUE(manager_->FileShare("foo", kP2PTestFileSize));
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700366 EXPECT_EQ(manager_->FileGetPath("foo"),
David Zeuthen27a48bc2013-08-06 12:06:29 -0700367 test_conf_->GetP2PDir().Append("foo.cros_au.p2p.tmp"));
368 EXPECT_TRUE(CheckP2PFile(test_conf_->GetP2PDir().value(),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800369 "foo.cros_au.p2p.tmp",
370 0,
371 kP2PTestFileSize));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700372
373 // Sharing it again - with the same expected size - should return true
Alex Deymo3c3807c2015-01-30 09:32:41 -0800374 EXPECT_TRUE(manager_->FileShare("foo", kP2PTestFileSize));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700375
376 // ... but if we use the wrong size, it should fail
Alex Deymo3c3807c2015-01-30 09:32:41 -0800377 EXPECT_FALSE(manager_->FileShare("foo", kP2PTestFileSize + 1));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700378}
379
380// Check that making a shared file visible, does what is expected.
381TEST_F(P2PManagerTest, MakeFileVisible) {
Alex Deymo3c3807c2015-01-30 09:32:41 -0800382 const int kP2PTestFileSize = 1000 * 1000; // 1 MB
David Zeuthen910ec5b2013-09-26 12:10:58 -0700383
David Zeuthen27a48bc2013-08-06 12:06:29 -0700384 // First, check that it's not visible.
Alex Deymo3c3807c2015-01-30 09:32:41 -0800385 manager_->FileShare("foo", kP2PTestFileSize);
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700386 EXPECT_EQ(manager_->FileGetPath("foo"),
David Zeuthen27a48bc2013-08-06 12:06:29 -0700387 test_conf_->GetP2PDir().Append("foo.cros_au.p2p.tmp"));
388 EXPECT_TRUE(CheckP2PFile(test_conf_->GetP2PDir().value(),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800389 "foo.cros_au.p2p.tmp",
390 0,
391 kP2PTestFileSize));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700392 // Make the file visible and check that it changed its name. Do it
393 // twice to check that FileMakeVisible() is idempotent.
394 for (int n = 0; n < 2; n++) {
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700395 manager_->FileMakeVisible("foo");
396 EXPECT_EQ(manager_->FileGetPath("foo"),
David Zeuthen27a48bc2013-08-06 12:06:29 -0700397 test_conf_->GetP2PDir().Append("foo.cros_au.p2p"));
398 EXPECT_TRUE(CheckP2PFile(test_conf_->GetP2PDir().value(),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800399 "foo.cros_au.p2p",
400 0,
401 kP2PTestFileSize));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700402 }
403}
404
405// Check that we return the right values for existing files in P2P_DIR.
406TEST_F(P2PManagerTest, ExistingFiles) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700407 bool visible;
408
409 // Check that errors are returned if the file does not exist
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700410 EXPECT_EQ(manager_->FileGetPath("foo"), base::FilePath());
411 EXPECT_EQ(manager_->FileGetSize("foo"), -1);
412 EXPECT_EQ(manager_->FileGetExpectedSize("foo"), -1);
413 EXPECT_FALSE(manager_->FileGetVisible("foo", nullptr));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700414 // ... then create the file ...
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800415 EXPECT_TRUE(CreateP2PFile(
416 test_conf_->GetP2PDir().value(), "foo.cros_au.p2p", 42, 43));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700417 // ... and then check that the expected values are returned
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700418 EXPECT_EQ(manager_->FileGetPath("foo"),
David Zeuthen27a48bc2013-08-06 12:06:29 -0700419 test_conf_->GetP2PDir().Append("foo.cros_au.p2p"));
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700420 EXPECT_EQ(manager_->FileGetSize("foo"), 42);
421 EXPECT_EQ(manager_->FileGetExpectedSize("foo"), 43);
422 EXPECT_TRUE(manager_->FileGetVisible("foo", &visible));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700423 EXPECT_TRUE(visible);
424
425 // One more time, this time with a .tmp variant. First ensure it errors out..
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700426 EXPECT_EQ(manager_->FileGetPath("bar"), base::FilePath());
427 EXPECT_EQ(manager_->FileGetSize("bar"), -1);
428 EXPECT_EQ(manager_->FileGetExpectedSize("bar"), -1);
429 EXPECT_FALSE(manager_->FileGetVisible("bar", nullptr));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700430 // ... then create the file ...
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800431 EXPECT_TRUE(CreateP2PFile(
432 test_conf_->GetP2PDir().value(), "bar.cros_au.p2p.tmp", 44, 45));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700433 // ... and then check that the expected values are returned
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700434 EXPECT_EQ(manager_->FileGetPath("bar"),
David Zeuthen27a48bc2013-08-06 12:06:29 -0700435 test_conf_->GetP2PDir().Append("bar.cros_au.p2p.tmp"));
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700436 EXPECT_EQ(manager_->FileGetSize("bar"), 44);
437 EXPECT_EQ(manager_->FileGetExpectedSize("bar"), 45);
438 EXPECT_TRUE(manager_->FileGetVisible("bar", &visible));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700439 EXPECT_FALSE(visible);
440}
441
David Zeuthen27a48bc2013-08-06 12:06:29 -0700442// This is a little bit ugly but short of mocking a 'p2p' service this
443// will have to do. E.g. we essentially simulate the various
444// behaviours of initctl(8) that we rely on.
445TEST_F(P2PManagerTest, StartP2P) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700446 // Check that we can start the service
Alex Deymob3391552015-07-10 10:48:06 -0700447 test_conf_->SetInitctlStartCommand({"true"});
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700448 EXPECT_TRUE(manager_->EnsureP2PRunning());
Alex Deymob3391552015-07-10 10:48:06 -0700449 test_conf_->SetInitctlStartCommand({"false"});
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700450 EXPECT_FALSE(manager_->EnsureP2PRunning());
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800451 test_conf_->SetInitctlStartCommand(
452 {"sh", "-c", "echo \"initctl: Job is already running: p2p\" >&2; false"});
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700453 EXPECT_TRUE(manager_->EnsureP2PRunning());
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800454 test_conf_->SetInitctlStartCommand(
455 {"sh", "-c", "echo something else >&2; false"});
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700456 EXPECT_FALSE(manager_->EnsureP2PRunning());
David Zeuthen27a48bc2013-08-06 12:06:29 -0700457}
458
459// Same comment as for StartP2P
460TEST_F(P2PManagerTest, StopP2P) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700461 // Check that we can start the service
Alex Deymob3391552015-07-10 10:48:06 -0700462 test_conf_->SetInitctlStopCommand({"true"});
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700463 EXPECT_TRUE(manager_->EnsureP2PNotRunning());
Alex Deymob3391552015-07-10 10:48:06 -0700464 test_conf_->SetInitctlStopCommand({"false"});
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700465 EXPECT_FALSE(manager_->EnsureP2PNotRunning());
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800466 test_conf_->SetInitctlStopCommand(
467 {"sh", "-c", "echo \"initctl: Unknown instance \" >&2; false"});
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700468 EXPECT_TRUE(manager_->EnsureP2PNotRunning());
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800469 test_conf_->SetInitctlStopCommand(
470 {"sh", "-c", "echo something else >&2; false"});
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700471 EXPECT_FALSE(manager_->EnsureP2PNotRunning());
David Zeuthen27a48bc2013-08-06 12:06:29 -0700472}
473
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800474static void ExpectUrl(const string& expected_url, const string& url) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700475 EXPECT_EQ(url, expected_url);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700476 MessageLoop::current()->BreakLoop();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700477}
478
479// Like StartP2P, we're mocking the different results that p2p-client
480// can return. It's not pretty but it works.
481TEST_F(P2PManagerTest, LookupURL) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700482 // Emulate p2p-client returning valid URL with "fooX", 42 and "cros_au"
483 // being propagated in the right places.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800484 test_conf_->SetP2PClientCommand(
485 {"echo", "http://1.2.3.4/{file_id}_{minsize}"});
486 manager_->LookupUrlForFile(
487 "fooX",
488 42,
489 TimeDelta(),
490 base::Bind(ExpectUrl, "http://1.2.3.4/fooX.cros_au_42"));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700491 loop_.Run();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700492
493 // Emulate p2p-client returning invalid URL.
Alex Deymob3391552015-07-10 10:48:06 -0700494 test_conf_->SetP2PClientCommand({"echo", "not_a_valid_url"});
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800495 manager_->LookupUrlForFile(
496 "foobar", 42, TimeDelta(), base::Bind(ExpectUrl, ""));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700497 loop_.Run();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700498
499 // Emulate p2p-client conveying failure.
Alex Deymob3391552015-07-10 10:48:06 -0700500 test_conf_->SetP2PClientCommand({"false"});
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800501 manager_->LookupUrlForFile(
502 "foobar", 42, TimeDelta(), base::Bind(ExpectUrl, ""));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700503 loop_.Run();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700504
505 // Emulate p2p-client not existing.
Alex Deymob3391552015-07-10 10:48:06 -0700506 test_conf_->SetP2PClientCommand({"/path/to/non/existent/helper/program"});
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800507 manager_->LookupUrlForFile(
508 "foobar", 42, TimeDelta(), base::Bind(ExpectUrl, ""));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700509 loop_.Run();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700510
511 // Emulate p2p-client crashing.
Alex Deymob3391552015-07-10 10:48:06 -0700512 test_conf_->SetP2PClientCommand({"sh", "-c", "kill -SEGV $$"});
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800513 manager_->LookupUrlForFile(
514 "foobar", 42, TimeDelta(), base::Bind(ExpectUrl, ""));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700515 loop_.Run();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700516
517 // Emulate p2p-client exceeding its timeout.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800518 test_conf_->SetP2PClientCommand(
519 {"sh",
520 "-c",
521 // The 'sleep' launched below could be left behind as an orphaned
522 // process when the 'sh' process is terminated by SIGTERM. As a
523 // remedy, trap SIGTERM and kill the 'sleep' process, which requires
524 // launching 'sleep' in background and then waiting for it.
525 "cleanup() { kill \"${sleep_pid}\"; exit 0; }; "
526 "trap cleanup TERM; "
527 "sleep 5 & "
528 "sleep_pid=$!; "
529 "echo http://1.2.3.4/; "
530 "wait"});
531 manager_->LookupUrlForFile("foobar",
532 42,
533 TimeDelta::FromMilliseconds(500),
Alex Deymo60ca1a72015-06-18 18:19:15 -0700534 base::Bind(ExpectUrl, ""));
535 loop_.Run();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700536}
537
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700538} // namespace chromeos_update_engine