blob: daebe91403943237d371013695df8247c2d331bc [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 Deymo29b81532015-07-09 11:51:49 -070037#include "update_engine/subprocess.h"
Gilad Arnold4a0321b2014-10-28 15:57:30 -070038#include "update_engine/update_manager/policy.h"
39#include "update_engine/update_manager/update_manager.h"
David Zeuthen27a48bc2013-08-06 12:06:29 -070040#include "update_engine/utils.h"
41
Gilad Arnold4a0321b2014-10-28 15:57:30 -070042using base::Bind;
43using base::Callback;
David Zeuthen27a48bc2013-08-06 12:06:29 -070044using base::FilePath;
45using base::StringPrintf;
46using base::Time;
47using base::TimeDelta;
Alex Deymo29b81532015-07-09 11:51:49 -070048using chromeos::MessageLoop;
Gilad Arnold4a0321b2014-10-28 15:57:30 -070049using chromeos_update_manager::EvalStatus;
50using chromeos_update_manager::Policy;
51using chromeos_update_manager::UpdateManager;
David Zeuthen27a48bc2013-08-06 12:06:29 -070052using std::map;
53using std::pair;
54using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070055using std::unique_ptr;
David Zeuthen27a48bc2013-08-06 12:06:29 -070056using std::vector;
57
58namespace chromeos_update_engine {
59
60namespace {
61
62// The default p2p directory.
63const char kDefaultP2PDir[] = "/var/cache/p2p";
64
65// The p2p xattr used for conveying the final size of a file - see the
66// p2p ddoc for details.
67const char kCrosP2PFileSizeXAttrName[] = "user.cros-p2p-filesize";
68
Alex Vakulenkod2779df2014-06-16 13:19:00 -070069} // namespace
David Zeuthen27a48bc2013-08-06 12:06:29 -070070
71// The default P2PManager::Configuration implementation.
72class ConfigurationImpl : public P2PManager::Configuration {
Alex Vakulenkod2779df2014-06-16 13:19:00 -070073 public:
David Zeuthen27a48bc2013-08-06 12:06:29 -070074 ConfigurationImpl() {}
75
Alex Deymo610277e2014-11-11 21:18:11 -080076 FilePath GetP2PDir() override {
Alex Deymof329b932014-10-30 01:37:48 -070077 return FilePath(kDefaultP2PDir);
David Zeuthen27a48bc2013-08-06 12:06:29 -070078 }
79
Alex Deymo610277e2014-11-11 21:18:11 -080080 vector<string> GetInitctlArgs(bool is_start) override {
David Zeuthen27a48bc2013-08-06 12:06:29 -070081 vector<string> args;
82 args.push_back("initctl");
83 args.push_back(is_start ? "start" : "stop");
84 args.push_back("p2p");
85 return args;
86 }
87
Alex Deymo610277e2014-11-11 21:18:11 -080088 vector<string> GetP2PClientArgs(const string &file_id,
89 size_t minimum_size) override {
David Zeuthen27a48bc2013-08-06 12:06:29 -070090 vector<string> args;
91 args.push_back("p2p-client");
92 args.push_back(string("--get-url=") + file_id);
Alex Deymof329b932014-10-30 01:37:48 -070093 args.push_back(StringPrintf("--minimum-size=%zu", minimum_size));
David Zeuthen27a48bc2013-08-06 12:06:29 -070094 return args;
95 }
96
Alex Vakulenkod2779df2014-06-16 13:19:00 -070097 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -070098 DISALLOW_COPY_AND_ASSIGN(ConfigurationImpl);
99};
100
101// The default P2PManager implementation.
102class P2PManagerImpl : public P2PManager {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700103 public:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700104 P2PManagerImpl(Configuration *configuration,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500105 ClockInterface *clock,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700106 UpdateManager* update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700107 const string& file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500108 const int num_files_to_keep,
Alex Deymo29b81532015-07-09 11:51:49 -0700109 const TimeDelta& max_file_age);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700110
111 // P2PManager methods.
Alex Deymo610277e2014-11-11 21:18:11 -0800112 void SetDevicePolicy(const policy::DevicePolicy* device_policy) override;
113 bool IsP2PEnabled() override;
114 bool EnsureP2PRunning() override;
115 bool EnsureP2PNotRunning() override;
116 bool PerformHousekeeping() override;
117 void LookupUrlForFile(const string& file_id,
118 size_t minimum_size,
119 TimeDelta max_time_to_wait,
120 LookupCallback callback) override;
121 bool FileShare(const string& file_id,
122 size_t expected_size) override;
123 FilePath FileGetPath(const string& file_id) override;
124 ssize_t FileGetSize(const string& file_id) override;
125 ssize_t FileGetExpectedSize(const string& file_id) override;
126 bool FileGetVisible(const string& file_id,
127 bool *out_result) override;
128 bool FileMakeVisible(const string& file_id) override;
129 int CountSharedFiles() override;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700130
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700131 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700132 // Enumeration for specifying visibility.
133 enum Visibility {
134 kVisible,
135 kNonVisible
136 };
137
138 // Returns "." + |file_extension_| + ".p2p" if |visibility| is
139 // |kVisible|. Returns the same concatenated with ".tmp" otherwise.
140 string GetExt(Visibility visibility);
141
142 // Gets the on-disk path for |file_id| depending on if the file
143 // is visible or not.
Alex Deymof329b932014-10-30 01:37:48 -0700144 FilePath GetPath(const string& file_id, Visibility visibility);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700145
146 // Utility function used by EnsureP2PRunning() and EnsureP2PNotRunning().
147 bool EnsureP2P(bool should_be_running);
148
David Zeuthen41f2cf52014-11-05 12:29:45 -0500149 // Utility function to delete a file given by |path| and log the
150 // path as well as |reason|. Returns false on failure.
Alex Deymo29b81532015-07-09 11:51:49 -0700151 bool DeleteP2PFile(const FilePath& path, const string& reason);
David Zeuthen41f2cf52014-11-05 12:29:45 -0500152
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700153 // Schedules an async request for tracking changes in P2P enabled status.
154 void ScheduleEnabledStatusChange();
155
156 // An async callback used by the above.
157 void OnEnabledStatusChange(EvalStatus status, const bool& result);
158
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700159 // The device policy being used or null if no policy is being used.
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700160 const policy::DevicePolicy* device_policy_ = nullptr;
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700161
David Zeuthen27a48bc2013-08-06 12:06:29 -0700162 // Configuration object.
Ben Chan02f7c1d2014-10-18 15:18:02 -0700163 unique_ptr<Configuration> configuration_;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700164
David Zeuthen41f2cf52014-11-05 12:29:45 -0500165 // Object for telling the time.
166 ClockInterface* clock_;
167
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700168 // A pointer to the global Update Manager.
169 UpdateManager* update_manager_;
170
David Zeuthen27a48bc2013-08-06 12:06:29 -0700171 // A short string unique to the application (for example "cros_au")
172 // used to mark a file as being owned by a particular application.
173 const string file_extension_;
174
175 // If non-zero, this number denotes how many files in /var/cache/p2p
176 // owned by the application (cf. |file_extension_|) to keep after
177 // performing housekeeping.
178 const int num_files_to_keep_;
179
David Zeuthen41f2cf52014-11-05 12:29:45 -0500180 // If non-zero, files older than this will not be kept after
181 // performing housekeeping.
Alex Deymo29b81532015-07-09 11:51:49 -0700182 const TimeDelta max_file_age_;
David Zeuthen41f2cf52014-11-05 12:29:45 -0500183
David Zeuthen27a48bc2013-08-06 12:06:29 -0700184 // The string ".p2p".
185 static const char kP2PExtension[];
186
187 // The string ".tmp".
188 static const char kTmpExtension[];
189
Gilad Arnoldccd09572014-10-27 13:37:50 -0700190 // Whether P2P service may be running; initially, we assume it may be.
191 bool may_be_running_ = true;
192
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700193 // The current known enabled status of the P2P feature (initialized lazily),
194 // and whether an async status check has been scheduled.
195 bool is_enabled_;
196 bool waiting_for_enabled_status_change_ = false;
197
David Zeuthen27a48bc2013-08-06 12:06:29 -0700198 DISALLOW_COPY_AND_ASSIGN(P2PManagerImpl);
199};
200
201const char P2PManagerImpl::kP2PExtension[] = ".p2p";
202
203const char P2PManagerImpl::kTmpExtension[] = ".tmp";
204
205P2PManagerImpl::P2PManagerImpl(Configuration *configuration,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500206 ClockInterface *clock,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700207 UpdateManager* update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700208 const string& file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500209 const int num_files_to_keep,
Alex Deymo29b81532015-07-09 11:51:49 -0700210 const TimeDelta& max_file_age)
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700211 : clock_(clock),
212 update_manager_(update_manager),
David Zeuthen27a48bc2013-08-06 12:06:29 -0700213 file_extension_(file_extension),
David Zeuthen41f2cf52014-11-05 12:29:45 -0500214 num_files_to_keep_(num_files_to_keep),
215 max_file_age_(max_file_age) {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700216 configuration_.reset(configuration != nullptr ? configuration :
David Zeuthen27a48bc2013-08-06 12:06:29 -0700217 new ConfigurationImpl());
218}
219
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700220void P2PManagerImpl::SetDevicePolicy(
221 const policy::DevicePolicy* device_policy) {
222 device_policy_ = device_policy;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700223}
224
225bool P2PManagerImpl::IsP2PEnabled() {
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700226 if (!waiting_for_enabled_status_change_) {
227 // Get and store an initial value.
228 if (update_manager_->PolicyRequest(&Policy::P2PEnabled, &is_enabled_) ==
229 EvalStatus::kFailed) {
230 is_enabled_ = false;
231 LOG(ERROR) << "Querying P2P enabled status failed, disabling.";
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400232 }
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700233
234 // Track future changes (async).
235 ScheduleEnabledStatusChange();
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400236 }
237
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700238 return is_enabled_;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700239}
240
241bool P2PManagerImpl::EnsureP2P(bool should_be_running) {
Alex Deymo29b81532015-07-09 11:51:49 -0700242 int return_code = 0;
243 string output;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700244
Gilad Arnoldccd09572014-10-27 13:37:50 -0700245 may_be_running_ = true; // Unless successful, we must be conservative.
246
David Zeuthen27a48bc2013-08-06 12:06:29 -0700247 vector<string> args = configuration_->GetInitctlArgs(should_be_running);
Alex Deymo29b81532015-07-09 11:51:49 -0700248 if (!Subprocess::SynchronousExec(args, &return_code, &output)) {
249 LOG(ERROR) << "Error spawning " << utils::StringVectorToString(args);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700250 return false;
251 }
252
Gilad Arnoldccd09572014-10-27 13:37:50 -0700253 // If initctl(8) does not exit normally (exit status other than zero), ensure
254 // that the error message is not benign by scanning stderr; this is a
255 // necessity because initctl does not offer actions such as "start if not
256 // running" or "stop if running".
David Zeuthen27a48bc2013-08-06 12:06:29 -0700257 // TODO(zeuthen,chromium:277051): Avoid doing this.
Alex Deymo29b81532015-07-09 11:51:49 -0700258 if (return_code != 0) {
259 const char *expected_error_message = should_be_running ?
Gilad Arnoldccd09572014-10-27 13:37:50 -0700260 "initctl: Job is already running: p2p\n" :
261 "initctl: Unknown instance \n";
Alex Deymo29b81532015-07-09 11:51:49 -0700262 if (output != expected_error_message)
Gilad Arnoldccd09572014-10-27 13:37:50 -0700263 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700264 }
265
Gilad Arnoldccd09572014-10-27 13:37:50 -0700266 may_be_running_ = should_be_running; // Successful after all.
267 return true;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700268}
269
270bool P2PManagerImpl::EnsureP2PRunning() {
271 return EnsureP2P(true);
272}
273
274bool P2PManagerImpl::EnsureP2PNotRunning() {
275 return EnsureP2P(false);
276}
277
278// Returns True if the timestamp in the first pair is greater than the
279// timestamp in the latter. If used with std::sort() this will yield a
280// sequence of elements where newer (high timestamps) elements precede
281// older ones (low timestamps).
282static bool MatchCompareFunc(const pair<FilePath, Time>& a,
283 const pair<FilePath, Time>& b) {
284 return a.second > b.second;
285}
286
287string P2PManagerImpl::GetExt(Visibility visibility) {
288 string ext = string(".") + file_extension_ + kP2PExtension;
289 switch (visibility) {
290 case kVisible:
291 break;
292 case kNonVisible:
293 ext += kTmpExtension;
294 break;
295 // Don't add a default case to let the compiler warn about newly
296 // added enum values.
297 }
298 return ext;
299}
300
301FilePath P2PManagerImpl::GetPath(const string& file_id, Visibility visibility) {
302 return configuration_->GetP2PDir().Append(file_id + GetExt(visibility));
303}
304
David Zeuthen41f2cf52014-11-05 12:29:45 -0500305bool P2PManagerImpl::DeleteP2PFile(const FilePath& path,
Alex Deymo29b81532015-07-09 11:51:49 -0700306 const string& reason) {
David Zeuthen41f2cf52014-11-05 12:29:45 -0500307 LOG(INFO) << "Deleting p2p file " << path.value()
308 << " (reason: " << reason << ")";
309 if (unlink(path.value().c_str()) != 0) {
310 PLOG(ERROR) << "Error deleting p2p file " << path.value();
311 return false;
312 }
313 return true;
314}
David Zeuthen27a48bc2013-08-06 12:06:29 -0700315
David Zeuthen41f2cf52014-11-05 12:29:45 -0500316
317bool P2PManagerImpl::PerformHousekeeping() {
318 // Open p2p dir.
Alex Deymof329b932014-10-30 01:37:48 -0700319 FilePath p2p_dir = configuration_->GetP2PDir();
Alex Deymo454b7982015-07-10 10:49:29 -0700320 const string ext_visible = GetExt(kVisible);
321 const string ext_non_visible = GetExt(kNonVisible);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700322
David Zeuthen41f2cf52014-11-05 12:29:45 -0500323 bool deletion_failed = false;
David Zeuthen41f2cf52014-11-05 12:29:45 -0500324 vector<pair<FilePath, Time>> matches;
Alex Deymo454b7982015-07-10 10:49:29 -0700325
326 base::FileEnumerator dir(p2p_dir, false, base::FileEnumerator::FILES);
327 // Go through all files and collect their mtime.
328 for (FilePath name = dir.Next(); !name.empty(); name = dir.Next()) {
329 if (!(base::EndsWith(name.value(), ext_visible, true) ||
330 base::EndsWith(name.value(), ext_non_visible, true)))
David Zeuthen27a48bc2013-08-06 12:06:29 -0700331 continue;
332
Alex Deymo454b7982015-07-10 10:49:29 -0700333 Time time = dir.GetInfo().GetLastModifiedTime();
David Zeuthen41f2cf52014-11-05 12:29:45 -0500334
335 // If instructed to keep only files younger than a given age
336 // (|max_file_age_| != 0), delete files satisfying this criteria
337 // right now. Otherwise add it to a list we'll consider for later.
Alex Deymo29b81532015-07-09 11:51:49 -0700338 if (clock_ != nullptr && max_file_age_ != TimeDelta() &&
David Zeuthen41f2cf52014-11-05 12:29:45 -0500339 clock_->GetWallclockTime() - time > max_file_age_) {
Alex Deymo454b7982015-07-10 10:49:29 -0700340 if (!DeleteP2PFile(name, "file too old"))
David Zeuthen41f2cf52014-11-05 12:29:45 -0500341 deletion_failed = true;
342 } else {
Alex Deymo454b7982015-07-10 10:49:29 -0700343 matches.push_back(std::make_pair(name, time));
David Zeuthen41f2cf52014-11-05 12:29:45 -0500344 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700345 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700346
David Zeuthen41f2cf52014-11-05 12:29:45 -0500347 // If instructed to only keep N files (|max_files_to_keep_ != 0),
348 // sort list of matches, newest (biggest time) to oldest (lowest
349 // time). Then delete starting at element |num_files_to_keep_|.
350 if (num_files_to_keep_ > 0) {
351 std::sort(matches.begin(), matches.end(), MatchCompareFunc);
352 vector<pair<FilePath, Time>>::const_iterator i;
353 for (i = matches.begin() + num_files_to_keep_; i < matches.end(); ++i) {
354 if (!DeleteP2PFile(i->first, "too many files"))
355 deletion_failed = true;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700356 }
357 }
358
David Zeuthen41f2cf52014-11-05 12:29:45 -0500359 return !deletion_failed;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700360}
361
362// Helper class for implementing LookupUrlForFile().
363class LookupData {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700364 public:
365 explicit LookupData(P2PManager::LookupCallback callback)
Alex Deymo29b81532015-07-09 11:51:49 -0700366 : callback_(callback) {}
David Zeuthen27a48bc2013-08-06 12:06:29 -0700367
368 ~LookupData() {
Alex Deymo29b81532015-07-09 11:51:49 -0700369 if (timeout_task_ != MessageLoop::kTaskIdNull)
370 MessageLoop::current()->CancelTask(timeout_task_);
Alex Deymo461b2592015-07-24 20:10:52 -0700371 if (child_pid_)
372 Subprocess::Get().KillExec(child_pid_);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700373 }
374
Alex Deymo29b81532015-07-09 11:51:49 -0700375 void InitiateLookup(const vector<string>& cmd, TimeDelta timeout) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700376 // NOTE: if we fail early (i.e. in this method), we need to schedule
377 // an idle to report the error. This is because we guarantee that
Alex Deymo29b81532015-07-09 11:51:49 -0700378 // the callback is always called from the message loop (this
David Zeuthen27a48bc2013-08-06 12:06:29 -0700379 // guarantee is useful for testing).
380
Alex Deymo29b81532015-07-09 11:51:49 -0700381 // We expect to run just "p2p-client" and find it in the path.
Alex Deymo461b2592015-07-24 20:10:52 -0700382 child_pid_ = Subprocess::Get().ExecFlags(
383 cmd, Subprocess::kSearchPath,
384 Bind(&LookupData::OnLookupDone, base::Unretained(this)));
Alex Deymo29b81532015-07-09 11:51:49 -0700385
Alex Deymo461b2592015-07-24 20:10:52 -0700386 if (!child_pid_) {
Alex Deymo29b81532015-07-09 11:51:49 -0700387 LOG(ERROR) << "Error spawning " << utils::StringVectorToString(cmd);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700388 ReportErrorAndDeleteInIdle();
389 return;
390 }
391
Alex Deymo29b81532015-07-09 11:51:49 -0700392 if (timeout > TimeDelta()) {
393 timeout_task_ = MessageLoop::current()->PostDelayedTask(
394 FROM_HERE,
395 Bind(&LookupData::OnTimeout, base::Unretained(this)),
396 timeout);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700397 }
398 }
399
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700400 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700401 void ReportErrorAndDeleteInIdle() {
Alex Deymo29b81532015-07-09 11:51:49 -0700402 MessageLoop::current()->PostTask(FROM_HERE, Bind(
403 &LookupData::OnIdleForReportErrorAndDelete,
404 base::Unretained(this)));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700405 }
406
Alex Deymo29b81532015-07-09 11:51:49 -0700407 void OnIdleForReportErrorAndDelete() {
408 ReportError();
409 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700410 }
411
412 void IssueCallback(const string& url) {
413 if (!callback_.is_null())
414 callback_.Run(url);
415 }
416
417 void ReportError() {
418 if (reported_)
419 return;
420 IssueCallback("");
421 reported_ = true;
422 }
423
Alex Deymo29b81532015-07-09 11:51:49 -0700424 void ReportSuccess(const string& output) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700425 if (reported_)
426 return;
Alex Deymo29b81532015-07-09 11:51:49 -0700427 string url = output;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700428 size_t newline_pos = url.find('\n');
429 if (newline_pos != string::npos)
430 url.resize(newline_pos);
431
432 // Since p2p-client(1) is constructing this URL itself strictly
433 // speaking there's no need to validate it... but, anyway, can't
434 // hurt.
435 if (url.compare(0, 7, "http://") == 0) {
436 IssueCallback(url);
437 } else {
438 LOG(ERROR) << "p2p URL '" << url << "' does not look right. Ignoring.";
439 ReportError();
440 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700441 reported_ = true;
442 }
443
Alex Deymo461b2592015-07-24 20:10:52 -0700444 void OnLookupDone(int return_code, const string& output) {
445 child_pid_ = 0;
Alex Deymo29b81532015-07-09 11:51:49 -0700446 if (return_code != 0) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700447 LOG(INFO) << "Child exited with non-zero exit code "
Alex Deymo29b81532015-07-09 11:51:49 -0700448 << return_code;
Alex Deymo461b2592015-07-24 20:10:52 -0700449 ReportError();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700450 } else {
Alex Deymo461b2592015-07-24 20:10:52 -0700451 ReportSuccess(output);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700452 }
Alex Deymo461b2592015-07-24 20:10:52 -0700453 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700454 }
455
Alex Deymo29b81532015-07-09 11:51:49 -0700456 void OnTimeout() {
457 timeout_task_ = MessageLoop::kTaskIdNull;
458 ReportError();
459 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700460 }
461
462 P2PManager::LookupCallback callback_;
Alex Deymo29b81532015-07-09 11:51:49 -0700463
464 // The Subprocess tag of the running process. A value of 0 means that the
465 // process is not running.
Alex Deymo461b2592015-07-24 20:10:52 -0700466 pid_t child_pid_{0};
Alex Deymo29b81532015-07-09 11:51:49 -0700467
468 // The timeout task_id we are waiting on, if any.
469 MessageLoop::TaskId timeout_task_{MessageLoop::kTaskIdNull};
470
471 bool reported_{false};
David Zeuthen27a48bc2013-08-06 12:06:29 -0700472};
473
474void P2PManagerImpl::LookupUrlForFile(const string& file_id,
475 size_t minimum_size,
476 TimeDelta max_time_to_wait,
477 LookupCallback callback) {
478 LookupData *lookup_data = new LookupData(callback);
479 string file_id_with_ext = file_id + "." + file_extension_;
480 vector<string> args = configuration_->GetP2PClientArgs(file_id_with_ext,
481 minimum_size);
Alex Deymo29b81532015-07-09 11:51:49 -0700482 lookup_data->InitiateLookup(args, max_time_to_wait);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700483}
484
485bool P2PManagerImpl::FileShare(const string& file_id,
486 size_t expected_size) {
487 // Check if file already exist.
Alex Deymof329b932014-10-30 01:37:48 -0700488 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700489 if (!path.empty()) {
490 // File exists - double check its expected size though.
491 ssize_t file_expected_size = FileGetExpectedSize(file_id);
492 if (file_expected_size == -1 ||
493 static_cast<size_t>(file_expected_size) != expected_size) {
494 LOG(ERROR) << "Existing p2p file " << path.value()
495 << " with expected_size=" << file_expected_size
496 << " does not match the passed in"
497 << " expected_size=" << expected_size;
498 return false;
499 }
500 return true;
501 }
502
503 // Before creating the file, bail if statvfs(3) indicates that at
504 // least twice the size is not available in P2P_DIR.
505 struct statvfs statvfsbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700506 FilePath p2p_dir = configuration_->GetP2PDir();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700507 if (statvfs(p2p_dir.value().c_str(), &statvfsbuf) != 0) {
508 PLOG(ERROR) << "Error calling statvfs() for dir " << p2p_dir.value();
509 return false;
510 }
511 size_t free_bytes =
512 static_cast<size_t>(statvfsbuf.f_bsize) * statvfsbuf.f_bavail;
513 if (free_bytes < 2 * expected_size) {
514 // This can easily happen and is worth reporting.
515 LOG(INFO) << "Refusing to allocate p2p file of " << expected_size
516 << " bytes since the directory " << p2p_dir.value()
517 << " only has " << free_bytes
518 << " bytes available and this is less than twice the"
519 << " requested size.";
520 return false;
521 }
522
523 // Okie-dokey looks like enough space is available - create the file.
524 path = GetPath(file_id, kNonVisible);
525 int fd = open(path.value().c_str(), O_CREAT | O_RDWR, 0644);
526 if (fd == -1) {
527 PLOG(ERROR) << "Error creating file with path " << path.value();
528 return false;
529 }
530 ScopedFdCloser fd_closer(&fd);
531
532 // If the final size is known, allocate the file (e.g. reserve disk
533 // space) and set the user.cros-p2p-filesize xattr.
534 if (expected_size != 0) {
535 if (fallocate(fd,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700536 FALLOC_FL_KEEP_SIZE, // Keep file size as 0.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700537 0,
538 expected_size) != 0) {
David Zeuthen910ec5b2013-09-26 12:10:58 -0700539 if (errno == ENOSYS || errno == EOPNOTSUPP) {
540 // If the filesystem doesn't support the fallocate, keep
541 // going. This is helpful when running unit tests on build
542 // machines with ancient filesystems and/or OSes.
543 PLOG(WARNING) << "Ignoring fallocate(2) failure";
544 } else {
545 // ENOSPC can happen (funky race though, cf. the statvfs() check
546 // above), handle it gracefully, e.g. use logging level INFO.
547 PLOG(INFO) << "Error allocating " << expected_size
548 << " bytes for file " << path.value();
549 if (unlink(path.value().c_str()) != 0) {
550 PLOG(ERROR) << "Error deleting file with path " << path.value();
551 }
552 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700553 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700554 }
555
Alex Deymof329b932014-10-30 01:37:48 -0700556 string decimal_size = StringPrintf("%zu", expected_size);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700557 if (fsetxattr(fd, kCrosP2PFileSizeXAttrName,
558 decimal_size.c_str(), decimal_size.size(), 0) != 0) {
559 PLOG(ERROR) << "Error setting xattr " << path.value();
560 return false;
561 }
562 }
563
564 return true;
565}
566
567FilePath P2PManagerImpl::FileGetPath(const string& file_id) {
568 struct stat statbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700569 FilePath path;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700570
571 path = GetPath(file_id, kVisible);
572 if (stat(path.value().c_str(), &statbuf) == 0) {
573 return path;
574 }
575
576 path = GetPath(file_id, kNonVisible);
577 if (stat(path.value().c_str(), &statbuf) == 0) {
578 return path;
579 }
580
581 path.clear();
582 return path;
583}
584
585bool P2PManagerImpl::FileGetVisible(const string& file_id,
586 bool *out_result) {
Alex Deymof329b932014-10-30 01:37:48 -0700587 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700588 if (path.empty()) {
589 LOG(ERROR) << "No file for id " << file_id;
590 return false;
591 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700592 if (out_result != nullptr)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700593 *out_result = path.MatchesExtension(kP2PExtension);
594 return true;
595}
596
597bool P2PManagerImpl::FileMakeVisible(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700598 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700599 if (path.empty()) {
600 LOG(ERROR) << "No file for id " << file_id;
601 return false;
602 }
603
604 // Already visible?
605 if (path.MatchesExtension(kP2PExtension))
606 return true;
607
608 LOG_ASSERT(path.MatchesExtension(kTmpExtension));
Alex Deymof329b932014-10-30 01:37:48 -0700609 FilePath new_path = path.RemoveExtension();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700610 LOG_ASSERT(new_path.MatchesExtension(kP2PExtension));
611 if (rename(path.value().c_str(), new_path.value().c_str()) != 0) {
612 PLOG(ERROR) << "Error renaming " << path.value()
613 << " to " << new_path.value();
614 return false;
615 }
616
617 return true;
618}
619
620ssize_t P2PManagerImpl::FileGetSize(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700621 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700622 if (path.empty())
623 return -1;
624
Gabe Blacka77939e2014-09-09 23:35:08 -0700625 return utils::FileSize(path.value());
David Zeuthen27a48bc2013-08-06 12:06:29 -0700626}
627
628ssize_t P2PManagerImpl::FileGetExpectedSize(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
633 char ea_value[64] = { 0 };
634 ssize_t ea_size;
635 ea_size = getxattr(path.value().c_str(), kCrosP2PFileSizeXAttrName,
636 &ea_value, sizeof(ea_value) - 1);
637 if (ea_size == -1) {
638 PLOG(ERROR) << "Error calling getxattr() on file " << path.value();
639 return -1;
640 }
641
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700642 char* endp = nullptr;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700643 long long int val = strtoll(ea_value, &endp, 0); // NOLINT(runtime/int)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700644 if (*endp != '\0') {
645 LOG(ERROR) << "Error parsing the value '" << ea_value
646 << "' of the xattr " << kCrosP2PFileSizeXAttrName
647 << " as an integer";
648 return -1;
649 }
650
651 return val;
652}
653
654int P2PManagerImpl::CountSharedFiles() {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700655 int num_files = 0;
656
Alex Deymof329b932014-10-30 01:37:48 -0700657 FilePath p2p_dir = configuration_->GetP2PDir();
Alex Deymo454b7982015-07-10 10:49:29 -0700658 const string ext_visible = GetExt(kVisible);
659 const string ext_non_visible = GetExt(kNonVisible);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700660
Alex Deymo454b7982015-07-10 10:49:29 -0700661 base::FileEnumerator dir(p2p_dir, false, base::FileEnumerator::FILES);
662 for (FilePath name = dir.Next(); !name.empty(); name = dir.Next()) {
663 if (base::EndsWith(name.value(), ext_visible, true) ||
664 base::EndsWith(name.value(), ext_non_visible, true))
David Zeuthen27a48bc2013-08-06 12:06:29 -0700665 num_files += 1;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700666 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700667
668 return num_files;
669}
670
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700671void P2PManagerImpl::ScheduleEnabledStatusChange() {
672 if (waiting_for_enabled_status_change_)
673 return;
Gilad Arnoldccd09572014-10-27 13:37:50 -0700674
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700675 Callback<void(EvalStatus, const bool&)> callback = Bind(
676 &P2PManagerImpl::OnEnabledStatusChange, base::Unretained(this));
677 update_manager_->AsyncPolicyRequest(callback, &Policy::P2PEnabledChanged,
678 is_enabled_);
679 waiting_for_enabled_status_change_ = true;
Gilad Arnoldccd09572014-10-27 13:37:50 -0700680}
681
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700682void P2PManagerImpl::OnEnabledStatusChange(EvalStatus status,
683 const bool& result) {
684 waiting_for_enabled_status_change_ = false;
685
686 if (status == EvalStatus::kSucceeded) {
687 if (result == is_enabled_) {
688 LOG(WARNING) << "P2P enabled status did not change, which means that it "
689 "is permanent; not scheduling further checks.";
690 waiting_for_enabled_status_change_ = true;
691 return;
692 }
693
694 is_enabled_ = result;
695
696 // If P2P is running but shouldn't be, make sure it isn't.
697 if (may_be_running_ && !is_enabled_ && !EnsureP2PNotRunning()) {
698 LOG(WARNING) << "Failed to stop P2P service.";
699 }
700 } else {
701 LOG(WARNING)
702 << "P2P enabled tracking failed (possibly timed out); retrying.";
703 }
704
705 ScheduleEnabledStatusChange();
706}
707
708P2PManager* P2PManager::Construct(
709 Configuration *configuration,
710 ClockInterface *clock,
711 UpdateManager* update_manager,
712 const string& file_extension,
713 const int num_files_to_keep,
Alex Deymo29b81532015-07-09 11:51:49 -0700714 const TimeDelta& max_file_age) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700715 return new P2PManagerImpl(configuration,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500716 clock,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700717 update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700718 file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500719 num_files_to_keep,
720 max_file_age);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700721}
722
723} // namespace chromeos_update_engine