blob: 240b44a293fb47c8a613c25179ef089953b38edb [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
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 Vakulenko75039d72014-03-25 12:36:28 -070034#include <base/strings/stringprintf.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070035
Alex Deymo44666f92014-07-22 20:29:24 -070036#include "update_engine/glib_utils.h"
David Zeuthen27a48bc2013-08-06 12:06:29 -070037#include "update_engine/utils.h"
38
39using base::FilePath;
40using base::StringPrintf;
41using base::Time;
42using base::TimeDelta;
43using std::map;
44using std::pair;
45using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070046using std::unique_ptr;
David Zeuthen27a48bc2013-08-06 12:06:29 -070047using std::vector;
48
49namespace chromeos_update_engine {
50
51namespace {
52
53// The default p2p directory.
54const char kDefaultP2PDir[] = "/var/cache/p2p";
55
56// The p2p xattr used for conveying the final size of a file - see the
57// p2p ddoc for details.
58const char kCrosP2PFileSizeXAttrName[] = "user.cros-p2p-filesize";
59
Alex Vakulenkod2779df2014-06-16 13:19:00 -070060} // namespace
David Zeuthen27a48bc2013-08-06 12:06:29 -070061
62// The default P2PManager::Configuration implementation.
63class ConfigurationImpl : public P2PManager::Configuration {
Alex Vakulenkod2779df2014-06-16 13:19:00 -070064 public:
David Zeuthen27a48bc2013-08-06 12:06:29 -070065 ConfigurationImpl() {}
66
67 virtual ~ConfigurationImpl() {}
68
Alex Deymof329b932014-10-30 01:37:48 -070069 virtual FilePath GetP2PDir() {
70 return FilePath(kDefaultP2PDir);
David Zeuthen27a48bc2013-08-06 12:06:29 -070071 }
72
73 virtual vector<string> GetInitctlArgs(bool is_start) {
74 vector<string> args;
75 args.push_back("initctl");
76 args.push_back(is_start ? "start" : "stop");
77 args.push_back("p2p");
78 return args;
79 }
80
81 virtual vector<string> GetP2PClientArgs(const string &file_id,
82 size_t minimum_size) {
83 vector<string> args;
84 args.push_back("p2p-client");
85 args.push_back(string("--get-url=") + file_id);
Alex Deymof329b932014-10-30 01:37:48 -070086 args.push_back(StringPrintf("--minimum-size=%zu", minimum_size));
David Zeuthen27a48bc2013-08-06 12:06:29 -070087 return args;
88 }
89
Alex Vakulenkod2779df2014-06-16 13:19:00 -070090 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -070091 DISALLOW_COPY_AND_ASSIGN(ConfigurationImpl);
92};
93
94// The default P2PManager implementation.
95class P2PManagerImpl : public P2PManager {
Alex Vakulenkod2779df2014-06-16 13:19:00 -070096 public:
David Zeuthen27a48bc2013-08-06 12:06:29 -070097 P2PManagerImpl(Configuration *configuration,
98 PrefsInterface *prefs,
99 const string& file_extension,
100 const int num_files_to_keep);
101
102 // P2PManager methods.
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700103 virtual void SetDevicePolicy(const policy::DevicePolicy* device_policy);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700104 virtual bool IsP2PEnabled();
105 virtual bool EnsureP2PRunning();
106 virtual bool EnsureP2PNotRunning();
107 virtual bool PerformHousekeeping();
108 virtual void LookupUrlForFile(const string& file_id,
109 size_t minimum_size,
110 TimeDelta max_time_to_wait,
111 LookupCallback callback);
112 virtual bool FileShare(const string& file_id,
113 size_t expected_size);
Alex Deymof329b932014-10-30 01:37:48 -0700114 virtual FilePath FileGetPath(const string& file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700115 virtual ssize_t FileGetSize(const string& file_id);
116 virtual ssize_t FileGetExpectedSize(const string& file_id);
117 virtual bool FileGetVisible(const string& file_id,
118 bool *out_result);
119 virtual bool FileMakeVisible(const string& file_id);
120 virtual int CountSharedFiles();
Gilad Arnoldccd09572014-10-27 13:37:50 -0700121 bool SetP2PEnabledPref(bool enabled) override;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700122
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700123 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700124 // Enumeration for specifying visibility.
125 enum Visibility {
126 kVisible,
127 kNonVisible
128 };
129
130 // Returns "." + |file_extension_| + ".p2p" if |visibility| is
131 // |kVisible|. Returns the same concatenated with ".tmp" otherwise.
132 string GetExt(Visibility visibility);
133
134 // Gets the on-disk path for |file_id| depending on if the file
135 // is visible or not.
Alex Deymof329b932014-10-30 01:37:48 -0700136 FilePath GetPath(const string& file_id, Visibility visibility);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700137
138 // Utility function used by EnsureP2PRunning() and EnsureP2PNotRunning().
139 bool EnsureP2P(bool should_be_running);
140
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700141 // The device policy being used or null if no policy is being used.
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700142 const policy::DevicePolicy* device_policy_;
143
David Zeuthen27a48bc2013-08-06 12:06:29 -0700144 // Configuration object.
Ben Chan02f7c1d2014-10-18 15:18:02 -0700145 unique_ptr<Configuration> configuration_;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700146
147 // Object for persisted state.
148 PrefsInterface* prefs_;
149
150 // A short string unique to the application (for example "cros_au")
151 // used to mark a file as being owned by a particular application.
152 const string file_extension_;
153
154 // If non-zero, this number denotes how many files in /var/cache/p2p
155 // owned by the application (cf. |file_extension_|) to keep after
156 // performing housekeeping.
157 const int num_files_to_keep_;
158
159 // The string ".p2p".
160 static const char kP2PExtension[];
161
162 // The string ".tmp".
163 static const char kTmpExtension[];
164
Gilad Arnoldccd09572014-10-27 13:37:50 -0700165 // Whether P2P service may be running; initially, we assume it may be.
166 bool may_be_running_ = true;
167
David Zeuthen27a48bc2013-08-06 12:06:29 -0700168 DISALLOW_COPY_AND_ASSIGN(P2PManagerImpl);
169};
170
171const char P2PManagerImpl::kP2PExtension[] = ".p2p";
172
173const char P2PManagerImpl::kTmpExtension[] = ".tmp";
174
175P2PManagerImpl::P2PManagerImpl(Configuration *configuration,
176 PrefsInterface *prefs,
177 const string& file_extension,
178 const int num_files_to_keep)
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700179 : device_policy_(nullptr),
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700180 prefs_(prefs),
David Zeuthen27a48bc2013-08-06 12:06:29 -0700181 file_extension_(file_extension),
182 num_files_to_keep_(num_files_to_keep) {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700183 configuration_.reset(configuration != nullptr ? configuration :
David Zeuthen27a48bc2013-08-06 12:06:29 -0700184 new ConfigurationImpl());
185}
186
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700187void P2PManagerImpl::SetDevicePolicy(
188 const policy::DevicePolicy* device_policy) {
189 device_policy_ = device_policy;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700190}
191
192bool P2PManagerImpl::IsP2PEnabled() {
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700193 bool p2p_enabled = false;
194
195 // The logic we want here is additive, e.g. p2p can be enabled by
196 // either the crosh flag OR by Enterprise Policy, e.g. the following
197 // truth table:
198 //
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400199 // crosh_flag == FALSE && enterprise_policy == unset -> use_p2p == *
200 // crosh_flag == TRUE && enterprise_policy == unset -> use_p2p == TRUE
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700201 // crosh_flag == FALSE && enterprise_policy == FALSE -> use_p2p == FALSE
202 // crosh_flag == FALSE && enterprise_policy == TRUE -> use_p2p == TRUE
203 // crosh_flag == TRUE && enterprise_policy == FALSE -> use_p2p == TRUE
204 // crosh_flag == TRUE && enterprise_policy == TRUE -> use_p2p == TRUE
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400205 //
206 // *: TRUE if Enterprise Enrolled, FALSE otherwise.
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700207
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700208 if (prefs_ != nullptr &&
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700209 prefs_->Exists(kPrefsP2PEnabled) &&
210 prefs_->GetBoolean(kPrefsP2PEnabled, &p2p_enabled) &&
211 p2p_enabled) {
212 LOG(INFO) << "The crosh flag indicates that p2p is enabled.";
213 return true;
214 }
215
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400216 if (device_policy_ != nullptr) {
217 if (device_policy_->GetAuP2PEnabled(&p2p_enabled)) {
218 if (p2p_enabled) {
219 LOG(INFO) << "Enterprise Policy indicates that p2p is enabled.";
220 return true;
221 }
222 } else {
223 // Enterprise-enrolled devices have an empty owner in their device policy.
224 string owner;
225 if (!device_policy_->GetOwner(&owner) || owner.empty()) {
226 LOG(INFO) << "No p2p_enabled setting in Enterprise Policy but device "
227 << "is Enterprise Enrolled so allowing p2p.";
228 return true;
229 }
230 }
231 }
232
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700233 LOG(INFO) << "Neither Enterprise Policy nor crosh flag indicates that p2p "
234 << "is enabled.";
235 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700236}
237
238bool P2PManagerImpl::EnsureP2P(bool should_be_running) {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700239 gchar *standard_error = nullptr;
240 GError *error = nullptr;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700241 gint exit_status = 0;
242
Gilad Arnoldccd09572014-10-27 13:37:50 -0700243 may_be_running_ = true; // Unless successful, we must be conservative.
244
David Zeuthen27a48bc2013-08-06 12:06:29 -0700245 vector<string> args = configuration_->GetInitctlArgs(should_be_running);
Ben Chan02f7c1d2014-10-18 15:18:02 -0700246 unique_ptr<gchar*, GLibStrvFreeDeleter> argv(
David Zeuthen27a48bc2013-08-06 12:06:29 -0700247 utils::StringVectorToGStrv(args));
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700248 if (!g_spawn_sync(nullptr, // working_directory
David Zeuthen27a48bc2013-08-06 12:06:29 -0700249 argv.get(),
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700250 nullptr, // envp
David Zeuthen27a48bc2013-08-06 12:06:29 -0700251 static_cast<GSpawnFlags>(G_SPAWN_SEARCH_PATH),
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700252 nullptr, nullptr, // child_setup, user_data
253 nullptr, // standard_output
David Zeuthen27a48bc2013-08-06 12:06:29 -0700254 &standard_error,
255 &exit_status,
256 &error)) {
257 LOG(ERROR) << "Error spawning " << utils::StringVectorToString(args)
258 << ": " << utils::GetAndFreeGError(&error);
259 return false;
260 }
Ben Chan02f7c1d2014-10-18 15:18:02 -0700261 unique_ptr<gchar, GLibFreeDeleter> standard_error_deleter(standard_error);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700262
263 if (!WIFEXITED(exit_status)) {
264 LOG(ERROR) << "Error spawning '" << utils::StringVectorToString(args)
265 << "': WIFEXITED is false";
266 return false;
267 }
268
Gilad Arnoldccd09572014-10-27 13:37:50 -0700269 // If initctl(8) does not exit normally (exit status other than zero), ensure
270 // that the error message is not benign by scanning stderr; this is a
271 // necessity because initctl does not offer actions such as "start if not
272 // running" or "stop if running".
David Zeuthen27a48bc2013-08-06 12:06:29 -0700273 // TODO(zeuthen,chromium:277051): Avoid doing this.
Gilad Arnoldccd09572014-10-27 13:37:50 -0700274 if (WEXITSTATUS(exit_status) != 0) {
275 const gchar *expected_error_message = should_be_running ?
276 "initctl: Job is already running: p2p\n" :
277 "initctl: Unknown instance \n";
278 if (g_strcmp0(standard_error, expected_error_message) != 0)
279 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700280 }
281
Gilad Arnoldccd09572014-10-27 13:37:50 -0700282 may_be_running_ = should_be_running; // Successful after all.
283 return true;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700284}
285
286bool P2PManagerImpl::EnsureP2PRunning() {
287 return EnsureP2P(true);
288}
289
290bool P2PManagerImpl::EnsureP2PNotRunning() {
291 return EnsureP2P(false);
292}
293
294// Returns True if the timestamp in the first pair is greater than the
295// timestamp in the latter. If used with std::sort() this will yield a
296// sequence of elements where newer (high timestamps) elements precede
297// older ones (low timestamps).
298static bool MatchCompareFunc(const pair<FilePath, Time>& a,
299 const pair<FilePath, Time>& b) {
300 return a.second > b.second;
301}
302
303string P2PManagerImpl::GetExt(Visibility visibility) {
304 string ext = string(".") + file_extension_ + kP2PExtension;
305 switch (visibility) {
306 case kVisible:
307 break;
308 case kNonVisible:
309 ext += kTmpExtension;
310 break;
311 // Don't add a default case to let the compiler warn about newly
312 // added enum values.
313 }
314 return ext;
315}
316
317FilePath P2PManagerImpl::GetPath(const string& file_id, Visibility visibility) {
318 return configuration_->GetP2PDir().Append(file_id + GetExt(visibility));
319}
320
321bool P2PManagerImpl::PerformHousekeeping() {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700322 GDir* dir = nullptr;
323 GError* error = nullptr;
324 const char* name = nullptr;
Ben Chanf9cb98c2014-09-21 18:31:30 -0700325 vector<pair<FilePath, Time>> matches;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700326
327 // Go through all files in the p2p dir and pick the ones that match
328 // and get their ctime.
Alex Deymof329b932014-10-30 01:37:48 -0700329 FilePath p2p_dir = configuration_->GetP2PDir();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700330 dir = g_dir_open(p2p_dir.value().c_str(), 0, &error);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700331 if (dir == nullptr) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700332 LOG(ERROR) << "Error opening directory " << p2p_dir.value() << ": "
333 << utils::GetAndFreeGError(&error);
334 return false;
335 }
336
337 if (num_files_to_keep_ == 0)
338 return true;
339
340 string ext_visible = GetExt(kVisible);
341 string ext_non_visible = GetExt(kNonVisible);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700342 while ((name = g_dir_read_name(dir)) != nullptr) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700343 if (!(g_str_has_suffix(name, ext_visible.c_str()) ||
344 g_str_has_suffix(name, ext_non_visible.c_str())))
345 continue;
346
347 struct stat statbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700348 FilePath file = p2p_dir.Append(name);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700349 if (stat(file.value().c_str(), &statbuf) != 0) {
350 PLOG(ERROR) << "Error getting file status for " << file.value();
351 continue;
352 }
353
354 Time time = utils::TimeFromStructTimespec(&statbuf.st_ctim);
355 matches.push_back(std::make_pair(file, time));
356 }
357 g_dir_close(dir);
358
359 // Sort list of matches, newest (biggest time) to oldest (lowest time).
360 std::sort(matches.begin(), matches.end(), MatchCompareFunc);
361
362 // Delete starting at element num_files_to_keep_.
Ben Chanf9cb98c2014-09-21 18:31:30 -0700363 vector<pair<FilePath, Time>>::const_iterator i;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700364 for (i = matches.begin() + num_files_to_keep_; i < matches.end(); ++i) {
Alex Deymof329b932014-10-30 01:37:48 -0700365 const FilePath& file = i->first;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700366 LOG(INFO) << "Deleting p2p file " << file.value();
367 if (unlink(file.value().c_str()) != 0) {
368 PLOG(ERROR) << "Error deleting p2p file " << file.value();
369 return false;
370 }
371 }
372
373 return true;
374}
375
376// Helper class for implementing LookupUrlForFile().
377class LookupData {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700378 public:
379 explicit LookupData(P2PManager::LookupCallback callback)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700380 : callback_(callback),
381 pid_(0),
382 stdout_fd_(-1),
383 stdout_channel_source_id_(0),
384 child_watch_source_id_(0),
385 timeout_source_id_(0),
386 reported_(false) {}
387
388 ~LookupData() {
389 if (child_watch_source_id_ != 0)
390 g_source_remove(child_watch_source_id_);
391 if (stdout_channel_source_id_ != 0)
392 g_source_remove(stdout_channel_source_id_);
393 if (timeout_source_id_ != 0)
394 g_source_remove(timeout_source_id_);
395 if (stdout_fd_ != -1)
396 close(stdout_fd_);
397 if (pid_ != 0)
398 kill(pid_, SIGTERM);
399 }
400
401 void InitiateLookup(gchar **argv, TimeDelta timeout) {
402 // NOTE: if we fail early (i.e. in this method), we need to schedule
403 // an idle to report the error. This is because we guarantee that
Alex Vakulenko072359c2014-07-18 11:41:07 -0700404 // the callback is always called from the GLib mainloop (this
David Zeuthen27a48bc2013-08-06 12:06:29 -0700405 // guarantee is useful for testing).
406
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700407 GError *error = nullptr;
408 if (!g_spawn_async_with_pipes(nullptr, // working_directory
David Zeuthen27a48bc2013-08-06 12:06:29 -0700409 argv,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700410 nullptr, // envp
David Zeuthen27a48bc2013-08-06 12:06:29 -0700411 static_cast<GSpawnFlags>(G_SPAWN_SEARCH_PATH |
412 G_SPAWN_DO_NOT_REAP_CHILD),
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700413 nullptr, // child_setup
David Zeuthen27a48bc2013-08-06 12:06:29 -0700414 this,
415 &pid_,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700416 nullptr, // standard_input
David Zeuthen27a48bc2013-08-06 12:06:29 -0700417 &stdout_fd_,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700418 nullptr, // standard_error
David Zeuthen27a48bc2013-08-06 12:06:29 -0700419 &error)) {
420 LOG(ERROR) << "Error spawning p2p-client: "
421 << utils::GetAndFreeGError(&error);
422 ReportErrorAndDeleteInIdle();
423 return;
424 }
425
426 GIOChannel* io_channel = g_io_channel_unix_new(stdout_fd_);
427 stdout_channel_source_id_ = g_io_add_watch(
428 io_channel,
429 static_cast<GIOCondition>(G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP),
430 OnIOChannelActivity, this);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700431 CHECK_NE(stdout_channel_source_id_, 0u);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700432 g_io_channel_unref(io_channel);
433
434 child_watch_source_id_ = g_child_watch_add(pid_, OnChildWatchActivity,
435 this);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700436 CHECK_NE(child_watch_source_id_, 0u);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700437
438 if (timeout.ToInternalValue() > 0) {
439 timeout_source_id_ = g_timeout_add(timeout.InMilliseconds(),
440 OnTimeout, this);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700441 CHECK_NE(timeout_source_id_, 0u);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700442 }
443 }
444
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700445 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700446 void ReportErrorAndDeleteInIdle() {
447 g_idle_add(static_cast<GSourceFunc>(OnIdleForReportErrorAndDelete), this);
448 }
449
450 static gboolean OnIdleForReportErrorAndDelete(gpointer user_data) {
451 LookupData *lookup_data = reinterpret_cast<LookupData*>(user_data);
452 lookup_data->ReportError();
453 delete lookup_data;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700454 return FALSE; // Remove source.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700455 }
456
457 void IssueCallback(const string& url) {
458 if (!callback_.is_null())
459 callback_.Run(url);
460 }
461
462 void ReportError() {
463 if (reported_)
464 return;
465 IssueCallback("");
466 reported_ = true;
467 }
468
469 void ReportSuccess() {
470 if (reported_)
471 return;
472
473 string url = stdout_;
474 size_t newline_pos = url.find('\n');
475 if (newline_pos != string::npos)
476 url.resize(newline_pos);
477
478 // Since p2p-client(1) is constructing this URL itself strictly
479 // speaking there's no need to validate it... but, anyway, can't
480 // hurt.
481 if (url.compare(0, 7, "http://") == 0) {
482 IssueCallback(url);
483 } else {
484 LOG(ERROR) << "p2p URL '" << url << "' does not look right. Ignoring.";
485 ReportError();
486 }
487
488 reported_ = true;
489 }
490
491 static gboolean OnIOChannelActivity(GIOChannel *source,
492 GIOCondition condition,
493 gpointer user_data) {
494 LookupData *lookup_data = reinterpret_cast<LookupData*>(user_data);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700495 gchar* str = nullptr;
496 GError* error = nullptr;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700497 GIOStatus status = g_io_channel_read_line(source,
498 &str,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700499 nullptr, // len
500 nullptr, // line_terminator
David Zeuthen27a48bc2013-08-06 12:06:29 -0700501 &error);
502 if (status != G_IO_STATUS_NORMAL) {
503 // Ignore EOF since we usually get that before SIGCHLD and we
504 // need to examine exit status there.
505 if (status != G_IO_STATUS_EOF) {
506 LOG(ERROR) << "Error reading a line from p2p-client: "
507 << utils::GetAndFreeGError(&error);
508 lookup_data->ReportError();
509 delete lookup_data;
510 }
511 } else {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700512 if (str != nullptr) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700513 lookup_data->stdout_ += str;
514 g_free(str);
515 }
516 }
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700517 return TRUE; // Don't remove source.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700518 }
519
520 static void OnChildWatchActivity(GPid pid,
521 gint status,
522 gpointer user_data) {
523 LookupData *lookup_data = reinterpret_cast<LookupData*>(user_data);
524
525 if (!WIFEXITED(status)) {
526 LOG(ERROR) << "Child didn't exit normally";
527 lookup_data->ReportError();
528 } else if (WEXITSTATUS(status) != 0) {
529 LOG(INFO) << "Child exited with non-zero exit code "
530 << WEXITSTATUS(status);
531 lookup_data->ReportError();
532 } else {
533 lookup_data->ReportSuccess();
534 }
535 delete lookup_data;
536 }
537
538 static gboolean OnTimeout(gpointer user_data) {
539 LookupData *lookup_data = reinterpret_cast<LookupData*>(user_data);
540 lookup_data->ReportError();
541 delete lookup_data;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700542 return TRUE; // Don't remove source.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700543 }
544
545 P2PManager::LookupCallback callback_;
546 GPid pid_;
547 gint stdout_fd_;
548 guint stdout_channel_source_id_;
549 guint child_watch_source_id_;
550 guint timeout_source_id_;
551 string stdout_;
552 bool reported_;
553};
554
555void P2PManagerImpl::LookupUrlForFile(const string& file_id,
556 size_t minimum_size,
557 TimeDelta max_time_to_wait,
558 LookupCallback callback) {
559 LookupData *lookup_data = new LookupData(callback);
560 string file_id_with_ext = file_id + "." + file_extension_;
561 vector<string> args = configuration_->GetP2PClientArgs(file_id_with_ext,
562 minimum_size);
563 gchar **argv = utils::StringVectorToGStrv(args);
564 lookup_data->InitiateLookup(argv, max_time_to_wait);
565 g_strfreev(argv);
566}
567
568bool P2PManagerImpl::FileShare(const string& file_id,
569 size_t expected_size) {
570 // Check if file already exist.
Alex Deymof329b932014-10-30 01:37:48 -0700571 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700572 if (!path.empty()) {
573 // File exists - double check its expected size though.
574 ssize_t file_expected_size = FileGetExpectedSize(file_id);
575 if (file_expected_size == -1 ||
576 static_cast<size_t>(file_expected_size) != expected_size) {
577 LOG(ERROR) << "Existing p2p file " << path.value()
578 << " with expected_size=" << file_expected_size
579 << " does not match the passed in"
580 << " expected_size=" << expected_size;
581 return false;
582 }
583 return true;
584 }
585
586 // Before creating the file, bail if statvfs(3) indicates that at
587 // least twice the size is not available in P2P_DIR.
588 struct statvfs statvfsbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700589 FilePath p2p_dir = configuration_->GetP2PDir();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700590 if (statvfs(p2p_dir.value().c_str(), &statvfsbuf) != 0) {
591 PLOG(ERROR) << "Error calling statvfs() for dir " << p2p_dir.value();
592 return false;
593 }
594 size_t free_bytes =
595 static_cast<size_t>(statvfsbuf.f_bsize) * statvfsbuf.f_bavail;
596 if (free_bytes < 2 * expected_size) {
597 // This can easily happen and is worth reporting.
598 LOG(INFO) << "Refusing to allocate p2p file of " << expected_size
599 << " bytes since the directory " << p2p_dir.value()
600 << " only has " << free_bytes
601 << " bytes available and this is less than twice the"
602 << " requested size.";
603 return false;
604 }
605
606 // Okie-dokey looks like enough space is available - create the file.
607 path = GetPath(file_id, kNonVisible);
608 int fd = open(path.value().c_str(), O_CREAT | O_RDWR, 0644);
609 if (fd == -1) {
610 PLOG(ERROR) << "Error creating file with path " << path.value();
611 return false;
612 }
613 ScopedFdCloser fd_closer(&fd);
614
615 // If the final size is known, allocate the file (e.g. reserve disk
616 // space) and set the user.cros-p2p-filesize xattr.
617 if (expected_size != 0) {
618 if (fallocate(fd,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700619 FALLOC_FL_KEEP_SIZE, // Keep file size as 0.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700620 0,
621 expected_size) != 0) {
David Zeuthen910ec5b2013-09-26 12:10:58 -0700622 if (errno == ENOSYS || errno == EOPNOTSUPP) {
623 // If the filesystem doesn't support the fallocate, keep
624 // going. This is helpful when running unit tests on build
625 // machines with ancient filesystems and/or OSes.
626 PLOG(WARNING) << "Ignoring fallocate(2) failure";
627 } else {
628 // ENOSPC can happen (funky race though, cf. the statvfs() check
629 // above), handle it gracefully, e.g. use logging level INFO.
630 PLOG(INFO) << "Error allocating " << expected_size
631 << " bytes for file " << path.value();
632 if (unlink(path.value().c_str()) != 0) {
633 PLOG(ERROR) << "Error deleting file with path " << path.value();
634 }
635 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700636 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700637 }
638
Alex Deymof329b932014-10-30 01:37:48 -0700639 string decimal_size = StringPrintf("%zu", expected_size);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700640 if (fsetxattr(fd, kCrosP2PFileSizeXAttrName,
641 decimal_size.c_str(), decimal_size.size(), 0) != 0) {
642 PLOG(ERROR) << "Error setting xattr " << path.value();
643 return false;
644 }
645 }
646
647 return true;
648}
649
650FilePath P2PManagerImpl::FileGetPath(const string& file_id) {
651 struct stat statbuf;
Alex Deymof329b932014-10-30 01:37:48 -0700652 FilePath path;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700653
654 path = GetPath(file_id, kVisible);
655 if (stat(path.value().c_str(), &statbuf) == 0) {
656 return path;
657 }
658
659 path = GetPath(file_id, kNonVisible);
660 if (stat(path.value().c_str(), &statbuf) == 0) {
661 return path;
662 }
663
664 path.clear();
665 return path;
666}
667
668bool P2PManagerImpl::FileGetVisible(const string& file_id,
669 bool *out_result) {
Alex Deymof329b932014-10-30 01:37:48 -0700670 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700671 if (path.empty()) {
672 LOG(ERROR) << "No file for id " << file_id;
673 return false;
674 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700675 if (out_result != nullptr)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700676 *out_result = path.MatchesExtension(kP2PExtension);
677 return true;
678}
679
680bool P2PManagerImpl::FileMakeVisible(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700681 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700682 if (path.empty()) {
683 LOG(ERROR) << "No file for id " << file_id;
684 return false;
685 }
686
687 // Already visible?
688 if (path.MatchesExtension(kP2PExtension))
689 return true;
690
691 LOG_ASSERT(path.MatchesExtension(kTmpExtension));
Alex Deymof329b932014-10-30 01:37:48 -0700692 FilePath new_path = path.RemoveExtension();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700693 LOG_ASSERT(new_path.MatchesExtension(kP2PExtension));
694 if (rename(path.value().c_str(), new_path.value().c_str()) != 0) {
695 PLOG(ERROR) << "Error renaming " << path.value()
696 << " to " << new_path.value();
697 return false;
698 }
699
700 return true;
701}
702
703ssize_t P2PManagerImpl::FileGetSize(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700704 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700705 if (path.empty())
706 return -1;
707
Gabe Blacka77939e2014-09-09 23:35:08 -0700708 return utils::FileSize(path.value());
David Zeuthen27a48bc2013-08-06 12:06:29 -0700709}
710
711ssize_t P2PManagerImpl::FileGetExpectedSize(const string& file_id) {
Alex Deymof329b932014-10-30 01:37:48 -0700712 FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700713 if (path.empty())
714 return -1;
715
716 char ea_value[64] = { 0 };
717 ssize_t ea_size;
718 ea_size = getxattr(path.value().c_str(), kCrosP2PFileSizeXAttrName,
719 &ea_value, sizeof(ea_value) - 1);
720 if (ea_size == -1) {
721 PLOG(ERROR) << "Error calling getxattr() on file " << path.value();
722 return -1;
723 }
724
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700725 char* endp = nullptr;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700726 long long int val = strtoll(ea_value, &endp, 0); // NOLINT(runtime/int)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700727 if (*endp != '\0') {
728 LOG(ERROR) << "Error parsing the value '" << ea_value
729 << "' of the xattr " << kCrosP2PFileSizeXAttrName
730 << " as an integer";
731 return -1;
732 }
733
734 return val;
735}
736
737int P2PManagerImpl::CountSharedFiles() {
738 GDir* dir;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700739 GError* error = nullptr;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700740 const char* name;
741 int num_files = 0;
742
Alex Deymof329b932014-10-30 01:37:48 -0700743 FilePath p2p_dir = configuration_->GetP2PDir();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700744 dir = g_dir_open(p2p_dir.value().c_str(), 0, &error);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700745 if (dir == nullptr) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700746 LOG(ERROR) << "Error opening directory " << p2p_dir.value() << ": "
747 << utils::GetAndFreeGError(&error);
748 return -1;
749 }
750
751 string ext_visible = GetExt(kVisible);
752 string ext_non_visible = GetExt(kNonVisible);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700753 while ((name = g_dir_read_name(dir)) != nullptr) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700754 if (g_str_has_suffix(name, ext_visible.c_str()) ||
755 g_str_has_suffix(name, ext_non_visible.c_str())) {
756 num_files += 1;
757 }
758 }
759 g_dir_close(dir);
760
761 return num_files;
762}
763
Gilad Arnoldccd09572014-10-27 13:37:50 -0700764bool P2PManagerImpl::SetP2PEnabledPref(bool enabled) {
765 if (!prefs_->SetBoolean(chromeos_update_engine::kPrefsP2PEnabled, enabled))
766 return false;
767
768 // If P2P should not be running, make sure it isn't.
769 if (may_be_running_ && !IsP2PEnabled())
770 EnsureP2PNotRunning();
771
772 return true;
773}
774
David Zeuthen27a48bc2013-08-06 12:06:29 -0700775P2PManager* P2PManager::Construct(Configuration *configuration,
776 PrefsInterface *prefs,
777 const string& file_extension,
778 const int num_files_to_keep) {
779 return new P2PManagerImpl(configuration,
780 prefs,
781 file_extension,
782 num_files_to_keep);
783}
784
785} // namespace chromeos_update_engine