blob: bcfe15611b061150104db03dc9db84dea4e781e1 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2013 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
David Zeuthen27a48bc2013-08-06 12:06:29 -070016
Alex Vakulenko072359c2014-07-18 11:41:07 -070017// This provides access to timestamps with nanosecond resolution in
David Zeuthen27a48bc2013-08-06 12:06:29 -070018// struct stat, See NOTES in stat(2) for details.
19#ifndef _BSD_SOURCE
20#define _BSD_SOURCE
21#endif
22
23#include "update_engine/p2p_manager.h"
24
David Zeuthen27a48bc2013-08-06 12:06:29 -070025#include <errno.h>
26#include <fcntl.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070027#include <linux/falloc.h>
28#include <signal.h>
29#include <string.h>
30#include <sys/stat.h>
31#include <sys/statvfs.h>
32#include <sys/types.h>
Alex Deymo6f20dd42015-08-18 16:42:46 -070033#include <sys/xattr.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070034#include <unistd.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070035
Alex Vakulenkod2779df2014-06-16 13:19:00 -070036#include <algorithm>
David Zeuthen27a48bc2013-08-06 12:06:29 -070037#include <map>
Ben Chan02f7c1d2014-10-18 15:18:02 -070038#include <memory>
David Zeuthen27a48bc2013-08-06 12:06:29 -070039#include <utility>
40#include <vector>
41
Gilad Arnold4a0321b2014-10-28 15:57:30 -070042#include <base/bind.h>
Alex Deymo454b7982015-07-10 10:49:29 -070043#include <base/files/file_enumerator.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070044#include <base/files/file_path.h>
Alex Deymoc00c98a2015-03-17 17:38:00 -070045#include <base/format_macros.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070046#include <base/logging.h>
Alex Deymo454b7982015-07-10 10:49:29 -070047#include <base/strings/string_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070048#include <base/strings/stringprintf.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070049
Alex Deymo39910dc2015-11-09 17:04:30 -080050#include "update_engine/common/subprocess.h"
51#include "update_engine/common/utils.h"
Gilad Arnold4a0321b2014-10-28 15:57:30 -070052#include "update_engine/update_manager/policy.h"
53#include "update_engine/update_manager/update_manager.h"
David Zeuthen27a48bc2013-08-06 12:06:29 -070054
Gilad Arnold4a0321b2014-10-28 15:57:30 -070055using base::Bind;
56using base::Callback;
David Zeuthen27a48bc2013-08-06 12:06:29 -070057using base::FilePath;
58using base::StringPrintf;
59using base::Time;
60using base::TimeDelta;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070061using brillo::MessageLoop;
Gilad Arnold4a0321b2014-10-28 15:57:30 -070062using chromeos_update_manager::EvalStatus;
63using chromeos_update_manager::Policy;
64using chromeos_update_manager::UpdateManager;
David Zeuthen27a48bc2013-08-06 12:06:29 -070065using std::map;
66using std::pair;
67using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070068using std::unique_ptr;
David Zeuthen27a48bc2013-08-06 12:06:29 -070069using std::vector;
70
71namespace chromeos_update_engine {
72
73namespace {
74
75// The default p2p directory.
76const char kDefaultP2PDir[] = "/var/cache/p2p";
77
78// The p2p xattr used for conveying the final size of a file - see the
79// p2p ddoc for details.
80const char kCrosP2PFileSizeXAttrName[] = "user.cros-p2p-filesize";
81
Alex Vakulenkod2779df2014-06-16 13:19:00 -070082} // namespace
David Zeuthen27a48bc2013-08-06 12:06:29 -070083
84// The default P2PManager::Configuration implementation.
85class ConfigurationImpl : public P2PManager::Configuration {
Alex Vakulenkod2779df2014-06-16 13:19:00 -070086 public:
David Zeuthen27a48bc2013-08-06 12:06:29 -070087 ConfigurationImpl() {}
88
Alex Deymo610277e2014-11-11 21:18:11 -080089 FilePath GetP2PDir() override {
Alex Deymof329b932014-10-30 01:37:48 -070090 return FilePath(kDefaultP2PDir);
David Zeuthen27a48bc2013-08-06 12:06:29 -070091 }
92
Alex Deymo610277e2014-11-11 21:18:11 -080093 vector<string> GetInitctlArgs(bool is_start) override {
David Zeuthen27a48bc2013-08-06 12:06:29 -070094 vector<string> args;
95 args.push_back("initctl");
96 args.push_back(is_start ? "start" : "stop");
97 args.push_back("p2p");
98 return args;
99 }
100
Alex Deymo610277e2014-11-11 21:18:11 -0800101 vector<string> GetP2PClientArgs(const string &file_id,
102 size_t minimum_size) override {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700103 vector<string> args;
104 args.push_back("p2p-client");
105 args.push_back(string("--get-url=") + file_id);
Alex Deymoc00c98a2015-03-17 17:38:00 -0700106 args.push_back(StringPrintf("--minimum-size=%" PRIuS, minimum_size));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700107 return args;
108 }
109
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700110 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700111 DISALLOW_COPY_AND_ASSIGN(ConfigurationImpl);
112};
113
114// The default P2PManager implementation.
115class P2PManagerImpl : public P2PManager {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700116 public:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700117 P2PManagerImpl(Configuration *configuration,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500118 ClockInterface *clock,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700119 UpdateManager* update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700120 const string& file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500121 const int num_files_to_keep,
Alex Deymo29b81532015-07-09 11:51:49 -0700122 const TimeDelta& max_file_age);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700123
124 // P2PManager methods.
Alex Deymo610277e2014-11-11 21:18:11 -0800125 void SetDevicePolicy(const policy::DevicePolicy* device_policy) override;
126 bool IsP2PEnabled() override;
127 bool EnsureP2PRunning() override;
128 bool EnsureP2PNotRunning() override;
129 bool PerformHousekeeping() override;
130 void LookupUrlForFile(const string& file_id,
131 size_t minimum_size,
132 TimeDelta max_time_to_wait,
133 LookupCallback callback) override;
134 bool FileShare(const string& file_id,
135 size_t expected_size) override;
136 FilePath FileGetPath(const string& file_id) override;
137 ssize_t FileGetSize(const string& file_id) override;
138 ssize_t FileGetExpectedSize(const string& file_id) override;
139 bool FileGetVisible(const string& file_id,
140 bool *out_result) override;
141 bool FileMakeVisible(const string& file_id) override;
142 int CountSharedFiles() override;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700143
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700144 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700145 // Enumeration for specifying visibility.
146 enum Visibility {
147 kVisible,
148 kNonVisible
149 };
150
151 // Returns "." + |file_extension_| + ".p2p" if |visibility| is
152 // |kVisible|. Returns the same concatenated with ".tmp" otherwise.
153 string GetExt(Visibility visibility);
154
155 // Gets the on-disk path for |file_id| depending on if the file
156 // is visible or not.
Alex Deymof329b932014-10-30 01:37:48 -0700157 FilePath GetPath(const string& file_id, Visibility visibility);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700158
159 // Utility function used by EnsureP2PRunning() and EnsureP2PNotRunning().
160 bool EnsureP2P(bool should_be_running);
161
David Zeuthen41f2cf52014-11-05 12:29:45 -0500162 // Utility function to delete a file given by |path| and log the
163 // path as well as |reason|. Returns false on failure.
Alex Deymo29b81532015-07-09 11:51:49 -0700164 bool DeleteP2PFile(const FilePath& path, const string& reason);
David Zeuthen41f2cf52014-11-05 12:29:45 -0500165
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700166 // Schedules an async request for tracking changes in P2P enabled status.
167 void ScheduleEnabledStatusChange();
168
169 // An async callback used by the above.
170 void OnEnabledStatusChange(EvalStatus status, const bool& result);
171
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700172 // The device policy being used or null if no policy is being used.
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700173 const policy::DevicePolicy* device_policy_ = nullptr;
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700174
David Zeuthen27a48bc2013-08-06 12:06:29 -0700175 // Configuration object.
Ben Chan02f7c1d2014-10-18 15:18:02 -0700176 unique_ptr<Configuration> configuration_;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700177
David Zeuthen41f2cf52014-11-05 12:29:45 -0500178 // Object for telling the time.
179 ClockInterface* clock_;
180
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700181 // A pointer to the global Update Manager.
182 UpdateManager* update_manager_;
183
David Zeuthen27a48bc2013-08-06 12:06:29 -0700184 // A short string unique to the application (for example "cros_au")
185 // used to mark a file as being owned by a particular application.
186 const string file_extension_;
187
188 // If non-zero, this number denotes how many files in /var/cache/p2p
189 // owned by the application (cf. |file_extension_|) to keep after
190 // performing housekeeping.
191 const int num_files_to_keep_;
192
David Zeuthen41f2cf52014-11-05 12:29:45 -0500193 // If non-zero, files older than this will not be kept after
194 // performing housekeeping.
Alex Deymo29b81532015-07-09 11:51:49 -0700195 const TimeDelta max_file_age_;
David Zeuthen41f2cf52014-11-05 12:29:45 -0500196
David Zeuthen27a48bc2013-08-06 12:06:29 -0700197 // The string ".p2p".
198 static const char kP2PExtension[];
199
200 // The string ".tmp".
201 static const char kTmpExtension[];
202
Gilad Arnoldccd09572014-10-27 13:37:50 -0700203 // Whether P2P service may be running; initially, we assume it may be.
204 bool may_be_running_ = true;
205
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700206 // The current known enabled status of the P2P feature (initialized lazily),
207 // and whether an async status check has been scheduled.
208 bool is_enabled_;
209 bool waiting_for_enabled_status_change_ = false;
210
David Zeuthen27a48bc2013-08-06 12:06:29 -0700211 DISALLOW_COPY_AND_ASSIGN(P2PManagerImpl);
212};
213
214const char P2PManagerImpl::kP2PExtension[] = ".p2p";
215
216const char P2PManagerImpl::kTmpExtension[] = ".tmp";
217
218P2PManagerImpl::P2PManagerImpl(Configuration *configuration,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500219 ClockInterface *clock,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700220 UpdateManager* update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700221 const string& file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500222 const int num_files_to_keep,
Alex Deymo29b81532015-07-09 11:51:49 -0700223 const TimeDelta& max_file_age)
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700224 : clock_(clock),
225 update_manager_(update_manager),
David Zeuthen27a48bc2013-08-06 12:06:29 -0700226 file_extension_(file_extension),
David Zeuthen41f2cf52014-11-05 12:29:45 -0500227 num_files_to_keep_(num_files_to_keep),
228 max_file_age_(max_file_age) {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700229 configuration_.reset(configuration != nullptr ? configuration :
David Zeuthen27a48bc2013-08-06 12:06:29 -0700230 new ConfigurationImpl());
231}
232
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700233void P2PManagerImpl::SetDevicePolicy(
234 const policy::DevicePolicy* device_policy) {
235 device_policy_ = device_policy;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700236}
237
238bool P2PManagerImpl::IsP2PEnabled() {
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700239 if (!waiting_for_enabled_status_change_) {
240 // Get and store an initial value.
241 if (update_manager_->PolicyRequest(&Policy::P2PEnabled, &is_enabled_) ==
242 EvalStatus::kFailed) {
243 is_enabled_ = false;
244 LOG(ERROR) << "Querying P2P enabled status failed, disabling.";
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400245 }
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700246
247 // Track future changes (async).
248 ScheduleEnabledStatusChange();
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400249 }
250
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700251 return is_enabled_;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700252}
253
254bool P2PManagerImpl::EnsureP2P(bool should_be_running) {
Alex Deymo29b81532015-07-09 11:51:49 -0700255 int return_code = 0;
256 string output;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700257
Gilad Arnoldccd09572014-10-27 13:37:50 -0700258 may_be_running_ = true; // Unless successful, we must be conservative.
259
David Zeuthen27a48bc2013-08-06 12:06:29 -0700260 vector<string> args = configuration_->GetInitctlArgs(should_be_running);
Alex Deymo29b81532015-07-09 11:51:49 -0700261 if (!Subprocess::SynchronousExec(args, &return_code, &output)) {
262 LOG(ERROR) << "Error spawning " << utils::StringVectorToString(args);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700263 return false;
264 }
265
Gilad Arnoldccd09572014-10-27 13:37:50 -0700266 // If initctl(8) does not exit normally (exit status other than zero), ensure
267 // that the error message is not benign by scanning stderr; this is a
268 // necessity because initctl does not offer actions such as "start if not
269 // running" or "stop if running".
David Zeuthen27a48bc2013-08-06 12:06:29 -0700270 // TODO(zeuthen,chromium:277051): Avoid doing this.
Alex Deymo29b81532015-07-09 11:51:49 -0700271 if (return_code != 0) {
272 const char *expected_error_message = should_be_running ?
Gilad Arnoldccd09572014-10-27 13:37:50 -0700273 "initctl: Job is already running: p2p\n" :
274 "initctl: Unknown instance \n";
Alex Deymo29b81532015-07-09 11:51:49 -0700275 if (output != expected_error_message)
Gilad Arnoldccd09572014-10-27 13:37:50 -0700276 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700277 }
278
Gilad Arnoldccd09572014-10-27 13:37:50 -0700279 may_be_running_ = should_be_running; // Successful after all.
280 return true;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700281}
282
283bool P2PManagerImpl::EnsureP2PRunning() {
284 return EnsureP2P(true);
285}
286
287bool P2PManagerImpl::EnsureP2PNotRunning() {
288 return EnsureP2P(false);
289}
290
291// Returns True if the timestamp in the first pair is greater than the
292// timestamp in the latter. If used with std::sort() this will yield a
293// sequence of elements where newer (high timestamps) elements precede
294// older ones (low timestamps).
295static bool MatchCompareFunc(const pair<FilePath, Time>& a,
296 const pair<FilePath, Time>& b) {
297 return a.second > b.second;
298}
299
300string P2PManagerImpl::GetExt(Visibility visibility) {
301 string ext = string(".") + file_extension_ + kP2PExtension;
302 switch (visibility) {
303 case kVisible:
304 break;
305 case kNonVisible:
306 ext += kTmpExtension;
307 break;
308 // Don't add a default case to let the compiler warn about newly
309 // added enum values.
310 }
311 return ext;
312}
313
314FilePath P2PManagerImpl::GetPath(const string& file_id, Visibility visibility) {
315 return configuration_->GetP2PDir().Append(file_id + GetExt(visibility));
316}
317
David Zeuthen41f2cf52014-11-05 12:29:45 -0500318bool P2PManagerImpl::DeleteP2PFile(const FilePath& path,
Alex Deymo29b81532015-07-09 11:51:49 -0700319 const string& reason) {
David Zeuthen41f2cf52014-11-05 12:29:45 -0500320 LOG(INFO) << "Deleting p2p file " << path.value()
321 << " (reason: " << reason << ")";
322 if (unlink(path.value().c_str()) != 0) {
323 PLOG(ERROR) << "Error deleting p2p file " << path.value();
324 return false;
325 }
326 return true;
327}
David Zeuthen27a48bc2013-08-06 12:06:29 -0700328
David Zeuthen41f2cf52014-11-05 12:29:45 -0500329
330bool P2PManagerImpl::PerformHousekeeping() {
331 // Open p2p dir.
Alex Deymof329b932014-10-30 01:37:48 -0700332 FilePath p2p_dir = configuration_->GetP2PDir();
Alex Deymo454b7982015-07-10 10:49:29 -0700333 const string ext_visible = GetExt(kVisible);
334 const string ext_non_visible = GetExt(kNonVisible);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700335
David Zeuthen41f2cf52014-11-05 12:29:45 -0500336 bool deletion_failed = false;
David Zeuthen41f2cf52014-11-05 12:29:45 -0500337 vector<pair<FilePath, Time>> matches;
Alex Deymo454b7982015-07-10 10:49:29 -0700338
339 base::FileEnumerator dir(p2p_dir, false, base::FileEnumerator::FILES);
340 // Go through all files and collect their mtime.
341 for (FilePath name = dir.Next(); !name.empty(); name = dir.Next()) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800342 if (!(base::EndsWith(name.value(), ext_visible,
343 base::CompareCase::SENSITIVE) ||
344 base::EndsWith(name.value(), ext_non_visible,
345 base::CompareCase::SENSITIVE))) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700346 continue;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800347 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700348
Alex Deymo454b7982015-07-10 10:49:29 -0700349 Time time = dir.GetInfo().GetLastModifiedTime();
David Zeuthen41f2cf52014-11-05 12:29:45 -0500350
351 // If instructed to keep only files younger than a given age
352 // (|max_file_age_| != 0), delete files satisfying this criteria
353 // right now. Otherwise add it to a list we'll consider for later.
Alex Deymo29b81532015-07-09 11:51:49 -0700354 if (clock_ != nullptr && max_file_age_ != TimeDelta() &&
David Zeuthen41f2cf52014-11-05 12:29:45 -0500355 clock_->GetWallclockTime() - time > max_file_age_) {
Alex Deymo454b7982015-07-10 10:49:29 -0700356 if (!DeleteP2PFile(name, "file too old"))
David Zeuthen41f2cf52014-11-05 12:29:45 -0500357 deletion_failed = true;
358 } else {
Alex Deymo454b7982015-07-10 10:49:29 -0700359 matches.push_back(std::make_pair(name, time));
David Zeuthen41f2cf52014-11-05 12:29:45 -0500360 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700361 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700362
David Zeuthen41f2cf52014-11-05 12:29:45 -0500363 // If instructed to only keep N files (|max_files_to_keep_ != 0),
364 // sort list of matches, newest (biggest time) to oldest (lowest
365 // time). Then delete starting at element |num_files_to_keep_|.
366 if (num_files_to_keep_ > 0) {
367 std::sort(matches.begin(), matches.end(), MatchCompareFunc);
368 vector<pair<FilePath, Time>>::const_iterator i;
369 for (i = matches.begin() + num_files_to_keep_; i < matches.end(); ++i) {
370 if (!DeleteP2PFile(i->first, "too many files"))
371 deletion_failed = true;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700372 }
373 }
374
David Zeuthen41f2cf52014-11-05 12:29:45 -0500375 return !deletion_failed;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700376}
377
378// Helper class for implementing LookupUrlForFile().
379class LookupData {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700380 public:
381 explicit LookupData(P2PManager::LookupCallback callback)
Alex Deymo29b81532015-07-09 11:51:49 -0700382 : callback_(callback) {}
David Zeuthen27a48bc2013-08-06 12:06:29 -0700383
384 ~LookupData() {
Alex Deymo29b81532015-07-09 11:51:49 -0700385 if (timeout_task_ != MessageLoop::kTaskIdNull)
386 MessageLoop::current()->CancelTask(timeout_task_);
Alex Deymo461b2592015-07-24 20:10:52 -0700387 if (child_pid_)
388 Subprocess::Get().KillExec(child_pid_);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700389 }
390
Alex Deymo29b81532015-07-09 11:51:49 -0700391 void InitiateLookup(const vector<string>& cmd, TimeDelta timeout) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700392 // NOTE: if we fail early (i.e. in this method), we need to schedule
393 // an idle to report the error. This is because we guarantee that
Alex Deymo29b81532015-07-09 11:51:49 -0700394 // the callback is always called from the message loop (this
David Zeuthen27a48bc2013-08-06 12:06:29 -0700395 // guarantee is useful for testing).
396
Alex Deymo29b81532015-07-09 11:51:49 -0700397 // We expect to run just "p2p-client" and find it in the path.
Alex Deymo461b2592015-07-24 20:10:52 -0700398 child_pid_ = Subprocess::Get().ExecFlags(
Alex Deymo20e39602016-04-04 19:09:22 -0700399 cmd,
400 Subprocess::kSearchPath,
401 {},
402 nullptr,
Alex Deymo461b2592015-07-24 20:10:52 -0700403 Bind(&LookupData::OnLookupDone, base::Unretained(this)));
Alex Deymo29b81532015-07-09 11:51:49 -0700404
Alex Deymo461b2592015-07-24 20:10:52 -0700405 if (!child_pid_) {
Alex Deymo29b81532015-07-09 11:51:49 -0700406 LOG(ERROR) << "Error spawning " << utils::StringVectorToString(cmd);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700407 ReportErrorAndDeleteInIdle();
408 return;
409 }
410
Alex Deymo29b81532015-07-09 11:51:49 -0700411 if (timeout > TimeDelta()) {
412 timeout_task_ = MessageLoop::current()->PostDelayedTask(
413 FROM_HERE,
414 Bind(&LookupData::OnTimeout, base::Unretained(this)),
415 timeout);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700416 }
417 }
418
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700419 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700420 void ReportErrorAndDeleteInIdle() {
Alex Deymo29b81532015-07-09 11:51:49 -0700421 MessageLoop::current()->PostTask(FROM_HERE, Bind(
422 &LookupData::OnIdleForReportErrorAndDelete,
423 base::Unretained(this)));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700424 }
425
Alex Deymo29b81532015-07-09 11:51:49 -0700426 void OnIdleForReportErrorAndDelete() {
427 ReportError();
428 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700429 }
430
431 void IssueCallback(const string& url) {
432 if (!callback_.is_null())
433 callback_.Run(url);
434 }
435
436 void ReportError() {
437 if (reported_)
438 return;
439 IssueCallback("");
440 reported_ = true;
441 }
442
Alex Deymo29b81532015-07-09 11:51:49 -0700443 void ReportSuccess(const string& output) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700444 if (reported_)
445 return;
Alex Deymo29b81532015-07-09 11:51:49 -0700446 string url = output;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700447 size_t newline_pos = url.find('\n');
448 if (newline_pos != string::npos)
449 url.resize(newline_pos);
450
451 // Since p2p-client(1) is constructing this URL itself strictly
452 // speaking there's no need to validate it... but, anyway, can't
453 // hurt.
454 if (url.compare(0, 7, "http://") == 0) {
455 IssueCallback(url);
456 } else {
457 LOG(ERROR) << "p2p URL '" << url << "' does not look right. Ignoring.";
458 ReportError();
459 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700460 reported_ = true;
461 }
462
Alex Deymo461b2592015-07-24 20:10:52 -0700463 void OnLookupDone(int return_code, const string& output) {
464 child_pid_ = 0;
Alex Deymo29b81532015-07-09 11:51:49 -0700465 if (return_code != 0) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700466 LOG(INFO) << "Child exited with non-zero exit code "
Alex Deymo29b81532015-07-09 11:51:49 -0700467 << return_code;
Alex Deymo461b2592015-07-24 20:10:52 -0700468 ReportError();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700469 } else {
Alex Deymo461b2592015-07-24 20:10:52 -0700470 ReportSuccess(output);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700471 }
Alex Deymo461b2592015-07-24 20:10:52 -0700472 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700473 }
474
Alex Deymo29b81532015-07-09 11:51:49 -0700475 void OnTimeout() {
476 timeout_task_ = MessageLoop::kTaskIdNull;
477 ReportError();
478 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700479 }
480
481 P2PManager::LookupCallback callback_;
Alex Deymo29b81532015-07-09 11:51:49 -0700482
483 // The Subprocess tag of the running process. A value of 0 means that the
484 // process is not running.
Alex Deymo461b2592015-07-24 20:10:52 -0700485 pid_t child_pid_{0};
Alex Deymo29b81532015-07-09 11:51:49 -0700486
487 // The timeout task_id we are waiting on, if any.
488 MessageLoop::TaskId timeout_task_{MessageLoop::kTaskIdNull};
489
490 bool reported_{false};
David Zeuthen27a48bc2013-08-06 12:06:29 -0700491};
492
493void P2PManagerImpl::LookupUrlForFile(const string& file_id,
494 size_t minimum_size,
495 TimeDelta max_time_to_wait,
496 LookupCallback callback) {
497 LookupData *lookup_data = new LookupData(callback);
498 string file_id_with_ext = file_id + "." + file_extension_;
499 vector<string> args = configuration_->GetP2PClientArgs(file_id_with_ext,
500 minimum_size);
Alex Deymo29b81532015-07-09 11:51:49 -0700501 lookup_data->InitiateLookup(args, max_time_to_wait);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700502}
503
504bool P2PManagerImpl::FileShare(const string& file_id,
505 size_t expected_size) {
506 // Check if file already exist.
Alex Deymof329b932014-10-30 01:37:48 -0700507 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700508 if (!path.empty()) {
509 // File exists - double check its expected size though.
510 ssize_t file_expected_size = FileGetExpectedSize(file_id);
511 if (file_expected_size == -1 ||
512 static_cast<size_t>(file_expected_size) != expected_size) {
513 LOG(ERROR) << "Existing p2p file " << path.value()
514 << " with expected_size=" << file_expected_size
515 << " does not match the passed in"
516 << " expected_size=" << expected_size;
517 return false;
518 }
519 return true;
520 }
521
522 // Before creating the file, bail if statvfs(3) indicates that at
523 // least twice the size is not available in P2P_DIR.
524 struct statvfs statvfsbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700525 FilePath p2p_dir = configuration_->GetP2PDir();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700526 if (statvfs(p2p_dir.value().c_str(), &statvfsbuf) != 0) {
527 PLOG(ERROR) << "Error calling statvfs() for dir " << p2p_dir.value();
528 return false;
529 }
530 size_t free_bytes =
531 static_cast<size_t>(statvfsbuf.f_bsize) * statvfsbuf.f_bavail;
532 if (free_bytes < 2 * expected_size) {
533 // This can easily happen and is worth reporting.
534 LOG(INFO) << "Refusing to allocate p2p file of " << expected_size
535 << " bytes since the directory " << p2p_dir.value()
536 << " only has " << free_bytes
537 << " bytes available and this is less than twice the"
538 << " requested size.";
539 return false;
540 }
541
542 // Okie-dokey looks like enough space is available - create the file.
543 path = GetPath(file_id, kNonVisible);
544 int fd = open(path.value().c_str(), O_CREAT | O_RDWR, 0644);
545 if (fd == -1) {
546 PLOG(ERROR) << "Error creating file with path " << path.value();
547 return false;
548 }
549 ScopedFdCloser fd_closer(&fd);
550
551 // If the final size is known, allocate the file (e.g. reserve disk
552 // space) and set the user.cros-p2p-filesize xattr.
553 if (expected_size != 0) {
554 if (fallocate(fd,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700555 FALLOC_FL_KEEP_SIZE, // Keep file size as 0.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700556 0,
557 expected_size) != 0) {
David Zeuthen910ec5b2013-09-26 12:10:58 -0700558 if (errno == ENOSYS || errno == EOPNOTSUPP) {
559 // If the filesystem doesn't support the fallocate, keep
560 // going. This is helpful when running unit tests on build
561 // machines with ancient filesystems and/or OSes.
562 PLOG(WARNING) << "Ignoring fallocate(2) failure";
563 } else {
564 // ENOSPC can happen (funky race though, cf. the statvfs() check
565 // above), handle it gracefully, e.g. use logging level INFO.
566 PLOG(INFO) << "Error allocating " << expected_size
567 << " bytes for file " << path.value();
568 if (unlink(path.value().c_str()) != 0) {
569 PLOG(ERROR) << "Error deleting file with path " << path.value();
570 }
571 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700572 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700573 }
574
Alex Deymoc00c98a2015-03-17 17:38:00 -0700575 string decimal_size = std::to_string(expected_size);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700576 if (fsetxattr(fd, kCrosP2PFileSizeXAttrName,
577 decimal_size.c_str(), decimal_size.size(), 0) != 0) {
578 PLOG(ERROR) << "Error setting xattr " << path.value();
579 return false;
580 }
581 }
582
583 return true;
584}
585
586FilePath P2PManagerImpl::FileGetPath(const string& file_id) {
587 struct stat statbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700588 FilePath path;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700589
590 path = GetPath(file_id, kVisible);
591 if (stat(path.value().c_str(), &statbuf) == 0) {
592 return path;
593 }
594
595 path = GetPath(file_id, kNonVisible);
596 if (stat(path.value().c_str(), &statbuf) == 0) {
597 return path;
598 }
599
600 path.clear();
601 return path;
602}
603
604bool P2PManagerImpl::FileGetVisible(const string& file_id,
605 bool *out_result) {
Alex Deymof329b932014-10-30 01:37:48 -0700606 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700607 if (path.empty()) {
608 LOG(ERROR) << "No file for id " << file_id;
609 return false;
610 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700611 if (out_result != nullptr)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700612 *out_result = path.MatchesExtension(kP2PExtension);
613 return true;
614}
615
616bool P2PManagerImpl::FileMakeVisible(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700617 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700618 if (path.empty()) {
619 LOG(ERROR) << "No file for id " << file_id;
620 return false;
621 }
622
623 // Already visible?
624 if (path.MatchesExtension(kP2PExtension))
625 return true;
626
627 LOG_ASSERT(path.MatchesExtension(kTmpExtension));
Alex Deymof329b932014-10-30 01:37:48 -0700628 FilePath new_path = path.RemoveExtension();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700629 LOG_ASSERT(new_path.MatchesExtension(kP2PExtension));
630 if (rename(path.value().c_str(), new_path.value().c_str()) != 0) {
631 PLOG(ERROR) << "Error renaming " << path.value()
632 << " to " << new_path.value();
633 return false;
634 }
635
636 return true;
637}
638
639ssize_t P2PManagerImpl::FileGetSize(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700640 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700641 if (path.empty())
642 return -1;
643
Gabe Blacka77939e2014-09-09 23:35:08 -0700644 return utils::FileSize(path.value());
David Zeuthen27a48bc2013-08-06 12:06:29 -0700645}
646
647ssize_t P2PManagerImpl::FileGetExpectedSize(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700648 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700649 if (path.empty())
650 return -1;
651
652 char ea_value[64] = { 0 };
653 ssize_t ea_size;
654 ea_size = getxattr(path.value().c_str(), kCrosP2PFileSizeXAttrName,
655 &ea_value, sizeof(ea_value) - 1);
656 if (ea_size == -1) {
657 PLOG(ERROR) << "Error calling getxattr() on file " << path.value();
658 return -1;
659 }
660
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700661 char* endp = nullptr;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700662 long long int val = strtoll(ea_value, &endp, 0); // NOLINT(runtime/int)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700663 if (*endp != '\0') {
664 LOG(ERROR) << "Error parsing the value '" << ea_value
665 << "' of the xattr " << kCrosP2PFileSizeXAttrName
666 << " as an integer";
667 return -1;
668 }
669
670 return val;
671}
672
673int P2PManagerImpl::CountSharedFiles() {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700674 int num_files = 0;
675
Alex Deymof329b932014-10-30 01:37:48 -0700676 FilePath p2p_dir = configuration_->GetP2PDir();
Alex Deymo454b7982015-07-10 10:49:29 -0700677 const string ext_visible = GetExt(kVisible);
678 const string ext_non_visible = GetExt(kNonVisible);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700679
Alex Deymo454b7982015-07-10 10:49:29 -0700680 base::FileEnumerator dir(p2p_dir, false, base::FileEnumerator::FILES);
681 for (FilePath name = dir.Next(); !name.empty(); name = dir.Next()) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800682 if (base::EndsWith(name.value(), ext_visible,
683 base::CompareCase::SENSITIVE) ||
684 base::EndsWith(name.value(), ext_non_visible,
685 base::CompareCase::SENSITIVE)) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700686 num_files += 1;
Alex Vakulenko0103c362016-01-20 07:56:15 -0800687 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700688 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700689
690 return num_files;
691}
692
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700693void P2PManagerImpl::ScheduleEnabledStatusChange() {
694 if (waiting_for_enabled_status_change_)
695 return;
Gilad Arnoldccd09572014-10-27 13:37:50 -0700696
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700697 Callback<void(EvalStatus, const bool&)> callback = Bind(
698 &P2PManagerImpl::OnEnabledStatusChange, base::Unretained(this));
699 update_manager_->AsyncPolicyRequest(callback, &Policy::P2PEnabledChanged,
700 is_enabled_);
701 waiting_for_enabled_status_change_ = true;
Gilad Arnoldccd09572014-10-27 13:37:50 -0700702}
703
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700704void P2PManagerImpl::OnEnabledStatusChange(EvalStatus status,
705 const bool& result) {
706 waiting_for_enabled_status_change_ = false;
707
708 if (status == EvalStatus::kSucceeded) {
709 if (result == is_enabled_) {
710 LOG(WARNING) << "P2P enabled status did not change, which means that it "
711 "is permanent; not scheduling further checks.";
712 waiting_for_enabled_status_change_ = true;
713 return;
714 }
715
716 is_enabled_ = result;
717
718 // If P2P is running but shouldn't be, make sure it isn't.
719 if (may_be_running_ && !is_enabled_ && !EnsureP2PNotRunning()) {
720 LOG(WARNING) << "Failed to stop P2P service.";
721 }
722 } else {
723 LOG(WARNING)
724 << "P2P enabled tracking failed (possibly timed out); retrying.";
725 }
726
727 ScheduleEnabledStatusChange();
728}
729
730P2PManager* P2PManager::Construct(
731 Configuration *configuration,
732 ClockInterface *clock,
733 UpdateManager* update_manager,
734 const string& file_extension,
735 const int num_files_to_keep,
Alex Deymo29b81532015-07-09 11:51:49 -0700736 const TimeDelta& max_file_age) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700737 return new P2PManagerImpl(configuration,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500738 clock,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700739 update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700740 file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500741 num_files_to_keep,
742 max_file_age);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700743}
744
745} // namespace chromeos_update_engine