blob: 6720908677bb8cf631aae22fdaa1427d97a0af84 [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::map;
69using 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,
119 ClockInterface* clock,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700120 UpdateManager* update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700121 const string& file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500122 const int num_files_to_keep,
Alex Deymo29b81532015-07-09 11:51:49 -0700123 const TimeDelta& max_file_age);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700124
125 // P2PManager methods.
Alex Deymo610277e2014-11-11 21:18:11 -0800126 void SetDevicePolicy(const policy::DevicePolicy* device_policy) override;
127 bool IsP2PEnabled() override;
128 bool EnsureP2PRunning() override;
129 bool EnsureP2PNotRunning() override;
130 bool PerformHousekeeping() override;
131 void LookupUrlForFile(const string& file_id,
132 size_t minimum_size,
133 TimeDelta max_time_to_wait,
134 LookupCallback callback) override;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800135 bool FileShare(const string& file_id, size_t expected_size) override;
Alex Deymo610277e2014-11-11 21:18:11 -0800136 FilePath FileGetPath(const string& file_id) override;
137 ssize_t FileGetSize(const string& file_id) override;
138 ssize_t FileGetExpectedSize(const string& file_id) override;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800139 bool FileGetVisible(const string& file_id, bool* out_result) override;
Alex Deymo610277e2014-11-11 21:18:11 -0800140 bool FileMakeVisible(const string& file_id) override;
141 int CountSharedFiles() override;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700142
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700143 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700144 // Enumeration for specifying visibility.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800145 enum Visibility { kVisible, kNonVisible };
David Zeuthen27a48bc2013-08-06 12:06:29 -0700146
147 // Returns "." + |file_extension_| + ".p2p" if |visibility| is
148 // |kVisible|. Returns the same concatenated with ".tmp" otherwise.
149 string GetExt(Visibility visibility);
150
151 // Gets the on-disk path for |file_id| depending on if the file
152 // is visible or not.
Alex Deymof329b932014-10-30 01:37:48 -0700153 FilePath GetPath(const string& file_id, Visibility visibility);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700154
155 // Utility function used by EnsureP2PRunning() and EnsureP2PNotRunning().
156 bool EnsureP2P(bool should_be_running);
157
David Zeuthen41f2cf52014-11-05 12:29:45 -0500158 // Utility function to delete a file given by |path| and log the
159 // path as well as |reason|. Returns false on failure.
Alex Deymo29b81532015-07-09 11:51:49 -0700160 bool DeleteP2PFile(const FilePath& path, const string& reason);
David Zeuthen41f2cf52014-11-05 12:29:45 -0500161
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700162 // Schedules an async request for tracking changes in P2P enabled status.
163 void ScheduleEnabledStatusChange();
164
165 // An async callback used by the above.
166 void OnEnabledStatusChange(EvalStatus status, const bool& result);
167
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700168 // The device policy being used or null if no policy is being used.
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700169 const policy::DevicePolicy* device_policy_ = nullptr;
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700170
David Zeuthen27a48bc2013-08-06 12:06:29 -0700171 // Configuration object.
Ben Chan02f7c1d2014-10-18 15:18:02 -0700172 unique_ptr<Configuration> configuration_;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700173
David Zeuthen41f2cf52014-11-05 12:29:45 -0500174 // Object for telling the time.
175 ClockInterface* clock_;
176
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700177 // A pointer to the global Update Manager.
178 UpdateManager* update_manager_;
179
David Zeuthen27a48bc2013-08-06 12:06:29 -0700180 // A short string unique to the application (for example "cros_au")
181 // used to mark a file as being owned by a particular application.
182 const string file_extension_;
183
184 // If non-zero, this number denotes how many files in /var/cache/p2p
185 // owned by the application (cf. |file_extension_|) to keep after
186 // performing housekeeping.
187 const int num_files_to_keep_;
188
David Zeuthen41f2cf52014-11-05 12:29:45 -0500189 // If non-zero, files older than this will not be kept after
190 // performing housekeeping.
Alex Deymo29b81532015-07-09 11:51:49 -0700191 const TimeDelta max_file_age_;
David Zeuthen41f2cf52014-11-05 12:29:45 -0500192
David Zeuthen27a48bc2013-08-06 12:06:29 -0700193 // The string ".p2p".
194 static const char kP2PExtension[];
195
196 // The string ".tmp".
197 static const char kTmpExtension[];
198
Gilad Arnoldccd09572014-10-27 13:37:50 -0700199 // Whether P2P service may be running; initially, we assume it may be.
200 bool may_be_running_ = true;
201
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700202 // The current known enabled status of the P2P feature (initialized lazily),
203 // and whether an async status check has been scheduled.
204 bool is_enabled_;
205 bool waiting_for_enabled_status_change_ = false;
206
David Zeuthen27a48bc2013-08-06 12:06:29 -0700207 DISALLOW_COPY_AND_ASSIGN(P2PManagerImpl);
208};
209
210const char P2PManagerImpl::kP2PExtension[] = ".p2p";
211
212const char P2PManagerImpl::kTmpExtension[] = ".tmp";
213
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800214P2PManagerImpl::P2PManagerImpl(Configuration* configuration,
215 ClockInterface* clock,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700216 UpdateManager* update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700217 const string& file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500218 const int num_files_to_keep,
Alex Deymo29b81532015-07-09 11:51:49 -0700219 const TimeDelta& max_file_age)
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800220 : clock_(clock),
221 update_manager_(update_manager),
222 file_extension_(file_extension),
223 num_files_to_keep_(num_files_to_keep),
224 max_file_age_(max_file_age) {
225 configuration_.reset(configuration != nullptr ? configuration
226 : new ConfigurationImpl());
David Zeuthen27a48bc2013-08-06 12:06:29 -0700227}
228
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700229void P2PManagerImpl::SetDevicePolicy(
230 const policy::DevicePolicy* device_policy) {
231 device_policy_ = device_policy;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700232}
233
234bool P2PManagerImpl::IsP2PEnabled() {
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700235 if (!waiting_for_enabled_status_change_) {
236 // Get and store an initial value.
237 if (update_manager_->PolicyRequest(&Policy::P2PEnabled, &is_enabled_) ==
238 EvalStatus::kFailed) {
239 is_enabled_ = false;
240 LOG(ERROR) << "Querying P2P enabled status failed, disabling.";
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400241 }
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700242
243 // Track future changes (async).
244 ScheduleEnabledStatusChange();
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400245 }
246
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700247 return is_enabled_;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700248}
249
250bool P2PManagerImpl::EnsureP2P(bool should_be_running) {
Alex Deymo29b81532015-07-09 11:51:49 -0700251 int return_code = 0;
252 string output;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700253
Gilad Arnoldccd09572014-10-27 13:37:50 -0700254 may_be_running_ = true; // Unless successful, we must be conservative.
255
David Zeuthen27a48bc2013-08-06 12:06:29 -0700256 vector<string> args = configuration_->GetInitctlArgs(should_be_running);
Alex Deymo29b81532015-07-09 11:51:49 -0700257 if (!Subprocess::SynchronousExec(args, &return_code, &output)) {
258 LOG(ERROR) << "Error spawning " << utils::StringVectorToString(args);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700259 return false;
260 }
261
Gilad Arnoldccd09572014-10-27 13:37:50 -0700262 // If initctl(8) does not exit normally (exit status other than zero), ensure
263 // that the error message is not benign by scanning stderr; this is a
264 // necessity because initctl does not offer actions such as "start if not
265 // running" or "stop if running".
David Zeuthen27a48bc2013-08-06 12:06:29 -0700266 // TODO(zeuthen,chromium:277051): Avoid doing this.
Alex Deymo29b81532015-07-09 11:51:49 -0700267 if (return_code != 0) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800268 const char* expected_error_message =
269 should_be_running ? "initctl: Job is already running: p2p\n"
270 : "initctl: Unknown instance \n";
Alex Deymo29b81532015-07-09 11:51:49 -0700271 if (output != expected_error_message)
Gilad Arnoldccd09572014-10-27 13:37:50 -0700272 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700273 }
274
Gilad Arnoldccd09572014-10-27 13:37:50 -0700275 may_be_running_ = should_be_running; // Successful after all.
276 return true;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700277}
278
279bool P2PManagerImpl::EnsureP2PRunning() {
280 return EnsureP2P(true);
281}
282
283bool P2PManagerImpl::EnsureP2PNotRunning() {
284 return EnsureP2P(false);
285}
286
287// Returns True if the timestamp in the first pair is greater than the
288// timestamp in the latter. If used with std::sort() this will yield a
289// sequence of elements where newer (high timestamps) elements precede
290// older ones (low timestamps).
291static bool MatchCompareFunc(const pair<FilePath, Time>& a,
292 const pair<FilePath, Time>& b) {
293 return a.second > b.second;
294}
295
296string P2PManagerImpl::GetExt(Visibility visibility) {
297 string ext = string(".") + file_extension_ + kP2PExtension;
298 switch (visibility) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800299 case kVisible:
300 break;
301 case kNonVisible:
302 ext += kTmpExtension;
303 break;
304 // Don't add a default case to let the compiler warn about newly
305 // added enum values.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700306 }
307 return ext;
308}
309
310FilePath P2PManagerImpl::GetPath(const string& file_id, Visibility visibility) {
311 return configuration_->GetP2PDir().Append(file_id + GetExt(visibility));
312}
313
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800314bool P2PManagerImpl::DeleteP2PFile(const FilePath& path, const string& reason) {
315 LOG(INFO) << "Deleting p2p file " << path.value() << " (reason: " << reason
316 << ")";
David Zeuthen41f2cf52014-11-05 12:29:45 -0500317 if (unlink(path.value().c_str()) != 0) {
318 PLOG(ERROR) << "Error deleting p2p file " << path.value();
319 return false;
320 }
321 return true;
322}
David Zeuthen27a48bc2013-08-06 12:06:29 -0700323
David Zeuthen41f2cf52014-11-05 12:29:45 -0500324bool P2PManagerImpl::PerformHousekeeping() {
325 // Open p2p dir.
Alex Deymof329b932014-10-30 01:37:48 -0700326 FilePath p2p_dir = configuration_->GetP2PDir();
Alex Deymo454b7982015-07-10 10:49:29 -0700327 const string ext_visible = GetExt(kVisible);
328 const string ext_non_visible = GetExt(kNonVisible);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700329
David Zeuthen41f2cf52014-11-05 12:29:45 -0500330 bool deletion_failed = false;
David Zeuthen41f2cf52014-11-05 12:29:45 -0500331 vector<pair<FilePath, Time>> matches;
Alex Deymo454b7982015-07-10 10:49:29 -0700332
333 base::FileEnumerator dir(p2p_dir, false, base::FileEnumerator::FILES);
334 // Go through all files and collect their mtime.
335 for (FilePath name = dir.Next(); !name.empty(); name = dir.Next()) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800336 if (!(base::EndsWith(
337 name.value(), ext_visible, base::CompareCase::SENSITIVE) ||
338 base::EndsWith(
339 name.value(), ext_non_visible, base::CompareCase::SENSITIVE))) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700340 continue;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800341 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700342
Alex Deymo454b7982015-07-10 10:49:29 -0700343 Time time = dir.GetInfo().GetLastModifiedTime();
David Zeuthen41f2cf52014-11-05 12:29:45 -0500344
345 // If instructed to keep only files younger than a given age
346 // (|max_file_age_| != 0), delete files satisfying this criteria
347 // right now. Otherwise add it to a list we'll consider for later.
Alex Deymo29b81532015-07-09 11:51:49 -0700348 if (clock_ != nullptr && max_file_age_ != TimeDelta() &&
David Zeuthen41f2cf52014-11-05 12:29:45 -0500349 clock_->GetWallclockTime() - time > max_file_age_) {
Alex Deymo454b7982015-07-10 10:49:29 -0700350 if (!DeleteP2PFile(name, "file too old"))
David Zeuthen41f2cf52014-11-05 12:29:45 -0500351 deletion_failed = true;
352 } else {
Alex Deymo454b7982015-07-10 10:49:29 -0700353 matches.push_back(std::make_pair(name, time));
David Zeuthen41f2cf52014-11-05 12:29:45 -0500354 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700355 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700356
David Zeuthen41f2cf52014-11-05 12:29:45 -0500357 // If instructed to only keep N files (|max_files_to_keep_ != 0),
358 // sort list of matches, newest (biggest time) to oldest (lowest
359 // time). Then delete starting at element |num_files_to_keep_|.
360 if (num_files_to_keep_ > 0) {
361 std::sort(matches.begin(), matches.end(), MatchCompareFunc);
362 vector<pair<FilePath, Time>>::const_iterator i;
363 for (i = matches.begin() + num_files_to_keep_; i < matches.end(); ++i) {
364 if (!DeleteP2PFile(i->first, "too many files"))
365 deletion_failed = true;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700366 }
367 }
368
David Zeuthen41f2cf52014-11-05 12:29:45 -0500369 return !deletion_failed;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700370}
371
372// Helper class for implementing LookupUrlForFile().
373class LookupData {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700374 public:
375 explicit LookupData(P2PManager::LookupCallback callback)
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800376 : callback_(callback) {}
David Zeuthen27a48bc2013-08-06 12:06:29 -0700377
378 ~LookupData() {
Alex Deymo29b81532015-07-09 11:51:49 -0700379 if (timeout_task_ != MessageLoop::kTaskIdNull)
380 MessageLoop::current()->CancelTask(timeout_task_);
Alex Deymo461b2592015-07-24 20:10:52 -0700381 if (child_pid_)
382 Subprocess::Get().KillExec(child_pid_);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700383 }
384
Alex Deymo29b81532015-07-09 11:51:49 -0700385 void InitiateLookup(const vector<string>& cmd, TimeDelta timeout) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700386 // NOTE: if we fail early (i.e. in this method), we need to schedule
387 // an idle to report the error. This is because we guarantee that
Alex Deymo29b81532015-07-09 11:51:49 -0700388 // the callback is always called from the message loop (this
David Zeuthen27a48bc2013-08-06 12:06:29 -0700389 // guarantee is useful for testing).
390
Alex Deymo29b81532015-07-09 11:51:49 -0700391 // We expect to run just "p2p-client" and find it in the path.
Alex Deymo461b2592015-07-24 20:10:52 -0700392 child_pid_ = Subprocess::Get().ExecFlags(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800393 cmd,
394 Subprocess::kSearchPath,
395 {},
Alex Deymo461b2592015-07-24 20:10:52 -0700396 Bind(&LookupData::OnLookupDone, base::Unretained(this)));
Alex Deymo29b81532015-07-09 11:51:49 -0700397
Alex Deymo461b2592015-07-24 20:10:52 -0700398 if (!child_pid_) {
Alex Deymo29b81532015-07-09 11:51:49 -0700399 LOG(ERROR) << "Error spawning " << utils::StringVectorToString(cmd);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700400 ReportErrorAndDeleteInIdle();
401 return;
402 }
403
Alex Deymo29b81532015-07-09 11:51:49 -0700404 if (timeout > TimeDelta()) {
405 timeout_task_ = MessageLoop::current()->PostDelayedTask(
406 FROM_HERE,
407 Bind(&LookupData::OnTimeout, base::Unretained(this)),
408 timeout);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700409 }
410 }
411
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700412 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700413 void ReportErrorAndDeleteInIdle() {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800414 MessageLoop::current()->PostTask(
415 FROM_HERE,
416 Bind(&LookupData::OnIdleForReportErrorAndDelete,
417 base::Unretained(this)));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700418 }
419
Alex Deymo29b81532015-07-09 11:51:49 -0700420 void OnIdleForReportErrorAndDelete() {
421 ReportError();
422 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700423 }
424
425 void IssueCallback(const string& url) {
426 if (!callback_.is_null())
427 callback_.Run(url);
428 }
429
430 void ReportError() {
431 if (reported_)
432 return;
433 IssueCallback("");
434 reported_ = true;
435 }
436
Alex Deymo29b81532015-07-09 11:51:49 -0700437 void ReportSuccess(const string& output) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700438 if (reported_)
439 return;
Alex Deymo29b81532015-07-09 11:51:49 -0700440 string url = output;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700441 size_t newline_pos = url.find('\n');
442 if (newline_pos != string::npos)
443 url.resize(newline_pos);
444
445 // Since p2p-client(1) is constructing this URL itself strictly
446 // speaking there's no need to validate it... but, anyway, can't
447 // hurt.
448 if (url.compare(0, 7, "http://") == 0) {
449 IssueCallback(url);
450 } else {
451 LOG(ERROR) << "p2p URL '" << url << "' does not look right. Ignoring.";
452 ReportError();
453 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700454 reported_ = true;
455 }
456
Alex Deymo461b2592015-07-24 20:10:52 -0700457 void OnLookupDone(int return_code, const string& output) {
458 child_pid_ = 0;
Alex Deymo29b81532015-07-09 11:51:49 -0700459 if (return_code != 0) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800460 LOG(INFO) << "Child exited with non-zero exit code " << return_code;
Alex Deymo461b2592015-07-24 20:10:52 -0700461 ReportError();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700462 } else {
Alex Deymo461b2592015-07-24 20:10:52 -0700463 ReportSuccess(output);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700464 }
Alex Deymo461b2592015-07-24 20:10:52 -0700465 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700466 }
467
Alex Deymo29b81532015-07-09 11:51:49 -0700468 void OnTimeout() {
469 timeout_task_ = MessageLoop::kTaskIdNull;
470 ReportError();
471 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700472 }
473
474 P2PManager::LookupCallback callback_;
Alex Deymo29b81532015-07-09 11:51:49 -0700475
476 // The Subprocess tag of the running process. A value of 0 means that the
477 // process is not running.
Alex Deymo461b2592015-07-24 20:10:52 -0700478 pid_t child_pid_{0};
Alex Deymo29b81532015-07-09 11:51:49 -0700479
480 // The timeout task_id we are waiting on, if any.
481 MessageLoop::TaskId timeout_task_{MessageLoop::kTaskIdNull};
482
483 bool reported_{false};
David Zeuthen27a48bc2013-08-06 12:06:29 -0700484};
485
486void P2PManagerImpl::LookupUrlForFile(const string& file_id,
487 size_t minimum_size,
488 TimeDelta max_time_to_wait,
489 LookupCallback callback) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800490 LookupData* lookup_data = new LookupData(callback);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700491 string file_id_with_ext = file_id + "." + file_extension_;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800492 vector<string> args =
493 configuration_->GetP2PClientArgs(file_id_with_ext, minimum_size);
Alex Deymo29b81532015-07-09 11:51:49 -0700494 lookup_data->InitiateLookup(args, max_time_to_wait);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700495}
496
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800497bool P2PManagerImpl::FileShare(const string& file_id, size_t expected_size) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700498 // Check if file already exist.
Alex Deymof329b932014-10-30 01:37:48 -0700499 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700500 if (!path.empty()) {
501 // File exists - double check its expected size though.
502 ssize_t file_expected_size = FileGetExpectedSize(file_id);
503 if (file_expected_size == -1 ||
504 static_cast<size_t>(file_expected_size) != expected_size) {
505 LOG(ERROR) << "Existing p2p file " << path.value()
506 << " with expected_size=" << file_expected_size
507 << " does not match the passed in"
508 << " expected_size=" << expected_size;
509 return false;
510 }
511 return true;
512 }
513
514 // Before creating the file, bail if statvfs(3) indicates that at
515 // least twice the size is not available in P2P_DIR.
516 struct statvfs statvfsbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700517 FilePath p2p_dir = configuration_->GetP2PDir();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700518 if (statvfs(p2p_dir.value().c_str(), &statvfsbuf) != 0) {
519 PLOG(ERROR) << "Error calling statvfs() for dir " << p2p_dir.value();
520 return false;
521 }
522 size_t free_bytes =
523 static_cast<size_t>(statvfsbuf.f_bsize) * statvfsbuf.f_bavail;
524 if (free_bytes < 2 * expected_size) {
525 // This can easily happen and is worth reporting.
526 LOG(INFO) << "Refusing to allocate p2p file of " << expected_size
527 << " bytes since the directory " << p2p_dir.value()
528 << " only has " << free_bytes
529 << " bytes available and this is less than twice the"
530 << " requested size.";
531 return false;
532 }
533
534 // Okie-dokey looks like enough space is available - create the file.
535 path = GetPath(file_id, kNonVisible);
536 int fd = open(path.value().c_str(), O_CREAT | O_RDWR, 0644);
537 if (fd == -1) {
538 PLOG(ERROR) << "Error creating file with path " << path.value();
539 return false;
540 }
541 ScopedFdCloser fd_closer(&fd);
542
543 // If the final size is known, allocate the file (e.g. reserve disk
544 // space) and set the user.cros-p2p-filesize xattr.
545 if (expected_size != 0) {
546 if (fallocate(fd,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700547 FALLOC_FL_KEEP_SIZE, // Keep file size as 0.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700548 0,
549 expected_size) != 0) {
David Zeuthen910ec5b2013-09-26 12:10:58 -0700550 if (errno == ENOSYS || errno == EOPNOTSUPP) {
551 // If the filesystem doesn't support the fallocate, keep
552 // going. This is helpful when running unit tests on build
553 // machines with ancient filesystems and/or OSes.
554 PLOG(WARNING) << "Ignoring fallocate(2) failure";
555 } else {
556 // ENOSPC can happen (funky race though, cf. the statvfs() check
557 // above), handle it gracefully, e.g. use logging level INFO.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800558 PLOG(INFO) << "Error allocating " << expected_size << " bytes for file "
559 << path.value();
David Zeuthen910ec5b2013-09-26 12:10:58 -0700560 if (unlink(path.value().c_str()) != 0) {
561 PLOG(ERROR) << "Error deleting file with path " << path.value();
562 }
563 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700564 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700565 }
566
Alex Deymoc00c98a2015-03-17 17:38:00 -0700567 string decimal_size = std::to_string(expected_size);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800568 if (fsetxattr(fd,
569 kCrosP2PFileSizeXAttrName,
570 decimal_size.c_str(),
571 decimal_size.size(),
572 0) != 0) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700573 PLOG(ERROR) << "Error setting xattr " << path.value();
574 return false;
575 }
576 }
577
578 return true;
579}
580
581FilePath P2PManagerImpl::FileGetPath(const string& file_id) {
582 struct stat statbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700583 FilePath path;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700584
585 path = GetPath(file_id, kVisible);
586 if (stat(path.value().c_str(), &statbuf) == 0) {
587 return path;
588 }
589
590 path = GetPath(file_id, kNonVisible);
591 if (stat(path.value().c_str(), &statbuf) == 0) {
592 return path;
593 }
594
595 path.clear();
596 return path;
597}
598
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800599bool P2PManagerImpl::FileGetVisible(const string& file_id, bool* out_result) {
Alex Deymof329b932014-10-30 01:37:48 -0700600 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700601 if (path.empty()) {
602 LOG(ERROR) << "No file for id " << file_id;
603 return false;
604 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700605 if (out_result != nullptr)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700606 *out_result = path.MatchesExtension(kP2PExtension);
607 return true;
608}
609
610bool P2PManagerImpl::FileMakeVisible(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700611 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700612 if (path.empty()) {
613 LOG(ERROR) << "No file for id " << file_id;
614 return false;
615 }
616
617 // Already visible?
618 if (path.MatchesExtension(kP2PExtension))
619 return true;
620
621 LOG_ASSERT(path.MatchesExtension(kTmpExtension));
Alex Deymof329b932014-10-30 01:37:48 -0700622 FilePath new_path = path.RemoveExtension();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700623 LOG_ASSERT(new_path.MatchesExtension(kP2PExtension));
624 if (rename(path.value().c_str(), new_path.value().c_str()) != 0) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800625 PLOG(ERROR) << "Error renaming " << path.value() << " to "
626 << new_path.value();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700627 return false;
628 }
629
630 return true;
631}
632
633ssize_t P2PManagerImpl::FileGetSize(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700634 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700635 if (path.empty())
636 return -1;
637
Gabe Blacka77939e2014-09-09 23:35:08 -0700638 return utils::FileSize(path.value());
David Zeuthen27a48bc2013-08-06 12:06:29 -0700639}
640
641ssize_t P2PManagerImpl::FileGetExpectedSize(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700642 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700643 if (path.empty())
644 return -1;
645
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800646 char ea_value[64] = {0};
David Zeuthen27a48bc2013-08-06 12:06:29 -0700647 ssize_t ea_size;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800648 ea_size = getxattr(path.value().c_str(),
649 kCrosP2PFileSizeXAttrName,
650 &ea_value,
651 sizeof(ea_value) - 1);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700652 if (ea_size == -1) {
653 PLOG(ERROR) << "Error calling getxattr() on file " << path.value();
654 return -1;
655 }
656
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700657 char* endp = nullptr;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700658 long long int val = strtoll(ea_value, &endp, 0); // NOLINT(runtime/int)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700659 if (*endp != '\0') {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800660 LOG(ERROR) << "Error parsing the value '" << ea_value << "' of the xattr "
661 << kCrosP2PFileSizeXAttrName << " as an integer";
David Zeuthen27a48bc2013-08-06 12:06:29 -0700662 return -1;
663 }
664
665 return val;
666}
667
668int P2PManagerImpl::CountSharedFiles() {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700669 int num_files = 0;
670
Alex Deymof329b932014-10-30 01:37:48 -0700671 FilePath p2p_dir = configuration_->GetP2PDir();
Alex Deymo454b7982015-07-10 10:49:29 -0700672 const string ext_visible = GetExt(kVisible);
673 const string ext_non_visible = GetExt(kNonVisible);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700674
Alex Deymo454b7982015-07-10 10:49:29 -0700675 base::FileEnumerator dir(p2p_dir, false, base::FileEnumerator::FILES);
676 for (FilePath name = dir.Next(); !name.empty(); name = dir.Next()) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800677 if (base::EndsWith(
678 name.value(), ext_visible, base::CompareCase::SENSITIVE) ||
679 base::EndsWith(
680 name.value(), ext_non_visible, base::CompareCase::SENSITIVE)) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700681 num_files += 1;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800682 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700683 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700684
685 return num_files;
686}
687
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700688void P2PManagerImpl::ScheduleEnabledStatusChange() {
689 if (waiting_for_enabled_status_change_)
690 return;
Gilad Arnoldccd09572014-10-27 13:37:50 -0700691
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800692 Callback<void(EvalStatus, const bool&)> callback =
693 Bind(&P2PManagerImpl::OnEnabledStatusChange, base::Unretained(this));
694 update_manager_->AsyncPolicyRequest(
695 callback, &Policy::P2PEnabledChanged, is_enabled_);
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700696 waiting_for_enabled_status_change_ = true;
Gilad Arnoldccd09572014-10-27 13:37:50 -0700697}
698
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700699void P2PManagerImpl::OnEnabledStatusChange(EvalStatus status,
700 const bool& result) {
701 waiting_for_enabled_status_change_ = false;
702
703 if (status == EvalStatus::kSucceeded) {
704 if (result == is_enabled_) {
705 LOG(WARNING) << "P2P enabled status did not change, which means that it "
706 "is permanent; not scheduling further checks.";
707 waiting_for_enabled_status_change_ = true;
708 return;
709 }
710
711 is_enabled_ = result;
712
713 // If P2P is running but shouldn't be, make sure it isn't.
714 if (may_be_running_ && !is_enabled_ && !EnsureP2PNotRunning()) {
715 LOG(WARNING) << "Failed to stop P2P service.";
716 }
717 } else {
718 LOG(WARNING)
719 << "P2P enabled tracking failed (possibly timed out); retrying.";
720 }
721
722 ScheduleEnabledStatusChange();
723}
724
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800725P2PManager* P2PManager::Construct(Configuration* configuration,
726 ClockInterface* clock,
727 UpdateManager* update_manager,
728 const string& file_extension,
729 const int num_files_to_keep,
730 const TimeDelta& max_file_age) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700731 return new P2PManagerImpl(configuration,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500732 clock,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700733 update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700734 file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500735 num_files_to_keep,
736 max_file_age);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700737}
738
739} // namespace chromeos_update_engine