p2p_manager.cc 23 KB

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