blob: ee0f5832cf7cf91ef0881b502e32dd4549fc1f08 [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>
14#include <dirent.h>
15#include <errno.h>
16#include <fcntl.h>
17#include <glib.h>
18#include <linux/falloc.h>
19#include <signal.h>
20#include <string.h>
21#include <sys/stat.h>
22#include <sys/statvfs.h>
23#include <sys/types.h>
24#include <unistd.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070025
Alex Vakulenkod2779df2014-06-16 13:19:00 -070026#include <algorithm>
David Zeuthen27a48bc2013-08-06 12:06:29 -070027#include <map>
Ben Chan02f7c1d2014-10-18 15:18:02 -070028#include <memory>
David Zeuthen27a48bc2013-08-06 12:06:29 -070029#include <utility>
30#include <vector>
31
Gilad Arnold4a0321b2014-10-28 15:57:30 -070032#include <base/bind.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070033#include <base/files/file_path.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070034#include <base/logging.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();
David Zeuthen41f2cf52014-11-05 12:29:45 -0500321 GError* error = nullptr;
322 GDir* dir = g_dir_open(p2p_dir.value().c_str(), 0, &error);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700323 if (dir == nullptr) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700324 LOG(ERROR) << "Error opening directory " << p2p_dir.value() << ": "
325 << utils::GetAndFreeGError(&error);
326 return false;
327 }
328
David Zeuthen41f2cf52014-11-05 12:29:45 -0500329 // Go through all files and collect their mtime.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700330 string ext_visible = GetExt(kVisible);
331 string ext_non_visible = GetExt(kNonVisible);
David Zeuthen41f2cf52014-11-05 12:29:45 -0500332 bool deletion_failed = false;
333 const char* name = nullptr;
334 vector<pair<FilePath, Time>> matches;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700335 while ((name = g_dir_read_name(dir)) != nullptr) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700336 if (!(g_str_has_suffix(name, ext_visible.c_str()) ||
337 g_str_has_suffix(name, ext_non_visible.c_str())))
338 continue;
339
340 struct stat statbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700341 FilePath file = p2p_dir.Append(name);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700342 if (stat(file.value().c_str(), &statbuf) != 0) {
343 PLOG(ERROR) << "Error getting file status for " << file.value();
344 continue;
345 }
346
David Zeuthen41f2cf52014-11-05 12:29:45 -0500347 Time time = utils::TimeFromStructTimespec(&statbuf.st_mtim);
348
349 // If instructed to keep only files younger than a given age
350 // (|max_file_age_| != 0), delete files satisfying this criteria
351 // right now. Otherwise add it to a list we'll consider for later.
Alex Deymo29b81532015-07-09 11:51:49 -0700352 if (clock_ != nullptr && max_file_age_ != TimeDelta() &&
David Zeuthen41f2cf52014-11-05 12:29:45 -0500353 clock_->GetWallclockTime() - time > max_file_age_) {
354 if (!DeleteP2PFile(file, "file too old"))
355 deletion_failed = true;
356 } else {
357 matches.push_back(std::make_pair(file, time));
358 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700359 }
360 g_dir_close(dir);
361
David Zeuthen41f2cf52014-11-05 12:29:45 -0500362 // If instructed to only keep N files (|max_files_to_keep_ != 0),
363 // sort list of matches, newest (biggest time) to oldest (lowest
364 // time). Then delete starting at element |num_files_to_keep_|.
365 if (num_files_to_keep_ > 0) {
366 std::sort(matches.begin(), matches.end(), MatchCompareFunc);
367 vector<pair<FilePath, Time>>::const_iterator i;
368 for (i = matches.begin() + num_files_to_keep_; i < matches.end(); ++i) {
369 if (!DeleteP2PFile(i->first, "too many files"))
370 deletion_failed = true;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700371 }
372 }
373
David Zeuthen41f2cf52014-11-05 12:29:45 -0500374 return !deletion_failed;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700375}
376
377// Helper class for implementing LookupUrlForFile().
378class LookupData {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700379 public:
380 explicit LookupData(P2PManager::LookupCallback callback)
Alex Deymo29b81532015-07-09 11:51:49 -0700381 : callback_(callback) {}
David Zeuthen27a48bc2013-08-06 12:06:29 -0700382
383 ~LookupData() {
Alex Deymo29b81532015-07-09 11:51:49 -0700384 if (timeout_task_ != MessageLoop::kTaskIdNull)
385 MessageLoop::current()->CancelTask(timeout_task_);
386 if (child_tag_)
387 Subprocess::Get().KillExec(child_tag_);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700388 }
389
Alex Deymo29b81532015-07-09 11:51:49 -0700390 void InitiateLookup(const vector<string>& cmd, TimeDelta timeout) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700391 // NOTE: if we fail early (i.e. in this method), we need to schedule
392 // an idle to report the error. This is because we guarantee that
Alex Deymo29b81532015-07-09 11:51:49 -0700393 // the callback is always called from the message loop (this
David Zeuthen27a48bc2013-08-06 12:06:29 -0700394 // guarantee is useful for testing).
395
Alex Deymo29b81532015-07-09 11:51:49 -0700396 // We expect to run just "p2p-client" and find it in the path.
397 child_tag_ = Subprocess::Get().ExecFlags(
398 cmd, G_SPAWN_SEARCH_PATH, false /* redirect stderr */, OnLookupDone,
399 this);
400
401 if (!child_tag_) {
402 LOG(ERROR) << "Error spawning " << utils::StringVectorToString(cmd);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700403 ReportErrorAndDeleteInIdle();
404 return;
405 }
406
Alex Deymo29b81532015-07-09 11:51:49 -0700407 if (timeout > TimeDelta()) {
408 timeout_task_ = MessageLoop::current()->PostDelayedTask(
409 FROM_HERE,
410 Bind(&LookupData::OnTimeout, base::Unretained(this)),
411 timeout);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700412 }
413 }
414
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700415 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700416 void ReportErrorAndDeleteInIdle() {
Alex Deymo29b81532015-07-09 11:51:49 -0700417 MessageLoop::current()->PostTask(FROM_HERE, Bind(
418 &LookupData::OnIdleForReportErrorAndDelete,
419 base::Unretained(this)));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700420 }
421
Alex Deymo29b81532015-07-09 11:51:49 -0700422 void OnIdleForReportErrorAndDelete() {
423 ReportError();
424 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700425 }
426
427 void IssueCallback(const string& url) {
428 if (!callback_.is_null())
429 callback_.Run(url);
430 }
431
432 void ReportError() {
433 if (reported_)
434 return;
435 IssueCallback("");
436 reported_ = true;
437 }
438
Alex Deymo29b81532015-07-09 11:51:49 -0700439 void ReportSuccess(const string& output) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700440 if (reported_)
441 return;
Alex Deymo29b81532015-07-09 11:51:49 -0700442 string url = output;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700443 size_t newline_pos = url.find('\n');
444 if (newline_pos != string::npos)
445 url.resize(newline_pos);
446
447 // Since p2p-client(1) is constructing this URL itself strictly
448 // speaking there's no need to validate it... but, anyway, can't
449 // hurt.
450 if (url.compare(0, 7, "http://") == 0) {
451 IssueCallback(url);
452 } else {
453 LOG(ERROR) << "p2p URL '" << url << "' does not look right. Ignoring.";
454 ReportError();
455 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700456 reported_ = true;
457 }
458
Alex Deymo29b81532015-07-09 11:51:49 -0700459 static void OnLookupDone(int return_code,
460 const string& output,
461 void *user_data) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700462 LookupData *lookup_data = reinterpret_cast<LookupData*>(user_data);
Alex Deymo29b81532015-07-09 11:51:49 -0700463 lookup_data->child_tag_ = 0;
464 if (return_code != 0) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700465 LOG(INFO) << "Child exited with non-zero exit code "
Alex Deymo29b81532015-07-09 11:51:49 -0700466 << return_code;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700467 lookup_data->ReportError();
468 } else {
Alex Deymo29b81532015-07-09 11:51:49 -0700469 lookup_data->ReportSuccess(output);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700470 }
471 delete lookup_data;
472 }
473
Alex Deymo29b81532015-07-09 11:51:49 -0700474 void OnTimeout() {
475 timeout_task_ = MessageLoop::kTaskIdNull;
476 ReportError();
477 delete this;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700478 }
479
480 P2PManager::LookupCallback callback_;
Alex Deymo29b81532015-07-09 11:51:49 -0700481
482 // The Subprocess tag of the running process. A value of 0 means that the
483 // process is not running.
484 uint32_t child_tag_{0};
485
486 // The timeout task_id we are waiting on, if any.
487 MessageLoop::TaskId timeout_task_{MessageLoop::kTaskIdNull};
488
489 bool reported_{false};
David Zeuthen27a48bc2013-08-06 12:06:29 -0700490};
491
492void P2PManagerImpl::LookupUrlForFile(const string& file_id,
493 size_t minimum_size,
494 TimeDelta max_time_to_wait,
495 LookupCallback callback) {
496 LookupData *lookup_data = new LookupData(callback);
497 string file_id_with_ext = file_id + "." + file_extension_;
498 vector<string> args = configuration_->GetP2PClientArgs(file_id_with_ext,
499 minimum_size);
Alex Deymo29b81532015-07-09 11:51:49 -0700500 lookup_data->InitiateLookup(args, max_time_to_wait);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700501}
502
503bool P2PManagerImpl::FileShare(const string& file_id,
504 size_t expected_size) {
505 // Check if file already exist.
Alex Deymof329b932014-10-30 01:37:48 -0700506 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700507 if (!path.empty()) {
508 // File exists - double check its expected size though.
509 ssize_t file_expected_size = FileGetExpectedSize(file_id);
510 if (file_expected_size == -1 ||
511 static_cast<size_t>(file_expected_size) != expected_size) {
512 LOG(ERROR) << "Existing p2p file " << path.value()
513 << " with expected_size=" << file_expected_size
514 << " does not match the passed in"
515 << " expected_size=" << expected_size;
516 return false;
517 }
518 return true;
519 }
520
521 // Before creating the file, bail if statvfs(3) indicates that at
522 // least twice the size is not available in P2P_DIR.
523 struct statvfs statvfsbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700524 FilePath p2p_dir = configuration_->GetP2PDir();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700525 if (statvfs(p2p_dir.value().c_str(), &statvfsbuf) != 0) {
526 PLOG(ERROR) << "Error calling statvfs() for dir " << p2p_dir.value();
527 return false;
528 }
529 size_t free_bytes =
530 static_cast<size_t>(statvfsbuf.f_bsize) * statvfsbuf.f_bavail;
531 if (free_bytes < 2 * expected_size) {
532 // This can easily happen and is worth reporting.
533 LOG(INFO) << "Refusing to allocate p2p file of " << expected_size
534 << " bytes since the directory " << p2p_dir.value()
535 << " only has " << free_bytes
536 << " bytes available and this is less than twice the"
537 << " requested size.";
538 return false;
539 }
540
541 // Okie-dokey looks like enough space is available - create the file.
542 path = GetPath(file_id, kNonVisible);
543 int fd = open(path.value().c_str(), O_CREAT | O_RDWR, 0644);
544 if (fd == -1) {
545 PLOG(ERROR) << "Error creating file with path " << path.value();
546 return false;
547 }
548 ScopedFdCloser fd_closer(&fd);
549
550 // If the final size is known, allocate the file (e.g. reserve disk
551 // space) and set the user.cros-p2p-filesize xattr.
552 if (expected_size != 0) {
553 if (fallocate(fd,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700554 FALLOC_FL_KEEP_SIZE, // Keep file size as 0.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700555 0,
556 expected_size) != 0) {
David Zeuthen910ec5b2013-09-26 12:10:58 -0700557 if (errno == ENOSYS || errno == EOPNOTSUPP) {
558 // If the filesystem doesn't support the fallocate, keep
559 // going. This is helpful when running unit tests on build
560 // machines with ancient filesystems and/or OSes.
561 PLOG(WARNING) << "Ignoring fallocate(2) failure";
562 } else {
563 // ENOSPC can happen (funky race though, cf. the statvfs() check
564 // above), handle it gracefully, e.g. use logging level INFO.
565 PLOG(INFO) << "Error allocating " << expected_size
566 << " bytes for file " << path.value();
567 if (unlink(path.value().c_str()) != 0) {
568 PLOG(ERROR) << "Error deleting file with path " << path.value();
569 }
570 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700571 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700572 }
573
Alex Deymof329b932014-10-30 01:37:48 -0700574 string decimal_size = StringPrintf("%zu", expected_size);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700575 if (fsetxattr(fd, kCrosP2PFileSizeXAttrName,
576 decimal_size.c_str(), decimal_size.size(), 0) != 0) {
577 PLOG(ERROR) << "Error setting xattr " << path.value();
578 return false;
579 }
580 }
581
582 return true;
583}
584
585FilePath P2PManagerImpl::FileGetPath(const string& file_id) {
586 struct stat statbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700587 FilePath path;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700588
589 path = GetPath(file_id, kVisible);
590 if (stat(path.value().c_str(), &statbuf) == 0) {
591 return path;
592 }
593
594 path = GetPath(file_id, kNonVisible);
595 if (stat(path.value().c_str(), &statbuf) == 0) {
596 return path;
597 }
598
599 path.clear();
600 return path;
601}
602
603bool P2PManagerImpl::FileGetVisible(const string& file_id,
604 bool *out_result) {
Alex Deymof329b932014-10-30 01:37:48 -0700605 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700606 if (path.empty()) {
607 LOG(ERROR) << "No file for id " << file_id;
608 return false;
609 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700610 if (out_result != nullptr)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700611 *out_result = path.MatchesExtension(kP2PExtension);
612 return true;
613}
614
615bool P2PManagerImpl::FileMakeVisible(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700616 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700617 if (path.empty()) {
618 LOG(ERROR) << "No file for id " << file_id;
619 return false;
620 }
621
622 // Already visible?
623 if (path.MatchesExtension(kP2PExtension))
624 return true;
625
626 LOG_ASSERT(path.MatchesExtension(kTmpExtension));
Alex Deymof329b932014-10-30 01:37:48 -0700627 FilePath new_path = path.RemoveExtension();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700628 LOG_ASSERT(new_path.MatchesExtension(kP2PExtension));
629 if (rename(path.value().c_str(), new_path.value().c_str()) != 0) {
630 PLOG(ERROR) << "Error renaming " << path.value()
631 << " to " << new_path.value();
632 return false;
633 }
634
635 return true;
636}
637
638ssize_t P2PManagerImpl::FileGetSize(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700639 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700640 if (path.empty())
641 return -1;
642
Gabe Blacka77939e2014-09-09 23:35:08 -0700643 return utils::FileSize(path.value());
David Zeuthen27a48bc2013-08-06 12:06:29 -0700644}
645
646ssize_t P2PManagerImpl::FileGetExpectedSize(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700647 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700648 if (path.empty())
649 return -1;
650
651 char ea_value[64] = { 0 };
652 ssize_t ea_size;
653 ea_size = getxattr(path.value().c_str(), kCrosP2PFileSizeXAttrName,
654 &ea_value, sizeof(ea_value) - 1);
655 if (ea_size == -1) {
656 PLOG(ERROR) << "Error calling getxattr() on file " << path.value();
657 return -1;
658 }
659
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700660 char* endp = nullptr;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700661 long long int val = strtoll(ea_value, &endp, 0); // NOLINT(runtime/int)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700662 if (*endp != '\0') {
663 LOG(ERROR) << "Error parsing the value '" << ea_value
664 << "' of the xattr " << kCrosP2PFileSizeXAttrName
665 << " as an integer";
666 return -1;
667 }
668
669 return val;
670}
671
672int P2PManagerImpl::CountSharedFiles() {
673 GDir* dir;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700674 GError* error = nullptr;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700675 const char* name;
676 int num_files = 0;
677
Alex Deymof329b932014-10-30 01:37:48 -0700678 FilePath p2p_dir = configuration_->GetP2PDir();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700679 dir = g_dir_open(p2p_dir.value().c_str(), 0, &error);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700680 if (dir == nullptr) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700681 LOG(ERROR) << "Error opening directory " << p2p_dir.value() << ": "
682 << utils::GetAndFreeGError(&error);
683 return -1;
684 }
685
686 string ext_visible = GetExt(kVisible);
687 string ext_non_visible = GetExt(kNonVisible);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700688 while ((name = g_dir_read_name(dir)) != nullptr) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700689 if (g_str_has_suffix(name, ext_visible.c_str()) ||
690 g_str_has_suffix(name, ext_non_visible.c_str())) {
691 num_files += 1;
692 }
693 }
694 g_dir_close(dir);
695
696 return num_files;
697}
698
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700699void P2PManagerImpl::ScheduleEnabledStatusChange() {
700 if (waiting_for_enabled_status_change_)
701 return;
Gilad Arnoldccd09572014-10-27 13:37:50 -0700702
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700703 Callback<void(EvalStatus, const bool&)> callback = Bind(
704 &P2PManagerImpl::OnEnabledStatusChange, base::Unretained(this));
705 update_manager_->AsyncPolicyRequest(callback, &Policy::P2PEnabledChanged,
706 is_enabled_);
707 waiting_for_enabled_status_change_ = true;
Gilad Arnoldccd09572014-10-27 13:37:50 -0700708}
709
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700710void P2PManagerImpl::OnEnabledStatusChange(EvalStatus status,
711 const bool& result) {
712 waiting_for_enabled_status_change_ = false;
713
714 if (status == EvalStatus::kSucceeded) {
715 if (result == is_enabled_) {
716 LOG(WARNING) << "P2P enabled status did not change, which means that it "
717 "is permanent; not scheduling further checks.";
718 waiting_for_enabled_status_change_ = true;
719 return;
720 }
721
722 is_enabled_ = result;
723
724 // If P2P is running but shouldn't be, make sure it isn't.
725 if (may_be_running_ && !is_enabled_ && !EnsureP2PNotRunning()) {
726 LOG(WARNING) << "Failed to stop P2P service.";
727 }
728 } else {
729 LOG(WARNING)
730 << "P2P enabled tracking failed (possibly timed out); retrying.";
731 }
732
733 ScheduleEnabledStatusChange();
734}
735
736P2PManager* P2PManager::Construct(
737 Configuration *configuration,
738 ClockInterface *clock,
739 UpdateManager* update_manager,
740 const string& file_extension,
741 const int num_files_to_keep,
Alex Deymo29b81532015-07-09 11:51:49 -0700742 const TimeDelta& max_file_age) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700743 return new P2PManagerImpl(configuration,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500744 clock,
Gilad Arnold4a0321b2014-10-28 15:57:30 -0700745 update_manager,
David Zeuthen27a48bc2013-08-06 12:06:29 -0700746 file_extension,
David Zeuthen41f2cf52014-11-05 12:29:45 -0500747 num_files_to_keep,
748 max_file_age);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700749}
750
751} // namespace chromeos_update_engine