blob: 2ec827acb6a130d2ea3f3ef0568a7766c42a86cb [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>
28#include <utility>
29#include <vector>
30
Alex Vakulenko75039d72014-03-25 12:36:28 -070031#include <base/files/file_path.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070032#include <base/logging.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070033#include <base/strings/stringprintf.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070034
Alex Deymo44666f92014-07-22 20:29:24 -070035#include "update_engine/glib_utils.h"
David Zeuthen27a48bc2013-08-06 12:06:29 -070036#include "update_engine/utils.h"
37
38using base::FilePath;
39using base::StringPrintf;
40using base::Time;
41using base::TimeDelta;
42using std::map;
43using std::pair;
44using std::string;
45using std::vector;
46
47namespace chromeos_update_engine {
48
49namespace {
50
51// The default p2p directory.
52const char kDefaultP2PDir[] = "/var/cache/p2p";
53
54// The p2p xattr used for conveying the final size of a file - see the
55// p2p ddoc for details.
56const char kCrosP2PFileSizeXAttrName[] = "user.cros-p2p-filesize";
57
Alex Vakulenkod2779df2014-06-16 13:19:00 -070058} // namespace
David Zeuthen27a48bc2013-08-06 12:06:29 -070059
60// The default P2PManager::Configuration implementation.
61class ConfigurationImpl : public P2PManager::Configuration {
Alex Vakulenkod2779df2014-06-16 13:19:00 -070062 public:
David Zeuthen27a48bc2013-08-06 12:06:29 -070063 ConfigurationImpl() {}
64
65 virtual ~ConfigurationImpl() {}
66
Alex Vakulenko75039d72014-03-25 12:36:28 -070067 virtual base::FilePath GetP2PDir() {
68 return base::FilePath(kDefaultP2PDir);
David Zeuthen27a48bc2013-08-06 12:06:29 -070069 }
70
71 virtual vector<string> GetInitctlArgs(bool is_start) {
72 vector<string> args;
73 args.push_back("initctl");
74 args.push_back(is_start ? "start" : "stop");
75 args.push_back("p2p");
76 return args;
77 }
78
79 virtual vector<string> GetP2PClientArgs(const string &file_id,
80 size_t minimum_size) {
81 vector<string> args;
82 args.push_back("p2p-client");
83 args.push_back(string("--get-url=") + file_id);
Alex Vakulenko75039d72014-03-25 12:36:28 -070084 args.push_back(base::StringPrintf("--minimum-size=%zu", minimum_size));
David Zeuthen27a48bc2013-08-06 12:06:29 -070085 return args;
86 }
87
Alex Vakulenkod2779df2014-06-16 13:19:00 -070088 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -070089 DISALLOW_COPY_AND_ASSIGN(ConfigurationImpl);
90};
91
92// The default P2PManager implementation.
93class P2PManagerImpl : public P2PManager {
Alex Vakulenkod2779df2014-06-16 13:19:00 -070094 public:
David Zeuthen27a48bc2013-08-06 12:06:29 -070095 P2PManagerImpl(Configuration *configuration,
96 PrefsInterface *prefs,
97 const string& file_extension,
98 const int num_files_to_keep);
99
100 // P2PManager methods.
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700101 virtual void SetDevicePolicy(const policy::DevicePolicy* device_policy);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700102 virtual bool IsP2PEnabled();
103 virtual bool EnsureP2PRunning();
104 virtual bool EnsureP2PNotRunning();
105 virtual bool PerformHousekeeping();
106 virtual void LookupUrlForFile(const string& file_id,
107 size_t minimum_size,
108 TimeDelta max_time_to_wait,
109 LookupCallback callback);
110 virtual bool FileShare(const string& file_id,
111 size_t expected_size);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700112 virtual base::FilePath FileGetPath(const string& file_id);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700113 virtual ssize_t FileGetSize(const string& file_id);
114 virtual ssize_t FileGetExpectedSize(const string& file_id);
115 virtual bool FileGetVisible(const string& file_id,
116 bool *out_result);
117 virtual bool FileMakeVisible(const string& file_id);
118 virtual int CountSharedFiles();
119
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700120 private:
David Zeuthen27a48bc2013-08-06 12:06:29 -0700121 // Enumeration for specifying visibility.
122 enum Visibility {
123 kVisible,
124 kNonVisible
125 };
126
127 // Returns "." + |file_extension_| + ".p2p" if |visibility| is
128 // |kVisible|. Returns the same concatenated with ".tmp" otherwise.
129 string GetExt(Visibility visibility);
130
131 // Gets the on-disk path for |file_id| depending on if the file
132 // is visible or not.
Alex Vakulenko75039d72014-03-25 12:36:28 -0700133 base::FilePath GetPath(const string& file_id, Visibility visibility);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700134
135 // Utility function used by EnsureP2PRunning() and EnsureP2PNotRunning().
136 bool EnsureP2P(bool should_be_running);
137
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700138 // The device policy being used or null if no policy is being used.
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700139 const policy::DevicePolicy* device_policy_;
140
David Zeuthen27a48bc2013-08-06 12:06:29 -0700141 // Configuration object.
142 scoped_ptr<Configuration> configuration_;
143
144 // Object for persisted state.
145 PrefsInterface* prefs_;
146
147 // A short string unique to the application (for example "cros_au")
148 // used to mark a file as being owned by a particular application.
149 const string file_extension_;
150
151 // If non-zero, this number denotes how many files in /var/cache/p2p
152 // owned by the application (cf. |file_extension_|) to keep after
153 // performing housekeeping.
154 const int num_files_to_keep_;
155
156 // The string ".p2p".
157 static const char kP2PExtension[];
158
159 // The string ".tmp".
160 static const char kTmpExtension[];
161
162 DISALLOW_COPY_AND_ASSIGN(P2PManagerImpl);
163};
164
165const char P2PManagerImpl::kP2PExtension[] = ".p2p";
166
167const char P2PManagerImpl::kTmpExtension[] = ".tmp";
168
169P2PManagerImpl::P2PManagerImpl(Configuration *configuration,
170 PrefsInterface *prefs,
171 const string& file_extension,
172 const int num_files_to_keep)
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700173 : device_policy_(nullptr),
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700174 prefs_(prefs),
David Zeuthen27a48bc2013-08-06 12:06:29 -0700175 file_extension_(file_extension),
176 num_files_to_keep_(num_files_to_keep) {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700177 configuration_.reset(configuration != nullptr ? configuration :
David Zeuthen27a48bc2013-08-06 12:06:29 -0700178 new ConfigurationImpl());
179}
180
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700181void P2PManagerImpl::SetDevicePolicy(
182 const policy::DevicePolicy* device_policy) {
183 device_policy_ = device_policy;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700184}
185
186bool P2PManagerImpl::IsP2PEnabled() {
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700187 bool p2p_enabled = false;
188
189 // The logic we want here is additive, e.g. p2p can be enabled by
190 // either the crosh flag OR by Enterprise Policy, e.g. the following
191 // truth table:
192 //
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400193 // crosh_flag == FALSE && enterprise_policy == unset -> use_p2p == *
194 // crosh_flag == TRUE && enterprise_policy == unset -> use_p2p == TRUE
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700195 // crosh_flag == FALSE && enterprise_policy == FALSE -> use_p2p == FALSE
196 // crosh_flag == FALSE && enterprise_policy == TRUE -> use_p2p == TRUE
197 // crosh_flag == TRUE && enterprise_policy == FALSE -> use_p2p == TRUE
198 // crosh_flag == TRUE && enterprise_policy == TRUE -> use_p2p == TRUE
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400199 //
200 // *: TRUE if Enterprise Enrolled, FALSE otherwise.
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700201
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700202 if (prefs_ != nullptr &&
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700203 prefs_->Exists(kPrefsP2PEnabled) &&
204 prefs_->GetBoolean(kPrefsP2PEnabled, &p2p_enabled) &&
205 p2p_enabled) {
206 LOG(INFO) << "The crosh flag indicates that p2p is enabled.";
207 return true;
208 }
209
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400210 if (device_policy_ != nullptr) {
211 if (device_policy_->GetAuP2PEnabled(&p2p_enabled)) {
212 if (p2p_enabled) {
213 LOG(INFO) << "Enterprise Policy indicates that p2p is enabled.";
214 return true;
215 }
216 } else {
217 // Enterprise-enrolled devices have an empty owner in their device policy.
218 string owner;
219 if (!device_policy_->GetOwner(&owner) || owner.empty()) {
220 LOG(INFO) << "No p2p_enabled setting in Enterprise Policy but device "
221 << "is Enterprise Enrolled so allowing p2p.";
222 return true;
223 }
224 }
225 }
226
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700227 LOG(INFO) << "Neither Enterprise Policy nor crosh flag indicates that p2p "
228 << "is enabled.";
229 return false;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700230}
231
232bool P2PManagerImpl::EnsureP2P(bool should_be_running) {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700233 gchar *standard_error = nullptr;
234 GError *error = nullptr;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700235 gint exit_status = 0;
236
237 vector<string> args = configuration_->GetInitctlArgs(should_be_running);
238 scoped_ptr<gchar*, GLibStrvFreeDeleter> argv(
239 utils::StringVectorToGStrv(args));
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700240 if (!g_spawn_sync(nullptr, // working_directory
David Zeuthen27a48bc2013-08-06 12:06:29 -0700241 argv.get(),
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700242 nullptr, // envp
David Zeuthen27a48bc2013-08-06 12:06:29 -0700243 static_cast<GSpawnFlags>(G_SPAWN_SEARCH_PATH),
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700244 nullptr, nullptr, // child_setup, user_data
245 nullptr, // standard_output
David Zeuthen27a48bc2013-08-06 12:06:29 -0700246 &standard_error,
247 &exit_status,
248 &error)) {
249 LOG(ERROR) << "Error spawning " << utils::StringVectorToString(args)
250 << ": " << utils::GetAndFreeGError(&error);
251 return false;
252 }
253 scoped_ptr<gchar, GLibFreeDeleter> standard_error_deleter(standard_error);
254
255 if (!WIFEXITED(exit_status)) {
256 LOG(ERROR) << "Error spawning '" << utils::StringVectorToString(args)
257 << "': WIFEXITED is false";
258 return false;
259 }
260
261 // If initctl(8) exits normally with exit status 0 ("success"), it
262 // meant that it did what we requested.
263 if (WEXITSTATUS(exit_status) == 0) {
264 return true;
265 }
266
267 // Otherwise, screenscape stderr from initctl(8). Ugh, yes, this is
268 // ugly but since the program lacks verbs/actions such as
269 //
270 // ensure-started (or start-or-return-success-if-already-started)
271 // ensure-stopped (or stop-or-return-success-if-not-running)
272 //
273 // this is what we have to do.
274 //
275 // TODO(zeuthen,chromium:277051): Avoid doing this.
276 const gchar *expected_error_message = should_be_running ?
277 "initctl: Job is already running: p2p\n" :
278 "initctl: Unknown instance \n";
279 if (g_strcmp0(standard_error, expected_error_message) == 0) {
280 return true;
281 }
282
283 return false;
284}
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 Vakulenko75039d72014-03-25 12:36:28 -0700329 base::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 Vakulenko75039d72014-03-25 12:36:28 -0700348 base::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 Vakulenko75039d72014-03-25 12:36:28 -0700365 const base::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 Vakulenko75039d72014-03-25 12:36:28 -0700571 base::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 Vakulenko75039d72014-03-25 12:36:28 -0700589 base::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 Vakulenko75039d72014-03-25 12:36:28 -0700639 string decimal_size = base::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 Vakulenko75039d72014-03-25 12:36:28 -0700652 base::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 Vakulenko75039d72014-03-25 12:36:28 -0700670 base::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 Vakulenko75039d72014-03-25 12:36:28 -0700681 base::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 Vakulenko75039d72014-03-25 12:36:28 -0700692 base::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 Vakulenko75039d72014-03-25 12:36:28 -0700704 base::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 Vakulenko75039d72014-03-25 12:36:28 -0700712 base::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 Vakulenko75039d72014-03-25 12:36:28 -0700743 base::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
764P2PManager* P2PManager::Construct(Configuration *configuration,
765 PrefsInterface *prefs,
766 const string& file_extension,
767 const int num_files_to_keep) {
768 return new P2PManagerImpl(configuration,
769 prefs,
770 file_extension,
771 num_files_to_keep);
772}
773
774} // namespace chromeos_update_engine