blob: 19e2600ee49700da6e1c6e49652e54b0cc2899ca [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
Amin Hassaniec7bc112020-10-29 16:47:58 -070026#include "update_engine/cros/p2p_manager.h"
David Zeuthen27a48bc2013-08-06 12:06:29 -070027
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"
Amin Hassani0468a762020-11-17 23:53:48 -080054#include "update_engine/common/system_state.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080055#include "update_engine/common/utils.h"
Gilad Arnold4a0321b2014-10-28 15:57:30 -070056#include "update_engine/update_manager/policy.h"
57#include "update_engine/update_manager/update_manager.h"
David Zeuthen27a48bc2013-08-06 12:06:29 -070058
Gilad Arnold4a0321b2014-10-28 15:57:30 -070059using base::Bind;
60using base::Callback;
David Zeuthen27a48bc2013-08-06 12:06:29 -070061using base::FilePath;
62using base::StringPrintf;
63using base::Time;
64using base::TimeDelta;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070065using brillo::MessageLoop;
Gilad Arnold4a0321b2014-10-28 15:57:30 -070066using chromeos_update_manager::EvalStatus;
67using chromeos_update_manager::Policy;
68using chromeos_update_manager::UpdateManager;
David Zeuthen27a48bc2013-08-06 12:06:29 -070069using std::pair;
70using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070071using std::unique_ptr;
David Zeuthen27a48bc2013-08-06 12:06:29 -070072using std::vector;
73
74namespace chromeos_update_engine {
75
76namespace {
77
78// The default p2p directory.
79const char kDefaultP2PDir[] = "/var/cache/p2p";
80
81// The p2p xattr used for conveying the final size of a file - see the
82// p2p ddoc for details.
83const char kCrosP2PFileSizeXAttrName[] = "user.cros-p2p-filesize";
84
Alex Vakulenkod2779df2014-06-16 13:19:00 -070085} // namespace
David Zeuthen27a48bc2013-08-06 12:06:29 -070086
87// The default P2PManager::Configuration implementation.
88class ConfigurationImpl : public P2PManager::Configuration {
Alex Vakulenkod2779df2014-06-16 13:19:00 -070089 public:
David Zeuthen27a48bc2013-08-06 12:06:29 -070090 ConfigurationImpl() {}
91
Amin Hassani7cc8bb02019-01-14 16:29:47 -080092 FilePath GetP2PDir() override { return FilePath(kDefaultP2PDir); }
David Zeuthen27a48bc2013-08-06 12:06:29 -070093
Alex Deymo610277e2014-11-11 21:18:11 -080094 vector<string> GetInitctlArgs(bool is_start) override {
David Zeuthen27a48bc2013-08-06 12:06:29 -070095 vector<string> args;
96 args.push_back("initctl");
97 args.push_back(is_start ? "start" : "stop");
98 args.push_back("p2p");
99 return args;
100 }
101
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800102 vector<string> GetP2PClientArgs(const string& file_id,
Alex Deymo610277e2014-11-11 21:18:11 -0800103 size_t minimum_size) override {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700104 vector<string> args;
105 args.push_back("p2p-client");
106 args.push_back(string("--get-url=") + file_id);
Alex Deymoc00c98a2015-03-17 17:38:00 -0700107 args.push_back(StringPrintf("--minimum-size=%" PRIuS, minimum_size));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700108 return args;
109 }
110
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700111 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700112 DISALLOW_COPY_AND_ASSIGN(ConfigurationImpl);
113};
114
115// The default P2PManager implementation.
116class P2PManagerImpl : public P2PManager {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700117 public:
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800118 P2PManagerImpl(Configuration* configuration,
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
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700173 // A pointer to the global Update Manager.
174 UpdateManager* update_manager_;
175
David Zeuthen27a48bc2013-08-06 12:06:29 -0700176 // A short string unique to the application (for example "cros_au")
177 // used to mark a file as being owned by a particular application.
178 const string file_extension_;
179
180 // If non-zero, this number denotes how many files in /var/cache/p2p
181 // owned by the application (cf. |file_extension_|) to keep after
182 // performing housekeeping.
183 const int num_files_to_keep_;
184
David Zeuthen41f2cf52014-11-05 12:29:45 -0500185 // If non-zero, files older than this will not be kept after
186 // performing housekeeping.
Alex Deymo29b81532015-07-09 11:51:49 -0700187 const TimeDelta max_file_age_;
David Zeuthen41f2cf52014-11-05 12:29:45 -0500188
David Zeuthen27a48bc2013-08-06 12:06:29 -0700189 // The string ".p2p".
190 static const char kP2PExtension[];
191
192 // The string ".tmp".
193 static const char kTmpExtension[];
194
Gilad Arnoldccd09572014-10-27 13:37:50 -0700195 // Whether P2P service may be running; initially, we assume it may be.
196 bool may_be_running_ = true;
197
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700198 // The current known enabled status of the P2P feature (initialized lazily),
199 // and whether an async status check has been scheduled.
200 bool is_enabled_;
201 bool waiting_for_enabled_status_change_ = false;
202
David Zeuthen27a48bc2013-08-06 12:06:29 -0700203 DISALLOW_COPY_AND_ASSIGN(P2PManagerImpl);
204};
205
206const char P2PManagerImpl::kP2PExtension[] = ".p2p";
207
208const char P2PManagerImpl::kTmpExtension[] = ".tmp";
209
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800210P2PManagerImpl::P2PManagerImpl(Configuration* configuration,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700211 UpdateManager* update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700212 const string& file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500213 const int num_files_to_keep,
Alex Deymo29b81532015-07-09 11:51:49 -0700214 const TimeDelta& max_file_age)
Amin Hassani0468a762020-11-17 23:53:48 -0800215 : update_manager_(update_manager),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800216 file_extension_(file_extension),
217 num_files_to_keep_(num_files_to_keep),
218 max_file_age_(max_file_age) {
219 configuration_.reset(configuration != nullptr ? configuration
220 : new ConfigurationImpl());
David Zeuthen27a48bc2013-08-06 12:06:29 -0700221}
222
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700223void P2PManagerImpl::SetDevicePolicy(
224 const policy::DevicePolicy* device_policy) {
225 device_policy_ = device_policy;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700226}
227
228bool P2PManagerImpl::IsP2PEnabled() {
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700229 if (!waiting_for_enabled_status_change_) {
230 // Get and store an initial value.
231 if (update_manager_->PolicyRequest(&Policy::P2PEnabled, &is_enabled_) ==
232 EvalStatus::kFailed) {
233 is_enabled_ = false;
234 LOG(ERROR) << "Querying P2P enabled status failed, disabling.";
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400235 }
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700236
237 // Track future changes (async).
238 ScheduleEnabledStatusChange();
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400239 }
240
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700241 return is_enabled_;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700242}
243
244bool P2PManagerImpl::EnsureP2P(bool should_be_running) {
Alex Deymo29b81532015-07-09 11:51:49 -0700245 int return_code = 0;
Amin Hassani3a4caa12019-11-06 11:12:28 -0800246 string stderr;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700247
Gilad Arnoldccd09572014-10-27 13:37:50 -0700248 may_be_running_ = true; // Unless successful, we must be conservative.
249
David Zeuthen27a48bc2013-08-06 12:06:29 -0700250 vector<string> args = configuration_->GetInitctlArgs(should_be_running);
Amin Hassani3a4caa12019-11-06 11:12:28 -0800251 if (!Subprocess::SynchronousExec(args, &return_code, nullptr, &stderr)) {
Alex Deymo29b81532015-07-09 11:51:49 -0700252 LOG(ERROR) << "Error spawning " << utils::StringVectorToString(args);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700253 return false;
254 }
255
Gilad Arnoldccd09572014-10-27 13:37:50 -0700256 // If initctl(8) does not exit normally (exit status other than zero), ensure
257 // that the error message is not benign by scanning stderr; this is a
258 // necessity because initctl does not offer actions such as "start if not
259 // running" or "stop if running".
David Zeuthen27a48bc2013-08-06 12:06:29 -0700260 // TODO(zeuthen,chromium:277051): Avoid doing this.
Alex Deymo29b81532015-07-09 11:51:49 -0700261 if (return_code != 0) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800262 const char* expected_error_message =
263 should_be_running ? "initctl: Job is already running: p2p\n"
264 : "initctl: Unknown instance \n";
Amin Hassani3a4caa12019-11-06 11:12:28 -0800265 if (stderr != expected_error_message)
Gilad Arnoldccd09572014-10-27 13:37:50 -0700266 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700267 }
268
Gilad Arnoldccd09572014-10-27 13:37:50 -0700269 may_be_running_ = should_be_running; // Successful after all.
270 return true;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700271}
272
273bool P2PManagerImpl::EnsureP2PRunning() {
274 return EnsureP2P(true);
275}
276
277bool P2PManagerImpl::EnsureP2PNotRunning() {
278 return EnsureP2P(false);
279}
280
281// Returns True if the timestamp in the first pair is greater than the
282// timestamp in the latter. If used with std::sort() this will yield a
283// sequence of elements where newer (high timestamps) elements precede
284// older ones (low timestamps).
285static bool MatchCompareFunc(const pair<FilePath, Time>& a,
286 const pair<FilePath, Time>& b) {
287 return a.second > b.second;
288}
289
290string P2PManagerImpl::GetExt(Visibility visibility) {
291 string ext = string(".") + file_extension_ + kP2PExtension;
292 switch (visibility) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800293 case kVisible:
294 break;
295 case kNonVisible:
296 ext += kTmpExtension;
297 break;
298 // Don't add a default case to let the compiler warn about newly
299 // added enum values.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700300 }
301 return ext;
302}
303
304FilePath P2PManagerImpl::GetPath(const string& file_id, Visibility visibility) {
305 return configuration_->GetP2PDir().Append(file_id + GetExt(visibility));
306}
307
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800308bool P2PManagerImpl::DeleteP2PFile(const FilePath& path, const string& reason) {
309 LOG(INFO) << "Deleting p2p file " << path.value() << " (reason: " << reason
310 << ")";
David Zeuthen41f2cf52014-11-05 12:29:45 -0500311 if (unlink(path.value().c_str()) != 0) {
312 PLOG(ERROR) << "Error deleting p2p file " << path.value();
313 return false;
314 }
315 return true;
316}
David Zeuthen27a48bc2013-08-06 12:06:29 -0700317
David Zeuthen41f2cf52014-11-05 12:29:45 -0500318bool P2PManagerImpl::PerformHousekeeping() {
319 // Open p2p dir.
Alex Deymof329b932014-10-30 01:37:48 -0700320 FilePath p2p_dir = configuration_->GetP2PDir();
Alex Deymo454b7982015-07-10 10:49:29 -0700321 const string ext_visible = GetExt(kVisible);
322 const string ext_non_visible = GetExt(kNonVisible);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700323
David Zeuthen41f2cf52014-11-05 12:29:45 -0500324 bool deletion_failed = false;
David Zeuthen41f2cf52014-11-05 12:29:45 -0500325 vector<pair<FilePath, Time>> matches;
Alex Deymo454b7982015-07-10 10:49:29 -0700326
327 base::FileEnumerator dir(p2p_dir, false, base::FileEnumerator::FILES);
328 // Go through all files and collect their mtime.
329 for (FilePath name = dir.Next(); !name.empty(); name = dir.Next()) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800330 if (!(base::EndsWith(
331 name.value(), ext_visible, base::CompareCase::SENSITIVE) ||
332 base::EndsWith(
333 name.value(), ext_non_visible, base::CompareCase::SENSITIVE))) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700334 continue;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800335 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700336
Alex Deymo454b7982015-07-10 10:49:29 -0700337 Time time = dir.GetInfo().GetLastModifiedTime();
David Zeuthen41f2cf52014-11-05 12:29:45 -0500338
339 // If instructed to keep only files younger than a given age
340 // (|max_file_age_| != 0), delete files satisfying this criteria
341 // right now. Otherwise add it to a list we'll consider for later.
Amin Hassani0468a762020-11-17 23:53:48 -0800342 if (max_file_age_ != TimeDelta() &&
343 SystemState::Get()->clock()->GetWallclockTime() - time >
344 max_file_age_) {
Alex Deymo454b7982015-07-10 10:49:29 -0700345 if (!DeleteP2PFile(name, "file too old"))
David Zeuthen41f2cf52014-11-05 12:29:45 -0500346 deletion_failed = true;
347 } else {
Alex Deymo454b7982015-07-10 10:49:29 -0700348 matches.push_back(std::make_pair(name, time));
David Zeuthen41f2cf52014-11-05 12:29:45 -0500349 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700350 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700351
David Zeuthen41f2cf52014-11-05 12:29:45 -0500352 // If instructed to only keep N files (|max_files_to_keep_ != 0),
353 // sort list of matches, newest (biggest time) to oldest (lowest
354 // time). Then delete starting at element |num_files_to_keep_|.
355 if (num_files_to_keep_ > 0) {
356 std::sort(matches.begin(), matches.end(), MatchCompareFunc);
357 vector<pair<FilePath, Time>>::const_iterator i;
358 for (i = matches.begin() + num_files_to_keep_; i < matches.end(); ++i) {
359 if (!DeleteP2PFile(i->first, "too many files"))
360 deletion_failed = true;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700361 }
362 }
363
David Zeuthen41f2cf52014-11-05 12:29:45 -0500364 return !deletion_failed;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700365}
366
367// Helper class for implementing LookupUrlForFile().
368class LookupData {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700369 public:
370 explicit LookupData(P2PManager::LookupCallback callback)
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800371 : callback_(callback) {}
David Zeuthen27a48bc2013-08-06 12:06:29 -0700372
373 ~LookupData() {
Alex Deymo29b81532015-07-09 11:51:49 -0700374 if (timeout_task_ != MessageLoop::kTaskIdNull)
375 MessageLoop::current()->CancelTask(timeout_task_);
Alex Deymo461b2592015-07-24 20:10:52 -0700376 if (child_pid_)
377 Subprocess::Get().KillExec(child_pid_);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700378 }
379
Alex Deymo29b81532015-07-09 11:51:49 -0700380 void InitiateLookup(const vector<string>& cmd, TimeDelta timeout) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700381 // NOTE: if we fail early (i.e. in this method), we need to schedule
382 // an idle to report the error. This is because we guarantee that
Alex Deymo29b81532015-07-09 11:51:49 -0700383 // the callback is always called from the message loop (this
David Zeuthen27a48bc2013-08-06 12:06:29 -0700384 // guarantee is useful for testing).
385
Alex Deymo29b81532015-07-09 11:51:49 -0700386 // We expect to run just "p2p-client" and find it in the path.
Alex Deymo461b2592015-07-24 20:10:52 -0700387 child_pid_ = Subprocess::Get().ExecFlags(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800388 cmd,
389 Subprocess::kSearchPath,
390 {},
Alex Deymo461b2592015-07-24 20:10:52 -0700391 Bind(&LookupData::OnLookupDone, base::Unretained(this)));
Alex Deymo29b81532015-07-09 11:51:49 -0700392
Alex Deymo461b2592015-07-24 20:10:52 -0700393 if (!child_pid_) {
Alex Deymo29b81532015-07-09 11:51:49 -0700394 LOG(ERROR) << "Error spawning " << utils::StringVectorToString(cmd);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700395 ReportErrorAndDeleteInIdle();
396 return;
397 }
398
Alex Deymo29b81532015-07-09 11:51:49 -0700399 if (timeout > TimeDelta()) {
400 timeout_task_ = MessageLoop::current()->PostDelayedTask(
401 FROM_HERE,
402 Bind(&LookupData::OnTimeout, base::Unretained(this)),
403 timeout);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700404 }
405 }
406
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700407 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700408 void ReportErrorAndDeleteInIdle() {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800409 MessageLoop::current()->PostTask(
410 FROM_HERE,
411 Bind(&LookupData::OnIdleForReportErrorAndDelete,
412 base::Unretained(this)));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700413 }
414
Alex Deymo29b81532015-07-09 11:51:49 -0700415 void OnIdleForReportErrorAndDelete() {
416 ReportError();
417 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700418 }
419
420 void IssueCallback(const string& url) {
421 if (!callback_.is_null())
422 callback_.Run(url);
423 }
424
425 void ReportError() {
426 if (reported_)
427 return;
428 IssueCallback("");
429 reported_ = true;
430 }
431
Alex Deymo29b81532015-07-09 11:51:49 -0700432 void ReportSuccess(const string& output) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700433 if (reported_)
434 return;
Alex Deymo29b81532015-07-09 11:51:49 -0700435 string url = output;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700436 size_t newline_pos = url.find('\n');
437 if (newline_pos != string::npos)
438 url.resize(newline_pos);
439
440 // Since p2p-client(1) is constructing this URL itself strictly
441 // speaking there's no need to validate it... but, anyway, can't
442 // hurt.
443 if (url.compare(0, 7, "http://") == 0) {
444 IssueCallback(url);
445 } else {
446 LOG(ERROR) << "p2p URL '" << url << "' does not look right. Ignoring.";
447 ReportError();
448 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700449 reported_ = true;
450 }
451
Alex Deymo461b2592015-07-24 20:10:52 -0700452 void OnLookupDone(int return_code, const string& output) {
453 child_pid_ = 0;
Alex Deymo29b81532015-07-09 11:51:49 -0700454 if (return_code != 0) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800455 LOG(INFO) << "Child exited with non-zero exit code " << return_code;
Alex Deymo461b2592015-07-24 20:10:52 -0700456 ReportError();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700457 } else {
Alex Deymo461b2592015-07-24 20:10:52 -0700458 ReportSuccess(output);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700459 }
Alex Deymo461b2592015-07-24 20:10:52 -0700460 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700461 }
462
Alex Deymo29b81532015-07-09 11:51:49 -0700463 void OnTimeout() {
464 timeout_task_ = MessageLoop::kTaskIdNull;
465 ReportError();
466 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700467 }
468
469 P2PManager::LookupCallback callback_;
Alex Deymo29b81532015-07-09 11:51:49 -0700470
471 // The Subprocess tag of the running process. A value of 0 means that the
472 // process is not running.
Alex Deymo461b2592015-07-24 20:10:52 -0700473 pid_t child_pid_{0};
Alex Deymo29b81532015-07-09 11:51:49 -0700474
475 // The timeout task_id we are waiting on, if any.
476 MessageLoop::TaskId timeout_task_{MessageLoop::kTaskIdNull};
477
478 bool reported_{false};
David Zeuthen27a48bc2013-08-06 12:06:29 -0700479};
480
481void P2PManagerImpl::LookupUrlForFile(const string& file_id,
482 size_t minimum_size,
483 TimeDelta max_time_to_wait,
484 LookupCallback callback) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800485 LookupData* lookup_data = new LookupData(callback);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700486 string file_id_with_ext = file_id + "." + file_extension_;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800487 vector<string> args =
488 configuration_->GetP2PClientArgs(file_id_with_ext, minimum_size);
Alex Deymo29b81532015-07-09 11:51:49 -0700489 lookup_data->InitiateLookup(args, max_time_to_wait);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700490}
491
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800492bool P2PManagerImpl::FileShare(const string& file_id, size_t expected_size) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700493 // Check if file already exist.
Alex Deymof329b932014-10-30 01:37:48 -0700494 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700495 if (!path.empty()) {
496 // File exists - double check its expected size though.
497 ssize_t file_expected_size = FileGetExpectedSize(file_id);
498 if (file_expected_size == -1 ||
499 static_cast<size_t>(file_expected_size) != expected_size) {
500 LOG(ERROR) << "Existing p2p file " << path.value()
501 << " with expected_size=" << file_expected_size
502 << " does not match the passed in"
503 << " expected_size=" << expected_size;
504 return false;
505 }
506 return true;
507 }
508
509 // Before creating the file, bail if statvfs(3) indicates that at
510 // least twice the size is not available in P2P_DIR.
511 struct statvfs statvfsbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700512 FilePath p2p_dir = configuration_->GetP2PDir();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700513 if (statvfs(p2p_dir.value().c_str(), &statvfsbuf) != 0) {
514 PLOG(ERROR) << "Error calling statvfs() for dir " << p2p_dir.value();
515 return false;
516 }
517 size_t free_bytes =
518 static_cast<size_t>(statvfsbuf.f_bsize) * statvfsbuf.f_bavail;
519 if (free_bytes < 2 * expected_size) {
520 // This can easily happen and is worth reporting.
521 LOG(INFO) << "Refusing to allocate p2p file of " << expected_size
522 << " bytes since the directory " << p2p_dir.value()
523 << " only has " << free_bytes
524 << " bytes available and this is less than twice the"
525 << " requested size.";
526 return false;
527 }
528
529 // Okie-dokey looks like enough space is available - create the file.
530 path = GetPath(file_id, kNonVisible);
531 int fd = open(path.value().c_str(), O_CREAT | O_RDWR, 0644);
532 if (fd == -1) {
533 PLOG(ERROR) << "Error creating file with path " << path.value();
534 return false;
535 }
536 ScopedFdCloser fd_closer(&fd);
537
538 // If the final size is known, allocate the file (e.g. reserve disk
539 // space) and set the user.cros-p2p-filesize xattr.
540 if (expected_size != 0) {
541 if (fallocate(fd,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700542 FALLOC_FL_KEEP_SIZE, // Keep file size as 0.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700543 0,
544 expected_size) != 0) {
David Zeuthen910ec5b2013-09-26 12:10:58 -0700545 if (errno == ENOSYS || errno == EOPNOTSUPP) {
546 // If the filesystem doesn't support the fallocate, keep
547 // going. This is helpful when running unit tests on build
548 // machines with ancient filesystems and/or OSes.
549 PLOG(WARNING) << "Ignoring fallocate(2) failure";
550 } else {
551 // ENOSPC can happen (funky race though, cf. the statvfs() check
552 // above), handle it gracefully, e.g. use logging level INFO.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800553 PLOG(INFO) << "Error allocating " << expected_size << " bytes for file "
554 << path.value();
David Zeuthen910ec5b2013-09-26 12:10:58 -0700555 if (unlink(path.value().c_str()) != 0) {
556 PLOG(ERROR) << "Error deleting file with path " << path.value();
557 }
558 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700559 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700560 }
561
Alex Deymoc00c98a2015-03-17 17:38:00 -0700562 string decimal_size = std::to_string(expected_size);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800563 if (fsetxattr(fd,
564 kCrosP2PFileSizeXAttrName,
565 decimal_size.c_str(),
566 decimal_size.size(),
567 0) != 0) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700568 PLOG(ERROR) << "Error setting xattr " << path.value();
569 return false;
570 }
571 }
572
573 return true;
574}
575
576FilePath P2PManagerImpl::FileGetPath(const string& file_id) {
577 struct stat statbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700578 FilePath path;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700579
580 path = GetPath(file_id, kVisible);
581 if (stat(path.value().c_str(), &statbuf) == 0) {
582 return path;
583 }
584
585 path = GetPath(file_id, kNonVisible);
586 if (stat(path.value().c_str(), &statbuf) == 0) {
587 return path;
588 }
589
590 path.clear();
591 return path;
592}
593
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800594bool P2PManagerImpl::FileGetVisible(const string& file_id, bool* out_result) {
Alex Deymof329b932014-10-30 01:37:48 -0700595 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700596 if (path.empty()) {
597 LOG(ERROR) << "No file for id " << file_id;
598 return false;
599 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700600 if (out_result != nullptr)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700601 *out_result = path.MatchesExtension(kP2PExtension);
602 return true;
603}
604
605bool P2PManagerImpl::FileMakeVisible(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700606 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700607 if (path.empty()) {
608 LOG(ERROR) << "No file for id " << file_id;
609 return false;
610 }
611
612 // Already visible?
613 if (path.MatchesExtension(kP2PExtension))
614 return true;
615
616 LOG_ASSERT(path.MatchesExtension(kTmpExtension));
Alex Deymof329b932014-10-30 01:37:48 -0700617 FilePath new_path = path.RemoveExtension();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700618 LOG_ASSERT(new_path.MatchesExtension(kP2PExtension));
619 if (rename(path.value().c_str(), new_path.value().c_str()) != 0) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800620 PLOG(ERROR) << "Error renaming " << path.value() << " to "
621 << new_path.value();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700622 return false;
623 }
624
625 return true;
626}
627
628ssize_t P2PManagerImpl::FileGetSize(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700629 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700630 if (path.empty())
631 return -1;
632
Gabe Blacka77939e2014-09-09 23:35:08 -0700633 return utils::FileSize(path.value());
David Zeuthen27a48bc2013-08-06 12:06:29 -0700634}
635
636ssize_t P2PManagerImpl::FileGetExpectedSize(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700637 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700638 if (path.empty())
639 return -1;
640
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800641 char ea_value[64] = {0};
David Zeuthen27a48bc2013-08-06 12:06:29 -0700642 ssize_t ea_size;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800643 ea_size = getxattr(path.value().c_str(),
644 kCrosP2PFileSizeXAttrName,
645 &ea_value,
646 sizeof(ea_value) - 1);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700647 if (ea_size == -1) {
648 PLOG(ERROR) << "Error calling getxattr() on file " << path.value();
649 return -1;
650 }
651
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700652 char* endp = nullptr;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700653 long long int val = strtoll(ea_value, &endp, 0); // NOLINT(runtime/int)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700654 if (*endp != '\0') {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800655 LOG(ERROR) << "Error parsing the value '" << ea_value << "' of the xattr "
656 << kCrosP2PFileSizeXAttrName << " as an integer";
David Zeuthen27a48bc2013-08-06 12:06:29 -0700657 return -1;
658 }
659
660 return val;
661}
662
663int P2PManagerImpl::CountSharedFiles() {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700664 int num_files = 0;
665
Alex Deymof329b932014-10-30 01:37:48 -0700666 FilePath p2p_dir = configuration_->GetP2PDir();
Alex Deymo454b7982015-07-10 10:49:29 -0700667 const string ext_visible = GetExt(kVisible);
668 const string ext_non_visible = GetExt(kNonVisible);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700669
Alex Deymo454b7982015-07-10 10:49:29 -0700670 base::FileEnumerator dir(p2p_dir, false, base::FileEnumerator::FILES);
671 for (FilePath name = dir.Next(); !name.empty(); name = dir.Next()) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800672 if (base::EndsWith(
673 name.value(), ext_visible, base::CompareCase::SENSITIVE) ||
674 base::EndsWith(
675 name.value(), ext_non_visible, base::CompareCase::SENSITIVE)) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700676 num_files += 1;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800677 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700678 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700679
680 return num_files;
681}
682
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700683void P2PManagerImpl::ScheduleEnabledStatusChange() {
684 if (waiting_for_enabled_status_change_)
685 return;
Gilad Arnoldccd09572014-10-27 13:37:50 -0700686
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800687 Callback<void(EvalStatus, const bool&)> callback =
688 Bind(&P2PManagerImpl::OnEnabledStatusChange, base::Unretained(this));
689 update_manager_->AsyncPolicyRequest(
690 callback, &Policy::P2PEnabledChanged, is_enabled_);
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700691 waiting_for_enabled_status_change_ = true;
Gilad Arnoldccd09572014-10-27 13:37:50 -0700692}
693
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700694void P2PManagerImpl::OnEnabledStatusChange(EvalStatus status,
695 const bool& result) {
696 waiting_for_enabled_status_change_ = false;
697
698 if (status == EvalStatus::kSucceeded) {
699 if (result == is_enabled_) {
700 LOG(WARNING) << "P2P enabled status did not change, which means that it "
701 "is permanent; not scheduling further checks.";
702 waiting_for_enabled_status_change_ = true;
703 return;
704 }
705
706 is_enabled_ = result;
707
708 // If P2P is running but shouldn't be, make sure it isn't.
709 if (may_be_running_ && !is_enabled_ && !EnsureP2PNotRunning()) {
710 LOG(WARNING) << "Failed to stop P2P service.";
711 }
712 } else {
713 LOG(WARNING)
714 << "P2P enabled tracking failed (possibly timed out); retrying.";
715 }
716
717 ScheduleEnabledStatusChange();
718}
719
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800720P2PManager* P2PManager::Construct(Configuration* configuration,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800721 UpdateManager* update_manager,
722 const string& file_extension,
723 const int num_files_to_keep,
724 const TimeDelta& max_file_age) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700725 return new P2PManagerImpl(configuration,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700726 update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700727 file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500728 num_files_to_keep,
729 max_file_age);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700730}
731
732} // namespace chromeos_update_engine