1 //
2 // Copyright (C) 2013 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 // This provides access to timestamps with nanosecond resolution in
18 // struct stat, See NOTES in stat(2) for details.
19 #ifndef _DEFAULT_SOURCE
20 #define _DEFAULT_SOURCE
21 #endif
22 #ifndef _BSD_SOURCE
23 #define _BSD_SOURCE
24 #endif
25 
26 #include "update_engine/cros/p2p_manager.h"
27 
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <linux/falloc.h>
31 #include <signal.h>
32 #include <string.h>
33 #include <sys/stat.h>
34 #include <sys/statvfs.h>
35 #include <sys/types.h>
36 #include <sys/xattr.h>
37 #include <unistd.h>
38 
39 #include <algorithm>
40 #include <map>
41 #include <memory>
42 #include <utility>
43 #include <vector>
44 
45 #include <base/bind.h>
46 #include <base/files/file_enumerator.h>
47 #include <base/files/file_path.h>
48 #include <base/format_macros.h>
49 #include <base/logging.h>
50 #include <base/strings/string_util.h>
51 #include <base/strings/stringprintf.h>
52 
53 #include "update_engine/common/subprocess.h"
54 #include "update_engine/common/system_state.h"
55 #include "update_engine/common/utils.h"
56 #include "update_engine/update_manager/policy.h"
57 #include "update_engine/update_manager/update_manager.h"
58 
59 using base::Bind;
60 using base::Callback;
61 using base::FilePath;
62 using base::StringPrintf;
63 using base::Time;
64 using base::TimeDelta;
65 using brillo::MessageLoop;
66 using chromeos_update_manager::EvalStatus;
67 using chromeos_update_manager::Policy;
68 using chromeos_update_manager::UpdateManager;
69 using std::pair;
70 using std::string;
71 using std::unique_ptr;
72 using std::vector;
73 
74 namespace chromeos_update_engine {
75 
76 namespace {
77 
78 // The default p2p directory.
79 const char kDefaultP2PDir[] = "/var/cache/p2p";
80 
81 // The p2p xattr used for conveying the final size of a file - see the
82 // p2p ddoc for details.
83 const char kCrosP2PFileSizeXAttrName[] = "user.cros-p2p-filesize";
84 
85 }  // namespace
86 
87 // The default P2PManager::Configuration implementation.
88 class ConfigurationImpl : public P2PManager::Configuration {
89  public:
ConfigurationImpl()90   ConfigurationImpl() {}
91 
GetP2PDir()92   FilePath GetP2PDir() override { return FilePath(kDefaultP2PDir); }
93 
GetInitctlArgs(bool is_start)94   vector<string> GetInitctlArgs(bool is_start) override {
95     vector<string> args;
96     args.push_back("initctl");
97     args.push_back(is_start ? "start" : "stop");
98     args.push_back("p2p");
99     return args;
100   }
101 
GetP2PClientArgs(const string & file_id,size_t minimum_size)102   vector<string> GetP2PClientArgs(const string& file_id,
103                                   size_t minimum_size) override {
104     vector<string> args;
105     args.push_back("p2p-client");
106     args.push_back(string("--get-url=") + file_id);
107     args.push_back(StringPrintf("--minimum-size=%" PRIuS, minimum_size));
108     return args;
109   }
110 
111  private:
112   DISALLOW_COPY_AND_ASSIGN(ConfigurationImpl);
113 };
114 
115 // The default P2PManager implementation.
116 class P2PManagerImpl : public P2PManager {
117  public:
118   P2PManagerImpl(Configuration* configuration,
119                  UpdateManager* update_manager,
120                  const string& file_extension,
121                  const int num_files_to_keep,
122                  const TimeDelta& max_file_age);
123 
124   // P2PManager methods.
125   void SetDevicePolicy(const policy::DevicePolicy* device_policy) override;
126   bool IsP2PEnabled() override;
127   bool EnsureP2PRunning() override;
128   bool EnsureP2PNotRunning() override;
129   bool PerformHousekeeping() override;
130   void LookupUrlForFile(const string& file_id,
131                         size_t minimum_size,
132                         TimeDelta max_time_to_wait,
133                         LookupCallback callback) override;
134   bool FileShare(const string& file_id, size_t expected_size) override;
135   FilePath FileGetPath(const string& file_id) override;
136   ssize_t FileGetSize(const string& file_id) override;
137   ssize_t FileGetExpectedSize(const string& file_id) override;
138   bool FileGetVisible(const string& file_id, bool* out_result) override;
139   bool FileMakeVisible(const string& file_id) override;
140   int CountSharedFiles() override;
141 
142  private:
143   // Enumeration for specifying visibility.
144   enum Visibility { kVisible, kNonVisible };
145 
146   // Returns "." + |file_extension_| + ".p2p" if |visibility| is
147   // |kVisible|. Returns the same concatenated with ".tmp" otherwise.
148   string GetExt(Visibility visibility);
149 
150   // Gets the on-disk path for |file_id| depending on if the file
151   // is visible or not.
152   FilePath GetPath(const string& file_id, Visibility visibility);
153 
154   // Utility function used by EnsureP2PRunning() and EnsureP2PNotRunning().
155   bool EnsureP2P(bool should_be_running);
156 
157   // Utility function to delete a file given by |path| and log the
158   // path as well as |reason|. Returns false on failure.
159   bool DeleteP2PFile(const FilePath& path, const string& reason);
160 
161   // Schedules an async request for tracking changes in P2P enabled status.
162   void ScheduleEnabledStatusChange();
163 
164   // An async callback used by the above.
165   void OnEnabledStatusChange(EvalStatus status, const bool& result);
166 
167   // The device policy being used or null if no policy is being used.
168   const policy::DevicePolicy* device_policy_ = nullptr;
169 
170   // Configuration object.
171   unique_ptr<Configuration> configuration_;
172 
173   // A pointer to the global Update Manager.
174   UpdateManager* update_manager_;
175 
176   // A short string unique to the application (for example "cros_au")
177   // used to mark a file as being owned by a particular application.
178   const string file_extension_;
179 
180   // If non-zero, this number denotes how many files in /var/cache/p2p
181   // owned by the application (cf. |file_extension_|) to keep after
182   // performing housekeeping.
183   const int num_files_to_keep_;
184 
185   // If non-zero, files older than this will not be kept after
186   // performing housekeeping.
187   const TimeDelta max_file_age_;
188 
189   // The string ".p2p".
190   static const char kP2PExtension[];
191 
192   // The string ".tmp".
193   static const char kTmpExtension[];
194 
195   // Whether P2P service may be running; initially, we assume it may be.
196   bool may_be_running_ = true;
197 
198   // The current known enabled status of the P2P feature (initialized lazily),
199   // and whether an async status check has been scheduled.
200   bool is_enabled_;
201   bool waiting_for_enabled_status_change_ = false;
202 
203   DISALLOW_COPY_AND_ASSIGN(P2PManagerImpl);
204 };
205 
206 const char P2PManagerImpl::kP2PExtension[] = ".p2p";
207 
208 const char P2PManagerImpl::kTmpExtension[] = ".tmp";
209 
P2PManagerImpl(Configuration * configuration,UpdateManager * update_manager,const string & file_extension,const int num_files_to_keep,const TimeDelta & max_file_age)210 P2PManagerImpl::P2PManagerImpl(Configuration* configuration,
211                                UpdateManager* update_manager,
212                                const string& file_extension,
213                                const int num_files_to_keep,
214                                const TimeDelta& max_file_age)
215     : update_manager_(update_manager),
216       file_extension_(file_extension),
217       num_files_to_keep_(num_files_to_keep),
218       max_file_age_(max_file_age) {
219   configuration_.reset(configuration != nullptr ? configuration
220                                                 : new ConfigurationImpl());
221 }
222 
SetDevicePolicy(const policy::DevicePolicy * device_policy)223 void P2PManagerImpl::SetDevicePolicy(
224     const policy::DevicePolicy* device_policy) {
225   device_policy_ = device_policy;
226 }
227 
IsP2PEnabled()228 bool P2PManagerImpl::IsP2PEnabled() {
229   if (!waiting_for_enabled_status_change_) {
230     // Get and store an initial value.
231     if (update_manager_->PolicyRequest(&Policy::P2PEnabled, &is_enabled_) ==
232         EvalStatus::kFailed) {
233       is_enabled_ = false;
234       LOG(ERROR) << "Querying P2P enabled status failed, disabling.";
235     }
236 
237     // Track future changes (async).
238     ScheduleEnabledStatusChange();
239   }
240 
241   return is_enabled_;
242 }
243 
EnsureP2P(bool should_be_running)244 bool P2PManagerImpl::EnsureP2P(bool should_be_running) {
245   int return_code = 0;
246   string stderr;
247 
248   may_be_running_ = true;  // Unless successful, we must be conservative.
249 
250   vector<string> args = configuration_->GetInitctlArgs(should_be_running);
251   if (!Subprocess::SynchronousExec(args, &return_code, nullptr, &stderr)) {
252     LOG(ERROR) << "Error spawning " << utils::StringVectorToString(args);
253     return false;
254   }
255 
256   // If initctl(8) does not exit normally (exit status other than zero), ensure
257   // that the error message is not benign by scanning stderr; this is a
258   // necessity because initctl does not offer actions such as "start if not
259   // running" or "stop if running".
260   // TODO(zeuthen,chromium:277051): Avoid doing this.
261   if (return_code != 0) {
262     const char* expected_error_message =
263         should_be_running ? "initctl: Job is already running: p2p\n"
264                           : "initctl: Unknown instance \n";
265     if (stderr != expected_error_message)
266       return false;
267   }
268 
269   may_be_running_ = should_be_running;  // Successful after all.
270   return true;
271 }
272 
EnsureP2PRunning()273 bool P2PManagerImpl::EnsureP2PRunning() {
274   return EnsureP2P(true);
275 }
276 
EnsureP2PNotRunning()277 bool P2PManagerImpl::EnsureP2PNotRunning() {
278   return EnsureP2P(false);
279 }
280 
281 // Returns True if the timestamp in the first pair is greater than the
282 // timestamp in the latter. If used with std::sort() this will yield a
283 // sequence of elements where newer (high timestamps) elements precede
284 // older ones (low timestamps).
MatchCompareFunc(const pair<FilePath,Time> & a,const pair<FilePath,Time> & b)285 static bool MatchCompareFunc(const pair<FilePath, Time>& a,
286                              const pair<FilePath, Time>& b) {
287   return a.second > b.second;
288 }
289 
GetExt(Visibility visibility)290 string P2PManagerImpl::GetExt(Visibility visibility) {
291   string ext = string(".") + file_extension_ + kP2PExtension;
292   switch (visibility) {
293     case kVisible:
294       break;
295     case kNonVisible:
296       ext += kTmpExtension;
297       break;
298       // Don't add a default case to let the compiler warn about newly
299       // added enum values.
300   }
301   return ext;
302 }
303 
GetPath(const string & file_id,Visibility visibility)304 FilePath P2PManagerImpl::GetPath(const string& file_id, Visibility visibility) {
305   return configuration_->GetP2PDir().Append(file_id + GetExt(visibility));
306 }
307 
DeleteP2PFile(const FilePath & path,const string & reason)308 bool P2PManagerImpl::DeleteP2PFile(const FilePath& path, const string& reason) {
309   LOG(INFO) << "Deleting p2p file " << path.value() << " (reason: " << reason
310             << ")";
311   if (unlink(path.value().c_str()) != 0) {
312     PLOG(ERROR) << "Error deleting p2p file " << path.value();
313     return false;
314   }
315   return true;
316 }
317 
PerformHousekeeping()318 bool P2PManagerImpl::PerformHousekeeping() {
319   // Open p2p dir.
320   FilePath p2p_dir = configuration_->GetP2PDir();
321   const string ext_visible = GetExt(kVisible);
322   const string ext_non_visible = GetExt(kNonVisible);
323 
324   bool deletion_failed = false;
325   vector<pair<FilePath, Time>> matches;
326 
327   base::FileEnumerator dir(p2p_dir, false, base::FileEnumerator::FILES);
328   // Go through all files and collect their mtime.
329   for (FilePath name = dir.Next(); !name.empty(); name = dir.Next()) {
330     if (!(base::EndsWith(
331               name.value(), ext_visible, base::CompareCase::SENSITIVE) ||
332           base::EndsWith(
333               name.value(), ext_non_visible, base::CompareCase::SENSITIVE))) {
334       continue;
335     }
336 
337     Time time = dir.GetInfo().GetLastModifiedTime();
338 
339     // If instructed to keep only files younger than a given age
340     // (|max_file_age_| != 0), delete files satisfying this criteria
341     // right now. Otherwise add it to a list we'll consider for later.
342     if (max_file_age_ != TimeDelta() &&
343         SystemState::Get()->clock()->GetWallclockTime() - time >
344             max_file_age_) {
345       if (!DeleteP2PFile(name, "file too old"))
346         deletion_failed = true;
347     } else {
348       matches.push_back(std::make_pair(name, time));
349     }
350   }
351 
352   // If instructed to only keep N files (|max_files_to_keep_ != 0),
353   // sort list of matches, newest (biggest time) to oldest (lowest
354   // time). Then delete starting at element |num_files_to_keep_|.
355   if (num_files_to_keep_ > 0) {
356     std::sort(matches.begin(), matches.end(), MatchCompareFunc);
357     vector<pair<FilePath, Time>>::const_iterator i;
358     for (i = matches.begin() + num_files_to_keep_; i < matches.end(); ++i) {
359       if (!DeleteP2PFile(i->first, "too many files"))
360         deletion_failed = true;
361     }
362   }
363 
364   return !deletion_failed;
365 }
366 
367 // Helper class for implementing LookupUrlForFile().
368 class LookupData {
369  public:
LookupData(P2PManager::LookupCallback callback)370   explicit LookupData(P2PManager::LookupCallback callback)
371       : callback_(callback) {}
372 
~LookupData()373   ~LookupData() {
374     if (timeout_task_ != MessageLoop::kTaskIdNull)
375       MessageLoop::current()->CancelTask(timeout_task_);
376     if (child_pid_)
377       Subprocess::Get().KillExec(child_pid_);
378   }
379 
InitiateLookup(const vector<string> & cmd,TimeDelta timeout)380   void InitiateLookup(const vector<string>& cmd, TimeDelta timeout) {
381     // NOTE: if we fail early (i.e. in this method), we need to schedule
382     // an idle to report the error. This is because we guarantee that
383     // the callback is always called from the message loop (this
384     // guarantee is useful for testing).
385 
386     // We expect to run just "p2p-client" and find it in the path.
387     child_pid_ = Subprocess::Get().ExecFlags(
388         cmd,
389         Subprocess::kSearchPath,
390         {},
391         Bind(&LookupData::OnLookupDone, base::Unretained(this)));
392 
393     if (!child_pid_) {
394       LOG(ERROR) << "Error spawning " << utils::StringVectorToString(cmd);
395       ReportErrorAndDeleteInIdle();
396       return;
397     }
398 
399     if (timeout > TimeDelta()) {
400       timeout_task_ = MessageLoop::current()->PostDelayedTask(
401           FROM_HERE,
402           Bind(&LookupData::OnTimeout, base::Unretained(this)),
403           timeout);
404     }
405   }
406 
407  private:
ReportErrorAndDeleteInIdle()408   void ReportErrorAndDeleteInIdle() {
409     MessageLoop::current()->PostTask(
410         FROM_HERE,
411         Bind(&LookupData::OnIdleForReportErrorAndDelete,
412              base::Unretained(this)));
413   }
414 
OnIdleForReportErrorAndDelete()415   void OnIdleForReportErrorAndDelete() {
416     ReportError();
417     delete this;
418   }
419 
IssueCallback(const string & url)420   void IssueCallback(const string& url) {
421     if (!callback_.is_null())
422       callback_.Run(url);
423   }
424 
ReportError()425   void ReportError() {
426     if (reported_)
427       return;
428     IssueCallback("");
429     reported_ = true;
430   }
431 
ReportSuccess(const string & output)432   void ReportSuccess(const string& output) {
433     if (reported_)
434       return;
435     string url = output;
436     size_t newline_pos = url.find('\n');
437     if (newline_pos != string::npos)
438       url.resize(newline_pos);
439 
440     // Since p2p-client(1) is constructing this URL itself strictly
441     // speaking there's no need to validate it... but, anyway, can't
442     // hurt.
443     if (url.compare(0, 7, "http://") == 0) {
444       IssueCallback(url);
445     } else {
446       LOG(ERROR) << "p2p URL '" << url << "' does not look right. Ignoring.";
447       ReportError();
448     }
449     reported_ = true;
450   }
451 
OnLookupDone(int return_code,const string & output)452   void OnLookupDone(int return_code, const string& output) {
453     child_pid_ = 0;
454     if (return_code != 0) {
455       LOG(INFO) << "Child exited with non-zero exit code " << return_code;
456       ReportError();
457     } else {
458       ReportSuccess(output);
459     }
460     delete this;
461   }
462 
OnTimeout()463   void OnTimeout() {
464     timeout_task_ = MessageLoop::kTaskIdNull;
465     ReportError();
466     delete this;
467   }
468 
469   P2PManager::LookupCallback callback_;
470 
471   // The Subprocess tag of the running process. A value of 0 means that the
472   // process is not running.
473   pid_t child_pid_{0};
474 
475   // The timeout task_id we are waiting on, if any.
476   MessageLoop::TaskId timeout_task_{MessageLoop::kTaskIdNull};
477 
478   bool reported_{false};
479 };
480 
LookupUrlForFile(const string & file_id,size_t minimum_size,TimeDelta max_time_to_wait,LookupCallback callback)481 void P2PManagerImpl::LookupUrlForFile(const string& file_id,
482                                       size_t minimum_size,
483                                       TimeDelta max_time_to_wait,
484                                       LookupCallback callback) {
485   LookupData* lookup_data = new LookupData(callback);
486   string file_id_with_ext = file_id + "." + file_extension_;
487   vector<string> args =
488       configuration_->GetP2PClientArgs(file_id_with_ext, minimum_size);
489   lookup_data->InitiateLookup(args, max_time_to_wait);
490 }
491 
FileShare(const string & file_id,size_t expected_size)492 bool P2PManagerImpl::FileShare(const string& file_id, size_t expected_size) {
493   // Check if file already exist.
494   FilePath path = FileGetPath(file_id);
495   if (!path.empty()) {
496     // File exists - double check its expected size though.
497     ssize_t file_expected_size = FileGetExpectedSize(file_id);
498     if (file_expected_size == -1 ||
499         static_cast<size_t>(file_expected_size) != expected_size) {
500       LOG(ERROR) << "Existing p2p file " << path.value()
501                  << " with expected_size=" << file_expected_size
502                  << " does not match the passed in"
503                  << " expected_size=" << expected_size;
504       return false;
505     }
506     return true;
507   }
508 
509   // Before creating the file, bail if statvfs(3) indicates that at
510   // least twice the size is not available in P2P_DIR.
511   struct statvfs statvfsbuf;
512   FilePath p2p_dir = configuration_->GetP2PDir();
513   if (statvfs(p2p_dir.value().c_str(), &statvfsbuf) != 0) {
514     PLOG(ERROR) << "Error calling statvfs() for dir " << p2p_dir.value();
515     return false;
516   }
517   size_t free_bytes =
518       static_cast<size_t>(statvfsbuf.f_bsize) * statvfsbuf.f_bavail;
519   if (free_bytes < 2 * expected_size) {
520     // This can easily happen and is worth reporting.
521     LOG(INFO) << "Refusing to allocate p2p file of " << expected_size
522               << " bytes since the directory " << p2p_dir.value()
523               << " only has " << free_bytes
524               << " bytes available and this is less than twice the"
525               << " requested size.";
526     return false;
527   }
528 
529   // Okie-dokey looks like enough space is available - create the file.
530   path = GetPath(file_id, kNonVisible);
531   int fd = open(path.value().c_str(), O_CREAT | O_RDWR, 0644);
532   if (fd == -1) {
533     PLOG(ERROR) << "Error creating file with path " << path.value();
534     return false;
535   }
536   ScopedFdCloser fd_closer(&fd);
537 
538   // If the final size is known, allocate the file (e.g. reserve disk
539   // space) and set the user.cros-p2p-filesize xattr.
540   if (expected_size != 0) {
541     if (fallocate(fd,
542                   FALLOC_FL_KEEP_SIZE,  // Keep file size as 0.
543                   0,
544                   expected_size) != 0) {
545       if (errno == ENOSYS || errno == EOPNOTSUPP) {
546         // If the filesystem doesn't support the fallocate, keep
547         // going. This is helpful when running unit tests on build
548         // machines with ancient filesystems and/or OSes.
549         PLOG(WARNING) << "Ignoring fallocate(2) failure";
550       } else {
551         // ENOSPC can happen (funky race though, cf. the statvfs() check
552         // above), handle it gracefully, e.g. use logging level INFO.
553         PLOG(INFO) << "Error allocating " << expected_size << " bytes for file "
554                    << path.value();
555         if (unlink(path.value().c_str()) != 0) {
556           PLOG(ERROR) << "Error deleting file with path " << path.value();
557         }
558         return false;
559       }
560     }
561 
562     string decimal_size = std::to_string(expected_size);
563     if (fsetxattr(fd,
564                   kCrosP2PFileSizeXAttrName,
565                   decimal_size.c_str(),
566                   decimal_size.size(),
567                   0) != 0) {
568       PLOG(ERROR) << "Error setting xattr " << path.value();
569       return false;
570     }
571   }
572 
573   return true;
574 }
575 
FileGetPath(const string & file_id)576 FilePath P2PManagerImpl::FileGetPath(const string& file_id) {
577   struct stat statbuf;
578   FilePath path;
579 
580   path = GetPath(file_id, kVisible);
581   if (stat(path.value().c_str(), &statbuf) == 0) {
582     return path;
583   }
584 
585   path = GetPath(file_id, kNonVisible);
586   if (stat(path.value().c_str(), &statbuf) == 0) {
587     return path;
588   }
589 
590   path.clear();
591   return path;
592 }
593 
FileGetVisible(const string & file_id,bool * out_result)594 bool P2PManagerImpl::FileGetVisible(const string& file_id, bool* out_result) {
595   FilePath path = FileGetPath(file_id);
596   if (path.empty()) {
597     LOG(ERROR) << "No file for id " << file_id;
598     return false;
599   }
600   if (out_result != nullptr)
601     *out_result = path.MatchesExtension(kP2PExtension);
602   return true;
603 }
604 
FileMakeVisible(const string & file_id)605 bool P2PManagerImpl::FileMakeVisible(const string& file_id) {
606   FilePath path = FileGetPath(file_id);
607   if (path.empty()) {
608     LOG(ERROR) << "No file for id " << file_id;
609     return false;
610   }
611 
612   // Already visible?
613   if (path.MatchesExtension(kP2PExtension))
614     return true;
615 
616   LOG_ASSERT(path.MatchesExtension(kTmpExtension));
617   FilePath new_path = path.RemoveExtension();
618   LOG_ASSERT(new_path.MatchesExtension(kP2PExtension));
619   if (rename(path.value().c_str(), new_path.value().c_str()) != 0) {
620     PLOG(ERROR) << "Error renaming " << path.value() << " to "
621                 << new_path.value();
622     return false;
623   }
624 
625   return true;
626 }
627 
FileGetSize(const string & file_id)628 ssize_t P2PManagerImpl::FileGetSize(const string& file_id) {
629   FilePath path = FileGetPath(file_id);
630   if (path.empty())
631     return -1;
632 
633   return utils::FileSize(path.value());
634 }
635 
FileGetExpectedSize(const string & file_id)636 ssize_t P2PManagerImpl::FileGetExpectedSize(const string& file_id) {
637   FilePath path = FileGetPath(file_id);
638   if (path.empty())
639     return -1;
640 
641   char ea_value[64] = {0};
642   ssize_t ea_size;
643   ea_size = getxattr(path.value().c_str(),
644                      kCrosP2PFileSizeXAttrName,
645                      &ea_value,
646                      sizeof(ea_value) - 1);
647   if (ea_size == -1) {
648     PLOG(ERROR) << "Error calling getxattr() on file " << path.value();
649     return -1;
650   }
651 
652   char* endp = nullptr;
653   long long int val = strtoll(ea_value, &endp, 0);  // NOLINT(runtime/int)
654   if (*endp != '\0') {
655     LOG(ERROR) << "Error parsing the value '" << ea_value << "' of the xattr "
656                << kCrosP2PFileSizeXAttrName << " as an integer";
657     return -1;
658   }
659 
660   return val;
661 }
662 
CountSharedFiles()663 int P2PManagerImpl::CountSharedFiles() {
664   int num_files = 0;
665 
666   FilePath p2p_dir = configuration_->GetP2PDir();
667   const string ext_visible = GetExt(kVisible);
668   const string ext_non_visible = GetExt(kNonVisible);
669 
670   base::FileEnumerator dir(p2p_dir, false, base::FileEnumerator::FILES);
671   for (FilePath name = dir.Next(); !name.empty(); name = dir.Next()) {
672     if (base::EndsWith(
673             name.value(), ext_visible, base::CompareCase::SENSITIVE) ||
674         base::EndsWith(
675             name.value(), ext_non_visible, base::CompareCase::SENSITIVE)) {
676       num_files += 1;
677     }
678   }
679 
680   return num_files;
681 }
682 
ScheduleEnabledStatusChange()683 void P2PManagerImpl::ScheduleEnabledStatusChange() {
684   if (waiting_for_enabled_status_change_)
685     return;
686 
687   Callback<void(EvalStatus, const bool&)> callback =
688       Bind(&P2PManagerImpl::OnEnabledStatusChange, base::Unretained(this));
689   update_manager_->AsyncPolicyRequest(
690       callback, &Policy::P2PEnabledChanged, is_enabled_);
691   waiting_for_enabled_status_change_ = true;
692 }
693 
OnEnabledStatusChange(EvalStatus status,const bool & result)694 void P2PManagerImpl::OnEnabledStatusChange(EvalStatus status,
695                                            const bool& result) {
696   waiting_for_enabled_status_change_ = false;
697 
698   if (status == EvalStatus::kSucceeded) {
699     if (result == is_enabled_) {
700       LOG(WARNING) << "P2P enabled status did not change, which means that it "
701                       "is permanent; not scheduling further checks.";
702       waiting_for_enabled_status_change_ = true;
703       return;
704     }
705 
706     is_enabled_ = result;
707 
708     // If P2P is running but shouldn't be, make sure it isn't.
709     if (may_be_running_ && !is_enabled_ && !EnsureP2PNotRunning()) {
710       LOG(WARNING) << "Failed to stop P2P service.";
711     }
712   } else {
713     LOG(WARNING)
714         << "P2P enabled tracking failed (possibly timed out); retrying.";
715   }
716 
717   ScheduleEnabledStatusChange();
718 }
719 
Construct(Configuration * configuration,UpdateManager * update_manager,const string & file_extension,const int num_files_to_keep,const TimeDelta & max_file_age)720 P2PManager* P2PManager::Construct(Configuration* configuration,
721                                   UpdateManager* update_manager,
722                                   const string& file_extension,
723                                   const int num_files_to_keep,
724                                   const TimeDelta& max_file_age) {
725   return new P2PManagerImpl(configuration,
726                             update_manager,
727                             file_extension,
728                             num_files_to_keep,
729                             max_file_age);
730 }
731 
732 }  // namespace chromeos_update_engine
733