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