blob: 34d97a2aa7e654856f6ea08b89d6f0bdb1c5424a [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>
adlr@google.com3defe6a2009-12-04 20:57:17 +000033#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070034
adlr@google.com3defe6a2009-12-04 20:57:17 +000035#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070036#include <utility>
Chris Sosac1972482013-04-30 22:31:10 -070037#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070038
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070039#include <base/callback.h>
Ben Chan736fcb52014-05-21 18:28:22 -070040#include <base/files/file_path.h>
Alex Deymo192393b2014-11-10 15:58:38 -080041#include <base/files/file_util.h>
Ben Chan736fcb52014-05-21 18:28:22 -070042#include <base/files/scoped_file.h>
Alex Deymoc00c98a2015-03-17 17:38:00 -070043#include <base/format_macros.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070044#include <base/location.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040045#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080046#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050047#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070048#include <base/strings/string_number_conversions.h>
49#include <base/strings/string_split.h>
50#include <base/strings/string_util.h>
51#include <base/strings/stringprintf.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070052#include <brillo/data_encoding.h>
Will Drewry8f71da82010-08-30 14:07:11 -050053
Alex Deymo39910dc2015-11-09 17:04:30 -080054#include "update_engine/common/clock_interface.h"
55#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 Arnold8e3f12632013-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
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080086// Return true if |disk_name| is an MTD or a UBI device. Note that this test is
87// simply based on the name of the device.
88bool IsMtdDeviceName(const string& disk_name) {
Amin Hassanib2689592019-01-13 17:04:28 -080089 return base::StartsWith(
90 disk_name, "/dev/ubi", base::CompareCase::SENSITIVE) ||
Alex Vakulenko0103c362016-01-20 07:56:15 -080091 base::StartsWith(disk_name, "/dev/mtd", base::CompareCase::SENSITIVE);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080092}
93
94// Return the device name for the corresponding partition on a NAND device.
95// WARNING: This function returns device names that are not mountable.
96string MakeNandPartitionName(int partition_num) {
97 switch (partition_num) {
98 case 2:
99 case 4:
100 case 6: {
101 return base::StringPrintf("/dev/mtd%d", partition_num);
102 }
103 default: {
104 return base::StringPrintf("/dev/ubi%d_0", partition_num);
105 }
106 }
107}
108
109// Return the device name for the corresponding partition on a NAND device that
110// may be mountable (but may not be writable).
111string MakeNandPartitionNameForMount(int partition_num) {
112 switch (partition_num) {
113 case 2:
114 case 4:
115 case 6: {
116 return base::StringPrintf("/dev/mtd%d", partition_num);
117 }
118 case 3:
119 case 5:
120 case 7: {
121 return base::StringPrintf("/dev/ubiblock%d_0", partition_num);
122 }
123 default: {
124 return base::StringPrintf("/dev/ubi%d_0", partition_num);
125 }
126 }
127}
128
Alex Deymo5aa1c542015-09-18 01:02:33 -0700129// If |path| is absolute, or explicit relative to the current working directory,
130// leaves it as is. Otherwise, uses the system's temp directory, as defined by
131// base::GetTempDir() and prepends it to |path|. On success stores the full
132// temporary path in |template_path| and returns true.
133bool GetTempName(const string& path, base::FilePath* template_path) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800134 if (path[0] == '/' ||
135 base::StartsWith(path, "./", base::CompareCase::SENSITIVE) ||
136 base::StartsWith(path, "../", base::CompareCase::SENSITIVE)) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700137 *template_path = base::FilePath(path);
138 return true;
139 }
140
141 base::FilePath temp_dir;
Sen Jiang9c123462015-11-19 13:16:23 -0800142#ifdef __ANDROID__
Sen Jiangc2b37662019-01-09 16:51:18 -0800143 temp_dir = base::FilePath(constants::kNonVolatileDirectory).Append("tmp");
Alex Deymo32951022016-08-10 17:02:49 -0700144#else
Sen Jiangc2b37662019-01-09 16:51:18 -0800145 TEST_AND_RETURN_FALSE(base::GetTempDir(&temp_dir));
Alex Deymo32951022016-08-10 17:02:49 -0700146#endif // __ANDROID__
Sen Jiang9c123462015-11-19 13:16:23 -0800147 if (!base::PathExists(temp_dir))
148 TEST_AND_RETURN_FALSE(base::CreateDirectory(temp_dir));
Alex Deymo5aa1c542015-09-18 01:02:33 -0700149 *template_path = temp_dir.Append(path);
150 return true;
151}
152
Ben Chan77a1eba2012-10-07 22:54:55 -0700153} // namespace
154
adlr@google.com3defe6a2009-12-04 20:57:17 +0000155namespace utils {
156
J. Richard Barnette63137e52013-10-28 10:57:29 -0700157string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -0700158 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -0700159
Alex Vakulenko75039d72014-03-25 12:36:28 -0700160 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -0700161 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -0700162 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -0700163 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -0800164 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -0700165 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800166 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -0700167 string output;
168 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800169 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -0700170 return output;
171 }
172 }
173 }
174 LOG(ERROR) << "Unable to parse fwid from ec info.";
175 return "";
176}
177
Alex Deymo335516c2016-11-28 13:37:06 -0800178bool WriteFile(const char* path, const void* data, size_t data_len) {
179 int fd = HANDLE_EINTR(open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600));
180 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
181 ScopedFdCloser fd_closer(&fd);
182 return WriteAll(fd, data, data_len);
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800183}
184
Alex Deymo0d298542016-03-30 18:31:49 -0700185bool ReadAll(
186 int fd, void* buf, size_t count, size_t* out_bytes_read, bool* eof) {
187 char* c_buf = static_cast<char*>(buf);
188 size_t bytes_read = 0;
189 *eof = false;
190 while (bytes_read < count) {
191 ssize_t rc = HANDLE_EINTR(read(fd, c_buf + bytes_read, count - bytes_read));
192 if (rc < 0) {
193 // EAGAIN and EWOULDBLOCK are normal return values when there's no more
194 // input and we are in non-blocking mode.
195 if (errno != EWOULDBLOCK && errno != EAGAIN) {
196 PLOG(ERROR) << "Error reading fd " << fd;
197 *out_bytes_read = bytes_read;
198 return false;
199 }
200 break;
201 } else if (rc == 0) {
202 // A value of 0 means that we reached EOF and there is nothing else to
203 // read from this fd.
204 *eof = true;
205 break;
206 } else {
207 bytes_read += rc;
208 }
209 }
210 *out_bytes_read = bytes_read;
211 return true;
212}
213
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700214bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700215 const char* c_buf = static_cast<const char*>(buf);
216 ssize_t bytes_written = 0;
217 while (bytes_written < static_cast<ssize_t>(count)) {
218 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
219 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
220 bytes_written += rc;
221 }
222 return true;
223}
224
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700225bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
226 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700227 size_t bytes_written = 0;
228 int num_attempts = 0;
229 while (bytes_written < count) {
230 num_attempts++;
Amin Hassanib2689592019-01-13 17:04:28 -0800231 ssize_t rc = pwrite(fd,
232 c_buf + bytes_written,
233 count - bytes_written,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700234 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700235 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
236 if (rc < 0) {
237 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
Amin Hassanib2689592019-01-13 17:04:28 -0800238 << " bytes_written=" << bytes_written << " count=" << count
239 << " offset=" << offset;
Gilad Arnold780db212012-07-11 13:12:49 -0700240 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700241 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
242 bytes_written += rc;
243 }
244 return true;
245}
246
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700247bool WriteAll(const FileDescriptorPtr& fd, const void* buf, size_t count) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800248 const char* c_buf = static_cast<const char*>(buf);
249 ssize_t bytes_written = 0;
250 while (bytes_written < static_cast<ssize_t>(count)) {
251 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
252 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
253 bytes_written += rc;
254 }
255 return true;
256}
257
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700258bool PWriteAll(const FileDescriptorPtr& fd,
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800259 const void* buf,
260 size_t count,
261 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700262 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
263 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800264 return WriteAll(fd, buf, count);
265}
266
Amin Hassanib2689592019-01-13 17:04:28 -0800267bool PReadAll(
268 int fd, void* buf, size_t count, off_t offset, ssize_t* out_bytes_read) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700269 char* c_buf = static_cast<char*>(buf);
270 ssize_t bytes_read = 0;
271 while (bytes_read < static_cast<ssize_t>(count)) {
Amin Hassanib2689592019-01-13 17:04:28 -0800272 ssize_t rc =
273 pread(fd, c_buf + bytes_read, count - bytes_read, offset + bytes_read);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700274 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
275 if (rc == 0) {
276 break;
277 }
278 bytes_read += rc;
279 }
280 *out_bytes_read = bytes_read;
281 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700282}
283
Marton Hunyadya0302682018-05-16 18:52:13 +0200284bool PReadAll(const FileDescriptorPtr& fd,
285 void* buf,
286 size_t count,
287 off_t offset,
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800288 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700289 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
290 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800291 char* c_buf = static_cast<char*>(buf);
292 ssize_t bytes_read = 0;
293 while (bytes_read < static_cast<ssize_t>(count)) {
294 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
295 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
296 if (rc == 0) {
297 break;
298 }
299 bytes_read += rc;
300 }
301 *out_bytes_read = bytes_read;
302 return true;
303}
304
Gilad Arnold19a45f02012-07-19 12:36:10 -0700305// Append |nbytes| of content from |buf| to the vector pointed to by either
306// |vec_p| or |str_p|.
Amin Hassanib2689592019-01-13 17:04:28 -0800307static void AppendBytes(const uint8_t* buf,
308 size_t nbytes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700309 brillo::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700310 CHECK(buf);
311 CHECK(vec_p);
312 vec_p->insert(vec_p->end(), buf, buf + nbytes);
313}
Amin Hassanib2689592019-01-13 17:04:28 -0800314static void AppendBytes(const uint8_t* buf, size_t nbytes, string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700315 CHECK(buf);
316 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800317 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700318}
319
320// Reads from an open file |fp|, appending the read content to the container
321// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200322// file's content, false otherwise. If |size| is not -1, reads up to |size|
323// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700324template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200325static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700326 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200327 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800328 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200329 while (size == -1 || size > 0) {
330 off_t bytes_to_read = sizeof(buf);
331 if (size > 0 && bytes_to_read > size) {
332 bytes_to_read = size;
333 }
334 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
335 if (!nbytes) {
336 break;
337 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700338 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200339 if (size != -1) {
340 CHECK(size >= static_cast<off_t>(nbytes));
341 size -= nbytes;
342 }
343 }
344 if (ferror(fp)) {
345 return false;
346 }
347 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700348}
349
Darin Petkov8e447e02013-04-16 16:23:50 +0200350// Opens a file |path| for reading and appends its the contents to a container
351// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
352// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700353template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700354static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200355 off_t offset,
356 off_t size,
357 T* out_p) {
358 CHECK_GE(offset, 0);
359 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700360 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200361 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000362 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200363 if (offset) {
364 // Return success without appending any data if a chunk beyond the end of
365 // the file is requested.
366 if (offset >= FileSize(path)) {
367 return true;
368 }
369 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
370 }
371 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000372}
373
Alex Deymo10875d92014-11-10 21:52:57 -0800374// TODO(deymo): This is only used in unittest, but requires the private
375// Read<string>() defined here. Expose Read<string>() or move to base/ version.
376bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700377 FILE* fp = popen(cmd.c_str(), "r");
378 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000379 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200380 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700381 return (success && pclose(fp) >= 0);
382}
383
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700384bool ReadFile(const string& path, brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200385 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700386}
387
Darin Petkov8e447e02013-04-16 16:23:50 +0200388bool ReadFile(const string& path, string* out_p) {
389 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700390}
391
Amin Hassanib2689592019-01-13 17:04:28 -0800392bool ReadFileChunk(const string& path,
393 off_t offset,
394 off_t size,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700395 brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200396 return ReadFileChunkAndAppend(path, offset, size, out_p);
397}
398
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700399off_t BlockDevSize(int fd) {
400 uint64_t dev_size;
401 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
402 if (rc == -1) {
403 dev_size = -1;
404 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
405 }
406 return dev_size;
407}
408
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700409off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700410 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700411 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700412 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700413 if (rc < 0) {
414 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700415 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700416 }
417 if (S_ISREG(stbuf.st_mode))
418 return stbuf.st_size;
419 if (S_ISBLK(stbuf.st_mode))
420 return BlockDevSize(fd);
421 LOG(ERROR) << "Couldn't determine the type of " << fd;
422 return -1;
423}
424
425off_t FileSize(const string& path) {
426 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
427 if (fd == -1) {
428 PLOG(ERROR) << "Error opening " << path;
429 return fd;
430 }
431 off_t size = FileSize(fd);
432 if (size == -1)
433 PLOG(ERROR) << "Error getting file size of " << path;
434 close(fd);
435 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700436}
437
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800438void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000439 LOG(INFO) << "Logging array of length: " << length;
440 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700441 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000442 const unsigned int bytes_remaining = length - i;
Amin Hassanib2689592019-01-13 17:04:28 -0800443 const unsigned int bytes_per_this_line =
444 min(bytes_per_line, bytes_remaining);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000445 char header[100];
446 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
447 TEST_AND_RETURN(r == 13);
448 string line = header;
449 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
450 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800451 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000452 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
453 TEST_AND_RETURN(r == 3);
454 line += buf;
455 }
456 LOG(INFO) << line;
457 }
458}
459
Alex Deymof329b932014-10-30 01:37:48 -0700460bool SplitPartitionName(const string& partition_name,
461 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800462 int* out_partition_num) {
Amin Hassanib2689592019-01-13 17:04:28 -0800463 if (!base::StartsWith(
464 partition_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800465 LOG(ERROR) << "Invalid partition device name: " << partition_name;
466 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700467 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800468
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700469 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
470 if (last_nondigit_pos == string::npos ||
471 (last_nondigit_pos + 1) == partition_name.size()) {
472 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800473 return false;
474 }
475
Alex Deymof329b932014-10-30 01:37:48 -0700476 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700477 if (partition_name[last_nondigit_pos] == '_') {
478 // NAND block devices have weird naming which could be something
479 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
480 size_t prev_nondigit_pos =
481 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
482 if (prev_nondigit_pos == string::npos ||
483 (prev_nondigit_pos + 1) == last_nondigit_pos) {
484 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
485 return false;
486 }
487
488 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
489 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800490 }
491
492 if (out_disk_name) {
493 // Special case for MMC devices which have the following naming scheme:
494 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700495 size_t disk_name_len = last_nondigit_pos;
Amin Hassanib2689592019-01-13 17:04:28 -0800496 if (partition_name[last_nondigit_pos] != 'p' || last_nondigit_pos == 0 ||
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700497 !isdigit(partition_name[last_nondigit_pos - 1])) {
498 disk_name_len++;
499 }
500 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800501 }
502
503 if (out_partition_num) {
Amin Hassanib2689592019-01-13 17:04:28 -0800504 string partition_str =
505 partition_name.substr(last_nondigit_pos + 1, partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800506 *out_partition_num = atoi(partition_str.c_str());
507 }
508 return true;
509}
510
Alex Deymof329b932014-10-30 01:37:48 -0700511string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800512 if (partition_num < 1) {
513 LOG(ERROR) << "Invalid partition number: " << partition_num;
514 return string();
515 }
516
Alex Vakulenko0103c362016-01-20 07:56:15 -0800517 if (!base::StartsWith(disk_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800518 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700519 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800520 }
521
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800522 if (IsMtdDeviceName(disk_name)) {
523 // Special case for UBI block devices.
524 // 1. ubiblock is not writable, we need to use plain "ubi".
525 // 2. There is a "_0" suffix.
526 return MakeNandPartitionName(partition_num);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800527 }
528
Alex Deymof329b932014-10-30 01:37:48 -0700529 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700530 if (isdigit(partition_name.back())) {
531 // Special case for devices with names ending with a digit.
532 // Add "p" to separate the disk name from partition number,
533 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800534 partition_name += 'p';
535 }
536
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700537 partition_name += std::to_string(partition_num);
538
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800539 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700540}
541
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800542string MakePartitionNameForMount(const string& part_name) {
543 if (IsMtdDeviceName(part_name)) {
544 int partition_num;
545 if (!SplitPartitionName(part_name, nullptr, &partition_num)) {
546 return "";
547 }
548 return MakeNandPartitionNameForMount(partition_num);
549 }
550 return part_name;
551}
552
Alex Deymof329b932014-10-30 01:37:48 -0700553string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000554 char buf[100];
555 buf[0] = '\0';
556 return strerror_r(err, buf, sizeof(buf));
557}
558
adlr@google.com3defe6a2009-12-04 20:57:17 +0000559bool FileExists(const char* path) {
560 struct stat stbuf;
561 return 0 == lstat(path, &stbuf);
562}
563
Darin Petkov30291ed2010-11-12 10:23:06 -0800564bool IsSymlink(const char* path) {
565 struct stat stbuf;
566 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
567}
568
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800569bool TryAttachingUbiVolume(int volume_num, int timeout) {
570 const string volume_path = base::StringPrintf("/dev/ubi%d_0", volume_num);
571 if (FileExists(volume_path.c_str())) {
572 return true;
573 }
574
575 int exit_code;
Amin Hassanib2689592019-01-13 17:04:28 -0800576 vector<string> cmd = {"ubiattach",
577 "-m",
578 base::StringPrintf("%d", volume_num),
579 "-d",
580 base::StringPrintf("%d", volume_num)};
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800581 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
582 TEST_AND_RETURN_FALSE(exit_code == 0);
583
Amin Hassanib2689592019-01-13 17:04:28 -0800584 cmd = {"ubiblock", "--create", volume_path};
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800585 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
586 TEST_AND_RETURN_FALSE(exit_code == 0);
587
588 while (timeout > 0 && !FileExists(volume_path.c_str())) {
589 sleep(1);
590 timeout--;
591 }
592
593 return FileExists(volume_path.c_str());
594}
595
Alex Deymof329b932014-10-30 01:37:48 -0700596bool MakeTempFile(const string& base_filename_template,
597 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700598 int* fd) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700599 base::FilePath filename_template;
600 TEST_AND_RETURN_FALSE(
601 GetTempName(base_filename_template, &filename_template));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700602 DCHECK(filename || fd);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700603 vector<char> buf(filename_template.value().size() + 1);
Amin Hassanib2689592019-01-13 17:04:28 -0800604 memcpy(buf.data(),
605 filename_template.value().data(),
Alex Deymo5aa1c542015-09-18 01:02:33 -0700606 filename_template.value().size());
607 buf[filename_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700608
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800609 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700610 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
611 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800612 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700613 }
614 if (fd) {
615 *fd = mkstemp_fd;
616 } else {
617 close(mkstemp_fd);
618 }
619 return true;
620}
621
Alex Deymo5fb356c2016-03-25 18:48:22 -0700622bool SetBlockDeviceReadOnly(const string& device, bool read_only) {
623 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY | O_CLOEXEC));
624 if (fd < 0) {
625 PLOG(ERROR) << "Opening block device " << device;
626 return false;
627 }
628 ScopedFdCloser fd_closer(&fd);
629 // We take no action if not needed.
630 int read_only_flag;
631 int expected_flag = read_only ? 1 : 0;
632 int rc = ioctl(fd, BLKROGET, &read_only_flag);
633 // In case of failure reading the setting we will try to set it anyway.
634 if (rc == 0 && read_only_flag == expected_flag)
635 return true;
636
637 rc = ioctl(fd, BLKROSET, &expected_flag);
638 if (rc != 0) {
Amin Hassanib2689592019-01-13 17:04:28 -0800639 PLOG(ERROR) << "Marking block device " << device
640 << " as read_only=" << expected_flag;
Alex Deymo5fb356c2016-03-25 18:48:22 -0700641 return false;
642 }
643 return true;
644}
645
adlr@google.com3defe6a2009-12-04 20:57:17 +0000646bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700647 const string& mountpoint,
Alex Deymo390efed2016-02-18 11:00:40 -0800648 unsigned long mountflags, // NOLINT(runtime/int)
Alex Deymo14dbd332016-03-01 18:55:54 -0800649 const string& type,
650 const string& fs_mount_options) {
Alex Deymo390efed2016-02-18 11:00:40 -0800651 vector<const char*> fstypes;
652 if (type.empty()) {
653 fstypes = {"ext2", "ext3", "ext4", "squashfs"};
654 } else {
655 fstypes = {type.c_str()};
656 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800657 for (const char* fstype : fstypes) {
Amin Hassanib2689592019-01-13 17:04:28 -0800658 int rc = mount(device.c_str(),
659 mountpoint.c_str(),
660 fstype,
661 mountflags,
Alex Deymo14dbd332016-03-01 18:55:54 -0800662 fs_mount_options.c_str());
Alex Deymo4c82df32014-11-10 22:25:57 -0800663 if (rc == 0)
664 return true;
665
Amin Hassanib2689592019-01-13 17:04:28 -0800666 PLOG(WARNING) << "Unable to mount destination device " << device << " on "
667 << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000668 }
Alex Deymo390efed2016-02-18 11:00:40 -0800669 if (!type.empty()) {
670 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
671 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800672 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000673}
674
675bool UnmountFilesystem(const string& mountpoint) {
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700676 int num_retries = 1;
677 for (;; ++num_retries) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700678 if (umount(mountpoint.c_str()) == 0)
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700679 return true;
680 if (errno != EBUSY || num_retries >= kUnmountMaxNumOfRetries)
Ben Chan77a1eba2012-10-07 22:54:55 -0700681 break;
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700682 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700683 }
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700684 if (errno == EINVAL) {
685 LOG(INFO) << "Not a mountpoint: " << mountpoint;
686 return false;
687 }
688 PLOG(WARNING) << "Error unmounting " << mountpoint << " after " << num_retries
689 << " attempts. Lazy unmounting instead, error was";
690 if (umount2(mountpoint.c_str(), MNT_DETACH) != 0) {
691 PLOG(ERROR) << "Lazy unmount failed";
692 return false;
693 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000694 return true;
695}
696
Alex Deymof4116502017-03-22 17:00:31 -0700697bool IsMountpoint(const std::string& mountpoint) {
698 struct stat stdir, stparent;
699
700 // Check whether the passed mountpoint is a directory and the /.. is in the
701 // same device or not. If mountpoint/.. is in a different device it means that
702 // there is a filesystem mounted there. If it is not, but they both point to
703 // the same inode it basically is the special case of /.. pointing to /. This
704 // test doesn't play well with bind mount but that's out of the scope of what
705 // we want to detect here.
706 if (lstat(mountpoint.c_str(), &stdir) != 0) {
707 PLOG(ERROR) << "Error stat'ing " << mountpoint;
708 return false;
709 }
710 if (!S_ISDIR(stdir.st_mode))
711 return false;
712
713 base::FilePath parent(mountpoint);
714 parent = parent.Append("..");
715 if (lstat(parent.value().c_str(), &stparent) != 0) {
716 PLOG(ERROR) << "Error stat'ing " << parent.value();
717 return false;
718 }
719 return S_ISDIR(stparent.st_mode) &&
720 (stparent.st_dev != stdir.st_dev || stparent.st_ino == stdir.st_ino);
721}
722
Alex Deymo032e7722014-03-25 17:53:56 -0700723// Tries to parse the header of an ELF file to obtain a human-readable
724// description of it on the |output| string.
Amin Hassanib2689592019-01-13 17:04:28 -0800725static bool GetFileFormatELF(const uint8_t* buffer,
726 size_t size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800727 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700728 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700729 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700730 return false;
731 *output = "ELF";
732
733 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700734 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700735 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700736 switch (buffer[EI_CLASS]) {
737 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700738 *output += " 32-bit";
739 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700740 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700741 *output += " 64-bit";
742 break;
743 default:
744 *output += " ?-bit";
745 }
746
747 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700748 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700749 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800750 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700751 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700752 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700753 *output += " little-endian";
754 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700755 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700756 *output += " big-endian";
757 break;
758 default:
759 *output += " ?-endian";
760 // Don't parse anything after the 0x10 offset if endianness is unknown.
761 return true;
762 }
763
Alex Deymoc1711e22014-08-08 13:16:23 -0700764 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
765 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
766 // and size is the same for both 32 and 64 bits.
767 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700768 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700769 uint16_t e_machine;
Sen Jiang771f6482018-04-04 17:59:10 -0700770 // Fix endianness regardless of the host endianness.
Alex Deymoc1711e22014-08-08 13:16:23 -0700771 if (ei_data == ELFDATA2LSB)
772 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700773 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700774 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700775
776 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700777 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700778 *output += " x86";
779 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700780 case EM_MIPS:
781 *output += " mips";
782 break;
783 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700784 *output += " arm";
785 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700786 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700787 *output += " x86-64";
788 break;
789 default:
790 *output += " unknown-arch";
791 }
792 return true;
793}
794
795string GetFileFormat(const string& path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700796 brillo::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700797 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
798 return "File not found.";
799
800 string result;
801 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
802 return result;
803
804 return "data";
805}
806
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700807int FuzzInt(int value, unsigned int range) {
808 int min = value - range / 2;
809 int max = value + range - range / 2;
810 return base::RandInt(min, max);
811}
812
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700813string FormatSecs(unsigned secs) {
Gilad Arnold8e3f12632013-01-08 14:59:54 -0800814 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700815}
816
Gilad Arnold8e3f12632013-01-08 14:59:54 -0800817string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400818 string str;
819
820 // Handle negative durations by prefixing with a minus.
821 if (delta.ToInternalValue() < 0) {
822 delta *= -1;
823 str = "-";
824 }
825
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700826 // Canonicalize into days, hours, minutes, seconds and microseconds.
827 unsigned days = delta.InDays();
Gilad Arnold8e3f12632013-01-08 14:59:54 -0800828 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700829 unsigned hours = delta.InHours();
Gilad Arnold8e3f12632013-01-08 14:59:54 -0800830 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700831 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f12632013-01-08 14:59:54 -0800832 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700833 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f12632013-01-08 14:59:54 -0800834 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700835 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800836
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700837 if (days)
838 base::StringAppendF(&str, "%ud", days);
839 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800840 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700841 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800842 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700843 base::StringAppendF(&str, "%u", secs);
844 if (usecs) {
845 int width = 6;
846 while ((usecs / 10) * 10 == usecs) {
847 usecs /= 10;
848 width--;
849 }
850 base::StringAppendF(&str, ".%0*u", width, usecs);
851 }
852 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800853 return str;
854}
855
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700856string ToString(const Time utc_time) {
857 Time::Exploded exp_time;
858 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700859 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Amin Hassanib2689592019-01-13 17:04:28 -0800860 exp_time.month,
861 exp_time.day_of_month,
862 exp_time.year,
863 exp_time.hour,
864 exp_time.minute,
865 exp_time.second);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700866}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000867
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700868string ToString(bool b) {
869 return (b ? "true" : "false");
870}
871
Alex Deymo1c656c42013-06-28 11:02:14 -0700872string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700873 switch (source) {
Amin Hassanib2689592019-01-13 17:04:28 -0800874 case kDownloadSourceHttpsServer:
875 return "HttpsServer";
876 case kDownloadSourceHttpServer:
877 return "HttpServer";
878 case kDownloadSourceHttpPeer:
879 return "HttpPeer";
880 case kNumDownloadSources:
881 return "Unknown";
882 // Don't add a default case to let the compiler warn about newly added
883 // download sources which should be added here.
Jay Srinivasan19409b72013-04-12 19:23:36 -0700884 }
885
886 return "Unknown";
887}
888
Alex Deymo1c656c42013-06-28 11:02:14 -0700889string ToString(PayloadType payload_type) {
890 switch (payload_type) {
Amin Hassanib2689592019-01-13 17:04:28 -0800891 case kPayloadTypeDelta:
892 return "Delta";
893 case kPayloadTypeFull:
894 return "Full";
895 case kPayloadTypeForcedFull:
896 return "ForcedFull";
897 case kNumPayloadTypes:
898 return "Unknown";
899 // Don't add a default case to let the compiler warn about newly added
900 // payload types which should be added here.
Alex Deymo1c656c42013-06-28 11:02:14 -0700901 }
902
903 return "Unknown";
904}
905
David Zeuthena99981f2013-04-29 13:42:47 -0700906ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700907 // Ignore the higher order bits in the code by applying the mask as
908 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700909 // with values less than ErrorCode::kUmaReportedMax.
910 ErrorCode base_code = static_cast<ErrorCode>(
911 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700912
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800913 // Make additional adjustments required for UMA and error classification.
914 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
915 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700916 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700917 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800918 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800919 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700920 << " to ErrorCode::kOmahaErrorInHTTPResponse";
921 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700922 }
923
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800924 return base_code;
925}
926
Alex Deymof329b932014-10-30 01:37:48 -0700927string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700928 string str = "[";
Amin Hassanib2689592019-01-13 17:04:28 -0800929 for (vector<string>::const_iterator i = vec_str.begin(); i != vec_str.end();
930 ++i) {
Alex Deymof329b932014-10-30 01:37:48 -0700931 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -0700932 str += ", ";
933 str += '"';
934 str += *i;
935 str += '"';
936 }
937 str += "]";
938 return str;
939}
940
Sen Jiang2703ef42017-03-16 13:36:21 -0700941// The P2P file id should be the same for devices running new version and old
942// version so that they can share it with each other. The hash in the response
943// was base64 encoded, but now that we switched to use "hash_sha256" field which
944// is hex encoded, we have to convert them back to base64 for P2P. However, the
945// base64 encoded hash was base64 encoded here again historically for some
946// reason, so we keep the same behavior here.
947string CalculateP2PFileId(const brillo::Blob& payload_hash,
948 size_t payload_size) {
949 string encoded_hash = brillo::data_encoding::Base64Encode(
950 brillo::data_encoding::Base64Encode(payload_hash));
Alex Deymoc00c98a2015-03-17 17:38:00 -0700951 return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800952 payload_size,
953 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -0700954}
955
Alex Deymof329b932014-10-30 01:37:48 -0700956bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -0800957 time_t unix_time = time.ToTimeT();
958 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
959 const time_t kOmahaEpoch = 1167638400;
Amin Hassanib2689592019-01-13 17:04:28 -0800960 const int64_t kNumSecondsPerWeek = 7 * 24 * 3600;
David Zeuthen639aa362014-02-03 16:23:44 -0800961 const int64_t kNumDaysPerWeek = 7;
962
963 time_t omaha_time = unix_time - kOmahaEpoch;
964
965 if (omaha_time < 0)
966 return false;
967
968 // Note, as per the comment in utils.h we are deliberately not
969 // handling DST correctly.
970
971 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
972 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
973
974 return true;
975}
976
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700977bool GetMinorVersion(const brillo::KeyValueStore& store,
Alex Deymob42b98d2015-07-06 17:42:38 -0700978 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700979 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -0700980 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -0800981 if (!base::StringToUint(result, minor_version)) {
982 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
983 return false;
984 }
Allie Wood78750a42015-02-11 15:42:11 -0800985 return true;
986 }
987 return false;
988}
989
Amin Hassanib2689592019-01-13 17:04:28 -0800990bool ReadExtents(const string& path,
991 const vector<Extent>& extents,
992 brillo::Blob* out_data,
993 ssize_t out_data_size,
Allie Wood56873452015-03-27 17:48:40 -0700994 size_t block_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700995 brillo::Blob data(out_data_size);
Allie Wood56873452015-03-27 17:48:40 -0700996 ssize_t bytes_read = 0;
997 int fd = open(path.c_str(), O_RDONLY);
998 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
999 ScopedFdCloser fd_closer(&fd);
1000
Gilad Arnold41e34742015-05-11 11:31:50 -07001001 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001002 ssize_t bytes_read_this_iteration = 0;
1003 ssize_t bytes = extent.num_blocks() * block_size;
1004 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
1005 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1006 &data[bytes_read],
1007 bytes,
1008 extent.start_block() * block_size,
1009 &bytes_read_this_iteration));
1010 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1011 bytes_read += bytes_read_this_iteration;
1012 }
1013 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1014 *out_data = data;
1015 return true;
1016}
1017
Alex Deymodd132f32015-09-14 19:12:07 -07001018bool GetBootId(string* boot_id) {
1019 TEST_AND_RETURN_FALSE(
1020 base::ReadFileToString(base::FilePath(kBootIdPath), boot_id));
1021 base::TrimWhitespaceASCII(*boot_id, base::TRIM_TRAILING, boot_id);
1022 return true;
1023}
1024
Marton Hunyadya0302682018-05-16 18:52:13 +02001025int VersionPrefix(const std::string& version) {
1026 if (version.empty()) {
1027 return 0;
1028 }
1029 vector<string> tokens = base::SplitString(
1030 version, ".", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
1031 int value;
1032 if (tokens.empty() || !base::StringToInt(tokens[0], &value))
1033 return -1; // Target version is invalid.
1034 return value;
1035}
1036
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -07001037void ParseRollbackKeyVersion(const string& raw_version,
1038 uint16_t* high_version,
1039 uint16_t* low_version) {
1040 DCHECK(high_version);
1041 DCHECK(low_version);
1042 *high_version = numeric_limits<uint16_t>::max();
1043 *low_version = numeric_limits<uint16_t>::max();
1044
1045 vector<string> parts = base::SplitString(
1046 raw_version, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
1047 if (parts.size() != 2) {
1048 // The version string must have exactly one period.
1049 return;
1050 }
1051
1052 int high;
1053 int low;
1054 if (!(base::StringToInt(parts[0], &high) &&
1055 base::StringToInt(parts[1], &low))) {
1056 // Both parts of the version could not be parsed correctly.
1057 return;
1058 }
1059
1060 if (high >= 0 && high < numeric_limits<uint16_t>::max() && low >= 0 &&
1061 low < numeric_limits<uint16_t>::max()) {
1062 *high_version = static_cast<uint16_t>(high);
1063 *low_version = static_cast<uint16_t>(low);
1064 }
1065}
1066
adlr@google.com3defe6a2009-12-04 20:57:17 +00001067} // namespace utils
1068
1069} // namespace chromeos_update_engine