blob: 002e6a04fccf030c2964205233aed592effddea7 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
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//
adlr@google.com3defe6a2009-12-04 20:57:17 +000016
Alex Deymo39910dc2015-11-09 17:04:30 -080017#include "update_engine/common/utils.h"
Darin Petkovf74eb652010-08-04 12:08:38 -070018
Ben Chan9abb7632014-08-07 00:10:53 -070019#include <stdint.h>
20
adlr@google.com3defe6a2009-12-04 20:57:17 +000021#include <dirent.h>
Alex Deymoc1711e22014-08-08 13:16:23 -070022#include <elf.h>
Alex Deymo6f20dd42015-08-18 16:42:46 -070023#include <endian.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000024#include <errno.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080025#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000026#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
Alex Deymoc4acdf42014-05-28 21:07:10 -070029#include <sys/mount.h>
30#include <sys/resource.h>
Kelvin Zhang8933d572021-01-28 10:17:34 -050031#include <sys/sendfile.h>
Alex Deymoc4acdf42014-05-28 21:07:10 -070032#include <sys/stat.h>
33#include <sys/types.h>
Yifan Hongc80de2d2020-02-25 17:13:53 -080034#include <time.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000035#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070036
adlr@google.com3defe6a2009-12-04 20:57:17 +000037#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070038#include <utility>
Chris Sosac1972482013-04-30 22:31:10 -070039#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070040
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070041#include <base/callback.h>
Ben Chan736fcb52014-05-21 18:28:22 -070042#include <base/files/file_path.h>
Alex Deymo192393b2014-11-10 15:58:38 -080043#include <base/files/file_util.h>
Ben Chan736fcb52014-05-21 18:28:22 -070044#include <base/files/scoped_file.h>
Alex Deymoc00c98a2015-03-17 17:38:00 -070045#include <base/format_macros.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070046#include <base/location.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040047#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080048#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050049#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070050#include <base/strings/string_number_conversions.h>
51#include <base/strings/string_split.h>
52#include <base/strings/string_util.h>
53#include <base/strings/stringprintf.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070054#include <brillo/data_encoding.h>
Will Drewry8f71da82010-08-30 14:07:11 -050055
Alex Deymo39910dc2015-11-09 17:04:30 -080056#include "update_engine/common/constants.h"
Sen Jiang9c123462015-11-19 13:16:23 -080057#include "update_engine/common/platform_constants.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080058#include "update_engine/common/prefs_interface.h"
59#include "update_engine/common/subprocess.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080060#include "update_engine/payload_consumer/file_descriptor.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000061
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070062using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080063using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000064using std::min;
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -070065using std::numeric_limits;
adlr@google.com3defe6a2009-12-04 20:57:17 +000066using std::string;
67using std::vector;
68
69namespace chromeos_update_engine {
70
Ben Chan77a1eba2012-10-07 22:54:55 -070071namespace {
72
73// The following constants control how UnmountFilesystem should retry if
74// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
75// one second.
76const int kUnmountMaxNumOfRetries = 5;
77const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070078
79// Number of bytes to read from a file to attempt to detect its contents. Used
80// in GetFileFormat.
81const int kGetFileFormatMaxHeaderSize = 32;
82
Alex Deymodd132f32015-09-14 19:12:07 -070083// The path to the kernel's boot_id.
84const char kBootIdPath[] = "/proc/sys/kernel/random/boot_id";
85
Alex Deymo5aa1c542015-09-18 01:02:33 -070086// If |path| is absolute, or explicit relative to the current working directory,
87// leaves it as is. Otherwise, uses the system's temp directory, as defined by
88// base::GetTempDir() and prepends it to |path|. On success stores the full
89// temporary path in |template_path| and returns true.
90bool GetTempName(const string& path, base::FilePath* template_path) {
Alex Vakulenko0103c362016-01-20 07:56:15 -080091 if (path[0] == '/' ||
92 base::StartsWith(path, "./", base::CompareCase::SENSITIVE) ||
93 base::StartsWith(path, "../", base::CompareCase::SENSITIVE)) {
Alex Deymo5aa1c542015-09-18 01:02:33 -070094 *template_path = base::FilePath(path);
95 return true;
96 }
97
98 base::FilePath temp_dir;
Sen Jiang9c123462015-11-19 13:16:23 -080099#ifdef __ANDROID__
Sen Jiangc2b37662019-01-09 16:51:18 -0800100 temp_dir = base::FilePath(constants::kNonVolatileDirectory).Append("tmp");
Alex Deymo32951022016-08-10 17:02:49 -0700101#else
Sen Jiangc2b37662019-01-09 16:51:18 -0800102 TEST_AND_RETURN_FALSE(base::GetTempDir(&temp_dir));
Alex Deymo32951022016-08-10 17:02:49 -0700103#endif // __ANDROID__
Sen Jiang9c123462015-11-19 13:16:23 -0800104 if (!base::PathExists(temp_dir))
105 TEST_AND_RETURN_FALSE(base::CreateDirectory(temp_dir));
Alex Deymo5aa1c542015-09-18 01:02:33 -0700106 *template_path = temp_dir.Append(path);
107 return true;
108}
109
Ben Chan77a1eba2012-10-07 22:54:55 -0700110} // namespace
111
adlr@google.com3defe6a2009-12-04 20:57:17 +0000112namespace utils {
113
Alex Deymo335516c2016-11-28 13:37:06 -0800114bool WriteFile(const char* path, const void* data, size_t data_len) {
115 int fd = HANDLE_EINTR(open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600));
116 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
117 ScopedFdCloser fd_closer(&fd);
118 return WriteAll(fd, data, data_len);
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800119}
120
Alex Deymo0d298542016-03-30 18:31:49 -0700121bool ReadAll(
122 int fd, void* buf, size_t count, size_t* out_bytes_read, bool* eof) {
123 char* c_buf = static_cast<char*>(buf);
124 size_t bytes_read = 0;
125 *eof = false;
126 while (bytes_read < count) {
127 ssize_t rc = HANDLE_EINTR(read(fd, c_buf + bytes_read, count - bytes_read));
128 if (rc < 0) {
129 // EAGAIN and EWOULDBLOCK are normal return values when there's no more
130 // input and we are in non-blocking mode.
131 if (errno != EWOULDBLOCK && errno != EAGAIN) {
132 PLOG(ERROR) << "Error reading fd " << fd;
133 *out_bytes_read = bytes_read;
134 return false;
135 }
136 break;
137 } else if (rc == 0) {
138 // A value of 0 means that we reached EOF and there is nothing else to
139 // read from this fd.
140 *eof = true;
141 break;
142 } else {
143 bytes_read += rc;
144 }
145 }
146 *out_bytes_read = bytes_read;
147 return true;
148}
149
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700150bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700151 const char* c_buf = static_cast<const char*>(buf);
152 ssize_t bytes_written = 0;
153 while (bytes_written < static_cast<ssize_t>(count)) {
154 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
155 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
156 bytes_written += rc;
157 }
158 return true;
159}
160
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700161bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
162 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700163 size_t bytes_written = 0;
164 int num_attempts = 0;
165 while (bytes_written < count) {
166 num_attempts++;
Amin Hassanib2689592019-01-13 17:04:28 -0800167 ssize_t rc = pwrite(fd,
168 c_buf + bytes_written,
169 count - bytes_written,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700170 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700171 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
172 if (rc < 0) {
173 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
Amin Hassanib2689592019-01-13 17:04:28 -0800174 << " bytes_written=" << bytes_written << " count=" << count
175 << " offset=" << offset;
Gilad Arnold780db212012-07-11 13:12:49 -0700176 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700177 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
178 bytes_written += rc;
179 }
180 return true;
181}
182
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700183bool WriteAll(const FileDescriptorPtr& fd, const void* buf, size_t count) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800184 const char* c_buf = static_cast<const char*>(buf);
185 ssize_t bytes_written = 0;
186 while (bytes_written < static_cast<ssize_t>(count)) {
187 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
188 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
189 bytes_written += rc;
190 }
191 return true;
192}
193
Kelvin Zhang4b280242020-11-06 16:07:45 -0500194bool WriteAll(const FileDescriptorPtr& fd,
195 const void* buf,
196 size_t count,
197 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700198 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
199 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800200 return WriteAll(fd, buf, count);
201}
202
Amin Hassanib2689592019-01-13 17:04:28 -0800203bool PReadAll(
204 int fd, void* buf, size_t count, off_t offset, ssize_t* out_bytes_read) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700205 char* c_buf = static_cast<char*>(buf);
206 ssize_t bytes_read = 0;
207 while (bytes_read < static_cast<ssize_t>(count)) {
Amin Hassanib2689592019-01-13 17:04:28 -0800208 ssize_t rc =
209 pread(fd, c_buf + bytes_read, count - bytes_read, offset + bytes_read);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700210 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
211 if (rc == 0) {
212 break;
213 }
214 bytes_read += rc;
215 }
216 *out_bytes_read = bytes_read;
217 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700218}
219
Kelvin Zhang4b280242020-11-06 16:07:45 -0500220bool ReadAll(const FileDescriptorPtr& fd,
221 void* buf,
222 size_t count,
223 off_t offset,
224 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700225 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
226 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800227 char* c_buf = static_cast<char*>(buf);
228 ssize_t bytes_read = 0;
229 while (bytes_read < static_cast<ssize_t>(count)) {
230 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
231 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
232 if (rc == 0) {
233 break;
234 }
235 bytes_read += rc;
236 }
237 *out_bytes_read = bytes_read;
238 return true;
239}
240
Kelvin Zhangc3c0a3a2020-11-09 16:08:13 -0500241bool PReadAll(const FileDescriptorPtr& fd,
242 void* buf,
243 size_t count,
244 off_t offset,
245 ssize_t* out_bytes_read) {
246 auto old_off = fd->Seek(0, SEEK_CUR);
247 TEST_AND_RETURN_FALSE_ERRNO(old_off >= 0);
248
249 auto success = ReadAll(fd, buf, count, offset, out_bytes_read);
250 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(old_off, SEEK_SET) == old_off);
251 return success;
252}
253
254bool PWriteAll(const FileDescriptorPtr& fd,
255 const void* buf,
256 size_t count,
257 off_t offset) {
258 auto old_off = fd->Seek(0, SEEK_CUR);
259 TEST_AND_RETURN_FALSE_ERRNO(old_off >= 0);
260
261 auto success = WriteAll(fd, buf, count, offset);
262 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(old_off, SEEK_SET) == old_off);
263 return success;
264}
265
Gilad Arnold19a45f02012-07-19 12:36:10 -0700266// Append |nbytes| of content from |buf| to the vector pointed to by either
267// |vec_p| or |str_p|.
Amin Hassanib2689592019-01-13 17:04:28 -0800268static void AppendBytes(const uint8_t* buf,
269 size_t nbytes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700270 brillo::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700271 CHECK(buf);
272 CHECK(vec_p);
273 vec_p->insert(vec_p->end(), buf, buf + nbytes);
274}
Amin Hassanib2689592019-01-13 17:04:28 -0800275static void AppendBytes(const uint8_t* buf, size_t nbytes, string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700276 CHECK(buf);
277 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800278 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700279}
280
281// Reads from an open file |fp|, appending the read content to the container
282// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200283// file's content, false otherwise. If |size| is not -1, reads up to |size|
284// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700285template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200286static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700287 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200288 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800289 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200290 while (size == -1 || size > 0) {
291 off_t bytes_to_read = sizeof(buf);
292 if (size > 0 && bytes_to_read > size) {
293 bytes_to_read = size;
294 }
295 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
296 if (!nbytes) {
297 break;
298 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700299 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200300 if (size != -1) {
301 CHECK(size >= static_cast<off_t>(nbytes));
302 size -= nbytes;
303 }
304 }
305 if (ferror(fp)) {
306 return false;
307 }
308 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700309}
310
Darin Petkov8e447e02013-04-16 16:23:50 +0200311// Opens a file |path| for reading and appends its the contents to a container
312// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
313// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700314template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700315static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200316 off_t offset,
317 off_t size,
318 T* out_p) {
319 CHECK_GE(offset, 0);
320 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700321 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200322 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000323 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200324 if (offset) {
325 // Return success without appending any data if a chunk beyond the end of
326 // the file is requested.
327 if (offset >= FileSize(path)) {
328 return true;
329 }
330 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
331 }
332 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000333}
334
Alex Deymo10875d92014-11-10 21:52:57 -0800335// TODO(deymo): This is only used in unittest, but requires the private
336// Read<string>() defined here. Expose Read<string>() or move to base/ version.
337bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700338 FILE* fp = popen(cmd.c_str(), "r");
339 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000340 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200341 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700342 return (success && pclose(fp) >= 0);
343}
344
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700345bool ReadFile(const string& path, brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200346 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700347}
348
Darin Petkov8e447e02013-04-16 16:23:50 +0200349bool ReadFile(const string& path, string* out_p) {
350 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700351}
352
Amin Hassanib2689592019-01-13 17:04:28 -0800353bool ReadFileChunk(const string& path,
354 off_t offset,
355 off_t size,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700356 brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200357 return ReadFileChunkAndAppend(path, offset, size, out_p);
358}
359
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700360off_t BlockDevSize(int fd) {
361 uint64_t dev_size;
362 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
363 if (rc == -1) {
364 dev_size = -1;
365 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
366 }
367 return dev_size;
368}
369
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700370off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700371 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700372 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700373 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700374 if (rc < 0) {
375 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700376 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700377 }
378 if (S_ISREG(stbuf.st_mode))
379 return stbuf.st_size;
380 if (S_ISBLK(stbuf.st_mode))
381 return BlockDevSize(fd);
382 LOG(ERROR) << "Couldn't determine the type of " << fd;
383 return -1;
384}
385
386off_t FileSize(const string& path) {
387 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
388 if (fd == -1) {
389 PLOG(ERROR) << "Error opening " << path;
390 return fd;
391 }
392 off_t size = FileSize(fd);
393 if (size == -1)
394 PLOG(ERROR) << "Error getting file size of " << path;
395 close(fd);
396 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700397}
398
Kelvin Zhang02fe6622021-11-01 16:37:58 -0700399bool SendFile(int out_fd, int in_fd, size_t count) {
400 off64_t offset = lseek(in_fd, 0, SEEK_CUR);
401 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
402 constexpr size_t BUFFER_SIZE = 4096;
403 while (count > 0) {
404 const auto bytes_written =
405 sendfile(out_fd, in_fd, &offset, std::min(count, BUFFER_SIZE));
406 TEST_AND_RETURN_FALSE_ERRNO(bytes_written > 0);
407 count -= bytes_written;
408 }
409 return true;
410}
411
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800412void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000413 LOG(INFO) << "Logging array of length: " << length;
414 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700415 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000416 const unsigned int bytes_remaining = length - i;
Amin Hassanib2689592019-01-13 17:04:28 -0800417 const unsigned int bytes_per_this_line =
418 min(bytes_per_line, bytes_remaining);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000419 char header[100];
420 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
421 TEST_AND_RETURN(r == 13);
422 string line = header;
423 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
424 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800425 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000426 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
427 TEST_AND_RETURN(r == 3);
428 line += buf;
429 }
430 LOG(INFO) << line;
431 }
432}
433
Alex Deymof329b932014-10-30 01:37:48 -0700434bool SplitPartitionName(const string& partition_name,
435 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800436 int* out_partition_num) {
Amin Hassanib2689592019-01-13 17:04:28 -0800437 if (!base::StartsWith(
438 partition_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800439 LOG(ERROR) << "Invalid partition device name: " << partition_name;
440 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700441 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800442
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700443 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
444 if (last_nondigit_pos == string::npos ||
445 (last_nondigit_pos + 1) == partition_name.size()) {
446 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800447 return false;
448 }
449
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800450 if (out_disk_name) {
451 // Special case for MMC devices which have the following naming scheme:
452 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700453 size_t disk_name_len = last_nondigit_pos;
Amin Hassanib2689592019-01-13 17:04:28 -0800454 if (partition_name[last_nondigit_pos] != 'p' || last_nondigit_pos == 0 ||
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700455 !isdigit(partition_name[last_nondigit_pos - 1])) {
456 disk_name_len++;
457 }
458 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800459 }
460
461 if (out_partition_num) {
Brian Norris7b428f52019-06-26 10:03:35 -0700462 string partition_str = partition_name.substr(last_nondigit_pos + 1);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800463 *out_partition_num = atoi(partition_str.c_str());
464 }
465 return true;
466}
467
Alex Deymof329b932014-10-30 01:37:48 -0700468string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800469 if (partition_num < 1) {
470 LOG(ERROR) << "Invalid partition number: " << partition_num;
471 return string();
472 }
473
Alex Vakulenko0103c362016-01-20 07:56:15 -0800474 if (!base::StartsWith(disk_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800475 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700476 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800477 }
478
Alex Deymof329b932014-10-30 01:37:48 -0700479 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700480 if (isdigit(partition_name.back())) {
481 // Special case for devices with names ending with a digit.
482 // Add "p" to separate the disk name from partition number,
483 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800484 partition_name += 'p';
485 }
486
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700487 partition_name += std::to_string(partition_num);
488
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800489 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700490}
491
Alex Deymof329b932014-10-30 01:37:48 -0700492string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000493 char buf[100];
494 buf[0] = '\0';
495 return strerror_r(err, buf, sizeof(buf));
496}
497
adlr@google.com3defe6a2009-12-04 20:57:17 +0000498bool FileExists(const char* path) {
499 struct stat stbuf;
500 return 0 == lstat(path, &stbuf);
501}
502
Darin Petkov30291ed2010-11-12 10:23:06 -0800503bool IsSymlink(const char* path) {
504 struct stat stbuf;
505 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
506}
507
Kelvin Zhangdeb34452021-01-21 11:54:36 -0500508bool IsRegFile(const char* path) {
509 struct stat stbuf;
510 return lstat(path, &stbuf) == 0 && S_ISREG(stbuf.st_mode) != 0;
511}
512
Alex Deymof329b932014-10-30 01:37:48 -0700513bool MakeTempFile(const string& base_filename_template,
514 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700515 int* fd) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700516 base::FilePath filename_template;
517 TEST_AND_RETURN_FALSE(
518 GetTempName(base_filename_template, &filename_template));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700519 DCHECK(filename || fd);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700520 vector<char> buf(filename_template.value().size() + 1);
Amin Hassanib2689592019-01-13 17:04:28 -0800521 memcpy(buf.data(),
522 filename_template.value().data(),
Alex Deymo5aa1c542015-09-18 01:02:33 -0700523 filename_template.value().size());
524 buf[filename_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700525
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800526 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700527 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
528 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800529 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700530 }
531 if (fd) {
532 *fd = mkstemp_fd;
533 } else {
534 close(mkstemp_fd);
535 }
536 return true;
537}
538
Alex Deymo5fb356c2016-03-25 18:48:22 -0700539bool SetBlockDeviceReadOnly(const string& device, bool read_only) {
540 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY | O_CLOEXEC));
541 if (fd < 0) {
542 PLOG(ERROR) << "Opening block device " << device;
543 return false;
544 }
545 ScopedFdCloser fd_closer(&fd);
546 // We take no action if not needed.
547 int read_only_flag;
548 int expected_flag = read_only ? 1 : 0;
549 int rc = ioctl(fd, BLKROGET, &read_only_flag);
550 // In case of failure reading the setting we will try to set it anyway.
551 if (rc == 0 && read_only_flag == expected_flag)
552 return true;
553
554 rc = ioctl(fd, BLKROSET, &expected_flag);
555 if (rc != 0) {
Amin Hassanib2689592019-01-13 17:04:28 -0800556 PLOG(ERROR) << "Marking block device " << device
557 << " as read_only=" << expected_flag;
Alex Deymo5fb356c2016-03-25 18:48:22 -0700558 return false;
559 }
560 return true;
561}
562
adlr@google.com3defe6a2009-12-04 20:57:17 +0000563bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700564 const string& mountpoint,
Alex Deymo390efed2016-02-18 11:00:40 -0800565 unsigned long mountflags, // NOLINT(runtime/int)
Alex Deymo14dbd332016-03-01 18:55:54 -0800566 const string& type,
567 const string& fs_mount_options) {
Alex Deymo390efed2016-02-18 11:00:40 -0800568 vector<const char*> fstypes;
569 if (type.empty()) {
Kelvin Zhang4eae81e2021-12-09 17:07:17 -0800570 fstypes = {"ext2", "ext3", "ext4", "squashfs", "erofs"};
Alex Deymo390efed2016-02-18 11:00:40 -0800571 } else {
572 fstypes = {type.c_str()};
573 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800574 for (const char* fstype : fstypes) {
Amin Hassanib2689592019-01-13 17:04:28 -0800575 int rc = mount(device.c_str(),
576 mountpoint.c_str(),
577 fstype,
578 mountflags,
Alex Deymo14dbd332016-03-01 18:55:54 -0800579 fs_mount_options.c_str());
Alex Deymo4c82df32014-11-10 22:25:57 -0800580 if (rc == 0)
581 return true;
582
Amin Hassanib2689592019-01-13 17:04:28 -0800583 PLOG(WARNING) << "Unable to mount destination device " << device << " on "
584 << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000585 }
Alex Deymo390efed2016-02-18 11:00:40 -0800586 if (!type.empty()) {
587 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
588 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800589 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000590}
591
592bool UnmountFilesystem(const string& mountpoint) {
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700593 int num_retries = 1;
594 for (;; ++num_retries) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700595 if (umount(mountpoint.c_str()) == 0)
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700596 return true;
597 if (errno != EBUSY || num_retries >= kUnmountMaxNumOfRetries)
Ben Chan77a1eba2012-10-07 22:54:55 -0700598 break;
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700599 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700600 }
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700601 if (errno == EINVAL) {
602 LOG(INFO) << "Not a mountpoint: " << mountpoint;
603 return false;
604 }
605 PLOG(WARNING) << "Error unmounting " << mountpoint << " after " << num_retries
606 << " attempts. Lazy unmounting instead, error was";
607 if (umount2(mountpoint.c_str(), MNT_DETACH) != 0) {
608 PLOG(ERROR) << "Lazy unmount failed";
609 return false;
610 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000611 return true;
612}
613
Alex Deymof4116502017-03-22 17:00:31 -0700614bool IsMountpoint(const std::string& mountpoint) {
615 struct stat stdir, stparent;
616
617 // Check whether the passed mountpoint is a directory and the /.. is in the
618 // same device or not. If mountpoint/.. is in a different device it means that
619 // there is a filesystem mounted there. If it is not, but they both point to
620 // the same inode it basically is the special case of /.. pointing to /. This
621 // test doesn't play well with bind mount but that's out of the scope of what
622 // we want to detect here.
623 if (lstat(mountpoint.c_str(), &stdir) != 0) {
624 PLOG(ERROR) << "Error stat'ing " << mountpoint;
625 return false;
626 }
627 if (!S_ISDIR(stdir.st_mode))
628 return false;
629
630 base::FilePath parent(mountpoint);
631 parent = parent.Append("..");
632 if (lstat(parent.value().c_str(), &stparent) != 0) {
633 PLOG(ERROR) << "Error stat'ing " << parent.value();
634 return false;
635 }
636 return S_ISDIR(stparent.st_mode) &&
637 (stparent.st_dev != stdir.st_dev || stparent.st_ino == stdir.st_ino);
638}
639
Alex Deymo032e7722014-03-25 17:53:56 -0700640// Tries to parse the header of an ELF file to obtain a human-readable
641// description of it on the |output| string.
Amin Hassanib2689592019-01-13 17:04:28 -0800642static bool GetFileFormatELF(const uint8_t* buffer,
643 size_t size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800644 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700645 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700646 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700647 return false;
648 *output = "ELF";
649
650 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700651 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700652 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700653 switch (buffer[EI_CLASS]) {
654 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700655 *output += " 32-bit";
656 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700657 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700658 *output += " 64-bit";
659 break;
660 default:
661 *output += " ?-bit";
662 }
663
664 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700665 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700666 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800667 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700668 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700669 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700670 *output += " little-endian";
671 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700672 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700673 *output += " big-endian";
674 break;
675 default:
676 *output += " ?-endian";
677 // Don't parse anything after the 0x10 offset if endianness is unknown.
678 return true;
679 }
680
Alex Deymoc1711e22014-08-08 13:16:23 -0700681 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
682 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
683 // and size is the same for both 32 and 64 bits.
684 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700685 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700686 uint16_t e_machine;
Sen Jiang771f6482018-04-04 17:59:10 -0700687 // Fix endianness regardless of the host endianness.
Alex Deymoc1711e22014-08-08 13:16:23 -0700688 if (ei_data == ELFDATA2LSB)
689 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700690 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700691 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700692
693 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700694 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700695 *output += " x86";
696 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700697 case EM_MIPS:
698 *output += " mips";
699 break;
700 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700701 *output += " arm";
702 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700703 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700704 *output += " x86-64";
705 break;
706 default:
707 *output += " unknown-arch";
708 }
709 return true;
710}
711
712string GetFileFormat(const string& path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700713 brillo::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700714 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
715 return "File not found.";
716
717 string result;
718 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
719 return result;
720
721 return "data";
722}
723
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700724int FuzzInt(int value, unsigned int range) {
725 int min = value - range / 2;
726 int max = value + range - range / 2;
727 return base::RandInt(min, max);
728}
729
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700730string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800731 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700732}
733
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800734string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400735 string str;
736
737 // Handle negative durations by prefixing with a minus.
738 if (delta.ToInternalValue() < 0) {
739 delta *= -1;
740 str = "-";
741 }
742
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700743 // Canonicalize into days, hours, minutes, seconds and microseconds.
744 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800745 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700746 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800747 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700748 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800749 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700750 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800751 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700752 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800753
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700754 if (days)
755 base::StringAppendF(&str, "%ud", days);
756 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800757 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700758 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800759 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700760 base::StringAppendF(&str, "%u", secs);
761 if (usecs) {
762 int width = 6;
763 while ((usecs / 10) * 10 == usecs) {
764 usecs /= 10;
765 width--;
766 }
767 base::StringAppendF(&str, ".%0*u", width, usecs);
768 }
769 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800770 return str;
771}
772
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700773string ToString(const Time utc_time) {
774 Time::Exploded exp_time;
775 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700776 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Amin Hassanib2689592019-01-13 17:04:28 -0800777 exp_time.month,
778 exp_time.day_of_month,
779 exp_time.year,
780 exp_time.hour,
781 exp_time.minute,
782 exp_time.second);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700783}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000784
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700785string ToString(bool b) {
786 return (b ? "true" : "false");
787}
788
Alex Deymo1c656c42013-06-28 11:02:14 -0700789string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700790 switch (source) {
Amin Hassanib2689592019-01-13 17:04:28 -0800791 case kDownloadSourceHttpsServer:
792 return "HttpsServer";
793 case kDownloadSourceHttpServer:
794 return "HttpServer";
795 case kDownloadSourceHttpPeer:
796 return "HttpPeer";
797 case kNumDownloadSources:
798 return "Unknown";
799 // Don't add a default case to let the compiler warn about newly added
800 // download sources which should be added here.
Jay Srinivasan19409b72013-04-12 19:23:36 -0700801 }
802
803 return "Unknown";
804}
805
Alex Deymo1c656c42013-06-28 11:02:14 -0700806string ToString(PayloadType payload_type) {
807 switch (payload_type) {
Amin Hassanib2689592019-01-13 17:04:28 -0800808 case kPayloadTypeDelta:
809 return "Delta";
810 case kPayloadTypeFull:
811 return "Full";
812 case kPayloadTypeForcedFull:
813 return "ForcedFull";
814 case kNumPayloadTypes:
815 return "Unknown";
816 // Don't add a default case to let the compiler warn about newly added
817 // payload types which should be added here.
Alex Deymo1c656c42013-06-28 11:02:14 -0700818 }
819
820 return "Unknown";
821}
822
David Zeuthena99981f2013-04-29 13:42:47 -0700823ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700824 // Ignore the higher order bits in the code by applying the mask as
825 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700826 // with values less than ErrorCode::kUmaReportedMax.
827 ErrorCode base_code = static_cast<ErrorCode>(
828 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700829
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800830 // Make additional adjustments required for UMA and error classification.
831 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
832 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700833 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700834 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800835 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800836 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700837 << " to ErrorCode::kOmahaErrorInHTTPResponse";
838 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700839 }
840
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800841 return base_code;
842}
843
Kelvin Zhangd7191032020-08-11 10:48:16 -0400844string StringVectorToString(const vector<string>& vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700845 string str = "[";
Amin Hassanib2689592019-01-13 17:04:28 -0800846 for (vector<string>::const_iterator i = vec_str.begin(); i != vec_str.end();
847 ++i) {
Alex Deymof329b932014-10-30 01:37:48 -0700848 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -0700849 str += ", ";
850 str += '"';
851 str += *i;
852 str += '"';
853 }
854 str += "]";
855 return str;
856}
857
Sen Jiang2703ef42017-03-16 13:36:21 -0700858// The P2P file id should be the same for devices running new version and old
859// version so that they can share it with each other. The hash in the response
860// was base64 encoded, but now that we switched to use "hash_sha256" field which
861// is hex encoded, we have to convert them back to base64 for P2P. However, the
862// base64 encoded hash was base64 encoded here again historically for some
863// reason, so we keep the same behavior here.
864string CalculateP2PFileId(const brillo::Blob& payload_hash,
865 size_t payload_size) {
866 string encoded_hash = brillo::data_encoding::Base64Encode(
867 brillo::data_encoding::Base64Encode(payload_hash));
Alex Deymoc00c98a2015-03-17 17:38:00 -0700868 return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800869 payload_size,
870 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -0700871}
872
Kelvin Zhangd7191032020-08-11 10:48:16 -0400873bool ConvertToOmahaInstallDate(Time time, int* out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -0800874 time_t unix_time = time.ToTimeT();
875 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
876 const time_t kOmahaEpoch = 1167638400;
Amin Hassanib2689592019-01-13 17:04:28 -0800877 const int64_t kNumSecondsPerWeek = 7 * 24 * 3600;
David Zeuthen639aa362014-02-03 16:23:44 -0800878 const int64_t kNumDaysPerWeek = 7;
879
880 time_t omaha_time = unix_time - kOmahaEpoch;
881
882 if (omaha_time < 0)
883 return false;
884
885 // Note, as per the comment in utils.h we are deliberately not
886 // handling DST correctly.
887
888 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
889 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
890
891 return true;
892}
893
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700894bool GetMinorVersion(const brillo::KeyValueStore& store,
Alex Deymob42b98d2015-07-06 17:42:38 -0700895 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700896 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -0700897 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -0800898 if (!base::StringToUint(result, minor_version)) {
899 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
900 return false;
901 }
Allie Wood78750a42015-02-11 15:42:11 -0800902 return true;
903 }
904 return false;
905}
906
Kelvin Zhang02fe6622021-11-01 16:37:58 -0700907bool ReadExtents(const std::string& path,
908 const google::protobuf::RepeatedPtrField<Extent>& extents,
909 brillo::Blob* out_data,
910 size_t block_size) {
911 return ReadExtents(path,
912 {extents.begin(), extents.end()},
913 out_data,
914 utils::BlocksInExtents(extents) * block_size,
915 block_size);
916}
917
918bool WriteExtents(const std::string& path,
919 const google::protobuf::RepeatedPtrField<Extent>& extents,
920 const brillo::Blob& data,
921 size_t block_size) {
922 EintrSafeFileDescriptor fd;
923 TEST_AND_RETURN_FALSE(fd.Open(path.c_str(), O_RDWR));
924 size_t bytes_written = 0;
925 for (const auto& ext : extents) {
926 TEST_AND_RETURN_FALSE_ERRNO(
927 fd.Seek(ext.start_block() * block_size, SEEK_SET));
928 TEST_AND_RETURN_FALSE_ERRNO(
929 fd.Write(data.data() + bytes_written, ext.num_blocks() * block_size));
930 bytes_written += ext.num_blocks() * block_size;
931 }
932 return true;
933}
Kelvin Zhang4eae81e2021-12-09 17:07:17 -0800934bool ReadExtents(const std::string& path,
935 const vector<Extent>& extents,
936 brillo::Blob* out_data,
937 ssize_t out_data_size,
938 size_t block_size) {
939 FileDescriptorPtr fd = std::make_shared<EintrSafeFileDescriptor>();
940 fd->Open(path.c_str(), O_RDONLY);
941 return ReadExtents(fd, extents, out_data, out_data_size, block_size);
942}
Kelvin Zhang02fe6622021-11-01 16:37:58 -0700943
Kelvin Zhang4eae81e2021-12-09 17:07:17 -0800944bool ReadExtents(FileDescriptorPtr fd,
945 const google::protobuf::RepeatedPtrField<Extent>& extents,
946 brillo::Blob* out_data,
947 size_t block_size) {
948 return ReadExtents(fd,
949 {extents.begin(), extents.end()},
950 out_data,
951 utils::BlocksInExtents(extents) * block_size,
952 block_size);
953}
954
955bool ReadExtents(FileDescriptorPtr fd,
Amin Hassanib2689592019-01-13 17:04:28 -0800956 const vector<Extent>& extents,
957 brillo::Blob* out_data,
958 ssize_t out_data_size,
Allie Wood56873452015-03-27 17:48:40 -0700959 size_t block_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700960 brillo::Blob data(out_data_size);
Allie Wood56873452015-03-27 17:48:40 -0700961 ssize_t bytes_read = 0;
Allie Wood56873452015-03-27 17:48:40 -0700962
Gilad Arnold41e34742015-05-11 11:31:50 -0700963 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -0700964 ssize_t bytes_read_this_iteration = 0;
965 ssize_t bytes = extent.num_blocks() * block_size;
Kelvin Zhang02fe6622021-11-01 16:37:58 -0700966 TEST_LE(bytes_read + bytes, out_data_size);
Allie Wood56873452015-03-27 17:48:40 -0700967 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
968 &data[bytes_read],
969 bytes,
970 extent.start_block() * block_size,
971 &bytes_read_this_iteration));
972 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
973 bytes_read += bytes_read_this_iteration;
974 }
975 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
976 *out_data = data;
977 return true;
978}
979
Matt Ziegelbaum91ba9be2020-06-10 16:56:40 -0400980bool GetVpdValue(string key, string* result) {
981 int exit_code = 0;
982 string value, error;
983 vector<string> cmd = {"vpd_get_value", key};
984 if (!chromeos_update_engine::Subprocess::SynchronousExec(
985 cmd, &exit_code, &value, &error) ||
986 exit_code) {
987 LOG(ERROR) << "Failed to get vpd key for " << value
988 << " with exit code: " << exit_code << " and error: " << error;
989 return false;
990 } else if (!error.empty()) {
991 LOG(INFO) << "vpd_get_value succeeded but with following errors: " << error;
992 }
993
994 base::TrimWhitespaceASCII(value, base::TRIM_ALL, &value);
995 *result = value;
996 return true;
997}
998
Alex Deymodd132f32015-09-14 19:12:07 -0700999bool GetBootId(string* boot_id) {
1000 TEST_AND_RETURN_FALSE(
1001 base::ReadFileToString(base::FilePath(kBootIdPath), boot_id));
1002 base::TrimWhitespaceASCII(*boot_id, base::TRIM_TRAILING, boot_id);
1003 return true;
1004}
1005
Marton Hunyadya0302682018-05-16 18:52:13 +02001006int VersionPrefix(const std::string& version) {
1007 if (version.empty()) {
1008 return 0;
1009 }
1010 vector<string> tokens = base::SplitString(
1011 version, ".", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
1012 int value;
1013 if (tokens.empty() || !base::StringToInt(tokens[0], &value))
1014 return -1; // Target version is invalid.
1015 return value;
1016}
1017
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -07001018void ParseRollbackKeyVersion(const string& raw_version,
1019 uint16_t* high_version,
1020 uint16_t* low_version) {
1021 DCHECK(high_version);
1022 DCHECK(low_version);
1023 *high_version = numeric_limits<uint16_t>::max();
1024 *low_version = numeric_limits<uint16_t>::max();
1025
1026 vector<string> parts = base::SplitString(
1027 raw_version, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
1028 if (parts.size() != 2) {
1029 // The version string must have exactly one period.
1030 return;
1031 }
1032
1033 int high;
1034 int low;
1035 if (!(base::StringToInt(parts[0], &high) &&
1036 base::StringToInt(parts[1], &low))) {
1037 // Both parts of the version could not be parsed correctly.
1038 return;
1039 }
1040
1041 if (high >= 0 && high < numeric_limits<uint16_t>::max() && low >= 0 &&
1042 low < numeric_limits<uint16_t>::max()) {
1043 *high_version = static_cast<uint16_t>(high);
1044 *low_version = static_cast<uint16_t>(low);
1045 }
1046}
1047
Kyeongkab.Nam500ca132019-06-26 13:48:07 +09001048string GetFilePath(int fd) {
1049 base::FilePath proc("/proc/self/fd/" + std::to_string(fd));
1050 base::FilePath file_name;
1051
1052 if (!base::ReadSymbolicLink(proc, &file_name)) {
1053 return "not found";
1054 }
1055 return file_name.value();
1056}
1057
Yifan Hongc80de2d2020-02-25 17:13:53 -08001058string GetTimeAsString(time_t utime) {
1059 struct tm tm;
1060 CHECK_EQ(localtime_r(&utime, &tm), &tm);
1061 char str[16];
1062 CHECK_EQ(strftime(str, sizeof(str), "%Y%m%d-%H%M%S", &tm), 15u);
1063 return str;
1064}
1065
Jae Hoon Kim694eeb02020-06-01 14:24:08 -07001066string GetExclusionName(const string& str_to_convert) {
1067 return base::NumberToString(base::StringPieceHash()(str_to_convert));
1068}
1069
Kelvin Zhangd7191032020-08-11 10:48:16 -04001070static bool ParseTimestamp(const std::string& str, int64_t* out) {
1071 if (!base::StringToInt64(str, out)) {
1072 LOG(WARNING) << "Invalid timestamp: " << str;
1073 return false;
1074 }
1075 return true;
1076}
1077
Yifan Hong87029332020-09-01 17:20:08 -07001078ErrorCode IsTimestampNewer(const std::string& old_version,
1079 const std::string& new_version) {
Kelvin Zhangd7191032020-08-11 10:48:16 -04001080 if (old_version.empty() || new_version.empty()) {
1081 LOG(WARNING)
1082 << "One of old/new timestamp is empty, permit update anyway. Old: "
1083 << old_version << " New: " << new_version;
Yifan Hong87029332020-09-01 17:20:08 -07001084 return ErrorCode::kSuccess;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001085 }
1086 int64_t old_ver = 0;
Yifan Hong87029332020-09-01 17:20:08 -07001087 if (!ParseTimestamp(old_version, &old_ver)) {
1088 return ErrorCode::kError;
1089 }
Kelvin Zhangd7191032020-08-11 10:48:16 -04001090 int64_t new_ver = 0;
Yifan Hong87029332020-09-01 17:20:08 -07001091 if (!ParseTimestamp(new_version, &new_ver)) {
1092 return ErrorCode::kDownloadManifestParseError;
1093 }
1094 if (old_ver > new_ver) {
1095 return ErrorCode::kPayloadTimestampError;
1096 }
1097 return ErrorCode::kSuccess;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001098}
1099
Kelvin Zhang4bb49202021-07-08 21:39:05 -04001100std::unique_ptr<android::base::MappedFile> GetReadonlyZeroBlock(size_t size) {
1101 android::base::unique_fd fd{HANDLE_EINTR(open("/dev/zero", O_RDONLY))};
1102 return android::base::MappedFile::FromFd(fd, 0, size, PROT_READ);
1103}
1104
Kelvin Zhang3fe49642021-10-04 15:35:02 -07001105std::string_view GetReadonlyZeroString(size_t size) {
1106 // Reserve 512MB of Virtual Address Space. No actual memory will be used.
1107 static auto zero_block = GetReadonlyZeroBlock(1024 * 1024 * 512);
1108 if (size > zero_block->size()) {
1109 auto larger_block = GetReadonlyZeroBlock(size);
1110 zero_block = std::move(larger_block);
1111 }
1112 return {zero_block->data(), size};
1113}
1114
adlr@google.com3defe6a2009-12-04 20:57:17 +00001115} // namespace utils
1116
Kelvin Zhang20982a52021-08-13 12:31:16 -07001117std::string HexEncode(const brillo::Blob& blob) noexcept {
1118 return base::HexEncode(blob.data(), blob.size());
1119}
1120
Kelvin Zhang3fe49642021-10-04 15:35:02 -07001121std::string HexEncode(const std::string_view blob) noexcept {
1122 return base::HexEncode(blob.data(), blob.size());
1123}
1124
adlr@google.com3defe6a2009-12-04 20:57:17 +00001125} // namespace chromeos_update_engine