1 //
2 // Copyright (C) 2012 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 #ifndef UPDATE_ENGINE_COMMON_UTILS_H_
18 #define UPDATE_ENGINE_COMMON_UTILS_H_
19
20 #include <errno.h>
21 #include <sys/types.h>
22 #include <time.h>
23 #include <unistd.h>
24
25 #include <algorithm>
26 #include <limits>
27 #include <map>
28 #include <memory>
29 #include <set>
30 #include <string>
31 #include <vector>
32
33 #include <base/files/file_path.h>
34 #include <base/posix/eintr_wrapper.h>
35 #include <base/time/time.h>
36 #include <brillo/key_value_store.h>
37 #include <brillo/secure_blob.h>
38
39 #include "update_engine/common/action.h"
40 #include "update_engine/common/action_processor.h"
41 #include "update_engine/common/constants.h"
42 #include "update_engine/payload_consumer/file_descriptor.h"
43 #include "update_engine/update_metadata.pb.h"
44
45 namespace chromeos_update_engine {
46
47 namespace utils {
48
49 // Formats |vec_str| as a string of the form ["<elem1>", "<elem2>"].
50 // Does no escaping, only use this for presentation in error messages.
51 std::string StringVectorToString(const std::vector<std::string>& vec_str);
52
53 // Calculates the p2p file id from payload hash and size
54 std::string CalculateP2PFileId(const brillo::Blob& payload_hash,
55 size_t payload_size);
56
57 // Writes the data passed to path. The file at path will be overwritten if it
58 // exists. Returns true on success, false otherwise.
59 bool WriteFile(const char* path, const void* data, size_t data_len);
60
61 // Calls write() or pwrite() repeatedly until all count bytes at buf are
62 // written to fd or an error occurs. Returns true on success.
63 bool WriteAll(int fd, const void* buf, size_t count);
64 bool PWriteAll(int fd, const void* buf, size_t count, off_t offset);
65
66 bool WriteAll(const FileDescriptorPtr& fd, const void* buf, size_t count);
67 // WriteAll writes data at specified offset, but it modifies file position.
68 bool WriteAll(const FileDescriptorPtr& fd,
69 const void* buf,
70 size_t count,
71 off_t off);
72
73 // https://man7.org/linux/man-pages/man2/pread.2.html
74 // PWriteAll writes data at specified offset, but it DOES NOT modify file
75 // position. Behaves similar to linux' pwrite syscall.
76 bool PWriteAll(const FileDescriptorPtr& fd,
77 const void* buf,
78 size_t count,
79 off_t offset);
80
81 // Calls read() repeatedly until |count| bytes are read or EOF or EWOULDBLOCK
82 // is reached. Returns whether all read() calls succeeded (including EWOULDBLOCK
83 // as a success case), sets |eof| to whether the eof was reached and sets
84 // |out_bytes_read| to the actual number of bytes read regardless of the return
85 // value.
86 bool ReadAll(
87 int fd, void* buf, size_t count, size_t* out_bytes_read, bool* eof);
88
89 // Calls pread() repeatedly until count bytes are read, or EOF is reached.
90 // Returns number of bytes read in *bytes_read. Returns true on success.
91 bool PReadAll(
92 int fd, void* buf, size_t count, off_t offset, ssize_t* out_bytes_read);
93
94 // Reads data at specified offset, this function does change file position.
95 bool ReadAll(const FileDescriptorPtr& fd,
96 void* buf,
97 size_t count,
98 off_t offset,
99 ssize_t* out_bytes_read);
100
101 // https://man7.org/linux/man-pages/man2/pread.2.html
102 // Reads data at specified offset, this function DOES NOT change file position.
103 // Behavior is similar to linux's pread syscall.
104 bool PReadAll(const FileDescriptorPtr& fd,
105 void* buf,
106 size_t count,
107 off_t offset,
108 ssize_t* out_bytes_read);
109
110 // Opens |path| for reading and appends its entire content to the container
111 // pointed to by |out_p|. Returns true upon successfully reading all of the
112 // file's content, false otherwise, in which case the state of the output
113 // container is unknown. ReadFileChunk starts reading the file from |offset|; if
114 // |size| is not -1, only up to |size| bytes are read in.
115 bool ReadFile(const std::string& path, brillo::Blob* out_p);
116 bool ReadFile(const std::string& path, std::string* out_p);
117 bool ReadFileChunk(const std::string& path,
118 off_t offset,
119 off_t size,
120 brillo::Blob* out_p);
121
122 // Invokes |cmd| in a pipe and appends its stdout to the container pointed to by
123 // |out_p|. Returns true upon successfully reading all of the output, false
124 // otherwise, in which case the state of the output container is unknown.
125 bool ReadPipe(const std::string& cmd, std::string* out_p);
126
127 // Returns the size of the block device at the file descriptor fd. If an error
128 // occurs, -1 is returned.
129 off_t BlockDevSize(int fd);
130
131 // Returns the size of the file at path, or the file descriptor fd. If the file
132 // is actually a block device, this function will automatically call
133 // BlockDevSize. If the file doesn't exist or some error occurrs, -1 is
134 // returned.
135 off_t FileSize(const std::string& path);
136 off_t FileSize(int fd);
137
138 std::string ErrnoNumberAsString(int err);
139
140 // Returns true if the file exists for sure. Returns false if it doesn't exist,
141 // or an error occurs.
142 bool FileExists(const char* path);
143
144 // Returns true if |path| exists and is a symbolic link.
145 bool IsSymlink(const char* path);
146
147 // Return true iff |path| exists and is a regular file
148 bool IsRegFile(const char* path);
149
150 // If |base_filename_template| is neither absolute (starts with "/") nor
151 // explicitly relative to the current working directory (starts with "./" or
152 // "../"), then it is prepended the system's temporary directory. On success,
153 // stores the name of the new temporary file in |filename|. If |fd| is
154 // non-null, the file descriptor returned by mkstemp is written to it and
155 // kept open; otherwise, it is closed. The template must end with "XXXXXX".
156 // Returns true on success.
157 bool MakeTempFile(const std::string& base_filename_template,
158 std::string* filename,
159 int* fd);
160
161 // Splits the partition device name into the block device name and partition
162 // number. For example, "/dev/sda3" will be split into {"/dev/sda", 3} and
163 // "/dev/mmcblk0p2" into {"/dev/mmcblk0", 2}
164 // Returns false when malformed device name is passed in.
165 // If both output parameters are omitted (null), can be used
166 // just to test the validity of the device name. Note that the function
167 // simply checks if the device name looks like a valid device, no other
168 // checks are performed (i.e. it doesn't check if the device actually exists).
169 bool SplitPartitionName(const std::string& partition_name,
170 std::string* out_disk_name,
171 int* out_partition_num);
172
173 // Builds a partition device name from the block device name and partition
174 // number. For example:
175 // {"/dev/sda", 1} => "/dev/sda1"
176 // {"/dev/mmcblk2", 12} => "/dev/mmcblk2p12"
177 // Returns empty string when invalid parameters are passed in
178 std::string MakePartitionName(const std::string& disk_name, int partition_num);
179
180 // Set the read-only attribute on the block device |device| to the value passed
181 // in |read_only|. Return whether the operation succeeded.
182 bool SetBlockDeviceReadOnly(const std::string& device, bool read_only);
183
184 // Synchronously mount or unmount a filesystem. Return true on success.
185 // When mounting, it will attempt to mount the device as the passed filesystem
186 // type |type|, with the passed |flags| options. If |type| is empty, "ext2",
187 // "ext3", "ext4" and "squashfs" will be tried.
188 bool MountFilesystem(const std::string& device,
189 const std::string& mountpoint,
190 unsigned long flags, // NOLINT(runtime/int)
191 const std::string& type,
192 const std::string& fs_mount_options);
193 bool UnmountFilesystem(const std::string& mountpoint);
194
195 // Return whether the passed |mountpoint| path is a directory where a filesystem
196 // is mounted. Due to detection mechanism limitations, when used on directories
197 // where another part of the tree was bind mounted returns true only if bind
198 // mounted on top of a different filesystem (not inside the same filesystem).
199 bool IsMountpoint(const std::string& mountpoint);
200
201 // Returns a human-readable string with the file format based on magic constants
202 // on the header of the file.
203 std::string GetFileFormat(const std::string& path);
204
205 // Returns the string representation of the given UTC time.
206 // such as "11/14/2011 14:05:30 GMT".
207 std::string ToString(const base::Time utc_time);
208
209 // Returns true or false depending on the value of b.
210 std::string ToString(bool b);
211
212 // Returns a string representation of the given enum.
213 std::string ToString(DownloadSource source);
214
215 // Returns a string representation of the given enum.
216 std::string ToString(PayloadType payload_type);
217
218 // Fuzzes an integer |value| randomly in the range:
219 // [value - range / 2, value + range - range / 2]
220 int FuzzInt(int value, unsigned int range);
221
222 // Log a string in hex to LOG(INFO). Useful for debugging.
223 void HexDumpArray(const uint8_t* const arr, const size_t length);
HexDumpString(const std::string & str)224 inline void HexDumpString(const std::string& str) {
225 HexDumpArray(reinterpret_cast<const uint8_t*>(str.data()), str.size());
226 }
HexDumpVector(const brillo::Blob & vect)227 inline void HexDumpVector(const brillo::Blob& vect) {
228 HexDumpArray(vect.data(), vect.size());
229 }
230
231 template <typename T>
VectorIndexOf(const std::vector<T> & vect,const T & value,typename std::vector<T>::size_type * out_index)232 bool VectorIndexOf(const std::vector<T>& vect,
233 const T& value,
234 typename std::vector<T>::size_type* out_index) {
235 typename std::vector<T>::const_iterator it =
236 std::find(vect.begin(), vect.end(), value);
237 if (it == vect.end()) {
238 return false;
239 } else {
240 *out_index = it - vect.begin();
241 return true;
242 }
243 }
244
245 // Return the total number of blocks in the passed |extents| collection.
246 template <class T>
BlocksInExtents(const T & extents)247 uint64_t BlocksInExtents(const T& extents) {
248 uint64_t sum = 0;
249 for (const auto& ext : extents) {
250 sum += ext.num_blocks();
251 }
252 return sum;
253 }
254
255 // Converts seconds into human readable notation including days, hours, minutes
256 // and seconds. For example, 185 will yield 3m5s, 4300 will yield 1h11m40s, and
257 // 360000 will yield 4d4h0m0s. Zero padding not applied. Seconds are always
258 // shown in the result.
259 std::string FormatSecs(unsigned secs);
260
261 // Converts a TimeDelta into human readable notation including days, hours,
262 // minutes, seconds and fractions of a second down to microsecond granularity,
263 // as necessary; for example, an output of 5d2h0m15.053s means that the input
264 // time was precise to the milliseconds only. Zero padding not applied, except
265 // for fractions. Seconds are always shown, but fractions thereof are only shown
266 // when applicable. If |delta| is negative, the output will have a leading '-'
267 // followed by the absolute duration.
268 std::string FormatTimeDelta(base::TimeDelta delta);
269
270 // This method transforms the given error code to be suitable for UMA and
271 // for error classification purposes by removing the higher order bits and
272 // aggregating error codes beyond the enum range, etc. This method is
273 // idempotent, i.e. if called with a value previously returned by this method,
274 // it'll return the same value again.
275 ErrorCode GetBaseErrorCode(ErrorCode code);
276
277 // Converts |time| to an Omaha InstallDate which is defined as "the
278 // number of PST8PDT calendar weeks since Jan 1st 2007 0:00 PST, times
279 // seven" with PST8PDT defined as "Pacific Time" (e.g. UTC-07:00 if
280 // daylight savings is observed and UTC-08:00 otherwise.)
281 //
282 // If the passed in |time| variable is before Monday January 1st 2007
283 // 0:00 PST, False is returned and the value returned in
284 // |out_num_days| is undefined. Otherwise the number of PST8PDT
285 // calendar weeks since that date times seven is returned in
286 // |out_num_days| and the function returns True.
287 //
288 // (NOTE: This function does not currently take daylight savings time
289 // into account so the result may up to one hour off. This is because
290 // the glibc date and timezone routines depend on the TZ environment
291 // variable and changing environment variables is not thread-safe.
292 bool ConvertToOmahaInstallDate(base::Time time, int* out_num_days);
293
294 // Look for the minor version value in the passed |store| and set
295 // |minor_version| to that value. Return whether the value was found and valid.
296 bool GetMinorVersion(const brillo::KeyValueStore& store,
297 uint32_t* minor_version);
298
299 // This function reads the specified data in |extents| into |out_data|. The
300 // extents are read from the file at |path|. |out_data_size| is the size of
301 // |out_data|. Returns false if the number of bytes to read given in
302 // |extents| does not equal |out_data_size|.
303 bool ReadExtents(const std::string& path,
304 const std::vector<Extent>& extents,
305 brillo::Blob* out_data,
306 ssize_t out_data_size,
307 size_t block_size);
308
309 // Read the current boot identifier and store it in |boot_id|. This identifier
310 // is constants during the same boot of the kernel and is regenerated after
311 // reboot. Returns whether it succeeded getting the boot_id.
312 bool GetBootId(std::string* boot_id);
313
314 // Gets a string value from the vpd for a given key using the `vpd_get_value`
315 // shell command. Returns true on success.
316 bool GetVpdValue(std::string key, std::string* result);
317
318 // This function gets the file path of the file pointed to by FileDiscriptor.
319 std::string GetFilePath(int fd);
320
321 // Divide |x| by |y| and round up to the nearest integer.
DivRoundUp(uint64_t x,uint64_t y)322 constexpr uint64_t DivRoundUp(uint64_t x, uint64_t y) {
323 return (x + y - 1) / y;
324 }
325
326 // Round |x| up to be a multiple of |y|.
RoundUp(uint64_t x,uint64_t y)327 constexpr uint64_t RoundUp(uint64_t x, uint64_t y) {
328 return DivRoundUp(x, y) * y;
329 }
330
331 // Returns the integer value of the first section of |version|. E.g. for
332 // "10575.39." returns 10575. Returns 0 if |version| is empty, returns -1 if
333 // first section of |version| is invalid (e.g. not a number).
334 int VersionPrefix(const std::string& version);
335
336 // Parses a string in the form high.low, where high and low are 16 bit unsigned
337 // integers. If there is more than 1 dot, or if either of the two parts are
338 // not valid 16 bit unsigned numbers, then 0xffff is returned for both.
339 void ParseRollbackKeyVersion(const std::string& raw_version,
340 uint16_t* high_version,
341 uint16_t* low_version);
342
343 // Return a string representation of |utime| for log file names.
344 std::string GetTimeAsString(time_t utime);
345 // Returns the string format of the hashed |str_to_convert| that can be used
346 // with |Excluder| as the exclusion name.
347 std::string GetExclusionName(const std::string& str_to_convert);
348
349 // Parse `old_version` and `new_version` as integer timestamps and
350 // Return kSuccess if `new_version` is larger/newer.
351 // Return kSuccess if either one is empty.
352 // Return kError if |old_version| is not empty and not an integer.
353 // Return kDownloadManifestParseError if |new_version| is not empty and not an
354 // integer.
355 // Return kPayloadTimestampError if both are integers but |new_version| <
356 // |old_version|.
357 ErrorCode IsTimestampNewer(const std::string& old_version,
358 const std::string& new_version);
359
360 } // namespace utils
361
362 // Utility class to close a file descriptor
363 class ScopedFdCloser {
364 public:
ScopedFdCloser(int * fd)365 explicit ScopedFdCloser(int* fd) : fd_(fd) {}
~ScopedFdCloser()366 ~ScopedFdCloser() {
367 if (should_close_ && fd_ && (*fd_ >= 0) && !IGNORE_EINTR(close(*fd_)))
368 *fd_ = -1;
369 }
set_should_close(bool should_close)370 void set_should_close(bool should_close) { should_close_ = should_close; }
371
372 private:
373 int* fd_;
374 bool should_close_ = true;
375 DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
376 };
377
378 // Utility class to delete a file when it goes out of scope.
379 class ScopedPathUnlinker {
380 public:
ScopedPathUnlinker(const std::string & path)381 explicit ScopedPathUnlinker(const std::string& path)
382 : path_(path), should_remove_(true) {}
~ScopedPathUnlinker()383 ~ScopedPathUnlinker() {
384 if (should_remove_ && unlink(path_.c_str()) < 0) {
385 PLOG(ERROR) << "Unable to unlink path " << path_;
386 }
387 }
set_should_remove(bool should_remove)388 void set_should_remove(bool should_remove) { should_remove_ = should_remove; }
389
390 private:
391 const std::string path_;
392 bool should_remove_;
393 DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
394 };
395
396 class ScopedTempFile {
397 public:
ScopedTempFile()398 ScopedTempFile() : ScopedTempFile("update_engine_temp.XXXXXX") {}
399
400 // If |open_fd| is true, a writable file descriptor will be opened for this
401 // file.
402 // If |truncate_size| is non-zero, truncate file to that size on creation.
403 explicit ScopedTempFile(const std::string& pattern,
404 bool open_fd = false,
405 size_t truncate_size = 0) {
406 CHECK(utils::MakeTempFile(pattern, &path_, open_fd ? &fd_ : nullptr));
407 unlinker_.reset(new ScopedPathUnlinker(path_));
408 if (open_fd) {
409 CHECK_GE(fd_, 0);
410 fd_closer_.reset(new ScopedFdCloser(&fd_));
411 }
412 if (truncate_size > 0) {
413 CHECK_EQ(0, truncate(path_.c_str(), truncate_size));
414 }
415 }
416 virtual ~ScopedTempFile() = default;
417
path()418 const std::string& path() const { return path_; }
fd()419 int fd() const {
420 CHECK(fd_closer_);
421 return fd_;
422 }
CloseFd()423 void CloseFd() {
424 CHECK(fd_closer_);
425 fd_closer_.reset();
426 }
427
428 private:
429 std::string path_;
430 std::unique_ptr<ScopedPathUnlinker> unlinker_;
431
432 int fd_{-1};
433 std::unique_ptr<ScopedFdCloser> fd_closer_;
434
435 DISALLOW_COPY_AND_ASSIGN(ScopedTempFile);
436 };
437
438 // A little object to call ActionComplete on the ActionProcessor when
439 // it's destructed.
440 class ScopedActionCompleter {
441 public:
ScopedActionCompleter(ActionProcessor * processor,AbstractAction * action)442 explicit ScopedActionCompleter(ActionProcessor* processor,
443 AbstractAction* action)
444 : processor_(processor),
445 action_(action),
446 code_(ErrorCode::kError),
447 should_complete_(true) {
448 CHECK(processor_);
449 }
~ScopedActionCompleter()450 ~ScopedActionCompleter() {
451 if (should_complete_)
452 processor_->ActionComplete(action_, code_);
453 }
set_code(ErrorCode code)454 void set_code(ErrorCode code) { code_ = code; }
set_should_complete(bool should_complete)455 void set_should_complete(bool should_complete) {
456 should_complete_ = should_complete;
457 }
get_code()458 ErrorCode get_code() const { return code_; }
459
460 private:
461 ActionProcessor* processor_;
462 AbstractAction* action_;
463 ErrorCode code_;
464 bool should_complete_;
465 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
466 };
467
468 } // namespace chromeos_update_engine
469
470 #define TEST_AND_RETURN_FALSE_ERRNO(_x) \
471 do { \
472 bool _success = static_cast<bool>(_x); \
473 if (!_success) { \
474 std::string _msg = \
475 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
476 LOG(ERROR) << #_x " failed: " << _msg; \
477 return false; \
478 } \
479 } while (0)
480
481 #define TEST_AND_RETURN_FALSE(_x) \
482 do { \
483 bool _success = static_cast<bool>(_x); \
484 if (!_success) { \
485 LOG(ERROR) << #_x " failed."; \
486 return false; \
487 } \
488 } while (0)
489
490 #define TEST_AND_RETURN_ERRNO(_x) \
491 do { \
492 bool _success = static_cast<bool>(_x); \
493 if (!_success) { \
494 std::string _msg = \
495 chromeos_update_engine::utils::ErrnoNumberAsString(errno); \
496 LOG(ERROR) << #_x " failed: " << _msg; \
497 return; \
498 } \
499 } while (0)
500
501 #define TEST_AND_RETURN(_x) \
502 do { \
503 bool _success = static_cast<bool>(_x); \
504 if (!_success) { \
505 LOG(ERROR) << #_x " failed."; \
506 return; \
507 } \
508 } while (0)
509
510 #define TEST_AND_RETURN_FALSE_ERRCODE(_x) \
511 do { \
512 errcode_t _error = (_x); \
513 if (_error) { \
514 errno = _error; \
515 LOG(ERROR) << #_x " failed: " << _error; \
516 return false; \
517 } \
518 } while (0)
519
520 #endif // UPDATE_ENGINE_COMMON_UTILS_H_
521