blob: b1383e21abccc5575449140a47e2697919045033 [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 Vakulenko75039d72014-03-25 12:36:28 -070069 virtual base::FilePath GetP2PDir() {
70 return base::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 Vakulenko75039d72014-03-25 12:36:28 -070086 args.push_back(base::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 Vakulenko75039d72014-03-25 12:36:28 -0700114 virtual base::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();
121
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700122 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700123 // Enumeration for specifying visibility.
124 enum Visibility {
125 kVisible,
126 kNonVisible
127 };
128
129 // Returns "." + |file_extension_| + ".p2p" if |visibility| is
130 // |kVisible|. Returns the same concatenated with ".tmp" otherwise.
131 string GetExt(Visibility visibility);
132
133 // Gets the on-disk path for |file_id| depending on if the file
134 // is visible or not.
Alex Vakulenko75039d72014-03-25 12:36:28 -0700135 base::FilePath GetPath(const string& file_id, Visibility visibility);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700136
137 // Utility function used by EnsureP2PRunning() and EnsureP2PNotRunning().
138 bool EnsureP2P(bool should_be_running);
139
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700140 // The device policy being used or null if no policy is being used.
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700141 const policy::DevicePolicy* device_policy_;
142
David Zeuthen27a48bc2013-08-06 12:06:29 -0700143 // Configuration object.
Ben Chan02f7c1d2014-10-18 15:18:02 -0700144 unique_ptr<Configuration> configuration_;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700145
146 // Object for persisted state.
147 PrefsInterface* prefs_;
148
149 // A short string unique to the application (for example "cros_au")
150 // used to mark a file as being owned by a particular application.
151 const string file_extension_;
152
153 // If non-zero, this number denotes how many files in /var/cache/p2p
154 // owned by the application (cf. |file_extension_|) to keep after
155 // performing housekeeping.
156 const int num_files_to_keep_;
157
158 // The string ".p2p".
159 static const char kP2PExtension[];
160
161 // The string ".tmp".
162 static const char kTmpExtension[];
163
164 DISALLOW_COPY_AND_ASSIGN(P2PManagerImpl);
165};
166
167const char P2PManagerImpl::kP2PExtension[] = ".p2p";
168
169const char P2PManagerImpl::kTmpExtension[] = ".tmp";
170
171P2PManagerImpl::P2PManagerImpl(Configuration *configuration,
172 PrefsInterface *prefs,
173 const string& file_extension,
174 const int num_files_to_keep)
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700175 : device_policy_(nullptr),
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700176 prefs_(prefs),
David Zeuthen27a48bc2013-08-06 12:06:29 -0700177 file_extension_(file_extension),
178 num_files_to_keep_(num_files_to_keep) {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700179 configuration_.reset(configuration != nullptr ? configuration :
David Zeuthen27a48bc2013-08-06 12:06:29 -0700180 new ConfigurationImpl());
181}
182
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700183void P2PManagerImpl::SetDevicePolicy(
184 const policy::DevicePolicy* device_policy) {
185 device_policy_ = device_policy;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700186}
187
188bool P2PManagerImpl::IsP2PEnabled() {
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700189 bool p2p_enabled = false;
190
191 // The logic we want here is additive, e.g. p2p can be enabled by
192 // either the crosh flag OR by Enterprise Policy, e.g. the following
193 // truth table:
194 //
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400195 // crosh_flag == FALSE && enterprise_policy == unset -> use_p2p == *
196 // crosh_flag == TRUE && enterprise_policy == unset -> use_p2p == TRUE
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700197 // crosh_flag == FALSE && enterprise_policy == FALSE -> use_p2p == FALSE
198 // crosh_flag == FALSE && enterprise_policy == TRUE -> use_p2p == TRUE
199 // crosh_flag == TRUE && enterprise_policy == FALSE -> use_p2p == TRUE
200 // crosh_flag == TRUE && enterprise_policy == TRUE -> use_p2p == TRUE
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400201 //
202 // *: TRUE if Enterprise Enrolled, FALSE otherwise.
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700203
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700204 if (prefs_ != nullptr &&
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700205 prefs_->Exists(kPrefsP2PEnabled) &&
206 prefs_->GetBoolean(kPrefsP2PEnabled, &p2p_enabled) &&
207 p2p_enabled) {
208 LOG(INFO) << "The crosh flag indicates that p2p is enabled.";
209 return true;
210 }
211
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400212 if (device_policy_ != nullptr) {
213 if (device_policy_->GetAuP2PEnabled(&p2p_enabled)) {
214 if (p2p_enabled) {
215 LOG(INFO) << "Enterprise Policy indicates that p2p is enabled.";
216 return true;
217 }
218 } else {
219 // Enterprise-enrolled devices have an empty owner in their device policy.
220 string owner;
221 if (!device_policy_->GetOwner(&owner) || owner.empty()) {
222 LOG(INFO) << "No p2p_enabled setting in Enterprise Policy but device "
223 << "is Enterprise Enrolled so allowing p2p.";
224 return true;
225 }
226 }
227 }
228
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700229 LOG(INFO) << "Neither Enterprise Policy nor crosh flag indicates that p2p "
230 << "is enabled.";
231 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700232}
233
234bool P2PManagerImpl::EnsureP2P(bool should_be_running) {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700235 gchar *standard_error = nullptr;
236 GError *error = nullptr;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700237 gint exit_status = 0;
238
239 vector<string> args = configuration_->GetInitctlArgs(should_be_running);
Ben Chan02f7c1d2014-10-18 15:18:02 -0700240 unique_ptr<gchar*, GLibStrvFreeDeleter> argv(
David Zeuthen27a48bc2013-08-06 12:06:29 -0700241 utils::StringVectorToGStrv(args));
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700242 if (!g_spawn_sync(nullptr, // working_directory
David Zeuthen27a48bc2013-08-06 12:06:29 -0700243 argv.get(),
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700244 nullptr, // envp
David Zeuthen27a48bc2013-08-06 12:06:29 -0700245 static_cast<GSpawnFlags>(G_SPAWN_SEARCH_PATH),
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700246 nullptr, nullptr, // child_setup, user_data
247 nullptr, // standard_output
David Zeuthen27a48bc2013-08-06 12:06:29 -0700248 &standard_error,
249 &exit_status,
250 &error)) {
251 LOG(ERROR) << "Error spawning " << utils::StringVectorToString(args)
252 << ": " << utils::GetAndFreeGError(&error);
253 return false;
254 }
Ben Chan02f7c1d2014-10-18 15:18:02 -0700255 unique_ptr<gchar, GLibFreeDeleter> standard_error_deleter(standard_error);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700256
257 if (!WIFEXITED(exit_status)) {
258 LOG(ERROR) << "Error spawning '" << utils::StringVectorToString(args)
259 << "': WIFEXITED is false";
260 return false;
261 }
262
263 // If initctl(8) exits normally with exit status 0 ("success"), it
264 // meant that it did what we requested.
265 if (WEXITSTATUS(exit_status) == 0) {
266 return true;
267 }
268
269 // Otherwise, screenscape stderr from initctl(8). Ugh, yes, this is
270 // ugly but since the program lacks verbs/actions such as
271 //
272 // ensure-started (or start-or-return-success-if-already-started)
273 // ensure-stopped (or stop-or-return-success-if-not-running)
274 //
275 // this is what we have to do.
276 //
277 // TODO(zeuthen,chromium:277051): Avoid doing this.
278 const gchar *expected_error_message = should_be_running ?
279 "initctl: Job is already running: p2p\n" :
280 "initctl: Unknown instance \n";
281 if (g_strcmp0(standard_error, expected_error_message) == 0) {
282 return true;
283 }
284
285 return false;
286}
287
288bool P2PManagerImpl::EnsureP2PRunning() {
289 return EnsureP2P(true);
290}
291
292bool P2PManagerImpl::EnsureP2PNotRunning() {
293 return EnsureP2P(false);
294}
295
296// Returns True if the timestamp in the first pair is greater than the
297// timestamp in the latter. If used with std::sort() this will yield a
298// sequence of elements where newer (high timestamps) elements precede
299// older ones (low timestamps).
300static bool MatchCompareFunc(const pair<FilePath, Time>& a,
301 const pair<FilePath, Time>& b) {
302 return a.second > b.second;
303}
304
305string P2PManagerImpl::GetExt(Visibility visibility) {
306 string ext = string(".") + file_extension_ + kP2PExtension;
307 switch (visibility) {
308 case kVisible:
309 break;
310 case kNonVisible:
311 ext += kTmpExtension;
312 break;
313 // Don't add a default case to let the compiler warn about newly
314 // added enum values.
315 }
316 return ext;
317}
318
319FilePath P2PManagerImpl::GetPath(const string& file_id, Visibility visibility) {
320 return configuration_->GetP2PDir().Append(file_id + GetExt(visibility));
321}
322
323bool P2PManagerImpl::PerformHousekeeping() {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700324 GDir* dir = nullptr;
325 GError* error = nullptr;
326 const char* name = nullptr;
Ben Chanf9cb98c2014-09-21 18:31:30 -0700327 vector<pair<FilePath, Time>> matches;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700328
329 // Go through all files in the p2p dir and pick the ones that match
330 // and get their ctime.
Alex Vakulenko75039d72014-03-25 12:36:28 -0700331 base::FilePath p2p_dir = configuration_->GetP2PDir();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700332 dir = g_dir_open(p2p_dir.value().c_str(), 0, &error);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700333 if (dir == nullptr) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700334 LOG(ERROR) << "Error opening directory " << p2p_dir.value() << ": "
335 << utils::GetAndFreeGError(&error);
336 return false;
337 }
338
339 if (num_files_to_keep_ == 0)
340 return true;
341
342 string ext_visible = GetExt(kVisible);
343 string ext_non_visible = GetExt(kNonVisible);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700344 while ((name = g_dir_read_name(dir)) != nullptr) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700345 if (!(g_str_has_suffix(name, ext_visible.c_str()) ||
346 g_str_has_suffix(name, ext_non_visible.c_str())))
347 continue;
348
349 struct stat statbuf;
Alex Vakulenko75039d72014-03-25 12:36:28 -0700350 base::FilePath file = p2p_dir.Append(name);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700351 if (stat(file.value().c_str(), &statbuf) != 0) {
352 PLOG(ERROR) << "Error getting file status for " << file.value();
353 continue;
354 }
355
356 Time time = utils::TimeFromStructTimespec(&statbuf.st_ctim);
357 matches.push_back(std::make_pair(file, time));
358 }
359 g_dir_close(dir);
360
361 // Sort list of matches, newest (biggest time) to oldest (lowest time).
362 std::sort(matches.begin(), matches.end(), MatchCompareFunc);
363
364 // Delete starting at element num_files_to_keep_.
Ben Chanf9cb98c2014-09-21 18:31:30 -0700365 vector<pair<FilePath, Time>>::const_iterator i;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700366 for (i = matches.begin() + num_files_to_keep_; i < matches.end(); ++i) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700367 const base::FilePath& file = i->first;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700368 LOG(INFO) << "Deleting p2p file " << file.value();
369 if (unlink(file.value().c_str()) != 0) {
370 PLOG(ERROR) << "Error deleting p2p file " << file.value();
371 return false;
372 }
373 }
374
375 return true;
376}
377
378// Helper class for implementing LookupUrlForFile().
379class LookupData {
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700380 public:
381 explicit LookupData(P2PManager::LookupCallback callback)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700382 : callback_(callback),
383 pid_(0),
384 stdout_fd_(-1),
385 stdout_channel_source_id_(0),
386 child_watch_source_id_(0),
387 timeout_source_id_(0),
388 reported_(false) {}
389
390 ~LookupData() {
391 if (child_watch_source_id_ != 0)
392 g_source_remove(child_watch_source_id_);
393 if (stdout_channel_source_id_ != 0)
394 g_source_remove(stdout_channel_source_id_);
395 if (timeout_source_id_ != 0)
396 g_source_remove(timeout_source_id_);
397 if (stdout_fd_ != -1)
398 close(stdout_fd_);
399 if (pid_ != 0)
400 kill(pid_, SIGTERM);
401 }
402
403 void InitiateLookup(gchar **argv, TimeDelta timeout) {
404 // NOTE: if we fail early (i.e. in this method), we need to schedule
405 // an idle to report the error. This is because we guarantee that
Alex Vakulenko072359c2014-07-18 11:41:07 -0700406 // the callback is always called from the GLib mainloop (this
David Zeuthen27a48bc2013-08-06 12:06:29 -0700407 // guarantee is useful for testing).
408
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700409 GError *error = nullptr;
410 if (!g_spawn_async_with_pipes(nullptr, // working_directory
David Zeuthen27a48bc2013-08-06 12:06:29 -0700411 argv,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700412 nullptr, // envp
David Zeuthen27a48bc2013-08-06 12:06:29 -0700413 static_cast<GSpawnFlags>(G_SPAWN_SEARCH_PATH |
414 G_SPAWN_DO_NOT_REAP_CHILD),
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700415 nullptr, // child_setup
David Zeuthen27a48bc2013-08-06 12:06:29 -0700416 this,
417 &pid_,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700418 nullptr, // standard_input
David Zeuthen27a48bc2013-08-06 12:06:29 -0700419 &stdout_fd_,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700420 nullptr, // standard_error
David Zeuthen27a48bc2013-08-06 12:06:29 -0700421 &error)) {
422 LOG(ERROR) << "Error spawning p2p-client: "
423 << utils::GetAndFreeGError(&error);
424 ReportErrorAndDeleteInIdle();
425 return;
426 }
427
428 GIOChannel* io_channel = g_io_channel_unix_new(stdout_fd_);
429 stdout_channel_source_id_ = g_io_add_watch(
430 io_channel,
431 static_cast<GIOCondition>(G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP),
432 OnIOChannelActivity, this);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700433 CHECK_NE(stdout_channel_source_id_, 0u);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700434 g_io_channel_unref(io_channel);
435
436 child_watch_source_id_ = g_child_watch_add(pid_, OnChildWatchActivity,
437 this);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700438 CHECK_NE(child_watch_source_id_, 0u);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700439
440 if (timeout.ToInternalValue() > 0) {
441 timeout_source_id_ = g_timeout_add(timeout.InMilliseconds(),
442 OnTimeout, this);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700443 CHECK_NE(timeout_source_id_, 0u);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700444 }
445 }
446
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700447 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700448 void ReportErrorAndDeleteInIdle() {
449 g_idle_add(static_cast<GSourceFunc>(OnIdleForReportErrorAndDelete), this);
450 }
451
452 static gboolean OnIdleForReportErrorAndDelete(gpointer user_data) {
453 LookupData *lookup_data = reinterpret_cast<LookupData*>(user_data);
454 lookup_data->ReportError();
455 delete lookup_data;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700456 return FALSE; // Remove source.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700457 }
458
459 void IssueCallback(const string& url) {
460 if (!callback_.is_null())
461 callback_.Run(url);
462 }
463
464 void ReportError() {
465 if (reported_)
466 return;
467 IssueCallback("");
468 reported_ = true;
469 }
470
471 void ReportSuccess() {
472 if (reported_)
473 return;
474
475 string url = stdout_;
476 size_t newline_pos = url.find('\n');
477 if (newline_pos != string::npos)
478 url.resize(newline_pos);
479
480 // Since p2p-client(1) is constructing this URL itself strictly
481 // speaking there's no need to validate it... but, anyway, can't
482 // hurt.
483 if (url.compare(0, 7, "http://") == 0) {
484 IssueCallback(url);
485 } else {
486 LOG(ERROR) << "p2p URL '" << url << "' does not look right. Ignoring.";
487 ReportError();
488 }
489
490 reported_ = true;
491 }
492
493 static gboolean OnIOChannelActivity(GIOChannel *source,
494 GIOCondition condition,
495 gpointer user_data) {
496 LookupData *lookup_data = reinterpret_cast<LookupData*>(user_data);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700497 gchar* str = nullptr;
498 GError* error = nullptr;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700499 GIOStatus status = g_io_channel_read_line(source,
500 &str,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700501 nullptr, // len
502 nullptr, // line_terminator
David Zeuthen27a48bc2013-08-06 12:06:29 -0700503 &error);
504 if (status != G_IO_STATUS_NORMAL) {
505 // Ignore EOF since we usually get that before SIGCHLD and we
506 // need to examine exit status there.
507 if (status != G_IO_STATUS_EOF) {
508 LOG(ERROR) << "Error reading a line from p2p-client: "
509 << utils::GetAndFreeGError(&error);
510 lookup_data->ReportError();
511 delete lookup_data;
512 }
513 } else {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700514 if (str != nullptr) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700515 lookup_data->stdout_ += str;
516 g_free(str);
517 }
518 }
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700519 return TRUE; // Don't remove source.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700520 }
521
522 static void OnChildWatchActivity(GPid pid,
523 gint status,
524 gpointer user_data) {
525 LookupData *lookup_data = reinterpret_cast<LookupData*>(user_data);
526
527 if (!WIFEXITED(status)) {
528 LOG(ERROR) << "Child didn't exit normally";
529 lookup_data->ReportError();
530 } else if (WEXITSTATUS(status) != 0) {
531 LOG(INFO) << "Child exited with non-zero exit code "
532 << WEXITSTATUS(status);
533 lookup_data->ReportError();
534 } else {
535 lookup_data->ReportSuccess();
536 }
537 delete lookup_data;
538 }
539
540 static gboolean OnTimeout(gpointer user_data) {
541 LookupData *lookup_data = reinterpret_cast<LookupData*>(user_data);
542 lookup_data->ReportError();
543 delete lookup_data;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700544 return TRUE; // Don't remove source.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700545 }
546
547 P2PManager::LookupCallback callback_;
548 GPid pid_;
549 gint stdout_fd_;
550 guint stdout_channel_source_id_;
551 guint child_watch_source_id_;
552 guint timeout_source_id_;
553 string stdout_;
554 bool reported_;
555};
556
557void P2PManagerImpl::LookupUrlForFile(const string& file_id,
558 size_t minimum_size,
559 TimeDelta max_time_to_wait,
560 LookupCallback callback) {
561 LookupData *lookup_data = new LookupData(callback);
562 string file_id_with_ext = file_id + "." + file_extension_;
563 vector<string> args = configuration_->GetP2PClientArgs(file_id_with_ext,
564 minimum_size);
565 gchar **argv = utils::StringVectorToGStrv(args);
566 lookup_data->InitiateLookup(argv, max_time_to_wait);
567 g_strfreev(argv);
568}
569
570bool P2PManagerImpl::FileShare(const string& file_id,
571 size_t expected_size) {
572 // Check if file already exist.
Alex Vakulenko75039d72014-03-25 12:36:28 -0700573 base::FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700574 if (!path.empty()) {
575 // File exists - double check its expected size though.
576 ssize_t file_expected_size = FileGetExpectedSize(file_id);
577 if (file_expected_size == -1 ||
578 static_cast<size_t>(file_expected_size) != expected_size) {
579 LOG(ERROR) << "Existing p2p file " << path.value()
580 << " with expected_size=" << file_expected_size
581 << " does not match the passed in"
582 << " expected_size=" << expected_size;
583 return false;
584 }
585 return true;
586 }
587
588 // Before creating the file, bail if statvfs(3) indicates that at
589 // least twice the size is not available in P2P_DIR.
590 struct statvfs statvfsbuf;
Alex Vakulenko75039d72014-03-25 12:36:28 -0700591 base::FilePath p2p_dir = configuration_->GetP2PDir();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700592 if (statvfs(p2p_dir.value().c_str(), &statvfsbuf) != 0) {
593 PLOG(ERROR) << "Error calling statvfs() for dir " << p2p_dir.value();
594 return false;
595 }
596 size_t free_bytes =
597 static_cast<size_t>(statvfsbuf.f_bsize) * statvfsbuf.f_bavail;
598 if (free_bytes < 2 * expected_size) {
599 // This can easily happen and is worth reporting.
600 LOG(INFO) << "Refusing to allocate p2p file of " << expected_size
601 << " bytes since the directory " << p2p_dir.value()
602 << " only has " << free_bytes
603 << " bytes available and this is less than twice the"
604 << " requested size.";
605 return false;
606 }
607
608 // Okie-dokey looks like enough space is available - create the file.
609 path = GetPath(file_id, kNonVisible);
610 int fd = open(path.value().c_str(), O_CREAT | O_RDWR, 0644);
611 if (fd == -1) {
612 PLOG(ERROR) << "Error creating file with path " << path.value();
613 return false;
614 }
615 ScopedFdCloser fd_closer(&fd);
616
617 // If the final size is known, allocate the file (e.g. reserve disk
618 // space) and set the user.cros-p2p-filesize xattr.
619 if (expected_size != 0) {
620 if (fallocate(fd,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700621 FALLOC_FL_KEEP_SIZE, // Keep file size as 0.
David Zeuthen27a48bc2013-08-06 12:06:29 -0700622 0,
623 expected_size) != 0) {
David Zeuthen910ec5b2013-09-26 12:10:58 -0700624 if (errno == ENOSYS || errno == EOPNOTSUPP) {
625 // If the filesystem doesn't support the fallocate, keep
626 // going. This is helpful when running unit tests on build
627 // machines with ancient filesystems and/or OSes.
628 PLOG(WARNING) << "Ignoring fallocate(2) failure";
629 } else {
630 // ENOSPC can happen (funky race though, cf. the statvfs() check
631 // above), handle it gracefully, e.g. use logging level INFO.
632 PLOG(INFO) << "Error allocating " << expected_size
633 << " bytes for file " << path.value();
634 if (unlink(path.value().c_str()) != 0) {
635 PLOG(ERROR) << "Error deleting file with path " << path.value();
636 }
637 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700638 }
David Zeuthen27a48bc2013-08-06 12:06:29 -0700639 }
640
Alex Vakulenko75039d72014-03-25 12:36:28 -0700641 string decimal_size = base::StringPrintf("%zu", expected_size);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700642 if (fsetxattr(fd, kCrosP2PFileSizeXAttrName,
643 decimal_size.c_str(), decimal_size.size(), 0) != 0) {
644 PLOG(ERROR) << "Error setting xattr " << path.value();
645 return false;
646 }
647 }
648
649 return true;
650}
651
652FilePath P2PManagerImpl::FileGetPath(const string& file_id) {
653 struct stat statbuf;
Alex Vakulenko75039d72014-03-25 12:36:28 -0700654 base::FilePath path;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700655
656 path = GetPath(file_id, kVisible);
657 if (stat(path.value().c_str(), &statbuf) == 0) {
658 return path;
659 }
660
661 path = GetPath(file_id, kNonVisible);
662 if (stat(path.value().c_str(), &statbuf) == 0) {
663 return path;
664 }
665
666 path.clear();
667 return path;
668}
669
670bool P2PManagerImpl::FileGetVisible(const string& file_id,
671 bool *out_result) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700672 base::FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700673 if (path.empty()) {
674 LOG(ERROR) << "No file for id " << file_id;
675 return false;
676 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700677 if (out_result != nullptr)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700678 *out_result = path.MatchesExtension(kP2PExtension);
679 return true;
680}
681
682bool P2PManagerImpl::FileMakeVisible(const string& file_id) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700683 base::FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700684 if (path.empty()) {
685 LOG(ERROR) << "No file for id " << file_id;
686 return false;
687 }
688
689 // Already visible?
690 if (path.MatchesExtension(kP2PExtension))
691 return true;
692
693 LOG_ASSERT(path.MatchesExtension(kTmpExtension));
Alex Vakulenko75039d72014-03-25 12:36:28 -0700694 base::FilePath new_path = path.RemoveExtension();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700695 LOG_ASSERT(new_path.MatchesExtension(kP2PExtension));
696 if (rename(path.value().c_str(), new_path.value().c_str()) != 0) {
697 PLOG(ERROR) << "Error renaming " << path.value()
698 << " to " << new_path.value();
699 return false;
700 }
701
702 return true;
703}
704
705ssize_t P2PManagerImpl::FileGetSize(const string& file_id) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700706 base::FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700707 if (path.empty())
708 return -1;
709
Gabe Blacka77939e2014-09-09 23:35:08 -0700710 return utils::FileSize(path.value());
David Zeuthen27a48bc2013-08-06 12:06:29 -0700711}
712
713ssize_t P2PManagerImpl::FileGetExpectedSize(const string& file_id) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700714 base::FilePath path = FileGetPath(file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700715 if (path.empty())
716 return -1;
717
718 char ea_value[64] = { 0 };
719 ssize_t ea_size;
720 ea_size = getxattr(path.value().c_str(), kCrosP2PFileSizeXAttrName,
721 &ea_value, sizeof(ea_value) - 1);
722 if (ea_size == -1) {
723 PLOG(ERROR) << "Error calling getxattr() on file " << path.value();
724 return -1;
725 }
726
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700727 char* endp = nullptr;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700728 long long int val = strtoll(ea_value, &endp, 0); // NOLINT(runtime/int)
David Zeuthen27a48bc2013-08-06 12:06:29 -0700729 if (*endp != '\0') {
730 LOG(ERROR) << "Error parsing the value '" << ea_value
731 << "' of the xattr " << kCrosP2PFileSizeXAttrName
732 << " as an integer";
733 return -1;
734 }
735
736 return val;
737}
738
739int P2PManagerImpl::CountSharedFiles() {
740 GDir* dir;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700741 GError* error = nullptr;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700742 const char* name;
743 int num_files = 0;
744
Alex Vakulenko75039d72014-03-25 12:36:28 -0700745 base::FilePath p2p_dir = configuration_->GetP2PDir();
David Zeuthen27a48bc2013-08-06 12:06:29 -0700746 dir = g_dir_open(p2p_dir.value().c_str(), 0, &error);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700747 if (dir == nullptr) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700748 LOG(ERROR) << "Error opening directory " << p2p_dir.value() << ": "
749 << utils::GetAndFreeGError(&error);
750 return -1;
751 }
752
753 string ext_visible = GetExt(kVisible);
754 string ext_non_visible = GetExt(kNonVisible);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700755 while ((name = g_dir_read_name(dir)) != nullptr) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700756 if (g_str_has_suffix(name, ext_visible.c_str()) ||
757 g_str_has_suffix(name, ext_non_visible.c_str())) {
758 num_files += 1;
759 }
760 }
761 g_dir_close(dir);
762
763 return num_files;
764}
765
766P2PManager* P2PManager::Construct(Configuration *configuration,
767 PrefsInterface *prefs,
768 const string& file_extension,
769 const int num_files_to_keep) {
770 return new P2PManagerImpl(configuration,
771 prefs,
772 file_extension,
773 num_files_to_keep);
774}
775
776} // namespace chromeos_update_engine