blob: ac9fa9cce7447b4607f001531999101fd48fd553 [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>
31#include <sys/stat.h>
32#include <sys/types.h>
Yifan Hongc80de2d2020-02-25 17:13:53 -080033#include <time.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000034#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070035
adlr@google.com3defe6a2009-12-04 20:57:17 +000036#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070037#include <utility>
Chris Sosac1972482013-04-30 22:31:10 -070038#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070039
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070040#include <base/callback.h>
Ben Chan736fcb52014-05-21 18:28:22 -070041#include <base/files/file_path.h>
Alex Deymo192393b2014-11-10 15:58:38 -080042#include <base/files/file_util.h>
Ben Chan736fcb52014-05-21 18:28:22 -070043#include <base/files/scoped_file.h>
Alex Deymoc00c98a2015-03-17 17:38:00 -070044#include <base/format_macros.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070045#include <base/location.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040046#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080047#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050048#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070049#include <base/strings/string_number_conversions.h>
50#include <base/strings/string_split.h>
51#include <base/strings/string_util.h>
52#include <base/strings/stringprintf.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070053#include <brillo/data_encoding.h>
Will Drewry8f71da82010-08-30 14:07:11 -050054
Alex Deymo39910dc2015-11-09 17:04:30 -080055#include "update_engine/common/constants.h"
Sen Jiang9c123462015-11-19 13:16:23 -080056#include "update_engine/common/platform_constants.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080057#include "update_engine/common/prefs_interface.h"
58#include "update_engine/common/subprocess.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080059#include "update_engine/payload_consumer/file_descriptor.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000060
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070061using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080062using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000063using std::min;
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -070064using std::numeric_limits;
Chris Sosac1972482013-04-30 22:31:10 -070065using std::pair;
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
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700194bool PWriteAll(const FileDescriptorPtr& fd,
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800195 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
Marton Hunyadya0302682018-05-16 18:52:13 +0200220bool PReadAll(const FileDescriptorPtr& fd,
221 void* buf,
222 size_t count,
223 off_t offset,
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800224 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
Gilad Arnold19a45f02012-07-19 12:36:10 -0700241// Append |nbytes| of content from |buf| to the vector pointed to by either
242// |vec_p| or |str_p|.
Amin Hassanib2689592019-01-13 17:04:28 -0800243static void AppendBytes(const uint8_t* buf,
244 size_t nbytes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700245 brillo::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700246 CHECK(buf);
247 CHECK(vec_p);
248 vec_p->insert(vec_p->end(), buf, buf + nbytes);
249}
Amin Hassanib2689592019-01-13 17:04:28 -0800250static void AppendBytes(const uint8_t* buf, size_t nbytes, string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700251 CHECK(buf);
252 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800253 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700254}
255
256// Reads from an open file |fp|, appending the read content to the container
257// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200258// file's content, false otherwise. If |size| is not -1, reads up to |size|
259// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700260template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200261static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700262 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200263 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800264 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200265 while (size == -1 || size > 0) {
266 off_t bytes_to_read = sizeof(buf);
267 if (size > 0 && bytes_to_read > size) {
268 bytes_to_read = size;
269 }
270 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
271 if (!nbytes) {
272 break;
273 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700274 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200275 if (size != -1) {
276 CHECK(size >= static_cast<off_t>(nbytes));
277 size -= nbytes;
278 }
279 }
280 if (ferror(fp)) {
281 return false;
282 }
283 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700284}
285
Darin Petkov8e447e02013-04-16 16:23:50 +0200286// Opens a file |path| for reading and appends its the contents to a container
287// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
288// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700289template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700290static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200291 off_t offset,
292 off_t size,
293 T* out_p) {
294 CHECK_GE(offset, 0);
295 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700296 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200297 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000298 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200299 if (offset) {
300 // Return success without appending any data if a chunk beyond the end of
301 // the file is requested.
302 if (offset >= FileSize(path)) {
303 return true;
304 }
305 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
306 }
307 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000308}
309
Alex Deymo10875d92014-11-10 21:52:57 -0800310// TODO(deymo): This is only used in unittest, but requires the private
311// Read<string>() defined here. Expose Read<string>() or move to base/ version.
312bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700313 FILE* fp = popen(cmd.c_str(), "r");
314 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000315 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200316 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700317 return (success && pclose(fp) >= 0);
318}
319
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700320bool ReadFile(const string& path, brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200321 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700322}
323
Darin Petkov8e447e02013-04-16 16:23:50 +0200324bool ReadFile(const string& path, string* out_p) {
325 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700326}
327
Amin Hassanib2689592019-01-13 17:04:28 -0800328bool ReadFileChunk(const string& path,
329 off_t offset,
330 off_t size,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700331 brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200332 return ReadFileChunkAndAppend(path, offset, size, out_p);
333}
334
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700335off_t BlockDevSize(int fd) {
336 uint64_t dev_size;
337 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
338 if (rc == -1) {
339 dev_size = -1;
340 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
341 }
342 return dev_size;
343}
344
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700345off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700346 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700347 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700348 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700349 if (rc < 0) {
350 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700351 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700352 }
353 if (S_ISREG(stbuf.st_mode))
354 return stbuf.st_size;
355 if (S_ISBLK(stbuf.st_mode))
356 return BlockDevSize(fd);
357 LOG(ERROR) << "Couldn't determine the type of " << fd;
358 return -1;
359}
360
361off_t FileSize(const string& path) {
362 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
363 if (fd == -1) {
364 PLOG(ERROR) << "Error opening " << path;
365 return fd;
366 }
367 off_t size = FileSize(fd);
368 if (size == -1)
369 PLOG(ERROR) << "Error getting file size of " << path;
370 close(fd);
371 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700372}
373
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800374void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000375 LOG(INFO) << "Logging array of length: " << length;
376 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700377 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000378 const unsigned int bytes_remaining = length - i;
Amin Hassanib2689592019-01-13 17:04:28 -0800379 const unsigned int bytes_per_this_line =
380 min(bytes_per_line, bytes_remaining);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000381 char header[100];
382 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
383 TEST_AND_RETURN(r == 13);
384 string line = header;
385 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
386 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800387 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000388 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
389 TEST_AND_RETURN(r == 3);
390 line += buf;
391 }
392 LOG(INFO) << line;
393 }
394}
395
Alex Deymof329b932014-10-30 01:37:48 -0700396bool SplitPartitionName(const string& partition_name,
397 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800398 int* out_partition_num) {
Amin Hassanib2689592019-01-13 17:04:28 -0800399 if (!base::StartsWith(
400 partition_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800401 LOG(ERROR) << "Invalid partition device name: " << partition_name;
402 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700403 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800404
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700405 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
406 if (last_nondigit_pos == string::npos ||
407 (last_nondigit_pos + 1) == partition_name.size()) {
408 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800409 return false;
410 }
411
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800412 if (out_disk_name) {
413 // Special case for MMC devices which have the following naming scheme:
414 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700415 size_t disk_name_len = last_nondigit_pos;
Amin Hassanib2689592019-01-13 17:04:28 -0800416 if (partition_name[last_nondigit_pos] != 'p' || last_nondigit_pos == 0 ||
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700417 !isdigit(partition_name[last_nondigit_pos - 1])) {
418 disk_name_len++;
419 }
420 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800421 }
422
423 if (out_partition_num) {
Brian Norris7b428f52019-06-26 10:03:35 -0700424 string partition_str = partition_name.substr(last_nondigit_pos + 1);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800425 *out_partition_num = atoi(partition_str.c_str());
426 }
427 return true;
428}
429
Alex Deymof329b932014-10-30 01:37:48 -0700430string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800431 if (partition_num < 1) {
432 LOG(ERROR) << "Invalid partition number: " << partition_num;
433 return string();
434 }
435
Alex Vakulenko0103c362016-01-20 07:56:15 -0800436 if (!base::StartsWith(disk_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800437 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700438 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800439 }
440
Alex Deymof329b932014-10-30 01:37:48 -0700441 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700442 if (isdigit(partition_name.back())) {
443 // Special case for devices with names ending with a digit.
444 // Add "p" to separate the disk name from partition number,
445 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800446 partition_name += 'p';
447 }
448
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700449 partition_name += std::to_string(partition_num);
450
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800451 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700452}
453
Alex Deymof329b932014-10-30 01:37:48 -0700454string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000455 char buf[100];
456 buf[0] = '\0';
457 return strerror_r(err, buf, sizeof(buf));
458}
459
adlr@google.com3defe6a2009-12-04 20:57:17 +0000460bool FileExists(const char* path) {
461 struct stat stbuf;
462 return 0 == lstat(path, &stbuf);
463}
464
Darin Petkov30291ed2010-11-12 10:23:06 -0800465bool IsSymlink(const char* path) {
466 struct stat stbuf;
467 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
468}
469
Alex Deymof329b932014-10-30 01:37:48 -0700470bool MakeTempFile(const string& base_filename_template,
471 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700472 int* fd) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700473 base::FilePath filename_template;
474 TEST_AND_RETURN_FALSE(
475 GetTempName(base_filename_template, &filename_template));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700476 DCHECK(filename || fd);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700477 vector<char> buf(filename_template.value().size() + 1);
Amin Hassanib2689592019-01-13 17:04:28 -0800478 memcpy(buf.data(),
479 filename_template.value().data(),
Alex Deymo5aa1c542015-09-18 01:02:33 -0700480 filename_template.value().size());
481 buf[filename_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700482
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800483 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700484 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
485 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800486 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700487 }
488 if (fd) {
489 *fd = mkstemp_fd;
490 } else {
491 close(mkstemp_fd);
492 }
493 return true;
494}
495
Alex Deymo5fb356c2016-03-25 18:48:22 -0700496bool SetBlockDeviceReadOnly(const string& device, bool read_only) {
497 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY | O_CLOEXEC));
498 if (fd < 0) {
499 PLOG(ERROR) << "Opening block device " << device;
500 return false;
501 }
502 ScopedFdCloser fd_closer(&fd);
503 // We take no action if not needed.
504 int read_only_flag;
505 int expected_flag = read_only ? 1 : 0;
506 int rc = ioctl(fd, BLKROGET, &read_only_flag);
507 // In case of failure reading the setting we will try to set it anyway.
508 if (rc == 0 && read_only_flag == expected_flag)
509 return true;
510
511 rc = ioctl(fd, BLKROSET, &expected_flag);
512 if (rc != 0) {
Amin Hassanib2689592019-01-13 17:04:28 -0800513 PLOG(ERROR) << "Marking block device " << device
514 << " as read_only=" << expected_flag;
Alex Deymo5fb356c2016-03-25 18:48:22 -0700515 return false;
516 }
517 return true;
518}
519
adlr@google.com3defe6a2009-12-04 20:57:17 +0000520bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700521 const string& mountpoint,
Alex Deymo390efed2016-02-18 11:00:40 -0800522 unsigned long mountflags, // NOLINT(runtime/int)
Alex Deymo14dbd332016-03-01 18:55:54 -0800523 const string& type,
524 const string& fs_mount_options) {
Alex Deymo390efed2016-02-18 11:00:40 -0800525 vector<const char*> fstypes;
526 if (type.empty()) {
527 fstypes = {"ext2", "ext3", "ext4", "squashfs"};
528 } else {
529 fstypes = {type.c_str()};
530 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800531 for (const char* fstype : fstypes) {
Amin Hassanib2689592019-01-13 17:04:28 -0800532 int rc = mount(device.c_str(),
533 mountpoint.c_str(),
534 fstype,
535 mountflags,
Alex Deymo14dbd332016-03-01 18:55:54 -0800536 fs_mount_options.c_str());
Alex Deymo4c82df32014-11-10 22:25:57 -0800537 if (rc == 0)
538 return true;
539
Amin Hassanib2689592019-01-13 17:04:28 -0800540 PLOG(WARNING) << "Unable to mount destination device " << device << " on "
541 << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000542 }
Alex Deymo390efed2016-02-18 11:00:40 -0800543 if (!type.empty()) {
544 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
545 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800546 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000547}
548
549bool UnmountFilesystem(const string& mountpoint) {
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700550 int num_retries = 1;
551 for (;; ++num_retries) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700552 if (umount(mountpoint.c_str()) == 0)
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700553 return true;
554 if (errno != EBUSY || num_retries >= kUnmountMaxNumOfRetries)
Ben Chan77a1eba2012-10-07 22:54:55 -0700555 break;
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700556 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700557 }
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700558 if (errno == EINVAL) {
559 LOG(INFO) << "Not a mountpoint: " << mountpoint;
560 return false;
561 }
562 PLOG(WARNING) << "Error unmounting " << mountpoint << " after " << num_retries
563 << " attempts. Lazy unmounting instead, error was";
564 if (umount2(mountpoint.c_str(), MNT_DETACH) != 0) {
565 PLOG(ERROR) << "Lazy unmount failed";
566 return false;
567 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000568 return true;
569}
570
Alex Deymof4116502017-03-22 17:00:31 -0700571bool IsMountpoint(const std::string& mountpoint) {
572 struct stat stdir, stparent;
573
574 // Check whether the passed mountpoint is a directory and the /.. is in the
575 // same device or not. If mountpoint/.. is in a different device it means that
576 // there is a filesystem mounted there. If it is not, but they both point to
577 // the same inode it basically is the special case of /.. pointing to /. This
578 // test doesn't play well with bind mount but that's out of the scope of what
579 // we want to detect here.
580 if (lstat(mountpoint.c_str(), &stdir) != 0) {
581 PLOG(ERROR) << "Error stat'ing " << mountpoint;
582 return false;
583 }
584 if (!S_ISDIR(stdir.st_mode))
585 return false;
586
587 base::FilePath parent(mountpoint);
588 parent = parent.Append("..");
589 if (lstat(parent.value().c_str(), &stparent) != 0) {
590 PLOG(ERROR) << "Error stat'ing " << parent.value();
591 return false;
592 }
593 return S_ISDIR(stparent.st_mode) &&
594 (stparent.st_dev != stdir.st_dev || stparent.st_ino == stdir.st_ino);
595}
596
Alex Deymo032e7722014-03-25 17:53:56 -0700597// Tries to parse the header of an ELF file to obtain a human-readable
598// description of it on the |output| string.
Amin Hassanib2689592019-01-13 17:04:28 -0800599static bool GetFileFormatELF(const uint8_t* buffer,
600 size_t size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800601 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700602 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700603 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700604 return false;
605 *output = "ELF";
606
607 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700608 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700609 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700610 switch (buffer[EI_CLASS]) {
611 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700612 *output += " 32-bit";
613 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700614 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700615 *output += " 64-bit";
616 break;
617 default:
618 *output += " ?-bit";
619 }
620
621 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700622 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700623 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800624 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700625 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700626 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700627 *output += " little-endian";
628 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700629 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700630 *output += " big-endian";
631 break;
632 default:
633 *output += " ?-endian";
634 // Don't parse anything after the 0x10 offset if endianness is unknown.
635 return true;
636 }
637
Alex Deymoc1711e22014-08-08 13:16:23 -0700638 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
639 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
640 // and size is the same for both 32 and 64 bits.
641 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700642 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700643 uint16_t e_machine;
Sen Jiang771f6482018-04-04 17:59:10 -0700644 // Fix endianness regardless of the host endianness.
Alex Deymoc1711e22014-08-08 13:16:23 -0700645 if (ei_data == ELFDATA2LSB)
646 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700647 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700648 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700649
650 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700651 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700652 *output += " x86";
653 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700654 case EM_MIPS:
655 *output += " mips";
656 break;
657 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700658 *output += " arm";
659 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700660 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700661 *output += " x86-64";
662 break;
663 default:
664 *output += " unknown-arch";
665 }
666 return true;
667}
668
669string GetFileFormat(const string& path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700670 brillo::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700671 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
672 return "File not found.";
673
674 string result;
675 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
676 return result;
677
678 return "data";
679}
680
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700681int FuzzInt(int value, unsigned int range) {
682 int min = value - range / 2;
683 int max = value + range - range / 2;
684 return base::RandInt(min, max);
685}
686
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700687string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800688 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700689}
690
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800691string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400692 string str;
693
694 // Handle negative durations by prefixing with a minus.
695 if (delta.ToInternalValue() < 0) {
696 delta *= -1;
697 str = "-";
698 }
699
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700700 // Canonicalize into days, hours, minutes, seconds and microseconds.
701 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800702 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700703 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800704 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700705 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800706 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700707 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800708 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700709 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800710
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700711 if (days)
712 base::StringAppendF(&str, "%ud", days);
713 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800714 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700715 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800716 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700717 base::StringAppendF(&str, "%u", secs);
718 if (usecs) {
719 int width = 6;
720 while ((usecs / 10) * 10 == usecs) {
721 usecs /= 10;
722 width--;
723 }
724 base::StringAppendF(&str, ".%0*u", width, usecs);
725 }
726 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800727 return str;
728}
729
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700730string ToString(const Time utc_time) {
731 Time::Exploded exp_time;
732 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700733 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Amin Hassanib2689592019-01-13 17:04:28 -0800734 exp_time.month,
735 exp_time.day_of_month,
736 exp_time.year,
737 exp_time.hour,
738 exp_time.minute,
739 exp_time.second);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700740}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000741
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700742string ToString(bool b) {
743 return (b ? "true" : "false");
744}
745
Alex Deymo1c656c42013-06-28 11:02:14 -0700746string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700747 switch (source) {
Amin Hassanib2689592019-01-13 17:04:28 -0800748 case kDownloadSourceHttpsServer:
749 return "HttpsServer";
750 case kDownloadSourceHttpServer:
751 return "HttpServer";
752 case kDownloadSourceHttpPeer:
753 return "HttpPeer";
754 case kNumDownloadSources:
755 return "Unknown";
756 // Don't add a default case to let the compiler warn about newly added
757 // download sources which should be added here.
Jay Srinivasan19409b72013-04-12 19:23:36 -0700758 }
759
760 return "Unknown";
761}
762
Alex Deymo1c656c42013-06-28 11:02:14 -0700763string ToString(PayloadType payload_type) {
764 switch (payload_type) {
Amin Hassanib2689592019-01-13 17:04:28 -0800765 case kPayloadTypeDelta:
766 return "Delta";
767 case kPayloadTypeFull:
768 return "Full";
769 case kPayloadTypeForcedFull:
770 return "ForcedFull";
771 case kNumPayloadTypes:
772 return "Unknown";
773 // Don't add a default case to let the compiler warn about newly added
774 // payload types which should be added here.
Alex Deymo1c656c42013-06-28 11:02:14 -0700775 }
776
777 return "Unknown";
778}
779
David Zeuthena99981f2013-04-29 13:42:47 -0700780ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700781 // Ignore the higher order bits in the code by applying the mask as
782 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700783 // with values less than ErrorCode::kUmaReportedMax.
784 ErrorCode base_code = static_cast<ErrorCode>(
785 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700786
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800787 // Make additional adjustments required for UMA and error classification.
788 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
789 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700790 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700791 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800792 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800793 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700794 << " to ErrorCode::kOmahaErrorInHTTPResponse";
795 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700796 }
797
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800798 return base_code;
799}
800
Kelvin Zhangd7191032020-08-11 10:48:16 -0400801string StringVectorToString(const vector<string>& vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700802 string str = "[";
Amin Hassanib2689592019-01-13 17:04:28 -0800803 for (vector<string>::const_iterator i = vec_str.begin(); i != vec_str.end();
804 ++i) {
Alex Deymof329b932014-10-30 01:37:48 -0700805 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -0700806 str += ", ";
807 str += '"';
808 str += *i;
809 str += '"';
810 }
811 str += "]";
812 return str;
813}
814
Sen Jiang2703ef42017-03-16 13:36:21 -0700815// The P2P file id should be the same for devices running new version and old
816// version so that they can share it with each other. The hash in the response
817// was base64 encoded, but now that we switched to use "hash_sha256" field which
818// is hex encoded, we have to convert them back to base64 for P2P. However, the
819// base64 encoded hash was base64 encoded here again historically for some
820// reason, so we keep the same behavior here.
821string CalculateP2PFileId(const brillo::Blob& payload_hash,
822 size_t payload_size) {
823 string encoded_hash = brillo::data_encoding::Base64Encode(
824 brillo::data_encoding::Base64Encode(payload_hash));
Alex Deymoc00c98a2015-03-17 17:38:00 -0700825 return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800826 payload_size,
827 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -0700828}
829
Kelvin Zhangd7191032020-08-11 10:48:16 -0400830bool ConvertToOmahaInstallDate(Time time, int* out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -0800831 time_t unix_time = time.ToTimeT();
832 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
833 const time_t kOmahaEpoch = 1167638400;
Amin Hassanib2689592019-01-13 17:04:28 -0800834 const int64_t kNumSecondsPerWeek = 7 * 24 * 3600;
David Zeuthen639aa362014-02-03 16:23:44 -0800835 const int64_t kNumDaysPerWeek = 7;
836
837 time_t omaha_time = unix_time - kOmahaEpoch;
838
839 if (omaha_time < 0)
840 return false;
841
842 // Note, as per the comment in utils.h we are deliberately not
843 // handling DST correctly.
844
845 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
846 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
847
848 return true;
849}
850
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700851bool GetMinorVersion(const brillo::KeyValueStore& store,
Alex Deymob42b98d2015-07-06 17:42:38 -0700852 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700853 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -0700854 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -0800855 if (!base::StringToUint(result, minor_version)) {
856 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
857 return false;
858 }
Allie Wood78750a42015-02-11 15:42:11 -0800859 return true;
860 }
861 return false;
862}
863
Amin Hassanib2689592019-01-13 17:04:28 -0800864bool ReadExtents(const string& path,
865 const vector<Extent>& extents,
866 brillo::Blob* out_data,
867 ssize_t out_data_size,
Allie Wood56873452015-03-27 17:48:40 -0700868 size_t block_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700869 brillo::Blob data(out_data_size);
Allie Wood56873452015-03-27 17:48:40 -0700870 ssize_t bytes_read = 0;
871 int fd = open(path.c_str(), O_RDONLY);
872 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
873 ScopedFdCloser fd_closer(&fd);
874
Gilad Arnold41e34742015-05-11 11:31:50 -0700875 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -0700876 ssize_t bytes_read_this_iteration = 0;
877 ssize_t bytes = extent.num_blocks() * block_size;
878 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
879 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
880 &data[bytes_read],
881 bytes,
882 extent.start_block() * block_size,
883 &bytes_read_this_iteration));
884 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
885 bytes_read += bytes_read_this_iteration;
886 }
887 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
888 *out_data = data;
889 return true;
890}
891
Matt Ziegelbaum91ba9be2020-06-10 16:56:40 -0400892bool GetVpdValue(string key, string* result) {
893 int exit_code = 0;
894 string value, error;
895 vector<string> cmd = {"vpd_get_value", key};
896 if (!chromeos_update_engine::Subprocess::SynchronousExec(
897 cmd, &exit_code, &value, &error) ||
898 exit_code) {
899 LOG(ERROR) << "Failed to get vpd key for " << value
900 << " with exit code: " << exit_code << " and error: " << error;
901 return false;
902 } else if (!error.empty()) {
903 LOG(INFO) << "vpd_get_value succeeded but with following errors: " << error;
904 }
905
906 base::TrimWhitespaceASCII(value, base::TRIM_ALL, &value);
907 *result = value;
908 return true;
909}
910
Alex Deymodd132f32015-09-14 19:12:07 -0700911bool GetBootId(string* boot_id) {
912 TEST_AND_RETURN_FALSE(
913 base::ReadFileToString(base::FilePath(kBootIdPath), boot_id));
914 base::TrimWhitespaceASCII(*boot_id, base::TRIM_TRAILING, boot_id);
915 return true;
916}
917
Marton Hunyadya0302682018-05-16 18:52:13 +0200918int VersionPrefix(const std::string& version) {
919 if (version.empty()) {
920 return 0;
921 }
922 vector<string> tokens = base::SplitString(
923 version, ".", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
924 int value;
925 if (tokens.empty() || !base::StringToInt(tokens[0], &value))
926 return -1; // Target version is invalid.
927 return value;
928}
929
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700930void ParseRollbackKeyVersion(const string& raw_version,
931 uint16_t* high_version,
932 uint16_t* low_version) {
933 DCHECK(high_version);
934 DCHECK(low_version);
935 *high_version = numeric_limits<uint16_t>::max();
936 *low_version = numeric_limits<uint16_t>::max();
937
938 vector<string> parts = base::SplitString(
939 raw_version, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
940 if (parts.size() != 2) {
941 // The version string must have exactly one period.
942 return;
943 }
944
945 int high;
946 int low;
947 if (!(base::StringToInt(parts[0], &high) &&
948 base::StringToInt(parts[1], &low))) {
949 // Both parts of the version could not be parsed correctly.
950 return;
951 }
952
953 if (high >= 0 && high < numeric_limits<uint16_t>::max() && low >= 0 &&
954 low < numeric_limits<uint16_t>::max()) {
955 *high_version = static_cast<uint16_t>(high);
956 *low_version = static_cast<uint16_t>(low);
957 }
958}
959
Kyeongkab.Nam500ca132019-06-26 13:48:07 +0900960string GetFilePath(int fd) {
961 base::FilePath proc("/proc/self/fd/" + std::to_string(fd));
962 base::FilePath file_name;
963
964 if (!base::ReadSymbolicLink(proc, &file_name)) {
965 return "not found";
966 }
967 return file_name.value();
968}
969
Yifan Hongc80de2d2020-02-25 17:13:53 -0800970string GetTimeAsString(time_t utime) {
971 struct tm tm;
972 CHECK_EQ(localtime_r(&utime, &tm), &tm);
973 char str[16];
974 CHECK_EQ(strftime(str, sizeof(str), "%Y%m%d-%H%M%S", &tm), 15u);
975 return str;
976}
977
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700978string GetExclusionName(const string& str_to_convert) {
979 return base::NumberToString(base::StringPieceHash()(str_to_convert));
980}
981
Kelvin Zhangd7191032020-08-11 10:48:16 -0400982static bool ParseTimestamp(const std::string& str, int64_t* out) {
983 if (!base::StringToInt64(str, out)) {
984 LOG(WARNING) << "Invalid timestamp: " << str;
985 return false;
986 }
987 return true;
988}
989
Yifan Hong87029332020-09-01 17:20:08 -0700990ErrorCode IsTimestampNewer(const std::string& old_version,
991 const std::string& new_version) {
Kelvin Zhangd7191032020-08-11 10:48:16 -0400992 if (old_version.empty() || new_version.empty()) {
993 LOG(WARNING)
994 << "One of old/new timestamp is empty, permit update anyway. Old: "
995 << old_version << " New: " << new_version;
Yifan Hong87029332020-09-01 17:20:08 -0700996 return ErrorCode::kSuccess;
Kelvin Zhangd7191032020-08-11 10:48:16 -0400997 }
998 int64_t old_ver = 0;
Yifan Hong87029332020-09-01 17:20:08 -0700999 if (!ParseTimestamp(old_version, &old_ver)) {
1000 return ErrorCode::kError;
1001 }
Kelvin Zhangd7191032020-08-11 10:48:16 -04001002 int64_t new_ver = 0;
Yifan Hong87029332020-09-01 17:20:08 -07001003 if (!ParseTimestamp(new_version, &new_ver)) {
1004 return ErrorCode::kDownloadManifestParseError;
1005 }
1006 if (old_ver > new_ver) {
1007 return ErrorCode::kPayloadTimestampError;
1008 }
1009 return ErrorCode::kSuccess;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001010}
1011
adlr@google.com3defe6a2009-12-04 20:57:17 +00001012} // namespace utils
1013
1014} // namespace chromeos_update_engine