blob: b1b44389cbf8909cd4234950aa022f76bf1c2a83 [file] [log] [blame]
David Zeuthen27a48bc2013-08-06 12:06:29 -07001// Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Alex Vakulenko072359c2014-07-18 11:41:07 -07005// This provides access to timestamps with nanosecond resolution in
David Zeuthen27a48bc2013-08-06 12:06:29 -07006// struct stat, See NOTES in stat(2) for details.
7#ifndef _BSD_SOURCE
8#define _BSD_SOURCE
9#endif
10
11#include "update_engine/p2p_manager.h"
12
13#include <attr/xattr.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070014#include <errno.h>
15#include <fcntl.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070016#include <linux/falloc.h>
17#include <signal.h>
18#include <string.h>
19#include <sys/stat.h>
20#include <sys/statvfs.h>
21#include <sys/types.h>
22#include <unistd.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070023
Alex Vakulenkod2779df2014-06-16 13:19:00 -070024#include <algorithm>
David Zeuthen27a48bc2013-08-06 12:06:29 -070025#include <map>
Ben Chan02f7c1d2014-10-18 15:18:02 -070026#include <memory>
David Zeuthen27a48bc2013-08-06 12:06:29 -070027#include <utility>
28#include <vector>
29
Gilad Arnold4a0321b2014-10-28 15:57:30 -070030#include <base/bind.h>
Alex Deymo454b7982015-07-10 10:49:29 -070031#include <base/files/file_enumerator.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070032#include <base/files/file_path.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070033#include <base/logging.h>
Alex Deymo454b7982015-07-10 10:49:29 -070034#include <base/strings/string_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070035#include <base/strings/stringprintf.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070036
Alex Deymo44666f92014-07-22 20:29:24 -070037#include "update_engine/glib_utils.h"
Alex Deymo29b81532015-07-09 11:51:49 -070038#include "update_engine/subprocess.h"
Gilad Arnold4a0321b2014-10-28 15:57:30 -070039#include "update_engine/update_manager/policy.h"
40#include "update_engine/update_manager/update_manager.h"
David Zeuthen27a48bc2013-08-06 12:06:29 -070041#include "update_engine/utils.h"
42
Gilad Arnold4a0321b2014-10-28 15:57:30 -070043using base::Bind;
44using base::Callback;
David Zeuthen27a48bc2013-08-06 12:06:29 -070045using base::FilePath;
46using base::StringPrintf;
47using base::Time;
48using base::TimeDelta;
Alex Deymo29b81532015-07-09 11:51:49 -070049using chromeos::MessageLoop;
Gilad Arnold4a0321b2014-10-28 15:57:30 -070050using chromeos_update_manager::EvalStatus;
51using chromeos_update_manager::Policy;
52using chromeos_update_manager::UpdateManager;
David Zeuthen27a48bc2013-08-06 12:06:29 -070053using std::map;
54using std::pair;
55using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070056using std::unique_ptr;
David Zeuthen27a48bc2013-08-06 12:06:29 -070057using std::vector;
58
59namespace chromeos_update_engine {
60
61namespace {
62
63// The default p2p directory.
64const char kDefaultP2PDir[] = "/var/cache/p2p";
65
66// The p2p xattr used for conveying the final size of a file - see the
67// p2p ddoc for details.
68const char kCrosP2PFileSizeXAttrName[] = "user.cros-p2p-filesize";
69
Alex Vakulenkod2779df2014-06-16 13:19:00 -070070} // namespace
David Zeuthen27a48bc2013-08-06 12:06:29 -070071
72// The default P2PManager::Configuration implementation.
73class ConfigurationImpl : public P2PManager::Configuration {
Alex Vakulenkod2779df2014-06-16 13:19:00 -070074 public:
David Zeuthen27a48bc2013-08-06 12:06:29 -070075 ConfigurationImpl() {}
76
Alex Deymo610277e2014-11-11 21:18:11 -080077 FilePath GetP2PDir() override {
Alex Deymof329b932014-10-30 01:37:48 -070078 return FilePath(kDefaultP2PDir);
David Zeuthen27a48bc2013-08-06 12:06:29 -070079 }
80
Alex Deymo610277e2014-11-11 21:18:11 -080081 vector<string> GetInitctlArgs(bool is_start) override {
David Zeuthen27a48bc2013-08-06 12:06:29 -070082 vector<string> args;
83 args.push_back("initctl");
84 args.push_back(is_start ? "start" : "stop");
85 args.push_back("p2p");
86 return args;
87 }
88
Alex Deymo610277e2014-11-11 21:18:11 -080089 vector<string> GetP2PClientArgs(const string &file_id,
90 size_t minimum_size) override {
David Zeuthen27a48bc2013-08-06 12:06:29 -070091 vector<string> args;
92 args.push_back("p2p-client");
93 args.push_back(string("--get-url=") + file_id);
Alex Deymof329b932014-10-30 01:37:48 -070094 args.push_back(StringPrintf("--minimum-size=%zu", minimum_size));
David Zeuthen27a48bc2013-08-06 12:06:29 -070095 return args;
96 }
97
Alex Vakulenkod2779df2014-06-16 13:19:00 -070098 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -070099 DISALLOW_COPY_AND_ASSIGN(ConfigurationImpl);
100};
101
102// The default P2PManager implementation.
103class P2PManagerImpl : public P2PManager {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700104 public:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700105 P2PManagerImpl(Configuration *configuration,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500106 ClockInterface *clock,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700107 UpdateManager* update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700108 const string& file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500109 const int num_files_to_keep,
Alex Deymo29b81532015-07-09 11:51:49 -0700110 const TimeDelta& max_file_age);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700111
112 // P2PManager methods.
Alex Deymo610277e2014-11-11 21:18:11 -0800113 void SetDevicePolicy(const policy::DevicePolicy* device_policy) override;
114 bool IsP2PEnabled() override;
115 bool EnsureP2PRunning() override;
116 bool EnsureP2PNotRunning() override;
117 bool PerformHousekeeping() override;
118 void LookupUrlForFile(const string& file_id,
119 size_t minimum_size,
120 TimeDelta max_time_to_wait,
121 LookupCallback callback) override;
122 bool FileShare(const string& file_id,
123 size_t expected_size) override;
124 FilePath FileGetPath(const string& file_id) override;
125 ssize_t FileGetSize(const string& file_id) override;
126 ssize_t FileGetExpectedSize(const string& file_id) override;
127 bool FileGetVisible(const string& file_id,
128 bool *out_result) override;
129 bool FileMakeVisible(const string& file_id) override;
130 int CountSharedFiles() override;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700131
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700132 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700133 // Enumeration for specifying visibility.
134 enum Visibility {
135 kVisible,
136 kNonVisible
137 };
138
139 // Returns "." + |file_extension_| + ".p2p" if |visibility| is
140 // |kVisible|. Returns the same concatenated with ".tmp" otherwise.
141 string GetExt(Visibility visibility);
142
143 // Gets the on-disk path for |file_id| depending on if the file
144 // is visible or not.
Alex Deymof329b932014-10-30 01:37:48 -0700145 FilePath GetPath(const string& file_id, Visibility visibility);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700146
147 // Utility function used by EnsureP2PRunning() and EnsureP2PNotRunning().
148 bool EnsureP2P(bool should_be_running);
149
David Zeuthen41f2cf52014-11-05 12:29:45 -0500150 // Utility function to delete a file given by |path| and log the
151 // path as well as |reason|. Returns false on failure.
Alex Deymo29b81532015-07-09 11:51:49 -0700152 bool DeleteP2PFile(const FilePath& path, const string& reason);
David Zeuthen41f2cf52014-11-05 12:29:45 -0500153
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700154 // Schedules an async request for tracking changes in P2P enabled status.
155 void ScheduleEnabledStatusChange();
156
157 // An async callback used by the above.
158 void OnEnabledStatusChange(EvalStatus status, const bool& result);
159
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700160 // The device policy being used or null if no policy is being used.
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700161 const policy::DevicePolicy* device_policy_ = nullptr;
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700162
David Zeuthen27a48bc2013-08-06 12:06:29 -0700163 // Configuration object.
Ben Chan02f7c1d2014-10-18 15:18:02 -0700164 unique_ptr<Configuration> configuration_;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700165
David Zeuthen41f2cf52014-11-05 12:29:45 -0500166 // Object for telling the time.
167 ClockInterface* clock_;
168
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700169 // A pointer to the global Update Manager.
170 UpdateManager* update_manager_;
171
David Zeuthen27a48bc2013-08-06 12:06:29 -0700172 // A short string unique to the application (for example "cros_au")
173 // used to mark a file as being owned by a particular application.
174 const string file_extension_;
175
176 // If non-zero, this number denotes how many files in /var/cache/p2p
177 // owned by the application (cf. |file_extension_|) to keep after
178 // performing housekeeping.
179 const int num_files_to_keep_;
180
David Zeuthen41f2cf52014-11-05 12:29:45 -0500181 // If non-zero, files older than this will not be kept after
182 // performing housekeeping.
Alex Deymo29b81532015-07-09 11:51:49 -0700183 const TimeDelta max_file_age_;
David Zeuthen41f2cf52014-11-05 12:29:45 -0500184
David Zeuthen27a48bc2013-08-06 12:06:29 -0700185 // The string ".p2p".
186 static const char kP2PExtension[];
187
188 // The string ".tmp".
189 static const char kTmpExtension[];
190
Gilad Arnoldccd09572014-10-27 13:37:50 -0700191 // Whether P2P service may be running; initially, we assume it may be.
192 bool may_be_running_ = true;
193
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700194 // The current known enabled status of the P2P feature (initialized lazily),
195 // and whether an async status check has been scheduled.
196 bool is_enabled_;
197 bool waiting_for_enabled_status_change_ = false;
198
David Zeuthen27a48bc2013-08-06 12:06:29 -0700199 DISALLOW_COPY_AND_ASSIGN(P2PManagerImpl);
200};
201
202const char P2PManagerImpl::kP2PExtension[] = ".p2p";
203
204const char P2PManagerImpl::kTmpExtension[] = ".tmp";
205
206P2PManagerImpl::P2PManagerImpl(Configuration *configuration,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500207 ClockInterface *clock,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700208 UpdateManager* update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700209 const string& file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500210 const int num_files_to_keep,
Alex Deymo29b81532015-07-09 11:51:49 -0700211 const TimeDelta& max_file_age)
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700212 : clock_(clock),
213 update_manager_(update_manager),
David Zeuthen27a48bc2013-08-06 12:06:29 -0700214 file_extension_(file_extension),
David Zeuthen41f2cf52014-11-05 12:29:45 -0500215 num_files_to_keep_(num_files_to_keep),
216 max_file_age_(max_file_age) {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700217 configuration_.reset(configuration != nullptr ? configuration :
David Zeuthen27a48bc2013-08-06 12:06:29 -0700218 new ConfigurationImpl());
219}
220
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700221void P2PManagerImpl::SetDevicePolicy(
222 const policy::DevicePolicy* device_policy) {
223 device_policy_ = device_policy;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700224}
225
226bool P2PManagerImpl::IsP2PEnabled() {
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700227 if (!waiting_for_enabled_status_change_) {
228 // Get and store an initial value.
229 if (update_manager_->PolicyRequest(&Policy::P2PEnabled, &is_enabled_) ==
230 EvalStatus::kFailed) {
231 is_enabled_ = false;
232 LOG(ERROR) << "Querying P2P enabled status failed, disabling.";
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400233 }
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700234
235 // Track future changes (async).
236 ScheduleEnabledStatusChange();
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400237 }
238
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700239 return is_enabled_;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700240}
241
242bool P2PManagerImpl::EnsureP2P(bool should_be_running) {
Alex Deymo29b81532015-07-09 11:51:49 -0700243 int return_code = 0;
244 string output;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700245
Gilad Arnoldccd09572014-10-27 13:37:50 -0700246 may_be_running_ = true; // Unless successful, we must be conservative.
247
David Zeuthen27a48bc2013-08-06 12:06:29 -0700248 vector<string> args = configuration_->GetInitctlArgs(should_be_running);
Alex Deymo29b81532015-07-09 11:51:49 -0700249 if (!Subprocess::SynchronousExec(args, &return_code, &output)) {
250 LOG(ERROR) << "Error spawning " << utils::StringVectorToString(args);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700251 return false;
252 }
253
Gilad Arnoldccd09572014-10-27 13:37:50 -0700254 // If initctl(8) does not exit normally (exit status other than zero), ensure
255 // that the error message is not benign by scanning stderr; this is a
256 // necessity because initctl does not offer actions such as "start if not
257 // running" or "stop if running".
David Zeuthen27a48bc2013-08-06 12:06:29 -0700258 // TODO(zeuthen,chromium:277051): Avoid doing this.
Alex Deymo29b81532015-07-09 11:51:49 -0700259 if (return_code != 0) {
260 const char *expected_error_message = should_be_running ?
Gilad Arnoldccd09572014-10-27 13:37:50 -0700261 "initctl: Job is already running: p2p\n" :
262 "initctl: Unknown instance \n";
Alex Deymo29b81532015-07-09 11:51:49 -0700263 if (output != expected_error_message)
Gilad Arnoldccd09572014-10-27 13:37:50 -0700264 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700265 }
266
Gilad Arnoldccd09572014-10-27 13:37:50 -0700267 may_be_running_ = should_be_running; // Successful after all.
268 return true;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700269}
270
271bool P2PManagerImpl::EnsureP2PRunning() {
272 return EnsureP2P(true);
273}
274
275bool P2PManagerImpl::EnsureP2PNotRunning() {
276 return EnsureP2P(false);
277}
278
279// Returns True if the timestamp in the first pair is greater than the
280// timestamp in the latter. If used with std::sort() this will yield a
281// sequence of elements where newer (high timestamps) elements precede
282// older ones (low timestamps).
283static bool MatchCompareFunc(const pair<FilePath, Time>& a,
284 const pair<FilePath, Time>& b) {
285 return a.second > b.second;
286}
287
288string P2PManagerImpl::GetExt(Visibility visibility) {
289 string ext = string(".") + file_extension_ + kP2PExtension;
290 switch (visibility) {
291 case kVisible:
292 break;
293 case kNonVisible:
294 ext += kTmpExtension;
295 break;
296 // Don't add a default case to let the compiler warn about newly
297 // added enum values.
298 }
299 return ext;
300}
301
302FilePath P2PManagerImpl::GetPath(const string& file_id, Visibility visibility) {
303 return configuration_->GetP2PDir().Append(file_id + GetExt(visibility));
304}
305
David Zeuthen41f2cf52014-11-05 12:29:45 -0500306bool P2PManagerImpl::DeleteP2PFile(const FilePath& path,
Alex Deymo29b81532015-07-09 11:51:49 -0700307 const string& reason) {
David Zeuthen41f2cf52014-11-05 12:29:45 -0500308 LOG(INFO) << "Deleting p2p file " << path.value()
309 << " (reason: " << reason << ")";
310 if (unlink(path.value().c_str()) != 0) {
311 PLOG(ERROR) << "Error deleting p2p file " << path.value();
312 return false;
313 }
314 return true;
315}
David Zeuthen27a48bc2013-08-06 12:06:29 -0700316
David Zeuthen41f2cf52014-11-05 12:29:45 -0500317
318bool 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()) {
330 if (!(base::EndsWith(name.value(), ext_visible, true) ||
331 base::EndsWith(name.value(), ext_non_visible, true)))
David Zeuthen27a48bc2013-08-06 12:06:29 -0700332 continue;
333
Alex Deymo454b7982015-07-10 10:49:29 -0700334 Time time = dir.GetInfo().GetLastModifiedTime();
David Zeuthen41f2cf52014-11-05 12:29:45 -0500335
336 // If instructed to keep only files younger than a given age
337 // (|max_file_age_| != 0), delete files satisfying this criteria
338 // right now. Otherwise add it to a list we'll consider for later.
Alex Deymo29b81532015-07-09 11:51:49 -0700339 if (clock_ != nullptr && max_file_age_ != TimeDelta() &&
David Zeuthen41f2cf52014-11-05 12:29:45 -0500340 clock_->GetWallclockTime() - time > max_file_age_) {
Alex Deymo454b7982015-07-10 10:49:29 -0700341 if (!DeleteP2PFile(name, "file too old"))
David Zeuthen41f2cf52014-11-05 12:29:45 -0500342 deletion_failed = true;
343 } else {
Alex Deymo454b7982015-07-10 10:49:29 -0700344 matches.push_back(std::make_pair(name, time));
David Zeuthen41f2cf52014-11-05 12:29:45 -0500345 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700346 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700347
David Zeuthen41f2cf52014-11-05 12:29:45 -0500348 // If instructed to only keep N files (|max_files_to_keep_ != 0),
349 // sort list of matches, newest (biggest time) to oldest (lowest
350 // time). Then delete starting at element |num_files_to_keep_|.
351 if (num_files_to_keep_ > 0) {
352 std::sort(matches.begin(), matches.end(), MatchCompareFunc);
353 vector<pair<FilePath, Time>>::const_iterator i;
354 for (i = matches.begin() + num_files_to_keep_; i < matches.end(); ++i) {
355 if (!DeleteP2PFile(i->first, "too many files"))
356 deletion_failed = true;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700357 }
358 }
359
David Zeuthen41f2cf52014-11-05 12:29:45 -0500360 return !deletion_failed;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700361}
362
363// Helper class for implementing LookupUrlForFile().
364class LookupData {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700365 public:
366 explicit LookupData(P2PManager::LookupCallback callback)
Alex Deymo29b81532015-07-09 11:51:49 -0700367 : callback_(callback) {}
David Zeuthen27a48bc2013-08-06 12:06:29 -0700368
369 ~LookupData() {
Alex Deymo29b81532015-07-09 11:51:49 -0700370 if (timeout_task_ != MessageLoop::kTaskIdNull)
371 MessageLoop::current()->CancelTask(timeout_task_);
Alex Deymo461b2592015-07-24 20:10:52 -0700372 if (child_pid_)
373 Subprocess::Get().KillExec(child_pid_);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700374 }
375
Alex Deymo29b81532015-07-09 11:51:49 -0700376 void InitiateLookup(const vector<string>& cmd, TimeDelta timeout) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700377 // NOTE: if we fail early (i.e. in this method), we need to schedule
378 // an idle to report the error. This is because we guarantee that
Alex Deymo29b81532015-07-09 11:51:49 -0700379 // the callback is always called from the message loop (this
David Zeuthen27a48bc2013-08-06 12:06:29 -0700380 // guarantee is useful for testing).
381
Alex Deymo29b81532015-07-09 11:51:49 -0700382 // We expect to run just "p2p-client" and find it in the path.
Alex Deymo461b2592015-07-24 20:10:52 -0700383 child_pid_ = Subprocess::Get().ExecFlags(
384 cmd, Subprocess::kSearchPath,
385 Bind(&LookupData::OnLookupDone, base::Unretained(this)));
Alex Deymo29b81532015-07-09 11:51:49 -0700386
Alex Deymo461b2592015-07-24 20:10:52 -0700387 if (!child_pid_) {
Alex Deymo29b81532015-07-09 11:51:49 -0700388 LOG(ERROR) << "Error spawning " << utils::StringVectorToString(cmd);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700389 ReportErrorAndDeleteInIdle();
390 return;
391 }
392
Alex Deymo29b81532015-07-09 11:51:49 -0700393 if (timeout > TimeDelta()) {
394 timeout_task_ = MessageLoop::current()->PostDelayedTask(
395 FROM_HERE,
396 Bind(&LookupData::OnTimeout, base::Unretained(this)),
397 timeout);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700398 }
399 }
400
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700401 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700402 void ReportErrorAndDeleteInIdle() {
Alex Deymo29b81532015-07-09 11:51:49 -0700403 MessageLoop::current()->PostTask(FROM_HERE, Bind(
404 &LookupData::OnIdleForReportErrorAndDelete,
405 base::Unretained(this)));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700406 }
407
Alex Deymo29b81532015-07-09 11:51:49 -0700408 void OnIdleForReportErrorAndDelete() {
409 ReportError();
410 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700411 }
412
413 void IssueCallback(const string& url) {
414 if (!callback_.is_null())
415 callback_.Run(url);
416 }
417
418 void ReportError() {
419 if (reported_)
420 return;
421 IssueCallback("");
422 reported_ = true;
423 }
424
Alex Deymo29b81532015-07-09 11:51:49 -0700425 void ReportSuccess(const string& output) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700426 if (reported_)
427 return;
Alex Deymo29b81532015-07-09 11:51:49 -0700428 string url = output;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700429 size_t newline_pos = url.find('\n');
430 if (newline_pos != string::npos)
431 url.resize(newline_pos);
432
433 // Since p2p-client(1) is constructing this URL itself strictly
434 // speaking there's no need to validate it... but, anyway, can't
435 // hurt.
436 if (url.compare(0, 7, "http://") == 0) {
437 IssueCallback(url);
438 } else {
439 LOG(ERROR) << "p2p URL '" << url << "' does not look right. Ignoring.";
440 ReportError();
441 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700442 reported_ = true;
443 }
444
Alex Deymo461b2592015-07-24 20:10:52 -0700445 void OnLookupDone(int return_code, const string& output) {
446 child_pid_ = 0;
Alex Deymo29b81532015-07-09 11:51:49 -0700447 if (return_code != 0) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700448 LOG(INFO) << "Child exited with non-zero exit code "
Alex Deymo29b81532015-07-09 11:51:49 -0700449 << return_code;
Alex Deymo461b2592015-07-24 20:10:52 -0700450 ReportError();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700451 } else {
Alex Deymo461b2592015-07-24 20:10:52 -0700452 ReportSuccess(output);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700453 }
Alex Deymo461b2592015-07-24 20:10:52 -0700454 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700455 }
456
Alex Deymo29b81532015-07-09 11:51:49 -0700457 void OnTimeout() {
458 timeout_task_ = MessageLoop::kTaskIdNull;
459 ReportError();
460 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700461 }
462
463 P2PManager::LookupCallback callback_;
Alex Deymo29b81532015-07-09 11:51:49 -0700464
465 // The Subprocess tag of the running process. A value of 0 means that the
466 // process is not running.
Alex Deymo461b2592015-07-24 20:10:52 -0700467 pid_t child_pid_{0};
Alex Deymo29b81532015-07-09 11:51:49 -0700468
469 // The timeout task_id we are waiting on, if any.
470 MessageLoop::TaskId timeout_task_{MessageLoop::kTaskIdNull};
471
472 bool reported_{false};
David Zeuthen27a48bc2013-08-06 12:06:29 -0700473};
474
475void P2PManagerImpl::LookupUrlForFile(const string& file_id,
476 size_t minimum_size,
477 TimeDelta max_time_to_wait,
478 LookupCallback callback) {
479 LookupData *lookup_data = new LookupData(callback);
480 string file_id_with_ext = file_id + "." + file_extension_;
481 vector<string> args = configuration_->GetP2PClientArgs(file_id_with_ext,
482 minimum_size);
Alex Deymo29b81532015-07-09 11:51:49 -0700483 lookup_data->InitiateLookup(args, max_time_to_wait);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700484}
485
486bool P2PManagerImpl::FileShare(const string& file_id,
487 size_t expected_size) {
488 // Check if file already exist.
Alex Deymof329b932014-10-30 01:37:48 -0700489 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700490 if (!path.empty()) {
491 // File exists - double check its expected size though.
492 ssize_t file_expected_size = FileGetExpectedSize(file_id);
493 if (file_expected_size == -1 ||
494 static_cast<size_t>(file_expected_size) != expected_size) {
495 LOG(ERROR) << "Existing p2p file " << path.value()
496 << " with expected_size=" << file_expected_size
497 << " does not match the passed in"
498 << " expected_size=" << expected_size;
499 return false;
500 }
501 return true;
502 }
503
504 // Before creating the file, bail if statvfs(3) indicates that at
505 // least twice the size is not available in P2P_DIR.
506 struct statvfs statvfsbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700507 FilePath p2p_dir = configuration_->GetP2PDir();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700508 if (statvfs(p2p_dir.value().c_str(), &statvfsbuf) != 0) {
509 PLOG(ERROR) << "Error calling statvfs() for dir " << p2p_dir.value();
510 return false;
511 }
512 size_t free_bytes =
513 static_cast<size_t>(statvfsbuf.f_bsize) * statvfsbuf.f_bavail;
514 if (free_bytes < 2 * expected_size) {
515 // This can easily happen and is worth reporting.
516 LOG(INFO) << "Refusing to allocate p2p file of " << expected_size
517 << " bytes since the directory " << p2p_dir.value()
518 << " only has " << free_bytes
519 << " bytes available and this is less than twice the"
520 << " requested size.";
521 return false;
522 }
523
524 // Okie-dokey looks like enough space is available - create the file.
525 path = GetPath(file_id, kNonVisible);
526 int fd = open(path.value().c_str(), O_CREAT | O_RDWR, 0644);
527 if (fd == -1) {
528 PLOG(ERROR) << "Error creating file with path " << path.value();
529 return false;
530 }
531 ScopedFdCloser fd_closer(&fd);
532
533 // If the final size is known, allocate the file (e.g. reserve disk
534 // space) and set the user.cros-p2p-filesize xattr.
535 if (expected_size != 0) {
536 if (fallocate(fd,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700537 FALLOC_FL_KEEP_SIZE, // Keep file size as 0.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700538 0,
539 expected_size) != 0) {
David Zeuthen910ec5b2013-09-26 12:10:58 -0700540 if (errno == ENOSYS || errno == EOPNOTSUPP) {
541 // If the filesystem doesn't support the fallocate, keep
542 // going. This is helpful when running unit tests on build
543 // machines with ancient filesystems and/or OSes.
544 PLOG(WARNING) << "Ignoring fallocate(2) failure";
545 } else {
546 // ENOSPC can happen (funky race though, cf. the statvfs() check
547 // above), handle it gracefully, e.g. use logging level INFO.
548 PLOG(INFO) << "Error allocating " << expected_size
549 << " bytes for file " << path.value();
550 if (unlink(path.value().c_str()) != 0) {
551 PLOG(ERROR) << "Error deleting file with path " << path.value();
552 }
553 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700554 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700555 }
556
Alex Deymof329b932014-10-30 01:37:48 -0700557 string decimal_size = StringPrintf("%zu", expected_size);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700558 if (fsetxattr(fd, kCrosP2PFileSizeXAttrName,
559 decimal_size.c_str(), decimal_size.size(), 0) != 0) {
560 PLOG(ERROR) << "Error setting xattr " << path.value();
561 return false;
562 }
563 }
564
565 return true;
566}
567
568FilePath P2PManagerImpl::FileGetPath(const string& file_id) {
569 struct stat statbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700570 FilePath path;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700571
572 path = GetPath(file_id, kVisible);
573 if (stat(path.value().c_str(), &statbuf) == 0) {
574 return path;
575 }
576
577 path = GetPath(file_id, kNonVisible);
578 if (stat(path.value().c_str(), &statbuf) == 0) {
579 return path;
580 }
581
582 path.clear();
583 return path;
584}
585
586bool P2PManagerImpl::FileGetVisible(const string& file_id,
587 bool *out_result) {
Alex Deymof329b932014-10-30 01:37:48 -0700588 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700589 if (path.empty()) {
590 LOG(ERROR) << "No file for id " << file_id;
591 return false;
592 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700593 if (out_result != nullptr)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700594 *out_result = path.MatchesExtension(kP2PExtension);
595 return true;
596}
597
598bool P2PManagerImpl::FileMakeVisible(const string& file_id) {
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 }
604
605 // Already visible?
606 if (path.MatchesExtension(kP2PExtension))
607 return true;
608
609 LOG_ASSERT(path.MatchesExtension(kTmpExtension));
Alex Deymof329b932014-10-30 01:37:48 -0700610 FilePath new_path = path.RemoveExtension();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700611 LOG_ASSERT(new_path.MatchesExtension(kP2PExtension));
612 if (rename(path.value().c_str(), new_path.value().c_str()) != 0) {
613 PLOG(ERROR) << "Error renaming " << path.value()
614 << " to " << new_path.value();
615 return false;
616 }
617
618 return true;
619}
620
621ssize_t P2PManagerImpl::FileGetSize(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700622 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700623 if (path.empty())
624 return -1;
625
Gabe Blacka77939e2014-09-09 23:35:08 -0700626 return utils::FileSize(path.value());
David Zeuthen27a48bc2013-08-06 12:06:29 -0700627}
628
629ssize_t P2PManagerImpl::FileGetExpectedSize(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700630 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700631 if (path.empty())
632 return -1;
633
634 char ea_value[64] = { 0 };
635 ssize_t ea_size;
636 ea_size = getxattr(path.value().c_str(), kCrosP2PFileSizeXAttrName,
637 &ea_value, sizeof(ea_value) - 1);
638 if (ea_size == -1) {
639 PLOG(ERROR) << "Error calling getxattr() on file " << path.value();
640 return -1;
641 }
642
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700643 char* endp = nullptr;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700644 long long int val = strtoll(ea_value, &endp, 0); // NOLINT(runtime/int)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700645 if (*endp != '\0') {
646 LOG(ERROR) << "Error parsing the value '" << ea_value
647 << "' of the xattr " << kCrosP2PFileSizeXAttrName
648 << " as an integer";
649 return -1;
650 }
651
652 return val;
653}
654
655int P2PManagerImpl::CountSharedFiles() {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700656 int num_files = 0;
657
Alex Deymof329b932014-10-30 01:37:48 -0700658 FilePath p2p_dir = configuration_->GetP2PDir();
Alex Deymo454b7982015-07-10 10:49:29 -0700659 const string ext_visible = GetExt(kVisible);
660 const string ext_non_visible = GetExt(kNonVisible);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700661
Alex Deymo454b7982015-07-10 10:49:29 -0700662 base::FileEnumerator dir(p2p_dir, false, base::FileEnumerator::FILES);
663 for (FilePath name = dir.Next(); !name.empty(); name = dir.Next()) {
664 if (base::EndsWith(name.value(), ext_visible, true) ||
665 base::EndsWith(name.value(), ext_non_visible, true))
David Zeuthen27a48bc2013-08-06 12:06:29 -0700666 num_files += 1;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700667 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700668
669 return num_files;
670}
671
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700672void P2PManagerImpl::ScheduleEnabledStatusChange() {
673 if (waiting_for_enabled_status_change_)
674 return;
Gilad Arnoldccd09572014-10-27 13:37:50 -0700675
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700676 Callback<void(EvalStatus, const bool&)> callback = Bind(
677 &P2PManagerImpl::OnEnabledStatusChange, base::Unretained(this));
678 update_manager_->AsyncPolicyRequest(callback, &Policy::P2PEnabledChanged,
679 is_enabled_);
680 waiting_for_enabled_status_change_ = true;
Gilad Arnoldccd09572014-10-27 13:37:50 -0700681}
682
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700683void P2PManagerImpl::OnEnabledStatusChange(EvalStatus status,
684 const bool& result) {
685 waiting_for_enabled_status_change_ = false;
686
687 if (status == EvalStatus::kSucceeded) {
688 if (result == is_enabled_) {
689 LOG(WARNING) << "P2P enabled status did not change, which means that it "
690 "is permanent; not scheduling further checks.";
691 waiting_for_enabled_status_change_ = true;
692 return;
693 }
694
695 is_enabled_ = result;
696
697 // If P2P is running but shouldn't be, make sure it isn't.
698 if (may_be_running_ && !is_enabled_ && !EnsureP2PNotRunning()) {
699 LOG(WARNING) << "Failed to stop P2P service.";
700 }
701 } else {
702 LOG(WARNING)
703 << "P2P enabled tracking failed (possibly timed out); retrying.";
704 }
705
706 ScheduleEnabledStatusChange();
707}
708
709P2PManager* P2PManager::Construct(
710 Configuration *configuration,
711 ClockInterface *clock,
712 UpdateManager* update_manager,
713 const string& file_extension,
714 const int num_files_to_keep,
Alex Deymo29b81532015-07-09 11:51:49 -0700715 const TimeDelta& max_file_age) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700716 return new P2PManagerImpl(configuration,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500717 clock,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700718 update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700719 file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500720 num_files_to_keep,
721 max_file_age);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700722}
723
724} // namespace chromeos_update_engine