blob: fc89040c37b48986915ea3f340245969b1a63407 [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/clock_interface.h"
56#include "update_engine/common/constants.h"
Sen Jiang9c123462015-11-19 13:16:23 -080057#include "update_engine/common/platform_constants.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080058#include "update_engine/common/prefs_interface.h"
59#include "update_engine/common/subprocess.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080060#include "update_engine/payload_consumer/file_descriptor.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000061
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070062using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080063using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000064using std::min;
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -070065using std::numeric_limits;
Chris Sosac1972482013-04-30 22:31:10 -070066using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000067using std::string;
68using std::vector;
69
70namespace chromeos_update_engine {
71
Ben Chan77a1eba2012-10-07 22:54:55 -070072namespace {
73
74// The following constants control how UnmountFilesystem should retry if
75// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
76// one second.
77const int kUnmountMaxNumOfRetries = 5;
78const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070079
80// Number of bytes to read from a file to attempt to detect its contents. Used
81// in GetFileFormat.
82const int kGetFileFormatMaxHeaderSize = 32;
83
Alex Deymodd132f32015-09-14 19:12:07 -070084// The path to the kernel's boot_id.
85const char kBootIdPath[] = "/proc/sys/kernel/random/boot_id";
86
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080087// Return true if |disk_name| is an MTD or a UBI device. Note that this test is
88// simply based on the name of the device.
89bool IsMtdDeviceName(const string& disk_name) {
Amin Hassanib2689592019-01-13 17:04:28 -080090 return base::StartsWith(
91 disk_name, "/dev/ubi", base::CompareCase::SENSITIVE) ||
Alex Vakulenko0103c362016-01-20 07:56:15 -080092 base::StartsWith(disk_name, "/dev/mtd", base::CompareCase::SENSITIVE);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080093}
94
95// Return the device name for the corresponding partition on a NAND device.
96// WARNING: This function returns device names that are not mountable.
97string MakeNandPartitionName(int partition_num) {
98 switch (partition_num) {
99 case 2:
100 case 4:
101 case 6: {
102 return base::StringPrintf("/dev/mtd%d", partition_num);
103 }
104 default: {
105 return base::StringPrintf("/dev/ubi%d_0", partition_num);
106 }
107 }
108}
109
110// Return the device name for the corresponding partition on a NAND device that
111// may be mountable (but may not be writable).
112string MakeNandPartitionNameForMount(int partition_num) {
113 switch (partition_num) {
114 case 2:
115 case 4:
116 case 6: {
117 return base::StringPrintf("/dev/mtd%d", partition_num);
118 }
119 case 3:
120 case 5:
121 case 7: {
122 return base::StringPrintf("/dev/ubiblock%d_0", partition_num);
123 }
124 default: {
125 return base::StringPrintf("/dev/ubi%d_0", partition_num);
126 }
127 }
128}
129
Alex Deymo5aa1c542015-09-18 01:02:33 -0700130// If |path| is absolute, or explicit relative to the current working directory,
131// leaves it as is. Otherwise, uses the system's temp directory, as defined by
132// base::GetTempDir() and prepends it to |path|. On success stores the full
133// temporary path in |template_path| and returns true.
134bool GetTempName(const string& path, base::FilePath* template_path) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800135 if (path[0] == '/' ||
136 base::StartsWith(path, "./", base::CompareCase::SENSITIVE) ||
137 base::StartsWith(path, "../", base::CompareCase::SENSITIVE)) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700138 *template_path = base::FilePath(path);
139 return true;
140 }
141
142 base::FilePath temp_dir;
Sen Jiang9c123462015-11-19 13:16:23 -0800143#ifdef __ANDROID__
Sen Jiangc2b37662019-01-09 16:51:18 -0800144 temp_dir = base::FilePath(constants::kNonVolatileDirectory).Append("tmp");
Alex Deymo32951022016-08-10 17:02:49 -0700145#else
Sen Jiangc2b37662019-01-09 16:51:18 -0800146 TEST_AND_RETURN_FALSE(base::GetTempDir(&temp_dir));
Alex Deymo32951022016-08-10 17:02:49 -0700147#endif // __ANDROID__
Sen Jiang9c123462015-11-19 13:16:23 -0800148 if (!base::PathExists(temp_dir))
149 TEST_AND_RETURN_FALSE(base::CreateDirectory(temp_dir));
Alex Deymo5aa1c542015-09-18 01:02:33 -0700150 *template_path = temp_dir.Append(path);
151 return true;
152}
153
Ben Chan77a1eba2012-10-07 22:54:55 -0700154} // namespace
155
adlr@google.com3defe6a2009-12-04 20:57:17 +0000156namespace utils {
157
J. Richard Barnette63137e52013-10-28 10:57:29 -0700158string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -0700159 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -0700160
Alex Vakulenko75039d72014-03-25 12:36:28 -0700161 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -0700162 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -0700163 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -0700164 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -0800165 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -0700166 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800167 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -0700168 string output;
169 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800170 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -0700171 return output;
172 }
173 }
174 }
175 LOG(ERROR) << "Unable to parse fwid from ec info.";
176 return "";
177}
178
Alex Deymo335516c2016-11-28 13:37:06 -0800179bool WriteFile(const char* path, const void* data, size_t data_len) {
180 int fd = HANDLE_EINTR(open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600));
181 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
182 ScopedFdCloser fd_closer(&fd);
183 return WriteAll(fd, data, data_len);
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800184}
185
Alex Deymo0d298542016-03-30 18:31:49 -0700186bool ReadAll(
187 int fd, void* buf, size_t count, size_t* out_bytes_read, bool* eof) {
188 char* c_buf = static_cast<char*>(buf);
189 size_t bytes_read = 0;
190 *eof = false;
191 while (bytes_read < count) {
192 ssize_t rc = HANDLE_EINTR(read(fd, c_buf + bytes_read, count - bytes_read));
193 if (rc < 0) {
194 // EAGAIN and EWOULDBLOCK are normal return values when there's no more
195 // input and we are in non-blocking mode.
196 if (errno != EWOULDBLOCK && errno != EAGAIN) {
197 PLOG(ERROR) << "Error reading fd " << fd;
198 *out_bytes_read = bytes_read;
199 return false;
200 }
201 break;
202 } else if (rc == 0) {
203 // A value of 0 means that we reached EOF and there is nothing else to
204 // read from this fd.
205 *eof = true;
206 break;
207 } else {
208 bytes_read += rc;
209 }
210 }
211 *out_bytes_read = bytes_read;
212 return true;
213}
214
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700215bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700216 const char* c_buf = static_cast<const char*>(buf);
217 ssize_t bytes_written = 0;
218 while (bytes_written < static_cast<ssize_t>(count)) {
219 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
220 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
221 bytes_written += rc;
222 }
223 return true;
224}
225
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700226bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
227 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700228 size_t bytes_written = 0;
229 int num_attempts = 0;
230 while (bytes_written < count) {
231 num_attempts++;
Amin Hassanib2689592019-01-13 17:04:28 -0800232 ssize_t rc = pwrite(fd,
233 c_buf + bytes_written,
234 count - bytes_written,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700235 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700236 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
237 if (rc < 0) {
238 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
Amin Hassanib2689592019-01-13 17:04:28 -0800239 << " bytes_written=" << bytes_written << " count=" << count
240 << " offset=" << offset;
Gilad Arnold780db212012-07-11 13:12:49 -0700241 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700242 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
243 bytes_written += rc;
244 }
245 return true;
246}
247
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700248bool WriteAll(const FileDescriptorPtr& fd, const void* buf, size_t count) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800249 const char* c_buf = static_cast<const char*>(buf);
250 ssize_t bytes_written = 0;
251 while (bytes_written < static_cast<ssize_t>(count)) {
252 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
253 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
254 bytes_written += rc;
255 }
256 return true;
257}
258
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700259bool PWriteAll(const FileDescriptorPtr& fd,
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800260 const void* buf,
261 size_t count,
262 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700263 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
264 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800265 return WriteAll(fd, buf, count);
266}
267
Amin Hassanib2689592019-01-13 17:04:28 -0800268bool PReadAll(
269 int fd, void* buf, size_t count, off_t offset, ssize_t* out_bytes_read) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700270 char* c_buf = static_cast<char*>(buf);
271 ssize_t bytes_read = 0;
272 while (bytes_read < static_cast<ssize_t>(count)) {
Amin Hassanib2689592019-01-13 17:04:28 -0800273 ssize_t rc =
274 pread(fd, c_buf + bytes_read, count - bytes_read, offset + bytes_read);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700275 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
276 if (rc == 0) {
277 break;
278 }
279 bytes_read += rc;
280 }
281 *out_bytes_read = bytes_read;
282 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700283}
284
Marton Hunyadya0302682018-05-16 18:52:13 +0200285bool PReadAll(const FileDescriptorPtr& fd,
286 void* buf,
287 size_t count,
288 off_t offset,
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800289 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700290 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
291 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800292 char* c_buf = static_cast<char*>(buf);
293 ssize_t bytes_read = 0;
294 while (bytes_read < static_cast<ssize_t>(count)) {
295 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
296 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
297 if (rc == 0) {
298 break;
299 }
300 bytes_read += rc;
301 }
302 *out_bytes_read = bytes_read;
303 return true;
304}
305
Gilad Arnold19a45f02012-07-19 12:36:10 -0700306// Append |nbytes| of content from |buf| to the vector pointed to by either
307// |vec_p| or |str_p|.
Amin Hassanib2689592019-01-13 17:04:28 -0800308static void AppendBytes(const uint8_t* buf,
309 size_t nbytes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700310 brillo::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700311 CHECK(buf);
312 CHECK(vec_p);
313 vec_p->insert(vec_p->end(), buf, buf + nbytes);
314}
Amin Hassanib2689592019-01-13 17:04:28 -0800315static void AppendBytes(const uint8_t* buf, size_t nbytes, string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700316 CHECK(buf);
317 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800318 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700319}
320
321// Reads from an open file |fp|, appending the read content to the container
322// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200323// file's content, false otherwise. If |size| is not -1, reads up to |size|
324// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700325template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200326static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700327 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200328 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800329 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200330 while (size == -1 || size > 0) {
331 off_t bytes_to_read = sizeof(buf);
332 if (size > 0 && bytes_to_read > size) {
333 bytes_to_read = size;
334 }
335 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
336 if (!nbytes) {
337 break;
338 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700339 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200340 if (size != -1) {
341 CHECK(size >= static_cast<off_t>(nbytes));
342 size -= nbytes;
343 }
344 }
345 if (ferror(fp)) {
346 return false;
347 }
348 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700349}
350
Darin Petkov8e447e02013-04-16 16:23:50 +0200351// Opens a file |path| for reading and appends its the contents to a container
352// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
353// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700354template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700355static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200356 off_t offset,
357 off_t size,
358 T* out_p) {
359 CHECK_GE(offset, 0);
360 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700361 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200362 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000363 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200364 if (offset) {
365 // Return success without appending any data if a chunk beyond the end of
366 // the file is requested.
367 if (offset >= FileSize(path)) {
368 return true;
369 }
370 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
371 }
372 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000373}
374
Alex Deymo10875d92014-11-10 21:52:57 -0800375// TODO(deymo): This is only used in unittest, but requires the private
376// Read<string>() defined here. Expose Read<string>() or move to base/ version.
377bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700378 FILE* fp = popen(cmd.c_str(), "r");
379 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000380 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200381 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700382 return (success && pclose(fp) >= 0);
383}
384
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700385bool ReadFile(const string& path, brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200386 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700387}
388
Darin Petkov8e447e02013-04-16 16:23:50 +0200389bool ReadFile(const string& path, string* out_p) {
390 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700391}
392
Amin Hassanib2689592019-01-13 17:04:28 -0800393bool ReadFileChunk(const string& path,
394 off_t offset,
395 off_t size,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700396 brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200397 return ReadFileChunkAndAppend(path, offset, size, out_p);
398}
399
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700400off_t BlockDevSize(int fd) {
401 uint64_t dev_size;
402 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
403 if (rc == -1) {
404 dev_size = -1;
405 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
406 }
407 return dev_size;
408}
409
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700410off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700411 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700412 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700413 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700414 if (rc < 0) {
415 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700416 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700417 }
418 if (S_ISREG(stbuf.st_mode))
419 return stbuf.st_size;
420 if (S_ISBLK(stbuf.st_mode))
421 return BlockDevSize(fd);
422 LOG(ERROR) << "Couldn't determine the type of " << fd;
423 return -1;
424}
425
426off_t FileSize(const string& path) {
427 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
428 if (fd == -1) {
429 PLOG(ERROR) << "Error opening " << path;
430 return fd;
431 }
432 off_t size = FileSize(fd);
433 if (size == -1)
434 PLOG(ERROR) << "Error getting file size of " << path;
435 close(fd);
436 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700437}
438
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800439void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000440 LOG(INFO) << "Logging array of length: " << length;
441 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700442 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000443 const unsigned int bytes_remaining = length - i;
Amin Hassanib2689592019-01-13 17:04:28 -0800444 const unsigned int bytes_per_this_line =
445 min(bytes_per_line, bytes_remaining);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000446 char header[100];
447 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
448 TEST_AND_RETURN(r == 13);
449 string line = header;
450 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
451 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800452 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000453 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
454 TEST_AND_RETURN(r == 3);
455 line += buf;
456 }
457 LOG(INFO) << line;
458 }
459}
460
Alex Deymof329b932014-10-30 01:37:48 -0700461bool SplitPartitionName(const string& partition_name,
462 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800463 int* out_partition_num) {
Amin Hassanib2689592019-01-13 17:04:28 -0800464 if (!base::StartsWith(
465 partition_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800466 LOG(ERROR) << "Invalid partition device name: " << partition_name;
467 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700468 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800469
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700470 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
471 if (last_nondigit_pos == string::npos ||
472 (last_nondigit_pos + 1) == partition_name.size()) {
473 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800474 return false;
475 }
476
Alex Deymof329b932014-10-30 01:37:48 -0700477 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700478 if (partition_name[last_nondigit_pos] == '_') {
479 // NAND block devices have weird naming which could be something
480 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
481 size_t prev_nondigit_pos =
482 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
483 if (prev_nondigit_pos == string::npos ||
484 (prev_nondigit_pos + 1) == last_nondigit_pos) {
485 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
486 return false;
487 }
488
489 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
490 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800491 }
492
493 if (out_disk_name) {
494 // Special case for MMC devices which have the following naming scheme:
495 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700496 size_t disk_name_len = last_nondigit_pos;
Amin Hassanib2689592019-01-13 17:04:28 -0800497 if (partition_name[last_nondigit_pos] != 'p' || last_nondigit_pos == 0 ||
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700498 !isdigit(partition_name[last_nondigit_pos - 1])) {
499 disk_name_len++;
500 }
501 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800502 }
503
504 if (out_partition_num) {
Amin Hassanib2689592019-01-13 17:04:28 -0800505 string partition_str =
506 partition_name.substr(last_nondigit_pos + 1, partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800507 *out_partition_num = atoi(partition_str.c_str());
508 }
509 return true;
510}
511
Alex Deymof329b932014-10-30 01:37:48 -0700512string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800513 if (partition_num < 1) {
514 LOG(ERROR) << "Invalid partition number: " << partition_num;
515 return string();
516 }
517
Alex Vakulenko0103c362016-01-20 07:56:15 -0800518 if (!base::StartsWith(disk_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800519 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700520 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800521 }
522
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800523 if (IsMtdDeviceName(disk_name)) {
524 // Special case for UBI block devices.
525 // 1. ubiblock is not writable, we need to use plain "ubi".
526 // 2. There is a "_0" suffix.
527 return MakeNandPartitionName(partition_num);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800528 }
529
Alex Deymof329b932014-10-30 01:37:48 -0700530 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700531 if (isdigit(partition_name.back())) {
532 // Special case for devices with names ending with a digit.
533 // Add "p" to separate the disk name from partition number,
534 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800535 partition_name += 'p';
536 }
537
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700538 partition_name += std::to_string(partition_num);
539
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800540 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700541}
542
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800543string MakePartitionNameForMount(const string& part_name) {
544 if (IsMtdDeviceName(part_name)) {
545 int partition_num;
546 if (!SplitPartitionName(part_name, nullptr, &partition_num)) {
547 return "";
548 }
549 return MakeNandPartitionNameForMount(partition_num);
550 }
551 return part_name;
552}
553
Alex Deymof329b932014-10-30 01:37:48 -0700554string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000555 char buf[100];
556 buf[0] = '\0';
557 return strerror_r(err, buf, sizeof(buf));
558}
559
adlr@google.com3defe6a2009-12-04 20:57:17 +0000560bool FileExists(const char* path) {
561 struct stat stbuf;
562 return 0 == lstat(path, &stbuf);
563}
564
Darin Petkov30291ed2010-11-12 10:23:06 -0800565bool IsSymlink(const char* path) {
566 struct stat stbuf;
567 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
568}
569
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800570bool TryAttachingUbiVolume(int volume_num, int timeout) {
571 const string volume_path = base::StringPrintf("/dev/ubi%d_0", volume_num);
572 if (FileExists(volume_path.c_str())) {
573 return true;
574 }
575
576 int exit_code;
Amin Hassanib2689592019-01-13 17:04:28 -0800577 vector<string> cmd = {"ubiattach",
578 "-m",
579 base::StringPrintf("%d", volume_num),
580 "-d",
581 base::StringPrintf("%d", volume_num)};
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800582 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
583 TEST_AND_RETURN_FALSE(exit_code == 0);
584
Amin Hassanib2689592019-01-13 17:04:28 -0800585 cmd = {"ubiblock", "--create", volume_path};
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800586 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
587 TEST_AND_RETURN_FALSE(exit_code == 0);
588
589 while (timeout > 0 && !FileExists(volume_path.c_str())) {
590 sleep(1);
591 timeout--;
592 }
593
594 return FileExists(volume_path.c_str());
595}
596
Alex Deymof329b932014-10-30 01:37:48 -0700597bool MakeTempFile(const string& base_filename_template,
598 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700599 int* fd) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700600 base::FilePath filename_template;
601 TEST_AND_RETURN_FALSE(
602 GetTempName(base_filename_template, &filename_template));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700603 DCHECK(filename || fd);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700604 vector<char> buf(filename_template.value().size() + 1);
Amin Hassanib2689592019-01-13 17:04:28 -0800605 memcpy(buf.data(),
606 filename_template.value().data(),
Alex Deymo5aa1c542015-09-18 01:02:33 -0700607 filename_template.value().size());
608 buf[filename_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700609
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800610 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700611 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
612 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800613 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700614 }
615 if (fd) {
616 *fd = mkstemp_fd;
617 } else {
618 close(mkstemp_fd);
619 }
620 return true;
621}
622
Alex Deymo5fb356c2016-03-25 18:48:22 -0700623bool SetBlockDeviceReadOnly(const string& device, bool read_only) {
624 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY | O_CLOEXEC));
625 if (fd < 0) {
626 PLOG(ERROR) << "Opening block device " << device;
627 return false;
628 }
629 ScopedFdCloser fd_closer(&fd);
630 // We take no action if not needed.
631 int read_only_flag;
632 int expected_flag = read_only ? 1 : 0;
633 int rc = ioctl(fd, BLKROGET, &read_only_flag);
634 // In case of failure reading the setting we will try to set it anyway.
635 if (rc == 0 && read_only_flag == expected_flag)
636 return true;
637
638 rc = ioctl(fd, BLKROSET, &expected_flag);
639 if (rc != 0) {
Amin Hassanib2689592019-01-13 17:04:28 -0800640 PLOG(ERROR) << "Marking block device " << device
641 << " as read_only=" << expected_flag;
Alex Deymo5fb356c2016-03-25 18:48:22 -0700642 return false;
643 }
644 return true;
645}
646
adlr@google.com3defe6a2009-12-04 20:57:17 +0000647bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700648 const string& mountpoint,
Alex Deymo390efed2016-02-18 11:00:40 -0800649 unsigned long mountflags, // NOLINT(runtime/int)
Alex Deymo14dbd332016-03-01 18:55:54 -0800650 const string& type,
651 const string& fs_mount_options) {
Alex Deymo390efed2016-02-18 11:00:40 -0800652 vector<const char*> fstypes;
653 if (type.empty()) {
654 fstypes = {"ext2", "ext3", "ext4", "squashfs"};
655 } else {
656 fstypes = {type.c_str()};
657 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800658 for (const char* fstype : fstypes) {
Amin Hassanib2689592019-01-13 17:04:28 -0800659 int rc = mount(device.c_str(),
660 mountpoint.c_str(),
661 fstype,
662 mountflags,
Alex Deymo14dbd332016-03-01 18:55:54 -0800663 fs_mount_options.c_str());
Alex Deymo4c82df32014-11-10 22:25:57 -0800664 if (rc == 0)
665 return true;
666
Amin Hassanib2689592019-01-13 17:04:28 -0800667 PLOG(WARNING) << "Unable to mount destination device " << device << " on "
668 << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000669 }
Alex Deymo390efed2016-02-18 11:00:40 -0800670 if (!type.empty()) {
671 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
672 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800673 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000674}
675
676bool UnmountFilesystem(const string& mountpoint) {
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700677 int num_retries = 1;
678 for (;; ++num_retries) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700679 if (umount(mountpoint.c_str()) == 0)
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700680 return true;
681 if (errno != EBUSY || num_retries >= kUnmountMaxNumOfRetries)
Ben Chan77a1eba2012-10-07 22:54:55 -0700682 break;
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700683 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700684 }
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700685 if (errno == EINVAL) {
686 LOG(INFO) << "Not a mountpoint: " << mountpoint;
687 return false;
688 }
689 PLOG(WARNING) << "Error unmounting " << mountpoint << " after " << num_retries
690 << " attempts. Lazy unmounting instead, error was";
691 if (umount2(mountpoint.c_str(), MNT_DETACH) != 0) {
692 PLOG(ERROR) << "Lazy unmount failed";
693 return false;
694 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000695 return true;
696}
697
Alex Deymof4116502017-03-22 17:00:31 -0700698bool IsMountpoint(const std::string& mountpoint) {
699 struct stat stdir, stparent;
700
701 // Check whether the passed mountpoint is a directory and the /.. is in the
702 // same device or not. If mountpoint/.. is in a different device it means that
703 // there is a filesystem mounted there. If it is not, but they both point to
704 // the same inode it basically is the special case of /.. pointing to /. This
705 // test doesn't play well with bind mount but that's out of the scope of what
706 // we want to detect here.
707 if (lstat(mountpoint.c_str(), &stdir) != 0) {
708 PLOG(ERROR) << "Error stat'ing " << mountpoint;
709 return false;
710 }
711 if (!S_ISDIR(stdir.st_mode))
712 return false;
713
714 base::FilePath parent(mountpoint);
715 parent = parent.Append("..");
716 if (lstat(parent.value().c_str(), &stparent) != 0) {
717 PLOG(ERROR) << "Error stat'ing " << parent.value();
718 return false;
719 }
720 return S_ISDIR(stparent.st_mode) &&
721 (stparent.st_dev != stdir.st_dev || stparent.st_ino == stdir.st_ino);
722}
723
Alex Deymo032e7722014-03-25 17:53:56 -0700724// Tries to parse the header of an ELF file to obtain a human-readable
725// description of it on the |output| string.
Amin Hassanib2689592019-01-13 17:04:28 -0800726static bool GetFileFormatELF(const uint8_t* buffer,
727 size_t size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800728 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700729 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700730 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700731 return false;
732 *output = "ELF";
733
734 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700735 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700736 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700737 switch (buffer[EI_CLASS]) {
738 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700739 *output += " 32-bit";
740 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700741 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700742 *output += " 64-bit";
743 break;
744 default:
745 *output += " ?-bit";
746 }
747
748 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700749 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700750 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800751 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700752 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700753 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700754 *output += " little-endian";
755 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700756 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700757 *output += " big-endian";
758 break;
759 default:
760 *output += " ?-endian";
761 // Don't parse anything after the 0x10 offset if endianness is unknown.
762 return true;
763 }
764
Alex Deymoc1711e22014-08-08 13:16:23 -0700765 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
766 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
767 // and size is the same for both 32 and 64 bits.
768 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700769 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700770 uint16_t e_machine;
Sen Jiang771f6482018-04-04 17:59:10 -0700771 // Fix endianness regardless of the host endianness.
Alex Deymoc1711e22014-08-08 13:16:23 -0700772 if (ei_data == ELFDATA2LSB)
773 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700774 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700775 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700776
777 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700778 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700779 *output += " x86";
780 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700781 case EM_MIPS:
782 *output += " mips";
783 break;
784 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700785 *output += " arm";
786 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700787 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700788 *output += " x86-64";
789 break;
790 default:
791 *output += " unknown-arch";
792 }
793 return true;
794}
795
796string GetFileFormat(const string& path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700797 brillo::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700798 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
799 return "File not found.";
800
801 string result;
802 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
803 return result;
804
805 return "data";
806}
807
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700808int FuzzInt(int value, unsigned int range) {
809 int min = value - range / 2;
810 int max = value + range - range / 2;
811 return base::RandInt(min, max);
812}
813
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700814string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800815 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700816}
817
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800818string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400819 string str;
820
821 // Handle negative durations by prefixing with a minus.
822 if (delta.ToInternalValue() < 0) {
823 delta *= -1;
824 str = "-";
825 }
826
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700827 // Canonicalize into days, hours, minutes, seconds and microseconds.
828 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800829 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700830 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800831 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700832 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800833 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700834 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800835 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700836 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800837
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700838 if (days)
839 base::StringAppendF(&str, "%ud", days);
840 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800841 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700842 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800843 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700844 base::StringAppendF(&str, "%u", secs);
845 if (usecs) {
846 int width = 6;
847 while ((usecs / 10) * 10 == usecs) {
848 usecs /= 10;
849 width--;
850 }
851 base::StringAppendF(&str, ".%0*u", width, usecs);
852 }
853 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800854 return str;
855}
856
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700857string ToString(const Time utc_time) {
858 Time::Exploded exp_time;
859 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700860 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Amin Hassanib2689592019-01-13 17:04:28 -0800861 exp_time.month,
862 exp_time.day_of_month,
863 exp_time.year,
864 exp_time.hour,
865 exp_time.minute,
866 exp_time.second);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700867}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000868
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700869string ToString(bool b) {
870 return (b ? "true" : "false");
871}
872
Alex Deymo1c656c42013-06-28 11:02:14 -0700873string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700874 switch (source) {
Amin Hassanib2689592019-01-13 17:04:28 -0800875 case kDownloadSourceHttpsServer:
876 return "HttpsServer";
877 case kDownloadSourceHttpServer:
878 return "HttpServer";
879 case kDownloadSourceHttpPeer:
880 return "HttpPeer";
881 case kNumDownloadSources:
882 return "Unknown";
883 // Don't add a default case to let the compiler warn about newly added
884 // download sources which should be added here.
Jay Srinivasan19409b72013-04-12 19:23:36 -0700885 }
886
887 return "Unknown";
888}
889
Alex Deymo1c656c42013-06-28 11:02:14 -0700890string ToString(PayloadType payload_type) {
891 switch (payload_type) {
Amin Hassanib2689592019-01-13 17:04:28 -0800892 case kPayloadTypeDelta:
893 return "Delta";
894 case kPayloadTypeFull:
895 return "Full";
896 case kPayloadTypeForcedFull:
897 return "ForcedFull";
898 case kNumPayloadTypes:
899 return "Unknown";
900 // Don't add a default case to let the compiler warn about newly added
901 // payload types which should be added here.
Alex Deymo1c656c42013-06-28 11:02:14 -0700902 }
903
904 return "Unknown";
905}
906
David Zeuthena99981f2013-04-29 13:42:47 -0700907ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700908 // Ignore the higher order bits in the code by applying the mask as
909 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700910 // with values less than ErrorCode::kUmaReportedMax.
911 ErrorCode base_code = static_cast<ErrorCode>(
912 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700913
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800914 // Make additional adjustments required for UMA and error classification.
915 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
916 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700917 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700918 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800919 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800920 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700921 << " to ErrorCode::kOmahaErrorInHTTPResponse";
922 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700923 }
924
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800925 return base_code;
926}
927
Alex Deymof329b932014-10-30 01:37:48 -0700928string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700929 string str = "[";
Amin Hassanib2689592019-01-13 17:04:28 -0800930 for (vector<string>::const_iterator i = vec_str.begin(); i != vec_str.end();
931 ++i) {
Alex Deymof329b932014-10-30 01:37:48 -0700932 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -0700933 str += ", ";
934 str += '"';
935 str += *i;
936 str += '"';
937 }
938 str += "]";
939 return str;
940}
941
Sen Jiang2703ef42017-03-16 13:36:21 -0700942// The P2P file id should be the same for devices running new version and old
943// version so that they can share it with each other. The hash in the response
944// was base64 encoded, but now that we switched to use "hash_sha256" field which
945// is hex encoded, we have to convert them back to base64 for P2P. However, the
946// base64 encoded hash was base64 encoded here again historically for some
947// reason, so we keep the same behavior here.
948string CalculateP2PFileId(const brillo::Blob& payload_hash,
949 size_t payload_size) {
950 string encoded_hash = brillo::data_encoding::Base64Encode(
951 brillo::data_encoding::Base64Encode(payload_hash));
Alex Deymoc00c98a2015-03-17 17:38:00 -0700952 return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800953 payload_size,
954 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -0700955}
956
Alex Deymof329b932014-10-30 01:37:48 -0700957bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -0800958 time_t unix_time = time.ToTimeT();
959 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
960 const time_t kOmahaEpoch = 1167638400;
Amin Hassanib2689592019-01-13 17:04:28 -0800961 const int64_t kNumSecondsPerWeek = 7 * 24 * 3600;
David Zeuthen639aa362014-02-03 16:23:44 -0800962 const int64_t kNumDaysPerWeek = 7;
963
964 time_t omaha_time = unix_time - kOmahaEpoch;
965
966 if (omaha_time < 0)
967 return false;
968
969 // Note, as per the comment in utils.h we are deliberately not
970 // handling DST correctly.
971
972 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
973 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
974
975 return true;
976}
977
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700978bool GetMinorVersion(const brillo::KeyValueStore& store,
Alex Deymob42b98d2015-07-06 17:42:38 -0700979 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700980 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -0700981 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -0800982 if (!base::StringToUint(result, minor_version)) {
983 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
984 return false;
985 }
Allie Wood78750a42015-02-11 15:42:11 -0800986 return true;
987 }
988 return false;
989}
990
Amin Hassanib2689592019-01-13 17:04:28 -0800991bool ReadExtents(const string& path,
992 const vector<Extent>& extents,
993 brillo::Blob* out_data,
994 ssize_t out_data_size,
Allie Wood56873452015-03-27 17:48:40 -0700995 size_t block_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700996 brillo::Blob data(out_data_size);
Allie Wood56873452015-03-27 17:48:40 -0700997 ssize_t bytes_read = 0;
998 int fd = open(path.c_str(), O_RDONLY);
999 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
1000 ScopedFdCloser fd_closer(&fd);
1001
Gilad Arnold41e34742015-05-11 11:31:50 -07001002 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001003 ssize_t bytes_read_this_iteration = 0;
1004 ssize_t bytes = extent.num_blocks() * block_size;
1005 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
1006 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1007 &data[bytes_read],
1008 bytes,
1009 extent.start_block() * block_size,
1010 &bytes_read_this_iteration));
1011 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1012 bytes_read += bytes_read_this_iteration;
1013 }
1014 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1015 *out_data = data;
1016 return true;
1017}
1018
Alex Deymodd132f32015-09-14 19:12:07 -07001019bool GetBootId(string* boot_id) {
1020 TEST_AND_RETURN_FALSE(
1021 base::ReadFileToString(base::FilePath(kBootIdPath), boot_id));
1022 base::TrimWhitespaceASCII(*boot_id, base::TRIM_TRAILING, boot_id);
1023 return true;
1024}
1025
Marton Hunyadya0302682018-05-16 18:52:13 +02001026int VersionPrefix(const std::string& version) {
1027 if (version.empty()) {
1028 return 0;
1029 }
1030 vector<string> tokens = base::SplitString(
1031 version, ".", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
1032 int value;
1033 if (tokens.empty() || !base::StringToInt(tokens[0], &value))
1034 return -1; // Target version is invalid.
1035 return value;
1036}
1037
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -07001038void ParseRollbackKeyVersion(const string& raw_version,
1039 uint16_t* high_version,
1040 uint16_t* low_version) {
1041 DCHECK(high_version);
1042 DCHECK(low_version);
1043 *high_version = numeric_limits<uint16_t>::max();
1044 *low_version = numeric_limits<uint16_t>::max();
1045
1046 vector<string> parts = base::SplitString(
1047 raw_version, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
1048 if (parts.size() != 2) {
1049 // The version string must have exactly one period.
1050 return;
1051 }
1052
1053 int high;
1054 int low;
1055 if (!(base::StringToInt(parts[0], &high) &&
1056 base::StringToInt(parts[1], &low))) {
1057 // Both parts of the version could not be parsed correctly.
1058 return;
1059 }
1060
1061 if (high >= 0 && high < numeric_limits<uint16_t>::max() && low >= 0 &&
1062 low < numeric_limits<uint16_t>::max()) {
1063 *high_version = static_cast<uint16_t>(high);
1064 *low_version = static_cast<uint16_t>(low);
1065 }
1066}
1067
Kyeongkab.Nam500ca132019-06-26 13:48:07 +09001068string GetFilePath(int fd) {
1069 base::FilePath proc("/proc/self/fd/" + std::to_string(fd));
1070 base::FilePath file_name;
1071
1072 if (!base::ReadSymbolicLink(proc, &file_name)) {
1073 return "not found";
1074 }
1075 return file_name.value();
1076}
1077
Yifan Hongc80de2d2020-02-25 17:13:53 -08001078string GetTimeAsString(time_t utime) {
1079 struct tm tm;
1080 CHECK_EQ(localtime_r(&utime, &tm), &tm);
1081 char str[16];
1082 CHECK_EQ(strftime(str, sizeof(str), "%Y%m%d-%H%M%S", &tm), 15u);
1083 return str;
1084}
1085
adlr@google.com3defe6a2009-12-04 20:57:17 +00001086} // namespace utils
1087
1088} // namespace chromeos_update_engine