blob: 00ff8cecf15d32c1ac25e8e6ed064c4e2247cb06 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2013 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 Vakulenko072359c2014-07-18 11:41:07 -070017// This provides access to timestamps with nanosecond resolution in
David Zeuthen27a48bc2013-08-06 12:06:29 -070018// struct stat, See NOTES in stat(2) for details.
Yunlian Jianga435daa2016-06-02 15:43:35 -070019#ifndef _DEFAULT_SOURCE
20#define _DEFAULT_SOURCE
21#endif
David Zeuthen27a48bc2013-08-06 12:06:29 -070022#ifndef _BSD_SOURCE
23#define _BSD_SOURCE
24#endif
25
26#include "update_engine/p2p_manager.h"
27
David Zeuthen27a48bc2013-08-06 12:06:29 -070028#include <errno.h>
29#include <fcntl.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070030#include <linux/falloc.h>
31#include <signal.h>
32#include <string.h>
33#include <sys/stat.h>
34#include <sys/statvfs.h>
35#include <sys/types.h>
Alex Deymo6f20dd42015-08-18 16:42:46 -070036#include <sys/xattr.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070037#include <unistd.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070038
Alex Vakulenkod2779df2014-06-16 13:19:00 -070039#include <algorithm>
David Zeuthen27a48bc2013-08-06 12:06:29 -070040#include <map>
Ben Chan02f7c1d2014-10-18 15:18:02 -070041#include <memory>
David Zeuthen27a48bc2013-08-06 12:06:29 -070042#include <utility>
43#include <vector>
44
Gilad Arnold4a0321b2014-10-28 15:57:30 -070045#include <base/bind.h>
Alex Deymo454b7982015-07-10 10:49:29 -070046#include <base/files/file_enumerator.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070047#include <base/files/file_path.h>
Alex Deymoc00c98a2015-03-17 17:38:00 -070048#include <base/format_macros.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070049#include <base/logging.h>
Alex Deymo454b7982015-07-10 10:49:29 -070050#include <base/strings/string_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070051#include <base/strings/stringprintf.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070052
Alex Deymo39910dc2015-11-09 17:04:30 -080053#include "update_engine/common/subprocess.h"
54#include "update_engine/common/utils.h"
Gilad Arnold4a0321b2014-10-28 15:57:30 -070055#include "update_engine/update_manager/policy.h"
56#include "update_engine/update_manager/update_manager.h"
David Zeuthen27a48bc2013-08-06 12:06:29 -070057
Gilad Arnold4a0321b2014-10-28 15:57:30 -070058using base::Bind;
59using base::Callback;
David Zeuthen27a48bc2013-08-06 12:06:29 -070060using base::FilePath;
61using base::StringPrintf;
62using base::Time;
63using base::TimeDelta;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070064using brillo::MessageLoop;
Gilad Arnold4a0321b2014-10-28 15:57:30 -070065using chromeos_update_manager::EvalStatus;
66using chromeos_update_manager::Policy;
67using chromeos_update_manager::UpdateManager;
David Zeuthen27a48bc2013-08-06 12:06:29 -070068using std::pair;
69using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070070using std::unique_ptr;
David Zeuthen27a48bc2013-08-06 12:06:29 -070071using std::vector;
72
73namespace chromeos_update_engine {
74
75namespace {
76
77// The default p2p directory.
78const char kDefaultP2PDir[] = "/var/cache/p2p";
79
80// The p2p xattr used for conveying the final size of a file - see the
81// p2p ddoc for details.
82const char kCrosP2PFileSizeXAttrName[] = "user.cros-p2p-filesize";
83
Alex Vakulenkod2779df2014-06-16 13:19:00 -070084} // namespace
David Zeuthen27a48bc2013-08-06 12:06:29 -070085
86// The default P2PManager::Configuration implementation.
87class ConfigurationImpl : public P2PManager::Configuration {
Alex Vakulenkod2779df2014-06-16 13:19:00 -070088 public:
David Zeuthen27a48bc2013-08-06 12:06:29 -070089 ConfigurationImpl() {}
90
Amin Hassani7cc8bb02019-01-14 16:29:47 -080091 FilePath GetP2PDir() override { return FilePath(kDefaultP2PDir); }
David Zeuthen27a48bc2013-08-06 12:06:29 -070092
Alex Deymo610277e2014-11-11 21:18:11 -080093 vector<string> GetInitctlArgs(bool is_start) override {
David Zeuthen27a48bc2013-08-06 12:06:29 -070094 vector<string> args;
95 args.push_back("initctl");
96 args.push_back(is_start ? "start" : "stop");
97 args.push_back("p2p");
98 return args;
99 }
100
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800101 vector<string> GetP2PClientArgs(const string& file_id,
Alex Deymo610277e2014-11-11 21:18:11 -0800102 size_t minimum_size) override {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700103 vector<string> args;
104 args.push_back("p2p-client");
105 args.push_back(string("--get-url=") + file_id);
Alex Deymoc00c98a2015-03-17 17:38:00 -0700106 args.push_back(StringPrintf("--minimum-size=%" PRIuS, minimum_size));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700107 return args;
108 }
109
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700110 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700111 DISALLOW_COPY_AND_ASSIGN(ConfigurationImpl);
112};
113
114// The default P2PManager implementation.
115class P2PManagerImpl : public P2PManager {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700116 public:
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800117 P2PManagerImpl(Configuration* configuration,
118 ClockInterface* clock,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700119 UpdateManager* update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700120 const string& file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500121 const int num_files_to_keep,
Alex Deymo29b81532015-07-09 11:51:49 -0700122 const TimeDelta& max_file_age);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700123
124 // P2PManager methods.
Alex Deymo610277e2014-11-11 21:18:11 -0800125 void SetDevicePolicy(const policy::DevicePolicy* device_policy) override;
126 bool IsP2PEnabled() override;
127 bool EnsureP2PRunning() override;
128 bool EnsureP2PNotRunning() override;
129 bool PerformHousekeeping() override;
130 void LookupUrlForFile(const string& file_id,
131 size_t minimum_size,
132 TimeDelta max_time_to_wait,
133 LookupCallback callback) override;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800134 bool FileShare(const string& file_id, size_t expected_size) override;
Alex Deymo610277e2014-11-11 21:18:11 -0800135 FilePath FileGetPath(const string& file_id) override;
136 ssize_t FileGetSize(const string& file_id) override;
137 ssize_t FileGetExpectedSize(const string& file_id) override;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800138 bool FileGetVisible(const string& file_id, bool* out_result) override;
Alex Deymo610277e2014-11-11 21:18:11 -0800139 bool FileMakeVisible(const string& file_id) override;
140 int CountSharedFiles() override;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700141
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700142 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700143 // Enumeration for specifying visibility.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800144 enum Visibility { kVisible, kNonVisible };
David Zeuthen27a48bc2013-08-06 12:06:29 -0700145
146 // Returns "." + |file_extension_| + ".p2p" if |visibility| is
147 // |kVisible|. Returns the same concatenated with ".tmp" otherwise.
148 string GetExt(Visibility visibility);
149
150 // Gets the on-disk path for |file_id| depending on if the file
151 // is visible or not.
Alex Deymof329b932014-10-30 01:37:48 -0700152 FilePath GetPath(const string& file_id, Visibility visibility);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700153
154 // Utility function used by EnsureP2PRunning() and EnsureP2PNotRunning().
155 bool EnsureP2P(bool should_be_running);
156
David Zeuthen41f2cf52014-11-05 12:29:45 -0500157 // Utility function to delete a file given by |path| and log the
158 // path as well as |reason|. Returns false on failure.
Alex Deymo29b81532015-07-09 11:51:49 -0700159 bool DeleteP2PFile(const FilePath& path, const string& reason);
David Zeuthen41f2cf52014-11-05 12:29:45 -0500160
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700161 // Schedules an async request for tracking changes in P2P enabled status.
162 void ScheduleEnabledStatusChange();
163
164 // An async callback used by the above.
165 void OnEnabledStatusChange(EvalStatus status, const bool& result);
166
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700167 // The device policy being used or null if no policy is being used.
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700168 const policy::DevicePolicy* device_policy_ = nullptr;
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700169
David Zeuthen27a48bc2013-08-06 12:06:29 -0700170 // Configuration object.
Ben Chan02f7c1d2014-10-18 15:18:02 -0700171 unique_ptr<Configuration> configuration_;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700172
David Zeuthen41f2cf52014-11-05 12:29:45 -0500173 // Object for telling the time.
174 ClockInterface* clock_;
175
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700176 // A pointer to the global Update Manager.
177 UpdateManager* update_manager_;
178
David Zeuthen27a48bc2013-08-06 12:06:29 -0700179 // A short string unique to the application (for example "cros_au")
180 // used to mark a file as being owned by a particular application.
181 const string file_extension_;
182
183 // If non-zero, this number denotes how many files in /var/cache/p2p
184 // owned by the application (cf. |file_extension_|) to keep after
185 // performing housekeeping.
186 const int num_files_to_keep_;
187
David Zeuthen41f2cf52014-11-05 12:29:45 -0500188 // If non-zero, files older than this will not be kept after
189 // performing housekeeping.
Alex Deymo29b81532015-07-09 11:51:49 -0700190 const TimeDelta max_file_age_;
David Zeuthen41f2cf52014-11-05 12:29:45 -0500191
David Zeuthen27a48bc2013-08-06 12:06:29 -0700192 // The string ".p2p".
193 static const char kP2PExtension[];
194
195 // The string ".tmp".
196 static const char kTmpExtension[];
197
Gilad Arnoldccd09572014-10-27 13:37:50 -0700198 // Whether P2P service may be running; initially, we assume it may be.
199 bool may_be_running_ = true;
200
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700201 // The current known enabled status of the P2P feature (initialized lazily),
202 // and whether an async status check has been scheduled.
203 bool is_enabled_;
204 bool waiting_for_enabled_status_change_ = false;
205
David Zeuthen27a48bc2013-08-06 12:06:29 -0700206 DISALLOW_COPY_AND_ASSIGN(P2PManagerImpl);
207};
208
209const char P2PManagerImpl::kP2PExtension[] = ".p2p";
210
211const char P2PManagerImpl::kTmpExtension[] = ".tmp";
212
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800213P2PManagerImpl::P2PManagerImpl(Configuration* configuration,
214 ClockInterface* clock,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700215 UpdateManager* update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700216 const string& file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500217 const int num_files_to_keep,
Alex Deymo29b81532015-07-09 11:51:49 -0700218 const TimeDelta& max_file_age)
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800219 : clock_(clock),
220 update_manager_(update_manager),
221 file_extension_(file_extension),
222 num_files_to_keep_(num_files_to_keep),
223 max_file_age_(max_file_age) {
224 configuration_.reset(configuration != nullptr ? configuration
225 : new ConfigurationImpl());
David Zeuthen27a48bc2013-08-06 12:06:29 -0700226}
227
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700228void P2PManagerImpl::SetDevicePolicy(
229 const policy::DevicePolicy* device_policy) {
230 device_policy_ = device_policy;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700231}
232
233bool P2PManagerImpl::IsP2PEnabled() {
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700234 if (!waiting_for_enabled_status_change_) {
235 // Get and store an initial value.
236 if (update_manager_->PolicyRequest(&Policy::P2PEnabled, &is_enabled_) ==
237 EvalStatus::kFailed) {
238 is_enabled_ = false;
239 LOG(ERROR) << "Querying P2P enabled status failed, disabling.";
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400240 }
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700241
242 // Track future changes (async).
243 ScheduleEnabledStatusChange();
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400244 }
245
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700246 return is_enabled_;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700247}
248
249bool P2PManagerImpl::EnsureP2P(bool should_be_running) {
Alex Deymo29b81532015-07-09 11:51:49 -0700250 int return_code = 0;
Amin Hassani3a4caa12019-11-06 11:12:28 -0800251 string stderr;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700252
Gilad Arnoldccd09572014-10-27 13:37:50 -0700253 may_be_running_ = true; // Unless successful, we must be conservative.
254
David Zeuthen27a48bc2013-08-06 12:06:29 -0700255 vector<string> args = configuration_->GetInitctlArgs(should_be_running);
Amin Hassani3a4caa12019-11-06 11:12:28 -0800256 if (!Subprocess::SynchronousExec(args, &return_code, nullptr, &stderr)) {
Alex Deymo29b81532015-07-09 11:51:49 -0700257 LOG(ERROR) << "Error spawning " << utils::StringVectorToString(args);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700258 return false;
259 }
260
Gilad Arnoldccd09572014-10-27 13:37:50 -0700261 // If initctl(8) does not exit normally (exit status other than zero), ensure
262 // that the error message is not benign by scanning stderr; this is a
263 // necessity because initctl does not offer actions such as "start if not
264 // running" or "stop if running".
David Zeuthen27a48bc2013-08-06 12:06:29 -0700265 // TODO(zeuthen,chromium:277051): Avoid doing this.
Alex Deymo29b81532015-07-09 11:51:49 -0700266 if (return_code != 0) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800267 const char* expected_error_message =
268 should_be_running ? "initctl: Job is already running: p2p\n"
269 : "initctl: Unknown instance \n";
Amin Hassani3a4caa12019-11-06 11:12:28 -0800270 if (stderr != expected_error_message)
Gilad Arnoldccd09572014-10-27 13:37:50 -0700271 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700272 }
273
Gilad Arnoldccd09572014-10-27 13:37:50 -0700274 may_be_running_ = should_be_running; // Successful after all.
275 return true;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700276}
277
278bool P2PManagerImpl::EnsureP2PRunning() {
279 return EnsureP2P(true);
280}
281
282bool P2PManagerImpl::EnsureP2PNotRunning() {
283 return EnsureP2P(false);
284}
285
286// Returns True if the timestamp in the first pair is greater than the
287// timestamp in the latter. If used with std::sort() this will yield a
288// sequence of elements where newer (high timestamps) elements precede
289// older ones (low timestamps).
290static bool MatchCompareFunc(const pair<FilePath, Time>& a,
291 const pair<FilePath, Time>& b) {
292 return a.second > b.second;
293}
294
295string P2PManagerImpl::GetExt(Visibility visibility) {
296 string ext = string(".") + file_extension_ + kP2PExtension;
297 switch (visibility) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800298 case kVisible:
299 break;
300 case kNonVisible:
301 ext += kTmpExtension;
302 break;
303 // Don't add a default case to let the compiler warn about newly
304 // added enum values.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700305 }
306 return ext;
307}
308
309FilePath P2PManagerImpl::GetPath(const string& file_id, Visibility visibility) {
310 return configuration_->GetP2PDir().Append(file_id + GetExt(visibility));
311}
312
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800313bool P2PManagerImpl::DeleteP2PFile(const FilePath& path, const string& reason) {
314 LOG(INFO) << "Deleting p2p file " << path.value() << " (reason: " << reason
315 << ")";
David Zeuthen41f2cf52014-11-05 12:29:45 -0500316 if (unlink(path.value().c_str()) != 0) {
317 PLOG(ERROR) << "Error deleting p2p file " << path.value();
318 return false;
319 }
320 return true;
321}
David Zeuthen27a48bc2013-08-06 12:06:29 -0700322
David Zeuthen41f2cf52014-11-05 12:29:45 -0500323bool P2PManagerImpl::PerformHousekeeping() {
324 // Open p2p dir.
Alex Deymof329b932014-10-30 01:37:48 -0700325 FilePath p2p_dir = configuration_->GetP2PDir();
Alex Deymo454b7982015-07-10 10:49:29 -0700326 const string ext_visible = GetExt(kVisible);
327 const string ext_non_visible = GetExt(kNonVisible);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700328
David Zeuthen41f2cf52014-11-05 12:29:45 -0500329 bool deletion_failed = false;
David Zeuthen41f2cf52014-11-05 12:29:45 -0500330 vector<pair<FilePath, Time>> matches;
Alex Deymo454b7982015-07-10 10:49:29 -0700331
332 base::FileEnumerator dir(p2p_dir, false, base::FileEnumerator::FILES);
333 // Go through all files and collect their mtime.
334 for (FilePath name = dir.Next(); !name.empty(); name = dir.Next()) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800335 if (!(base::EndsWith(
336 name.value(), ext_visible, base::CompareCase::SENSITIVE) ||
337 base::EndsWith(
338 name.value(), ext_non_visible, base::CompareCase::SENSITIVE))) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700339 continue;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800340 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700341
Alex Deymo454b7982015-07-10 10:49:29 -0700342 Time time = dir.GetInfo().GetLastModifiedTime();
David Zeuthen41f2cf52014-11-05 12:29:45 -0500343
344 // If instructed to keep only files younger than a given age
345 // (|max_file_age_| != 0), delete files satisfying this criteria
346 // right now. Otherwise add it to a list we'll consider for later.
Alex Deymo29b81532015-07-09 11:51:49 -0700347 if (clock_ != nullptr && max_file_age_ != TimeDelta() &&
David Zeuthen41f2cf52014-11-05 12:29:45 -0500348 clock_->GetWallclockTime() - time > max_file_age_) {
Alex Deymo454b7982015-07-10 10:49:29 -0700349 if (!DeleteP2PFile(name, "file too old"))
David Zeuthen41f2cf52014-11-05 12:29:45 -0500350 deletion_failed = true;
351 } else {
Alex Deymo454b7982015-07-10 10:49:29 -0700352 matches.push_back(std::make_pair(name, time));
David Zeuthen41f2cf52014-11-05 12:29:45 -0500353 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700354 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700355
David Zeuthen41f2cf52014-11-05 12:29:45 -0500356 // If instructed to only keep N files (|max_files_to_keep_ != 0),
357 // sort list of matches, newest (biggest time) to oldest (lowest
358 // time). Then delete starting at element |num_files_to_keep_|.
359 if (num_files_to_keep_ > 0) {
360 std::sort(matches.begin(), matches.end(), MatchCompareFunc);
361 vector<pair<FilePath, Time>>::const_iterator i;
362 for (i = matches.begin() + num_files_to_keep_; i < matches.end(); ++i) {
363 if (!DeleteP2PFile(i->first, "too many files"))
364 deletion_failed = true;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700365 }
366 }
367
David Zeuthen41f2cf52014-11-05 12:29:45 -0500368 return !deletion_failed;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700369}
370
371// Helper class for implementing LookupUrlForFile().
372class LookupData {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700373 public:
374 explicit LookupData(P2PManager::LookupCallback callback)
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800375 : callback_(callback) {}
David Zeuthen27a48bc2013-08-06 12:06:29 -0700376
377 ~LookupData() {
Alex Deymo29b81532015-07-09 11:51:49 -0700378 if (timeout_task_ != MessageLoop::kTaskIdNull)
379 MessageLoop::current()->CancelTask(timeout_task_);
Alex Deymo461b2592015-07-24 20:10:52 -0700380 if (child_pid_)
381 Subprocess::Get().KillExec(child_pid_);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700382 }
383
Alex Deymo29b81532015-07-09 11:51:49 -0700384 void InitiateLookup(const vector<string>& cmd, TimeDelta timeout) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700385 // NOTE: if we fail early (i.e. in this method), we need to schedule
386 // an idle to report the error. This is because we guarantee that
Alex Deymo29b81532015-07-09 11:51:49 -0700387 // the callback is always called from the message loop (this
David Zeuthen27a48bc2013-08-06 12:06:29 -0700388 // guarantee is useful for testing).
389
Alex Deymo29b81532015-07-09 11:51:49 -0700390 // We expect to run just "p2p-client" and find it in the path.
Alex Deymo461b2592015-07-24 20:10:52 -0700391 child_pid_ = Subprocess::Get().ExecFlags(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800392 cmd,
393 Subprocess::kSearchPath,
394 {},
Alex Deymo461b2592015-07-24 20:10:52 -0700395 Bind(&LookupData::OnLookupDone, base::Unretained(this)));
Alex Deymo29b81532015-07-09 11:51:49 -0700396
Alex Deymo461b2592015-07-24 20:10:52 -0700397 if (!child_pid_) {
Alex Deymo29b81532015-07-09 11:51:49 -0700398 LOG(ERROR) << "Error spawning " << utils::StringVectorToString(cmd);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700399 ReportErrorAndDeleteInIdle();
400 return;
401 }
402
Alex Deymo29b81532015-07-09 11:51:49 -0700403 if (timeout > TimeDelta()) {
404 timeout_task_ = MessageLoop::current()->PostDelayedTask(
405 FROM_HERE,
406 Bind(&LookupData::OnTimeout, base::Unretained(this)),
407 timeout);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700408 }
409 }
410
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700411 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700412 void ReportErrorAndDeleteInIdle() {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800413 MessageLoop::current()->PostTask(
414 FROM_HERE,
415 Bind(&LookupData::OnIdleForReportErrorAndDelete,
416 base::Unretained(this)));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700417 }
418
Alex Deymo29b81532015-07-09 11:51:49 -0700419 void OnIdleForReportErrorAndDelete() {
420 ReportError();
421 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700422 }
423
424 void IssueCallback(const string& url) {
425 if (!callback_.is_null())
426 callback_.Run(url);
427 }
428
429 void ReportError() {
430 if (reported_)
431 return;
432 IssueCallback("");
433 reported_ = true;
434 }
435
Alex Deymo29b81532015-07-09 11:51:49 -0700436 void ReportSuccess(const string& output) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700437 if (reported_)
438 return;
Alex Deymo29b81532015-07-09 11:51:49 -0700439 string url = output;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700440 size_t newline_pos = url.find('\n');
441 if (newline_pos != string::npos)
442 url.resize(newline_pos);
443
444 // Since p2p-client(1) is constructing this URL itself strictly
445 // speaking there's no need to validate it... but, anyway, can't
446 // hurt.
447 if (url.compare(0, 7, "http://") == 0) {
448 IssueCallback(url);
449 } else {
450 LOG(ERROR) << "p2p URL '" << url << "' does not look right. Ignoring.";
451 ReportError();
452 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700453 reported_ = true;
454 }
455
Alex Deymo461b2592015-07-24 20:10:52 -0700456 void OnLookupDone(int return_code, const string& output) {
457 child_pid_ = 0;
Alex Deymo29b81532015-07-09 11:51:49 -0700458 if (return_code != 0) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800459 LOG(INFO) << "Child exited with non-zero exit code " << return_code;
Alex Deymo461b2592015-07-24 20:10:52 -0700460 ReportError();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700461 } else {
Alex Deymo461b2592015-07-24 20:10:52 -0700462 ReportSuccess(output);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700463 }
Alex Deymo461b2592015-07-24 20:10:52 -0700464 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700465 }
466
Alex Deymo29b81532015-07-09 11:51:49 -0700467 void OnTimeout() {
468 timeout_task_ = MessageLoop::kTaskIdNull;
469 ReportError();
470 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700471 }
472
473 P2PManager::LookupCallback callback_;
Alex Deymo29b81532015-07-09 11:51:49 -0700474
475 // The Subprocess tag of the running process. A value of 0 means that the
476 // process is not running.
Alex Deymo461b2592015-07-24 20:10:52 -0700477 pid_t child_pid_{0};
Alex Deymo29b81532015-07-09 11:51:49 -0700478
479 // The timeout task_id we are waiting on, if any.
480 MessageLoop::TaskId timeout_task_{MessageLoop::kTaskIdNull};
481
482 bool reported_{false};
David Zeuthen27a48bc2013-08-06 12:06:29 -0700483};
484
485void P2PManagerImpl::LookupUrlForFile(const string& file_id,
486 size_t minimum_size,
487 TimeDelta max_time_to_wait,
488 LookupCallback callback) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800489 LookupData* lookup_data = new LookupData(callback);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700490 string file_id_with_ext = file_id + "." + file_extension_;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800491 vector<string> args =
492 configuration_->GetP2PClientArgs(file_id_with_ext, minimum_size);
Alex Deymo29b81532015-07-09 11:51:49 -0700493 lookup_data->InitiateLookup(args, max_time_to_wait);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700494}
495
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800496bool P2PManagerImpl::FileShare(const string& file_id, size_t expected_size) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700497 // Check if file already exist.
Alex Deymof329b932014-10-30 01:37:48 -0700498 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700499 if (!path.empty()) {
500 // File exists - double check its expected size though.
501 ssize_t file_expected_size = FileGetExpectedSize(file_id);
502 if (file_expected_size == -1 ||
503 static_cast<size_t>(file_expected_size) != expected_size) {
504 LOG(ERROR) << "Existing p2p file " << path.value()
505 << " with expected_size=" << file_expected_size
506 << " does not match the passed in"
507 << " expected_size=" << expected_size;
508 return false;
509 }
510 return true;
511 }
512
513 // Before creating the file, bail if statvfs(3) indicates that at
514 // least twice the size is not available in P2P_DIR.
515 struct statvfs statvfsbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700516 FilePath p2p_dir = configuration_->GetP2PDir();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700517 if (statvfs(p2p_dir.value().c_str(), &statvfsbuf) != 0) {
518 PLOG(ERROR) << "Error calling statvfs() for dir " << p2p_dir.value();
519 return false;
520 }
521 size_t free_bytes =
522 static_cast<size_t>(statvfsbuf.f_bsize) * statvfsbuf.f_bavail;
523 if (free_bytes < 2 * expected_size) {
524 // This can easily happen and is worth reporting.
525 LOG(INFO) << "Refusing to allocate p2p file of " << expected_size
526 << " bytes since the directory " << p2p_dir.value()
527 << " only has " << free_bytes
528 << " bytes available and this is less than twice the"
529 << " requested size.";
530 return false;
531 }
532
533 // Okie-dokey looks like enough space is available - create the file.
534 path = GetPath(file_id, kNonVisible);
535 int fd = open(path.value().c_str(), O_CREAT | O_RDWR, 0644);
536 if (fd == -1) {
537 PLOG(ERROR) << "Error creating file with path " << path.value();
538 return false;
539 }
540 ScopedFdCloser fd_closer(&fd);
541
542 // If the final size is known, allocate the file (e.g. reserve disk
543 // space) and set the user.cros-p2p-filesize xattr.
544 if (expected_size != 0) {
545 if (fallocate(fd,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700546 FALLOC_FL_KEEP_SIZE, // Keep file size as 0.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700547 0,
548 expected_size) != 0) {
David Zeuthen910ec5b2013-09-26 12:10:58 -0700549 if (errno == ENOSYS || errno == EOPNOTSUPP) {
550 // If the filesystem doesn't support the fallocate, keep
551 // going. This is helpful when running unit tests on build
552 // machines with ancient filesystems and/or OSes.
553 PLOG(WARNING) << "Ignoring fallocate(2) failure";
554 } else {
555 // ENOSPC can happen (funky race though, cf. the statvfs() check
556 // above), handle it gracefully, e.g. use logging level INFO.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800557 PLOG(INFO) << "Error allocating " << expected_size << " bytes for file "
558 << path.value();
David Zeuthen910ec5b2013-09-26 12:10:58 -0700559 if (unlink(path.value().c_str()) != 0) {
560 PLOG(ERROR) << "Error deleting file with path " << path.value();
561 }
562 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700563 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700564 }
565
Alex Deymoc00c98a2015-03-17 17:38:00 -0700566 string decimal_size = std::to_string(expected_size);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800567 if (fsetxattr(fd,
568 kCrosP2PFileSizeXAttrName,
569 decimal_size.c_str(),
570 decimal_size.size(),
571 0) != 0) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700572 PLOG(ERROR) << "Error setting xattr " << path.value();
573 return false;
574 }
575 }
576
577 return true;
578}
579
580FilePath P2PManagerImpl::FileGetPath(const string& file_id) {
581 struct stat statbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700582 FilePath path;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700583
584 path = GetPath(file_id, kVisible);
585 if (stat(path.value().c_str(), &statbuf) == 0) {
586 return path;
587 }
588
589 path = GetPath(file_id, kNonVisible);
590 if (stat(path.value().c_str(), &statbuf) == 0) {
591 return path;
592 }
593
594 path.clear();
595 return path;
596}
597
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800598bool P2PManagerImpl::FileGetVisible(const string& file_id, bool* out_result) {
Alex Deymof329b932014-10-30 01:37:48 -0700599 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700600 if (path.empty()) {
601 LOG(ERROR) << "No file for id " << file_id;
602 return false;
603 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700604 if (out_result != nullptr)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700605 *out_result = path.MatchesExtension(kP2PExtension);
606 return true;
607}
608
609bool P2PManagerImpl::FileMakeVisible(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700610 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700611 if (path.empty()) {
612 LOG(ERROR) << "No file for id " << file_id;
613 return false;
614 }
615
616 // Already visible?
617 if (path.MatchesExtension(kP2PExtension))
618 return true;
619
620 LOG_ASSERT(path.MatchesExtension(kTmpExtension));
Alex Deymof329b932014-10-30 01:37:48 -0700621 FilePath new_path = path.RemoveExtension();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700622 LOG_ASSERT(new_path.MatchesExtension(kP2PExtension));
623 if (rename(path.value().c_str(), new_path.value().c_str()) != 0) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800624 PLOG(ERROR) << "Error renaming " << path.value() << " to "
625 << new_path.value();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700626 return false;
627 }
628
629 return true;
630}
631
632ssize_t P2PManagerImpl::FileGetSize(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700633 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700634 if (path.empty())
635 return -1;
636
Gabe Blacka77939e2014-09-09 23:35:08 -0700637 return utils::FileSize(path.value());
David Zeuthen27a48bc2013-08-06 12:06:29 -0700638}
639
640ssize_t P2PManagerImpl::FileGetExpectedSize(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700641 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700642 if (path.empty())
643 return -1;
644
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800645 char ea_value[64] = {0};
David Zeuthen27a48bc2013-08-06 12:06:29 -0700646 ssize_t ea_size;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800647 ea_size = getxattr(path.value().c_str(),
648 kCrosP2PFileSizeXAttrName,
649 &ea_value,
650 sizeof(ea_value) - 1);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700651 if (ea_size == -1) {
652 PLOG(ERROR) << "Error calling getxattr() on file " << path.value();
653 return -1;
654 }
655
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700656 char* endp = nullptr;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700657 long long int val = strtoll(ea_value, &endp, 0); // NOLINT(runtime/int)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700658 if (*endp != '\0') {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800659 LOG(ERROR) << "Error parsing the value '" << ea_value << "' of the xattr "
660 << kCrosP2PFileSizeXAttrName << " as an integer";
David Zeuthen27a48bc2013-08-06 12:06:29 -0700661 return -1;
662 }
663
664 return val;
665}
666
667int P2PManagerImpl::CountSharedFiles() {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700668 int num_files = 0;
669
Alex Deymof329b932014-10-30 01:37:48 -0700670 FilePath p2p_dir = configuration_->GetP2PDir();
Alex Deymo454b7982015-07-10 10:49:29 -0700671 const string ext_visible = GetExt(kVisible);
672 const string ext_non_visible = GetExt(kNonVisible);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700673
Alex Deymo454b7982015-07-10 10:49:29 -0700674 base::FileEnumerator dir(p2p_dir, false, base::FileEnumerator::FILES);
675 for (FilePath name = dir.Next(); !name.empty(); name = dir.Next()) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800676 if (base::EndsWith(
677 name.value(), ext_visible, base::CompareCase::SENSITIVE) ||
678 base::EndsWith(
679 name.value(), ext_non_visible, base::CompareCase::SENSITIVE)) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700680 num_files += 1;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800681 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700682 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700683
684 return num_files;
685}
686
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700687void P2PManagerImpl::ScheduleEnabledStatusChange() {
688 if (waiting_for_enabled_status_change_)
689 return;
Gilad Arnoldccd09572014-10-27 13:37:50 -0700690
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800691 Callback<void(EvalStatus, const bool&)> callback =
692 Bind(&P2PManagerImpl::OnEnabledStatusChange, base::Unretained(this));
693 update_manager_->AsyncPolicyRequest(
694 callback, &Policy::P2PEnabledChanged, is_enabled_);
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700695 waiting_for_enabled_status_change_ = true;
Gilad Arnoldccd09572014-10-27 13:37:50 -0700696}
697
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700698void P2PManagerImpl::OnEnabledStatusChange(EvalStatus status,
699 const bool& result) {
700 waiting_for_enabled_status_change_ = false;
701
702 if (status == EvalStatus::kSucceeded) {
703 if (result == is_enabled_) {
704 LOG(WARNING) << "P2P enabled status did not change, which means that it "
705 "is permanent; not scheduling further checks.";
706 waiting_for_enabled_status_change_ = true;
707 return;
708 }
709
710 is_enabled_ = result;
711
712 // If P2P is running but shouldn't be, make sure it isn't.
713 if (may_be_running_ && !is_enabled_ && !EnsureP2PNotRunning()) {
714 LOG(WARNING) << "Failed to stop P2P service.";
715 }
716 } else {
717 LOG(WARNING)
718 << "P2P enabled tracking failed (possibly timed out); retrying.";
719 }
720
721 ScheduleEnabledStatusChange();
722}
723
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800724P2PManager* P2PManager::Construct(Configuration* configuration,
725 ClockInterface* clock,
726 UpdateManager* update_manager,
727 const string& file_extension,
728 const int num_files_to_keep,
729 const TimeDelta& max_file_age) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700730 return new P2PManagerImpl(configuration,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500731 clock,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700732 update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700733 file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500734 num_files_to_keep,
735 max_file_age);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700736}
737
738} // namespace chromeos_update_engine