blob: c72a0231a61a5cc942eaa561a721c8a68253901b [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_);
372 if (child_tag_)
373 Subprocess::Get().KillExec(child_tag_);
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.
383 child_tag_ = Subprocess::Get().ExecFlags(
384 cmd, G_SPAWN_SEARCH_PATH, false /* redirect stderr */, OnLookupDone,
385 this);
386
387 if (!child_tag_) {
388 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 Deymo29b81532015-07-09 11:51:49 -0700445 static void OnLookupDone(int return_code,
446 const string& output,
447 void *user_data) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700448 LookupData *lookup_data = reinterpret_cast<LookupData*>(user_data);
Alex Deymo29b81532015-07-09 11:51:49 -0700449 lookup_data->child_tag_ = 0;
450 if (return_code != 0) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700451 LOG(INFO) << "Child exited with non-zero exit code "
Alex Deymo29b81532015-07-09 11:51:49 -0700452 << return_code;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700453 lookup_data->ReportError();
454 } else {
Alex Deymo29b81532015-07-09 11:51:49 -0700455 lookup_data->ReportSuccess(output);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700456 }
457 delete lookup_data;
458 }
459
Alex Deymo29b81532015-07-09 11:51:49 -0700460 void OnTimeout() {
461 timeout_task_ = MessageLoop::kTaskIdNull;
462 ReportError();
463 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700464 }
465
466 P2PManager::LookupCallback callback_;
Alex Deymo29b81532015-07-09 11:51:49 -0700467
468 // The Subprocess tag of the running process. A value of 0 means that the
469 // process is not running.
470 uint32_t child_tag_{0};
471
472 // The timeout task_id we are waiting on, if any.
473 MessageLoop::TaskId timeout_task_{MessageLoop::kTaskIdNull};
474
475 bool reported_{false};
David Zeuthen27a48bc2013-08-06 12:06:29 -0700476};
477
478void P2PManagerImpl::LookupUrlForFile(const string& file_id,
479 size_t minimum_size,
480 TimeDelta max_time_to_wait,
481 LookupCallback callback) {
482 LookupData *lookup_data = new LookupData(callback);
483 string file_id_with_ext = file_id + "." + file_extension_;
484 vector<string> args = configuration_->GetP2PClientArgs(file_id_with_ext,
485 minimum_size);
Alex Deymo29b81532015-07-09 11:51:49 -0700486 lookup_data->InitiateLookup(args, max_time_to_wait);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700487}
488
489bool P2PManagerImpl::FileShare(const string& file_id,
490 size_t expected_size) {
491 // Check if file already exist.
Alex Deymof329b932014-10-30 01:37:48 -0700492 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700493 if (!path.empty()) {
494 // File exists - double check its expected size though.
495 ssize_t file_expected_size = FileGetExpectedSize(file_id);
496 if (file_expected_size == -1 ||
497 static_cast<size_t>(file_expected_size) != expected_size) {
498 LOG(ERROR) << "Existing p2p file " << path.value()
499 << " with expected_size=" << file_expected_size
500 << " does not match the passed in"
501 << " expected_size=" << expected_size;
502 return false;
503 }
504 return true;
505 }
506
507 // Before creating the file, bail if statvfs(3) indicates that at
508 // least twice the size is not available in P2P_DIR.
509 struct statvfs statvfsbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700510 FilePath p2p_dir = configuration_->GetP2PDir();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700511 if (statvfs(p2p_dir.value().c_str(), &statvfsbuf) != 0) {
512 PLOG(ERROR) << "Error calling statvfs() for dir " << p2p_dir.value();
513 return false;
514 }
515 size_t free_bytes =
516 static_cast<size_t>(statvfsbuf.f_bsize) * statvfsbuf.f_bavail;
517 if (free_bytes < 2 * expected_size) {
518 // This can easily happen and is worth reporting.
519 LOG(INFO) << "Refusing to allocate p2p file of " << expected_size
520 << " bytes since the directory " << p2p_dir.value()
521 << " only has " << free_bytes
522 << " bytes available and this is less than twice the"
523 << " requested size.";
524 return false;
525 }
526
527 // Okie-dokey looks like enough space is available - create the file.
528 path = GetPath(file_id, kNonVisible);
529 int fd = open(path.value().c_str(), O_CREAT | O_RDWR, 0644);
530 if (fd == -1) {
531 PLOG(ERROR) << "Error creating file with path " << path.value();
532 return false;
533 }
534 ScopedFdCloser fd_closer(&fd);
535
536 // If the final size is known, allocate the file (e.g. reserve disk
537 // space) and set the user.cros-p2p-filesize xattr.
538 if (expected_size != 0) {
539 if (fallocate(fd,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700540 FALLOC_FL_KEEP_SIZE, // Keep file size as 0.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700541 0,
542 expected_size) != 0) {
David Zeuthen910ec5b2013-09-26 12:10:58 -0700543 if (errno == ENOSYS || errno == EOPNOTSUPP) {
544 // If the filesystem doesn't support the fallocate, keep
545 // going. This is helpful when running unit tests on build
546 // machines with ancient filesystems and/or OSes.
547 PLOG(WARNING) << "Ignoring fallocate(2) failure";
548 } else {
549 // ENOSPC can happen (funky race though, cf. the statvfs() check
550 // above), handle it gracefully, e.g. use logging level INFO.
551 PLOG(INFO) << "Error allocating " << expected_size
552 << " bytes for file " << path.value();
553 if (unlink(path.value().c_str()) != 0) {
554 PLOG(ERROR) << "Error deleting file with path " << path.value();
555 }
556 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700557 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700558 }
559
Alex Deymof329b932014-10-30 01:37:48 -0700560 string decimal_size = StringPrintf("%zu", expected_size);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700561 if (fsetxattr(fd, kCrosP2PFileSizeXAttrName,
562 decimal_size.c_str(), decimal_size.size(), 0) != 0) {
563 PLOG(ERROR) << "Error setting xattr " << path.value();
564 return false;
565 }
566 }
567
568 return true;
569}
570
571FilePath P2PManagerImpl::FileGetPath(const string& file_id) {
572 struct stat statbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700573 FilePath path;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700574
575 path = GetPath(file_id, kVisible);
576 if (stat(path.value().c_str(), &statbuf) == 0) {
577 return path;
578 }
579
580 path = GetPath(file_id, kNonVisible);
581 if (stat(path.value().c_str(), &statbuf) == 0) {
582 return path;
583 }
584
585 path.clear();
586 return path;
587}
588
589bool P2PManagerImpl::FileGetVisible(const string& file_id,
590 bool *out_result) {
Alex Deymof329b932014-10-30 01:37:48 -0700591 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700592 if (path.empty()) {
593 LOG(ERROR) << "No file for id " << file_id;
594 return false;
595 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700596 if (out_result != nullptr)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700597 *out_result = path.MatchesExtension(kP2PExtension);
598 return true;
599}
600
601bool P2PManagerImpl::FileMakeVisible(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700602 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700603 if (path.empty()) {
604 LOG(ERROR) << "No file for id " << file_id;
605 return false;
606 }
607
608 // Already visible?
609 if (path.MatchesExtension(kP2PExtension))
610 return true;
611
612 LOG_ASSERT(path.MatchesExtension(kTmpExtension));
Alex Deymof329b932014-10-30 01:37:48 -0700613 FilePath new_path = path.RemoveExtension();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700614 LOG_ASSERT(new_path.MatchesExtension(kP2PExtension));
615 if (rename(path.value().c_str(), new_path.value().c_str()) != 0) {
616 PLOG(ERROR) << "Error renaming " << path.value()
617 << " to " << new_path.value();
618 return false;
619 }
620
621 return true;
622}
623
624ssize_t P2PManagerImpl::FileGetSize(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700625 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700626 if (path.empty())
627 return -1;
628
Gabe Blacka77939e2014-09-09 23:35:08 -0700629 return utils::FileSize(path.value());
David Zeuthen27a48bc2013-08-06 12:06:29 -0700630}
631
632ssize_t P2PManagerImpl::FileGetExpectedSize(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700633 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700634 if (path.empty())
635 return -1;
636
637 char ea_value[64] = { 0 };
638 ssize_t ea_size;
639 ea_size = getxattr(path.value().c_str(), kCrosP2PFileSizeXAttrName,
640 &ea_value, sizeof(ea_value) - 1);
641 if (ea_size == -1) {
642 PLOG(ERROR) << "Error calling getxattr() on file " << path.value();
643 return -1;
644 }
645
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700646 char* endp = nullptr;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700647 long long int val = strtoll(ea_value, &endp, 0); // NOLINT(runtime/int)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700648 if (*endp != '\0') {
649 LOG(ERROR) << "Error parsing the value '" << ea_value
650 << "' of the xattr " << kCrosP2PFileSizeXAttrName
651 << " as an integer";
652 return -1;
653 }
654
655 return val;
656}
657
658int P2PManagerImpl::CountSharedFiles() {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700659 int num_files = 0;
660
Alex Deymof329b932014-10-30 01:37:48 -0700661 FilePath p2p_dir = configuration_->GetP2PDir();
Alex Deymo454b7982015-07-10 10:49:29 -0700662 const string ext_visible = GetExt(kVisible);
663 const string ext_non_visible = GetExt(kNonVisible);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700664
Alex Deymo454b7982015-07-10 10:49:29 -0700665 base::FileEnumerator dir(p2p_dir, false, base::FileEnumerator::FILES);
666 for (FilePath name = dir.Next(); !name.empty(); name = dir.Next()) {
667 if (base::EndsWith(name.value(), ext_visible, true) ||
668 base::EndsWith(name.value(), ext_non_visible, true))
David Zeuthen27a48bc2013-08-06 12:06:29 -0700669 num_files += 1;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700670 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700671
672 return num_files;
673}
674
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700675void P2PManagerImpl::ScheduleEnabledStatusChange() {
676 if (waiting_for_enabled_status_change_)
677 return;
Gilad Arnoldccd09572014-10-27 13:37:50 -0700678
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700679 Callback<void(EvalStatus, const bool&)> callback = Bind(
680 &P2PManagerImpl::OnEnabledStatusChange, base::Unretained(this));
681 update_manager_->AsyncPolicyRequest(callback, &Policy::P2PEnabledChanged,
682 is_enabled_);
683 waiting_for_enabled_status_change_ = true;
Gilad Arnoldccd09572014-10-27 13:37:50 -0700684}
685
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700686void P2PManagerImpl::OnEnabledStatusChange(EvalStatus status,
687 const bool& result) {
688 waiting_for_enabled_status_change_ = false;
689
690 if (status == EvalStatus::kSucceeded) {
691 if (result == is_enabled_) {
692 LOG(WARNING) << "P2P enabled status did not change, which means that it "
693 "is permanent; not scheduling further checks.";
694 waiting_for_enabled_status_change_ = true;
695 return;
696 }
697
698 is_enabled_ = result;
699
700 // If P2P is running but shouldn't be, make sure it isn't.
701 if (may_be_running_ && !is_enabled_ && !EnsureP2PNotRunning()) {
702 LOG(WARNING) << "Failed to stop P2P service.";
703 }
704 } else {
705 LOG(WARNING)
706 << "P2P enabled tracking failed (possibly timed out); retrying.";
707 }
708
709 ScheduleEnabledStatusChange();
710}
711
712P2PManager* P2PManager::Construct(
713 Configuration *configuration,
714 ClockInterface *clock,
715 UpdateManager* update_manager,
716 const string& file_extension,
717 const int num_files_to_keep,
Alex Deymo29b81532015-07-09 11:51:49 -0700718 const TimeDelta& max_file_age) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700719 return new P2PManagerImpl(configuration,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500720 clock,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700721 update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700722 file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500723 num_files_to_keep,
724 max_file_age);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700725}
726
727} // namespace chromeos_update_engine