blob: 0b76eea94c2221d67b37dad19cb3394081f681b7 [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
Colin Cross84fe9da2021-12-21 13:19:14 -080041#include <android-base/strings.h>
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070042#include <base/callback.h>
Ben Chan736fcb52014-05-21 18:28:22 -070043#include <base/files/file_path.h>
Alex Deymo192393b2014-11-10 15:58:38 -080044#include <base/files/file_util.h>
Ben Chan736fcb52014-05-21 18:28:22 -070045#include <base/files/scoped_file.h>
Alex Deymoc00c98a2015-03-17 17:38:00 -070046#include <base/format_macros.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070047#include <base/location.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040048#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080049#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050050#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070051#include <base/strings/string_number_conversions.h>
52#include <base/strings/string_split.h>
53#include <base/strings/string_util.h>
54#include <base/strings/stringprintf.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070055#include <brillo/data_encoding.h>
Will Drewry8f71da82010-08-30 14:07:11 -050056
Alex Deymo39910dc2015-11-09 17:04:30 -080057#include "update_engine/common/constants.h"
Sen Jiang9c123462015-11-19 13:16:23 -080058#include "update_engine/common/platform_constants.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080059#include "update_engine/common/prefs_interface.h"
60#include "update_engine/common/subprocess.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080061#include "update_engine/payload_consumer/file_descriptor.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000062
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070063using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080064using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000065using std::min;
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -070066using std::numeric_limits;
adlr@google.com3defe6a2009-12-04 20:57:17 +000067using std::string;
68using std::vector;
69
70namespace chromeos_update_engine {
71
Ben Chan77a1eba2012-10-07 22:54:55 -070072namespace {
73
74// The following constants control how UnmountFilesystem should retry if
75// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
76// one second.
77const int kUnmountMaxNumOfRetries = 5;
78const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070079
80// Number of bytes to read from a file to attempt to detect its contents. Used
81// in GetFileFormat.
82const int kGetFileFormatMaxHeaderSize = 32;
83
Alex Deymodd132f32015-09-14 19:12:07 -070084// The path to the kernel's boot_id.
85const char kBootIdPath[] = "/proc/sys/kernel/random/boot_id";
86
Alex Deymo5aa1c542015-09-18 01:02:33 -070087// If |path| is absolute, or explicit relative to the current working directory,
88// leaves it as is. Otherwise, uses the system's temp directory, as defined by
89// base::GetTempDir() and prepends it to |path|. On success stores the full
90// temporary path in |template_path| and returns true.
91bool GetTempName(const string& path, base::FilePath* template_path) {
Alex Vakulenko0103c362016-01-20 07:56:15 -080092 if (path[0] == '/' ||
93 base::StartsWith(path, "./", base::CompareCase::SENSITIVE) ||
94 base::StartsWith(path, "../", base::CompareCase::SENSITIVE)) {
Alex Deymo5aa1c542015-09-18 01:02:33 -070095 *template_path = base::FilePath(path);
96 return true;
97 }
98
99 base::FilePath temp_dir;
Sen Jiang9c123462015-11-19 13:16:23 -0800100#ifdef __ANDROID__
Sen Jiangc2b37662019-01-09 16:51:18 -0800101 temp_dir = base::FilePath(constants::kNonVolatileDirectory).Append("tmp");
Alex Deymo32951022016-08-10 17:02:49 -0700102#else
Sen Jiangc2b37662019-01-09 16:51:18 -0800103 TEST_AND_RETURN_FALSE(base::GetTempDir(&temp_dir));
Alex Deymo32951022016-08-10 17:02:49 -0700104#endif // __ANDROID__
Sen Jiang9c123462015-11-19 13:16:23 -0800105 if (!base::PathExists(temp_dir))
106 TEST_AND_RETURN_FALSE(base::CreateDirectory(temp_dir));
Alex Deymo5aa1c542015-09-18 01:02:33 -0700107 *template_path = temp_dir.Append(path);
108 return true;
109}
110
Ben Chan77a1eba2012-10-07 22:54:55 -0700111} // namespace
112
adlr@google.com3defe6a2009-12-04 20:57:17 +0000113namespace utils {
114
Alex Deymo335516c2016-11-28 13:37:06 -0800115bool WriteFile(const char* path, const void* data, size_t data_len) {
116 int fd = HANDLE_EINTR(open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600));
117 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
118 ScopedFdCloser fd_closer(&fd);
119 return WriteAll(fd, data, data_len);
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800120}
121
Alex Deymo0d298542016-03-30 18:31:49 -0700122bool ReadAll(
123 int fd, void* buf, size_t count, size_t* out_bytes_read, bool* eof) {
124 char* c_buf = static_cast<char*>(buf);
125 size_t bytes_read = 0;
126 *eof = false;
127 while (bytes_read < count) {
128 ssize_t rc = HANDLE_EINTR(read(fd, c_buf + bytes_read, count - bytes_read));
129 if (rc < 0) {
130 // EAGAIN and EWOULDBLOCK are normal return values when there's no more
131 // input and we are in non-blocking mode.
132 if (errno != EWOULDBLOCK && errno != EAGAIN) {
133 PLOG(ERROR) << "Error reading fd " << fd;
134 *out_bytes_read = bytes_read;
135 return false;
136 }
137 break;
138 } else if (rc == 0) {
139 // A value of 0 means that we reached EOF and there is nothing else to
140 // read from this fd.
141 *eof = true;
142 break;
143 } else {
144 bytes_read += rc;
145 }
146 }
147 *out_bytes_read = bytes_read;
148 return true;
149}
150
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700151bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700152 const char* c_buf = static_cast<const char*>(buf);
153 ssize_t bytes_written = 0;
154 while (bytes_written < static_cast<ssize_t>(count)) {
155 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
156 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
157 bytes_written += rc;
158 }
159 return true;
160}
161
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700162bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
163 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700164 size_t bytes_written = 0;
165 int num_attempts = 0;
166 while (bytes_written < count) {
167 num_attempts++;
Amin Hassanib2689592019-01-13 17:04:28 -0800168 ssize_t rc = pwrite(fd,
169 c_buf + bytes_written,
170 count - bytes_written,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700171 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700172 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
173 if (rc < 0) {
174 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
Amin Hassanib2689592019-01-13 17:04:28 -0800175 << " bytes_written=" << bytes_written << " count=" << count
176 << " offset=" << offset;
Gilad Arnold780db212012-07-11 13:12:49 -0700177 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700178 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
179 bytes_written += rc;
180 }
181 return true;
182}
183
Kelvin Zhang1a0ed712022-01-26 16:09:05 -0800184bool WriteAll(FileDescriptor* fd, const void* buf, size_t count) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800185 const char* c_buf = static_cast<const char*>(buf);
186 ssize_t bytes_written = 0;
187 while (bytes_written < static_cast<ssize_t>(count)) {
188 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
189 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
190 bytes_written += rc;
191 }
192 return true;
193}
194
Kelvin Zhang4b280242020-11-06 16:07:45 -0500195bool WriteAll(const FileDescriptorPtr& fd,
196 const void* buf,
197 size_t count,
198 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700199 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
200 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800201 return WriteAll(fd, buf, count);
202}
203
Amin Hassanib2689592019-01-13 17:04:28 -0800204bool PReadAll(
205 int fd, void* buf, size_t count, off_t offset, ssize_t* out_bytes_read) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700206 char* c_buf = static_cast<char*>(buf);
207 ssize_t bytes_read = 0;
208 while (bytes_read < static_cast<ssize_t>(count)) {
Amin Hassanib2689592019-01-13 17:04:28 -0800209 ssize_t rc =
210 pread(fd, c_buf + bytes_read, count - bytes_read, offset + bytes_read);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700211 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
212 if (rc == 0) {
213 break;
214 }
215 bytes_read += rc;
216 }
217 *out_bytes_read = bytes_read;
218 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700219}
220
Kelvin Zhang1a0ed712022-01-26 16:09:05 -0800221bool ReadAll(FileDescriptor* fd,
Kelvin Zhang4b280242020-11-06 16:07:45 -0500222 void* buf,
223 size_t count,
224 off_t offset,
225 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700226 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
227 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800228 char* c_buf = static_cast<char*>(buf);
229 ssize_t bytes_read = 0;
230 while (bytes_read < static_cast<ssize_t>(count)) {
231 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
232 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
233 if (rc == 0) {
234 break;
235 }
236 bytes_read += rc;
237 }
238 *out_bytes_read = bytes_read;
239 return true;
240}
241
Kelvin Zhang1a0ed712022-01-26 16:09:05 -0800242bool PReadAll(FileDescriptor* fd,
Kelvin Zhangc3c0a3a2020-11-09 16:08:13 -0500243 void* buf,
244 size_t count,
245 off_t offset,
246 ssize_t* out_bytes_read) {
247 auto old_off = fd->Seek(0, SEEK_CUR);
248 TEST_AND_RETURN_FALSE_ERRNO(old_off >= 0);
249
250 auto success = ReadAll(fd, buf, count, offset, out_bytes_read);
251 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(old_off, SEEK_SET) == old_off);
252 return success;
253}
254
255bool PWriteAll(const FileDescriptorPtr& fd,
256 const void* buf,
257 size_t count,
258 off_t offset) {
259 auto old_off = fd->Seek(0, SEEK_CUR);
260 TEST_AND_RETURN_FALSE_ERRNO(old_off >= 0);
261
262 auto success = WriteAll(fd, buf, count, offset);
263 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(old_off, SEEK_SET) == old_off);
264 return success;
265}
266
Gilad Arnold19a45f02012-07-19 12:36:10 -0700267// Append |nbytes| of content from |buf| to the vector pointed to by either
268// |vec_p| or |str_p|.
Amin Hassanib2689592019-01-13 17:04:28 -0800269static void AppendBytes(const uint8_t* buf,
270 size_t nbytes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700271 brillo::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700272 CHECK(buf);
273 CHECK(vec_p);
274 vec_p->insert(vec_p->end(), buf, buf + nbytes);
275}
Amin Hassanib2689592019-01-13 17:04:28 -0800276static void AppendBytes(const uint8_t* buf, size_t nbytes, string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700277 CHECK(buf);
278 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800279 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700280}
281
282// Reads from an open file |fp|, appending the read content to the container
283// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200284// file's content, false otherwise. If |size| is not -1, reads up to |size|
285// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700286template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200287static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700288 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200289 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800290 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200291 while (size == -1 || size > 0) {
292 off_t bytes_to_read = sizeof(buf);
293 if (size > 0 && bytes_to_read > size) {
294 bytes_to_read = size;
295 }
296 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
297 if (!nbytes) {
298 break;
299 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700300 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200301 if (size != -1) {
302 CHECK(size >= static_cast<off_t>(nbytes));
303 size -= nbytes;
304 }
305 }
306 if (ferror(fp)) {
307 return false;
308 }
309 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700310}
311
Darin Petkov8e447e02013-04-16 16:23:50 +0200312// Opens a file |path| for reading and appends its the contents to a container
313// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
314// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700315template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700316static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200317 off_t offset,
318 off_t size,
319 T* out_p) {
320 CHECK_GE(offset, 0);
321 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700322 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200323 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000324 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200325 if (offset) {
326 // Return success without appending any data if a chunk beyond the end of
327 // the file is requested.
328 if (offset >= FileSize(path)) {
329 return true;
330 }
331 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
332 }
333 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000334}
335
Alex Deymo10875d92014-11-10 21:52:57 -0800336// TODO(deymo): This is only used in unittest, but requires the private
337// Read<string>() defined here. Expose Read<string>() or move to base/ version.
338bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700339 FILE* fp = popen(cmd.c_str(), "r");
340 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000341 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200342 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700343 return (success && pclose(fp) >= 0);
344}
345
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700346bool ReadFile(const string& path, brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200347 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700348}
349
Darin Petkov8e447e02013-04-16 16:23:50 +0200350bool ReadFile(const string& path, string* out_p) {
351 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700352}
353
Amin Hassanib2689592019-01-13 17:04:28 -0800354bool ReadFileChunk(const string& path,
355 off_t offset,
356 off_t size,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700357 brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200358 return ReadFileChunkAndAppend(path, offset, size, out_p);
359}
360
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700361off_t BlockDevSize(int fd) {
362 uint64_t dev_size;
363 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
364 if (rc == -1) {
365 dev_size = -1;
366 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
367 }
368 return dev_size;
369}
370
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700371off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700372 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700373 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700374 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700375 if (rc < 0) {
376 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700377 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700378 }
379 if (S_ISREG(stbuf.st_mode))
380 return stbuf.st_size;
381 if (S_ISBLK(stbuf.st_mode))
382 return BlockDevSize(fd);
383 LOG(ERROR) << "Couldn't determine the type of " << fd;
384 return -1;
385}
386
387off_t FileSize(const string& path) {
388 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
389 if (fd == -1) {
390 PLOG(ERROR) << "Error opening " << path;
391 return fd;
392 }
393 off_t size = FileSize(fd);
394 if (size == -1)
395 PLOG(ERROR) << "Error getting file size of " << path;
396 close(fd);
397 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700398}
399
Kelvin Zhang02fe6622021-11-01 16:37:58 -0700400bool SendFile(int out_fd, int in_fd, size_t count) {
401 off64_t offset = lseek(in_fd, 0, SEEK_CUR);
402 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
403 constexpr size_t BUFFER_SIZE = 4096;
404 while (count > 0) {
405 const auto bytes_written =
406 sendfile(out_fd, in_fd, &offset, std::min(count, BUFFER_SIZE));
407 TEST_AND_RETURN_FALSE_ERRNO(bytes_written > 0);
408 count -= bytes_written;
409 }
410 return true;
411}
412
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800413void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000414 LOG(INFO) << "Logging array of length: " << length;
415 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700416 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000417 const unsigned int bytes_remaining = length - i;
Amin Hassanib2689592019-01-13 17:04:28 -0800418 const unsigned int bytes_per_this_line =
419 min(bytes_per_line, bytes_remaining);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000420 char header[100];
421 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
422 TEST_AND_RETURN(r == 13);
423 string line = header;
424 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
425 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800426 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000427 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
428 TEST_AND_RETURN(r == 3);
429 line += buf;
430 }
431 LOG(INFO) << line;
432 }
433}
434
Alex Deymof329b932014-10-30 01:37:48 -0700435bool SplitPartitionName(const string& partition_name,
436 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800437 int* out_partition_num) {
Amin Hassanib2689592019-01-13 17:04:28 -0800438 if (!base::StartsWith(
439 partition_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800440 LOG(ERROR) << "Invalid partition device name: " << partition_name;
441 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700442 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800443
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700444 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
445 if (last_nondigit_pos == string::npos ||
446 (last_nondigit_pos + 1) == partition_name.size()) {
447 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800448 return false;
449 }
450
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800451 if (out_disk_name) {
452 // Special case for MMC devices which have the following naming scheme:
453 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700454 size_t disk_name_len = last_nondigit_pos;
Amin Hassanib2689592019-01-13 17:04:28 -0800455 if (partition_name[last_nondigit_pos] != 'p' || last_nondigit_pos == 0 ||
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700456 !isdigit(partition_name[last_nondigit_pos - 1])) {
457 disk_name_len++;
458 }
459 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800460 }
461
462 if (out_partition_num) {
Brian Norris7b428f52019-06-26 10:03:35 -0700463 string partition_str = partition_name.substr(last_nondigit_pos + 1);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800464 *out_partition_num = atoi(partition_str.c_str());
465 }
466 return true;
467}
468
Alex Deymof329b932014-10-30 01:37:48 -0700469string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800470 if (partition_num < 1) {
471 LOG(ERROR) << "Invalid partition number: " << partition_num;
472 return string();
473 }
474
Alex Vakulenko0103c362016-01-20 07:56:15 -0800475 if (!base::StartsWith(disk_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800476 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700477 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800478 }
479
Alex Deymof329b932014-10-30 01:37:48 -0700480 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700481 if (isdigit(partition_name.back())) {
482 // Special case for devices with names ending with a digit.
483 // Add "p" to separate the disk name from partition number,
484 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800485 partition_name += 'p';
486 }
487
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700488 partition_name += std::to_string(partition_num);
489
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800490 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700491}
492
adlr@google.com3defe6a2009-12-04 20:57:17 +0000493bool FileExists(const char* path) {
494 struct stat stbuf;
495 return 0 == lstat(path, &stbuf);
496}
497
Darin Petkov30291ed2010-11-12 10:23:06 -0800498bool IsSymlink(const char* path) {
499 struct stat stbuf;
500 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
501}
502
Kelvin Zhangdeb34452021-01-21 11:54:36 -0500503bool IsRegFile(const char* path) {
504 struct stat stbuf;
505 return lstat(path, &stbuf) == 0 && S_ISREG(stbuf.st_mode) != 0;
506}
507
Alex Deymof329b932014-10-30 01:37:48 -0700508bool MakeTempFile(const string& base_filename_template,
509 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700510 int* fd) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700511 base::FilePath filename_template;
512 TEST_AND_RETURN_FALSE(
513 GetTempName(base_filename_template, &filename_template));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700514 DCHECK(filename || fd);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700515 vector<char> buf(filename_template.value().size() + 1);
Amin Hassanib2689592019-01-13 17:04:28 -0800516 memcpy(buf.data(),
517 filename_template.value().data(),
Alex Deymo5aa1c542015-09-18 01:02:33 -0700518 filename_template.value().size());
519 buf[filename_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700520
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800521 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700522 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
523 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800524 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700525 }
526 if (fd) {
527 *fd = mkstemp_fd;
528 } else {
529 close(mkstemp_fd);
530 }
531 return true;
532}
533
Alex Deymo5fb356c2016-03-25 18:48:22 -0700534bool SetBlockDeviceReadOnly(const string& device, bool read_only) {
535 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY | O_CLOEXEC));
536 if (fd < 0) {
537 PLOG(ERROR) << "Opening block device " << device;
538 return false;
539 }
540 ScopedFdCloser fd_closer(&fd);
541 // We take no action if not needed.
542 int read_only_flag;
543 int expected_flag = read_only ? 1 : 0;
544 int rc = ioctl(fd, BLKROGET, &read_only_flag);
545 // In case of failure reading the setting we will try to set it anyway.
546 if (rc == 0 && read_only_flag == expected_flag)
547 return true;
548
549 rc = ioctl(fd, BLKROSET, &expected_flag);
550 if (rc != 0) {
Amin Hassanib2689592019-01-13 17:04:28 -0800551 PLOG(ERROR) << "Marking block device " << device
552 << " as read_only=" << expected_flag;
Alex Deymo5fb356c2016-03-25 18:48:22 -0700553 return false;
554 }
555 return true;
556}
557
adlr@google.com3defe6a2009-12-04 20:57:17 +0000558bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700559 const string& mountpoint,
Alex Deymo390efed2016-02-18 11:00:40 -0800560 unsigned long mountflags, // NOLINT(runtime/int)
Alex Deymo14dbd332016-03-01 18:55:54 -0800561 const string& type,
562 const string& fs_mount_options) {
Alex Deymo390efed2016-02-18 11:00:40 -0800563 vector<const char*> fstypes;
564 if (type.empty()) {
Kelvin Zhang4eae81e2021-12-09 17:07:17 -0800565 fstypes = {"ext2", "ext3", "ext4", "squashfs", "erofs"};
Alex Deymo390efed2016-02-18 11:00:40 -0800566 } else {
567 fstypes = {type.c_str()};
568 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800569 for (const char* fstype : fstypes) {
Amin Hassanib2689592019-01-13 17:04:28 -0800570 int rc = mount(device.c_str(),
571 mountpoint.c_str(),
572 fstype,
573 mountflags,
Alex Deymo14dbd332016-03-01 18:55:54 -0800574 fs_mount_options.c_str());
Alex Deymo4c82df32014-11-10 22:25:57 -0800575 if (rc == 0)
576 return true;
577
Amin Hassanib2689592019-01-13 17:04:28 -0800578 PLOG(WARNING) << "Unable to mount destination device " << device << " on "
579 << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000580 }
Alex Deymo390efed2016-02-18 11:00:40 -0800581 if (!type.empty()) {
582 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
583 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800584 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000585}
586
587bool UnmountFilesystem(const string& mountpoint) {
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700588 int num_retries = 1;
589 for (;; ++num_retries) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700590 if (umount(mountpoint.c_str()) == 0)
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700591 return true;
592 if (errno != EBUSY || num_retries >= kUnmountMaxNumOfRetries)
Ben Chan77a1eba2012-10-07 22:54:55 -0700593 break;
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700594 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700595 }
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700596 if (errno == EINVAL) {
597 LOG(INFO) << "Not a mountpoint: " << mountpoint;
598 return false;
599 }
600 PLOG(WARNING) << "Error unmounting " << mountpoint << " after " << num_retries
601 << " attempts. Lazy unmounting instead, error was";
602 if (umount2(mountpoint.c_str(), MNT_DETACH) != 0) {
603 PLOG(ERROR) << "Lazy unmount failed";
604 return false;
605 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000606 return true;
607}
608
Alex Deymof4116502017-03-22 17:00:31 -0700609bool IsMountpoint(const std::string& mountpoint) {
610 struct stat stdir, stparent;
611
612 // Check whether the passed mountpoint is a directory and the /.. is in the
613 // same device or not. If mountpoint/.. is in a different device it means that
614 // there is a filesystem mounted there. If it is not, but they both point to
615 // the same inode it basically is the special case of /.. pointing to /. This
616 // test doesn't play well with bind mount but that's out of the scope of what
617 // we want to detect here.
618 if (lstat(mountpoint.c_str(), &stdir) != 0) {
619 PLOG(ERROR) << "Error stat'ing " << mountpoint;
620 return false;
621 }
622 if (!S_ISDIR(stdir.st_mode))
623 return false;
624
625 base::FilePath parent(mountpoint);
626 parent = parent.Append("..");
627 if (lstat(parent.value().c_str(), &stparent) != 0) {
628 PLOG(ERROR) << "Error stat'ing " << parent.value();
629 return false;
630 }
631 return S_ISDIR(stparent.st_mode) &&
632 (stparent.st_dev != stdir.st_dev || stparent.st_ino == stdir.st_ino);
633}
634
Alex Deymo032e7722014-03-25 17:53:56 -0700635// Tries to parse the header of an ELF file to obtain a human-readable
636// description of it on the |output| string.
Amin Hassanib2689592019-01-13 17:04:28 -0800637static bool GetFileFormatELF(const uint8_t* buffer,
638 size_t size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800639 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700640 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700641 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700642 return false;
643 *output = "ELF";
644
645 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700646 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700647 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700648 switch (buffer[EI_CLASS]) {
649 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700650 *output += " 32-bit";
651 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700652 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700653 *output += " 64-bit";
654 break;
655 default:
656 *output += " ?-bit";
657 }
658
659 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700660 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700661 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800662 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700663 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700664 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700665 *output += " little-endian";
666 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700667 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700668 *output += " big-endian";
669 break;
670 default:
671 *output += " ?-endian";
672 // Don't parse anything after the 0x10 offset if endianness is unknown.
673 return true;
674 }
675
Alex Deymoc1711e22014-08-08 13:16:23 -0700676 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
677 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
678 // and size is the same for both 32 and 64 bits.
679 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700680 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700681 uint16_t e_machine;
Sen Jiang771f6482018-04-04 17:59:10 -0700682 // Fix endianness regardless of the host endianness.
Alex Deymoc1711e22014-08-08 13:16:23 -0700683 if (ei_data == ELFDATA2LSB)
684 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700685 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700686 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700687
688 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700689 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700690 *output += " x86";
691 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700692 case EM_MIPS:
693 *output += " mips";
694 break;
695 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700696 *output += " arm";
697 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700698 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700699 *output += " x86-64";
700 break;
701 default:
702 *output += " unknown-arch";
703 }
704 return true;
705}
706
707string GetFileFormat(const string& path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700708 brillo::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700709 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
710 return "File not found.";
711
712 string result;
713 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
714 return result;
715
716 return "data";
717}
718
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700719int FuzzInt(int value, unsigned int range) {
720 int min = value - range / 2;
721 int max = value + range - range / 2;
722 return base::RandInt(min, max);
723}
724
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700725string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800726 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700727}
728
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800729string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400730 string str;
731
732 // Handle negative durations by prefixing with a minus.
733 if (delta.ToInternalValue() < 0) {
734 delta *= -1;
735 str = "-";
736 }
737
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700738 // Canonicalize into days, hours, minutes, seconds and microseconds.
739 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800740 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700741 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800742 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700743 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800744 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700745 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800746 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700747 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800748
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700749 if (days)
750 base::StringAppendF(&str, "%ud", days);
751 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800752 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700753 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800754 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700755 base::StringAppendF(&str, "%u", secs);
756 if (usecs) {
757 int width = 6;
758 while ((usecs / 10) * 10 == usecs) {
759 usecs /= 10;
760 width--;
761 }
762 base::StringAppendF(&str, ".%0*u", width, usecs);
763 }
764 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800765 return str;
766}
767
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700768string ToString(const Time utc_time) {
769 Time::Exploded exp_time;
770 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700771 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Amin Hassanib2689592019-01-13 17:04:28 -0800772 exp_time.month,
773 exp_time.day_of_month,
774 exp_time.year,
775 exp_time.hour,
776 exp_time.minute,
777 exp_time.second);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700778}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000779
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700780string ToString(bool b) {
781 return (b ? "true" : "false");
782}
783
Alex Deymo1c656c42013-06-28 11:02:14 -0700784string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700785 switch (source) {
Amin Hassanib2689592019-01-13 17:04:28 -0800786 case kDownloadSourceHttpsServer:
787 return "HttpsServer";
788 case kDownloadSourceHttpServer:
789 return "HttpServer";
790 case kDownloadSourceHttpPeer:
791 return "HttpPeer";
792 case kNumDownloadSources:
793 return "Unknown";
794 // Don't add a default case to let the compiler warn about newly added
795 // download sources which should be added here.
Jay Srinivasan19409b72013-04-12 19:23:36 -0700796 }
797
798 return "Unknown";
799}
800
Alex Deymo1c656c42013-06-28 11:02:14 -0700801string ToString(PayloadType payload_type) {
802 switch (payload_type) {
Amin Hassanib2689592019-01-13 17:04:28 -0800803 case kPayloadTypeDelta:
804 return "Delta";
805 case kPayloadTypeFull:
806 return "Full";
807 case kPayloadTypeForcedFull:
808 return "ForcedFull";
809 case kNumPayloadTypes:
810 return "Unknown";
811 // Don't add a default case to let the compiler warn about newly added
812 // payload types which should be added here.
Alex Deymo1c656c42013-06-28 11:02:14 -0700813 }
814
815 return "Unknown";
816}
817
David Zeuthena99981f2013-04-29 13:42:47 -0700818ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700819 // Ignore the higher order bits in the code by applying the mask as
820 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700821 // with values less than ErrorCode::kUmaReportedMax.
822 ErrorCode base_code = static_cast<ErrorCode>(
823 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700824
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800825 // Make additional adjustments required for UMA and error classification.
826 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
827 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700828 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700829 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800830 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800831 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700832 << " to ErrorCode::kOmahaErrorInHTTPResponse";
833 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700834 }
835
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800836 return base_code;
837}
838
Kelvin Zhangd7191032020-08-11 10:48:16 -0400839string StringVectorToString(const vector<string>& vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700840 string str = "[";
Amin Hassanib2689592019-01-13 17:04:28 -0800841 for (vector<string>::const_iterator i = vec_str.begin(); i != vec_str.end();
842 ++i) {
Alex Deymof329b932014-10-30 01:37:48 -0700843 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -0700844 str += ", ";
845 str += '"';
846 str += *i;
847 str += '"';
848 }
849 str += "]";
850 return str;
851}
852
Sen Jiang2703ef42017-03-16 13:36:21 -0700853// The P2P file id should be the same for devices running new version and old
854// version so that they can share it with each other. The hash in the response
855// was base64 encoded, but now that we switched to use "hash_sha256" field which
856// is hex encoded, we have to convert them back to base64 for P2P. However, the
857// base64 encoded hash was base64 encoded here again historically for some
858// reason, so we keep the same behavior here.
859string CalculateP2PFileId(const brillo::Blob& payload_hash,
860 size_t payload_size) {
861 string encoded_hash = brillo::data_encoding::Base64Encode(
862 brillo::data_encoding::Base64Encode(payload_hash));
Alex Deymoc00c98a2015-03-17 17:38:00 -0700863 return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800864 payload_size,
865 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -0700866}
867
Kelvin Zhangd7191032020-08-11 10:48:16 -0400868bool ConvertToOmahaInstallDate(Time time, int* out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -0800869 time_t unix_time = time.ToTimeT();
870 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
871 const time_t kOmahaEpoch = 1167638400;
Amin Hassanib2689592019-01-13 17:04:28 -0800872 const int64_t kNumSecondsPerWeek = 7 * 24 * 3600;
David Zeuthen639aa362014-02-03 16:23:44 -0800873 const int64_t kNumDaysPerWeek = 7;
874
875 time_t omaha_time = unix_time - kOmahaEpoch;
876
877 if (omaha_time < 0)
878 return false;
879
880 // Note, as per the comment in utils.h we are deliberately not
881 // handling DST correctly.
882
883 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
884 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
885
886 return true;
887}
888
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700889bool GetMinorVersion(const brillo::KeyValueStore& store,
Alex Deymob42b98d2015-07-06 17:42:38 -0700890 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700891 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -0700892 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -0800893 if (!base::StringToUint(result, minor_version)) {
894 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
895 return false;
896 }
Allie Wood78750a42015-02-11 15:42:11 -0800897 return true;
898 }
899 return false;
900}
901
Kelvin Zhang02fe6622021-11-01 16:37:58 -0700902bool ReadExtents(const std::string& path,
903 const google::protobuf::RepeatedPtrField<Extent>& extents,
904 brillo::Blob* out_data,
905 size_t block_size) {
906 return ReadExtents(path,
907 {extents.begin(), extents.end()},
908 out_data,
909 utils::BlocksInExtents(extents) * block_size,
910 block_size);
911}
912
913bool WriteExtents(const std::string& path,
914 const google::protobuf::RepeatedPtrField<Extent>& extents,
915 const brillo::Blob& data,
916 size_t block_size) {
917 EintrSafeFileDescriptor fd;
918 TEST_AND_RETURN_FALSE(fd.Open(path.c_str(), O_RDWR));
919 size_t bytes_written = 0;
920 for (const auto& ext : extents) {
921 TEST_AND_RETURN_FALSE_ERRNO(
922 fd.Seek(ext.start_block() * block_size, SEEK_SET));
923 TEST_AND_RETURN_FALSE_ERRNO(
924 fd.Write(data.data() + bytes_written, ext.num_blocks() * block_size));
925 bytes_written += ext.num_blocks() * block_size;
926 }
927 return true;
928}
Kelvin Zhang4eae81e2021-12-09 17:07:17 -0800929bool ReadExtents(const std::string& path,
930 const vector<Extent>& extents,
931 brillo::Blob* out_data,
932 ssize_t out_data_size,
933 size_t block_size) {
934 FileDescriptorPtr fd = std::make_shared<EintrSafeFileDescriptor>();
935 fd->Open(path.c_str(), O_RDONLY);
936 return ReadExtents(fd, extents, out_data, out_data_size, block_size);
937}
Kelvin Zhang02fe6622021-11-01 16:37:58 -0700938
Kelvin Zhang4eae81e2021-12-09 17:07:17 -0800939bool ReadExtents(FileDescriptorPtr fd,
940 const google::protobuf::RepeatedPtrField<Extent>& extents,
941 brillo::Blob* out_data,
942 size_t block_size) {
943 return ReadExtents(fd,
944 {extents.begin(), extents.end()},
945 out_data,
946 utils::BlocksInExtents(extents) * block_size,
947 block_size);
948}
949
950bool ReadExtents(FileDescriptorPtr fd,
Amin Hassanib2689592019-01-13 17:04:28 -0800951 const vector<Extent>& extents,
952 brillo::Blob* out_data,
953 ssize_t out_data_size,
Allie Wood56873452015-03-27 17:48:40 -0700954 size_t block_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700955 brillo::Blob data(out_data_size);
Allie Wood56873452015-03-27 17:48:40 -0700956 ssize_t bytes_read = 0;
Allie Wood56873452015-03-27 17:48:40 -0700957
Gilad Arnold41e34742015-05-11 11:31:50 -0700958 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -0700959 ssize_t bytes_read_this_iteration = 0;
960 ssize_t bytes = extent.num_blocks() * block_size;
Kelvin Zhang02fe6622021-11-01 16:37:58 -0700961 TEST_LE(bytes_read + bytes, out_data_size);
Allie Wood56873452015-03-27 17:48:40 -0700962 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
963 &data[bytes_read],
964 bytes,
965 extent.start_block() * block_size,
966 &bytes_read_this_iteration));
967 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
968 bytes_read += bytes_read_this_iteration;
969 }
970 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
971 *out_data = data;
972 return true;
973}
974
Matt Ziegelbaum91ba9be2020-06-10 16:56:40 -0400975bool GetVpdValue(string key, string* result) {
976 int exit_code = 0;
977 string value, error;
978 vector<string> cmd = {"vpd_get_value", key};
979 if (!chromeos_update_engine::Subprocess::SynchronousExec(
980 cmd, &exit_code, &value, &error) ||
981 exit_code) {
982 LOG(ERROR) << "Failed to get vpd key for " << value
983 << " with exit code: " << exit_code << " and error: " << error;
984 return false;
985 } else if (!error.empty()) {
986 LOG(INFO) << "vpd_get_value succeeded but with following errors: " << error;
987 }
988
989 base::TrimWhitespaceASCII(value, base::TRIM_ALL, &value);
990 *result = value;
991 return true;
992}
993
Alex Deymodd132f32015-09-14 19:12:07 -0700994bool GetBootId(string* boot_id) {
995 TEST_AND_RETURN_FALSE(
996 base::ReadFileToString(base::FilePath(kBootIdPath), boot_id));
997 base::TrimWhitespaceASCII(*boot_id, base::TRIM_TRAILING, boot_id);
998 return true;
999}
1000
Marton Hunyadya0302682018-05-16 18:52:13 +02001001int VersionPrefix(const std::string& version) {
1002 if (version.empty()) {
1003 return 0;
1004 }
1005 vector<string> tokens = base::SplitString(
1006 version, ".", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
1007 int value;
1008 if (tokens.empty() || !base::StringToInt(tokens[0], &value))
1009 return -1; // Target version is invalid.
1010 return value;
1011}
1012
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -07001013void ParseRollbackKeyVersion(const string& raw_version,
1014 uint16_t* high_version,
1015 uint16_t* low_version) {
1016 DCHECK(high_version);
1017 DCHECK(low_version);
1018 *high_version = numeric_limits<uint16_t>::max();
1019 *low_version = numeric_limits<uint16_t>::max();
1020
1021 vector<string> parts = base::SplitString(
1022 raw_version, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
1023 if (parts.size() != 2) {
1024 // The version string must have exactly one period.
1025 return;
1026 }
1027
1028 int high;
1029 int low;
1030 if (!(base::StringToInt(parts[0], &high) &&
1031 base::StringToInt(parts[1], &low))) {
1032 // Both parts of the version could not be parsed correctly.
1033 return;
1034 }
1035
1036 if (high >= 0 && high < numeric_limits<uint16_t>::max() && low >= 0 &&
1037 low < numeric_limits<uint16_t>::max()) {
1038 *high_version = static_cast<uint16_t>(high);
1039 *low_version = static_cast<uint16_t>(low);
1040 }
1041}
1042
Kyeongkab.Nam500ca132019-06-26 13:48:07 +09001043string GetFilePath(int fd) {
1044 base::FilePath proc("/proc/self/fd/" + std::to_string(fd));
1045 base::FilePath file_name;
1046
1047 if (!base::ReadSymbolicLink(proc, &file_name)) {
1048 return "not found";
1049 }
1050 return file_name.value();
1051}
1052
Yifan Hongc80de2d2020-02-25 17:13:53 -08001053string GetTimeAsString(time_t utime) {
1054 struct tm tm;
1055 CHECK_EQ(localtime_r(&utime, &tm), &tm);
1056 char str[16];
1057 CHECK_EQ(strftime(str, sizeof(str), "%Y%m%d-%H%M%S", &tm), 15u);
1058 return str;
1059}
1060
Jae Hoon Kim694eeb02020-06-01 14:24:08 -07001061string GetExclusionName(const string& str_to_convert) {
1062 return base::NumberToString(base::StringPieceHash()(str_to_convert));
1063}
1064
Kelvin Zhang636ba2f2022-02-09 14:40:22 -08001065static bool ParseTimestamp(std::string_view str, int64_t* out) {
1066 if (!base::StringToInt64(base::StringPiece(str.data(), str.size()), out)) {
Kelvin Zhangd7191032020-08-11 10:48:16 -04001067 LOG(WARNING) << "Invalid timestamp: " << str;
1068 return false;
1069 }
1070 return true;
1071}
1072
Kelvin Zhang636ba2f2022-02-09 14:40:22 -08001073ErrorCode IsTimestampNewer(const std::string_view old_version,
1074 const std::string_view new_version) {
Kelvin Zhangd7191032020-08-11 10:48:16 -04001075 if (old_version.empty() || new_version.empty()) {
1076 LOG(WARNING)
1077 << "One of old/new timestamp is empty, permit update anyway. Old: "
1078 << old_version << " New: " << new_version;
Yifan Hong87029332020-09-01 17:20:08 -07001079 return ErrorCode::kSuccess;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001080 }
1081 int64_t old_ver = 0;
Yifan Hong87029332020-09-01 17:20:08 -07001082 if (!ParseTimestamp(old_version, &old_ver)) {
1083 return ErrorCode::kError;
1084 }
Kelvin Zhangd7191032020-08-11 10:48:16 -04001085 int64_t new_ver = 0;
Yifan Hong87029332020-09-01 17:20:08 -07001086 if (!ParseTimestamp(new_version, &new_ver)) {
1087 return ErrorCode::kDownloadManifestParseError;
1088 }
1089 if (old_ver > new_ver) {
1090 return ErrorCode::kPayloadTimestampError;
1091 }
1092 return ErrorCode::kSuccess;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001093}
1094
Kelvin Zhang4bb49202021-07-08 21:39:05 -04001095std::unique_ptr<android::base::MappedFile> GetReadonlyZeroBlock(size_t size) {
1096 android::base::unique_fd fd{HANDLE_EINTR(open("/dev/zero", O_RDONLY))};
1097 return android::base::MappedFile::FromFd(fd, 0, size, PROT_READ);
1098}
1099
Kelvin Zhang3fe49642021-10-04 15:35:02 -07001100std::string_view GetReadonlyZeroString(size_t size) {
1101 // Reserve 512MB of Virtual Address Space. No actual memory will be used.
1102 static auto zero_block = GetReadonlyZeroBlock(1024 * 1024 * 512);
1103 if (size > zero_block->size()) {
1104 auto larger_block = GetReadonlyZeroBlock(size);
1105 zero_block = std::move(larger_block);
1106 }
1107 return {zero_block->data(), size};
1108}
1109
adlr@google.com3defe6a2009-12-04 20:57:17 +00001110} // namespace utils
1111
Kelvin Zhang20982a52021-08-13 12:31:16 -07001112std::string HexEncode(const brillo::Blob& blob) noexcept {
1113 return base::HexEncode(blob.data(), blob.size());
1114}
1115
Kelvin Zhang3fe49642021-10-04 15:35:02 -07001116std::string HexEncode(const std::string_view blob) noexcept {
1117 return base::HexEncode(blob.data(), blob.size());
1118}
1119
Kelvin Zhang760c3342022-02-08 13:41:49 -08001120[[nodiscard]] std::string_view ToStringView(
1121 const std::vector<unsigned char>& blob) noexcept {
1122 return std::string_view{reinterpret_cast<const char*>(blob.data()),
1123 blob.size()};
1124}
1125
1126[[nodiscard]] std::string_view ToStringView(const void* data,
1127 size_t size) noexcept {
1128 return std::string_view(reinterpret_cast<const char*>(data), size);
1129}
1130
adlr@google.com3defe6a2009-12-04 20:57:17 +00001131} // namespace chromeos_update_engine