blob: b06954b05ae78a84d30a57e9f39ff7913c3c62ff [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 Arnold8e3f1262013-01-08 14:59:54 -080062using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000063using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070064using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000065using std::string;
66using std::vector;
67
68namespace chromeos_update_engine {
69
Ben Chan77a1eba2012-10-07 22:54:55 -070070namespace {
71
72// The following constants control how UnmountFilesystem should retry if
73// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
74// one second.
75const int kUnmountMaxNumOfRetries = 5;
76const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070077
78// Number of bytes to read from a file to attempt to detect its contents. Used
79// in GetFileFormat.
80const int kGetFileFormatMaxHeaderSize = 32;
81
Alex Deymodd132f32015-09-14 19:12:07 -070082// The path to the kernel's boot_id.
83const char kBootIdPath[] = "/proc/sys/kernel/random/boot_id";
84
Alex Deymo32951022016-08-10 17:02:49 -070085// A pointer to a null-terminated string containing the root directory where all
86// the temporary files should be created. If null, the system default is used
87// instead.
88const char* root_temp_dir = nullptr;
89
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080090// Return true if |disk_name| is an MTD or a UBI device. Note that this test is
91// simply based on the name of the device.
92bool IsMtdDeviceName(const string& disk_name) {
Alex Vakulenko0103c362016-01-20 07:56:15 -080093 return base::StartsWith(disk_name, "/dev/ubi",
94 base::CompareCase::SENSITIVE) ||
95 base::StartsWith(disk_name, "/dev/mtd", base::CompareCase::SENSITIVE);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080096}
97
98// Return the device name for the corresponding partition on a NAND device.
99// WARNING: This function returns device names that are not mountable.
100string MakeNandPartitionName(int partition_num) {
101 switch (partition_num) {
102 case 2:
103 case 4:
104 case 6: {
105 return base::StringPrintf("/dev/mtd%d", partition_num);
106 }
107 default: {
108 return base::StringPrintf("/dev/ubi%d_0", partition_num);
109 }
110 }
111}
112
113// Return the device name for the corresponding partition on a NAND device that
114// may be mountable (but may not be writable).
115string MakeNandPartitionNameForMount(int partition_num) {
116 switch (partition_num) {
117 case 2:
118 case 4:
119 case 6: {
120 return base::StringPrintf("/dev/mtd%d", partition_num);
121 }
122 case 3:
123 case 5:
124 case 7: {
125 return base::StringPrintf("/dev/ubiblock%d_0", partition_num);
126 }
127 default: {
128 return base::StringPrintf("/dev/ubi%d_0", partition_num);
129 }
130 }
131}
132
Alex Deymo5aa1c542015-09-18 01:02:33 -0700133// If |path| is absolute, or explicit relative to the current working directory,
134// leaves it as is. Otherwise, uses the system's temp directory, as defined by
135// base::GetTempDir() and prepends it to |path|. On success stores the full
136// temporary path in |template_path| and returns true.
137bool GetTempName(const string& path, base::FilePath* template_path) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800138 if (path[0] == '/' ||
139 base::StartsWith(path, "./", base::CompareCase::SENSITIVE) ||
140 base::StartsWith(path, "../", base::CompareCase::SENSITIVE)) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700141 *template_path = base::FilePath(path);
142 return true;
143 }
144
145 base::FilePath temp_dir;
Alex Deymo32951022016-08-10 17:02:49 -0700146 if (root_temp_dir) {
147 temp_dir = base::FilePath(root_temp_dir);
148 } else {
Sen Jiang9c123462015-11-19 13:16:23 -0800149#ifdef __ANDROID__
Alex Deymo32951022016-08-10 17:02:49 -0700150 temp_dir = base::FilePath(constants::kNonVolatileDirectory).Append("tmp");
151#else
152 TEST_AND_RETURN_FALSE(base::GetTempDir(&temp_dir));
153#endif // __ANDROID__
154 }
Sen Jiang9c123462015-11-19 13:16:23 -0800155 if (!base::PathExists(temp_dir))
156 TEST_AND_RETURN_FALSE(base::CreateDirectory(temp_dir));
Alex Deymo5aa1c542015-09-18 01:02:33 -0700157 *template_path = temp_dir.Append(path);
158 return true;
159}
160
Ben Chan77a1eba2012-10-07 22:54:55 -0700161} // namespace
162
adlr@google.com3defe6a2009-12-04 20:57:17 +0000163namespace utils {
164
Alex Deymo32951022016-08-10 17:02:49 -0700165void SetRootTempDir(const char* new_root_temp_dir) {
166 root_temp_dir = new_root_temp_dir;
167}
168
J. Richard Barnette63137e52013-10-28 10:57:29 -0700169string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -0700170 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -0700171
Alex Vakulenko75039d72014-03-25 12:36:28 -0700172 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -0700173 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -0700174 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -0700175 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -0800176 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -0700177 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800178 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -0700179 string output;
180 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800181 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -0700182 return output;
183 }
184 }
185 }
186 LOG(ERROR) << "Unable to parse fwid from ec info.";
187 return "";
188}
189
Alex Deymo335516c2016-11-28 13:37:06 -0800190bool WriteFile(const char* path, const void* data, size_t data_len) {
191 int fd = HANDLE_EINTR(open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600));
192 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
193 ScopedFdCloser fd_closer(&fd);
194 return WriteAll(fd, data, data_len);
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800195}
196
Alex Deymo0d298542016-03-30 18:31:49 -0700197bool ReadAll(
198 int fd, void* buf, size_t count, size_t* out_bytes_read, bool* eof) {
199 char* c_buf = static_cast<char*>(buf);
200 size_t bytes_read = 0;
201 *eof = false;
202 while (bytes_read < count) {
203 ssize_t rc = HANDLE_EINTR(read(fd, c_buf + bytes_read, count - bytes_read));
204 if (rc < 0) {
205 // EAGAIN and EWOULDBLOCK are normal return values when there's no more
206 // input and we are in non-blocking mode.
207 if (errno != EWOULDBLOCK && errno != EAGAIN) {
208 PLOG(ERROR) << "Error reading fd " << fd;
209 *out_bytes_read = bytes_read;
210 return false;
211 }
212 break;
213 } else if (rc == 0) {
214 // A value of 0 means that we reached EOF and there is nothing else to
215 // read from this fd.
216 *eof = true;
217 break;
218 } else {
219 bytes_read += rc;
220 }
221 }
222 *out_bytes_read = bytes_read;
223 return true;
224}
225
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700226bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700227 const char* c_buf = static_cast<const char*>(buf);
228 ssize_t bytes_written = 0;
229 while (bytes_written < static_cast<ssize_t>(count)) {
230 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
231 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
232 bytes_written += rc;
233 }
234 return true;
235}
236
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700237bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
238 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700239 size_t bytes_written = 0;
240 int num_attempts = 0;
241 while (bytes_written < count) {
242 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700243 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
244 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700245 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
246 if (rc < 0) {
247 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
248 << " bytes_written=" << bytes_written
249 << " count=" << count << " offset=" << offset;
250 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700251 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
252 bytes_written += rc;
253 }
254 return true;
255}
256
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700257bool WriteAll(const FileDescriptorPtr& fd, const void* buf, size_t count) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800258 const char* c_buf = static_cast<const char*>(buf);
259 ssize_t bytes_written = 0;
260 while (bytes_written < static_cast<ssize_t>(count)) {
261 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
262 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
263 bytes_written += rc;
264 }
265 return true;
266}
267
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700268bool PWriteAll(const FileDescriptorPtr& fd,
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800269 const void* buf,
270 size_t count,
271 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700272 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
273 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800274 return WriteAll(fd, buf, count);
275}
276
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700277bool PReadAll(int fd, void* buf, size_t count, off_t offset,
278 ssize_t* out_bytes_read) {
279 char* c_buf = static_cast<char*>(buf);
280 ssize_t bytes_read = 0;
281 while (bytes_read < static_cast<ssize_t>(count)) {
282 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
283 offset + bytes_read);
284 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
285 if (rc == 0) {
286 break;
287 }
288 bytes_read += rc;
289 }
290 *out_bytes_read = bytes_read;
291 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700292}
293
Marton Hunyadya0302682018-05-16 18:52:13 +0200294bool PReadAll(const FileDescriptorPtr& fd,
295 void* buf,
296 size_t count,
297 off_t offset,
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800298 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700299 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
300 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800301 char* c_buf = static_cast<char*>(buf);
302 ssize_t bytes_read = 0;
303 while (bytes_read < static_cast<ssize_t>(count)) {
304 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
305 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
306 if (rc == 0) {
307 break;
308 }
309 bytes_read += rc;
310 }
311 *out_bytes_read = bytes_read;
312 return true;
313}
314
Gilad Arnold19a45f02012-07-19 12:36:10 -0700315// Append |nbytes| of content from |buf| to the vector pointed to by either
316// |vec_p| or |str_p|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800317static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700318 brillo::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700319 CHECK(buf);
320 CHECK(vec_p);
321 vec_p->insert(vec_p->end(), buf, buf + nbytes);
322}
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800323static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700324 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700325 CHECK(buf);
326 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800327 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700328}
329
330// Reads from an open file |fp|, appending the read content to the container
331// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200332// file's content, false otherwise. If |size| is not -1, reads up to |size|
333// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700334template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200335static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700336 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200337 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800338 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200339 while (size == -1 || size > 0) {
340 off_t bytes_to_read = sizeof(buf);
341 if (size > 0 && bytes_to_read > size) {
342 bytes_to_read = size;
343 }
344 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
345 if (!nbytes) {
346 break;
347 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700348 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200349 if (size != -1) {
350 CHECK(size >= static_cast<off_t>(nbytes));
351 size -= nbytes;
352 }
353 }
354 if (ferror(fp)) {
355 return false;
356 }
357 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700358}
359
Darin Petkov8e447e02013-04-16 16:23:50 +0200360// Opens a file |path| for reading and appends its the contents to a container
361// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
362// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700363template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700364static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200365 off_t offset,
366 off_t size,
367 T* out_p) {
368 CHECK_GE(offset, 0);
369 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700370 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200371 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000372 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200373 if (offset) {
374 // Return success without appending any data if a chunk beyond the end of
375 // the file is requested.
376 if (offset >= FileSize(path)) {
377 return true;
378 }
379 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
380 }
381 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000382}
383
Alex Deymo10875d92014-11-10 21:52:57 -0800384// TODO(deymo): This is only used in unittest, but requires the private
385// Read<string>() defined here. Expose Read<string>() or move to base/ version.
386bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700387 FILE* fp = popen(cmd.c_str(), "r");
388 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000389 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200390 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700391 return (success && pclose(fp) >= 0);
392}
393
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700394bool ReadFile(const string& path, brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200395 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700396}
397
Darin Petkov8e447e02013-04-16 16:23:50 +0200398bool ReadFile(const string& path, string* out_p) {
399 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700400}
401
Darin Petkov8e447e02013-04-16 16:23:50 +0200402bool ReadFileChunk(const string& path, off_t offset, off_t size,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700403 brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200404 return ReadFileChunkAndAppend(path, offset, size, out_p);
405}
406
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700407off_t BlockDevSize(int fd) {
408 uint64_t dev_size;
409 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
410 if (rc == -1) {
411 dev_size = -1;
412 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
413 }
414 return dev_size;
415}
416
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700417off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700418 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700419 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700420 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700421 if (rc < 0) {
422 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700423 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700424 }
425 if (S_ISREG(stbuf.st_mode))
426 return stbuf.st_size;
427 if (S_ISBLK(stbuf.st_mode))
428 return BlockDevSize(fd);
429 LOG(ERROR) << "Couldn't determine the type of " << fd;
430 return -1;
431}
432
433off_t FileSize(const string& path) {
434 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
435 if (fd == -1) {
436 PLOG(ERROR) << "Error opening " << path;
437 return fd;
438 }
439 off_t size = FileSize(fd);
440 if (size == -1)
441 PLOG(ERROR) << "Error getting file size of " << path;
442 close(fd);
443 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700444}
445
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800446void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000447 LOG(INFO) << "Logging array of length: " << length;
448 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700449 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000450 const unsigned int bytes_remaining = length - i;
451 const unsigned int bytes_per_this_line = min(bytes_per_line,
452 bytes_remaining);
453 char header[100];
454 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
455 TEST_AND_RETURN(r == 13);
456 string line = header;
457 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
458 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800459 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000460 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
461 TEST_AND_RETURN(r == 3);
462 line += buf;
463 }
464 LOG(INFO) << line;
465 }
466}
467
Alex Deymof329b932014-10-30 01:37:48 -0700468bool SplitPartitionName(const string& partition_name,
469 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800470 int* out_partition_num) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800471 if (!base::StartsWith(partition_name, "/dev/",
472 base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800473 LOG(ERROR) << "Invalid partition device name: " << partition_name;
474 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700475 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800476
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700477 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
478 if (last_nondigit_pos == string::npos ||
479 (last_nondigit_pos + 1) == partition_name.size()) {
480 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800481 return false;
482 }
483
Alex Deymof329b932014-10-30 01:37:48 -0700484 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700485 if (partition_name[last_nondigit_pos] == '_') {
486 // NAND block devices have weird naming which could be something
487 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
488 size_t prev_nondigit_pos =
489 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
490 if (prev_nondigit_pos == string::npos ||
491 (prev_nondigit_pos + 1) == last_nondigit_pos) {
492 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
493 return false;
494 }
495
496 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
497 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800498 }
499
500 if (out_disk_name) {
501 // Special case for MMC devices which have the following naming scheme:
502 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700503 size_t disk_name_len = last_nondigit_pos;
504 if (partition_name[last_nondigit_pos] != 'p' ||
505 last_nondigit_pos == 0 ||
506 !isdigit(partition_name[last_nondigit_pos - 1])) {
507 disk_name_len++;
508 }
509 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800510 }
511
512 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700513 string partition_str = partition_name.substr(last_nondigit_pos + 1,
514 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800515 *out_partition_num = atoi(partition_str.c_str());
516 }
517 return true;
518}
519
Alex Deymof329b932014-10-30 01:37:48 -0700520string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800521 if (partition_num < 1) {
522 LOG(ERROR) << "Invalid partition number: " << partition_num;
523 return string();
524 }
525
Alex Vakulenko0103c362016-01-20 07:56:15 -0800526 if (!base::StartsWith(disk_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800527 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700528 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800529 }
530
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800531 if (IsMtdDeviceName(disk_name)) {
532 // Special case for UBI block devices.
533 // 1. ubiblock is not writable, we need to use plain "ubi".
534 // 2. There is a "_0" suffix.
535 return MakeNandPartitionName(partition_num);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800536 }
537
Alex Deymof329b932014-10-30 01:37:48 -0700538 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700539 if (isdigit(partition_name.back())) {
540 // Special case for devices with names ending with a digit.
541 // Add "p" to separate the disk name from partition number,
542 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800543 partition_name += 'p';
544 }
545
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700546 partition_name += std::to_string(partition_num);
547
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800548 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700549}
550
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800551string MakePartitionNameForMount(const string& part_name) {
552 if (IsMtdDeviceName(part_name)) {
553 int partition_num;
554 if (!SplitPartitionName(part_name, nullptr, &partition_num)) {
555 return "";
556 }
557 return MakeNandPartitionNameForMount(partition_num);
558 }
559 return part_name;
560}
561
Alex Deymof329b932014-10-30 01:37:48 -0700562string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000563 char buf[100];
564 buf[0] = '\0';
565 return strerror_r(err, buf, sizeof(buf));
566}
567
adlr@google.com3defe6a2009-12-04 20:57:17 +0000568bool FileExists(const char* path) {
569 struct stat stbuf;
570 return 0 == lstat(path, &stbuf);
571}
572
Darin Petkov30291ed2010-11-12 10:23:06 -0800573bool IsSymlink(const char* path) {
574 struct stat stbuf;
575 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
576}
577
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800578bool TryAttachingUbiVolume(int volume_num, int timeout) {
579 const string volume_path = base::StringPrintf("/dev/ubi%d_0", volume_num);
580 if (FileExists(volume_path.c_str())) {
581 return true;
582 }
583
584 int exit_code;
585 vector<string> cmd = {
586 "ubiattach",
587 "-m",
588 base::StringPrintf("%d", volume_num),
589 "-d",
590 base::StringPrintf("%d", volume_num)
591 };
592 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
593 TEST_AND_RETURN_FALSE(exit_code == 0);
594
595 cmd = {
596 "ubiblock",
597 "--create",
598 volume_path
599 };
600 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
601 TEST_AND_RETURN_FALSE(exit_code == 0);
602
603 while (timeout > 0 && !FileExists(volume_path.c_str())) {
604 sleep(1);
605 timeout--;
606 }
607
608 return FileExists(volume_path.c_str());
609}
610
Alex Deymof329b932014-10-30 01:37:48 -0700611bool MakeTempFile(const string& base_filename_template,
612 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700613 int* fd) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700614 base::FilePath filename_template;
615 TEST_AND_RETURN_FALSE(
616 GetTempName(base_filename_template, &filename_template));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700617 DCHECK(filename || fd);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700618 vector<char> buf(filename_template.value().size() + 1);
619 memcpy(buf.data(), filename_template.value().data(),
620 filename_template.value().size());
621 buf[filename_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700622
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800623 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700624 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
625 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800626 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700627 }
628 if (fd) {
629 *fd = mkstemp_fd;
630 } else {
631 close(mkstemp_fd);
632 }
633 return true;
634}
635
Alex Deymo5fb356c2016-03-25 18:48:22 -0700636bool SetBlockDeviceReadOnly(const string& device, bool read_only) {
637 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY | O_CLOEXEC));
638 if (fd < 0) {
639 PLOG(ERROR) << "Opening block device " << device;
640 return false;
641 }
642 ScopedFdCloser fd_closer(&fd);
643 // We take no action if not needed.
644 int read_only_flag;
645 int expected_flag = read_only ? 1 : 0;
646 int rc = ioctl(fd, BLKROGET, &read_only_flag);
647 // In case of failure reading the setting we will try to set it anyway.
648 if (rc == 0 && read_only_flag == expected_flag)
649 return true;
650
651 rc = ioctl(fd, BLKROSET, &expected_flag);
652 if (rc != 0) {
653 PLOG(ERROR) << "Marking block device " << device << " as read_only="
654 << expected_flag;
655 return false;
656 }
657 return true;
658}
659
adlr@google.com3defe6a2009-12-04 20:57:17 +0000660bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700661 const string& mountpoint,
Alex Deymo390efed2016-02-18 11:00:40 -0800662 unsigned long mountflags, // NOLINT(runtime/int)
Alex Deymo14dbd332016-03-01 18:55:54 -0800663 const string& type,
664 const string& fs_mount_options) {
Alex Deymo390efed2016-02-18 11:00:40 -0800665 vector<const char*> fstypes;
666 if (type.empty()) {
667 fstypes = {"ext2", "ext3", "ext4", "squashfs"};
668 } else {
669 fstypes = {type.c_str()};
670 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800671 for (const char* fstype : fstypes) {
672 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
Alex Deymo14dbd332016-03-01 18:55:54 -0800673 fs_mount_options.c_str());
Alex Deymo4c82df32014-11-10 22:25:57 -0800674 if (rc == 0)
675 return true;
676
677 PLOG(WARNING) << "Unable to mount destination device " << device
678 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000679 }
Alex Deymo390efed2016-02-18 11:00:40 -0800680 if (!type.empty()) {
681 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
682 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800683 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000684}
685
686bool UnmountFilesystem(const string& mountpoint) {
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700687 int num_retries = 1;
688 for (;; ++num_retries) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700689 if (umount(mountpoint.c_str()) == 0)
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700690 return true;
691 if (errno != EBUSY || num_retries >= kUnmountMaxNumOfRetries)
Ben Chan77a1eba2012-10-07 22:54:55 -0700692 break;
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700693 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700694 }
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700695 if (errno == EINVAL) {
696 LOG(INFO) << "Not a mountpoint: " << mountpoint;
697 return false;
698 }
699 PLOG(WARNING) << "Error unmounting " << mountpoint << " after " << num_retries
700 << " attempts. Lazy unmounting instead, error was";
701 if (umount2(mountpoint.c_str(), MNT_DETACH) != 0) {
702 PLOG(ERROR) << "Lazy unmount failed";
703 return false;
704 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000705 return true;
706}
707
Alex Deymof4116502017-03-22 17:00:31 -0700708bool IsMountpoint(const std::string& mountpoint) {
709 struct stat stdir, stparent;
710
711 // Check whether the passed mountpoint is a directory and the /.. is in the
712 // same device or not. If mountpoint/.. is in a different device it means that
713 // there is a filesystem mounted there. If it is not, but they both point to
714 // the same inode it basically is the special case of /.. pointing to /. This
715 // test doesn't play well with bind mount but that's out of the scope of what
716 // we want to detect here.
717 if (lstat(mountpoint.c_str(), &stdir) != 0) {
718 PLOG(ERROR) << "Error stat'ing " << mountpoint;
719 return false;
720 }
721 if (!S_ISDIR(stdir.st_mode))
722 return false;
723
724 base::FilePath parent(mountpoint);
725 parent = parent.Append("..");
726 if (lstat(parent.value().c_str(), &stparent) != 0) {
727 PLOG(ERROR) << "Error stat'ing " << parent.value();
728 return false;
729 }
730 return S_ISDIR(stparent.st_mode) &&
731 (stparent.st_dev != stdir.st_dev || stparent.st_ino == stdir.st_ino);
732}
733
Alex Deymo032e7722014-03-25 17:53:56 -0700734// Tries to parse the header of an ELF file to obtain a human-readable
735// description of it on the |output| string.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800736static bool GetFileFormatELF(const uint8_t* buffer, size_t size,
737 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700738 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700739 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700740 return false;
741 *output = "ELF";
742
743 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700744 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700745 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700746 switch (buffer[EI_CLASS]) {
747 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700748 *output += " 32-bit";
749 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700750 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700751 *output += " 64-bit";
752 break;
753 default:
754 *output += " ?-bit";
755 }
756
757 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700758 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700759 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800760 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700761 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700762 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700763 *output += " little-endian";
764 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700765 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700766 *output += " big-endian";
767 break;
768 default:
769 *output += " ?-endian";
770 // Don't parse anything after the 0x10 offset if endianness is unknown.
771 return true;
772 }
773
Alex Deymoc1711e22014-08-08 13:16:23 -0700774 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
775 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
776 // and size is the same for both 32 and 64 bits.
777 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700778 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700779 uint16_t e_machine;
Sen Jiang771f6482018-04-04 17:59:10 -0700780 // Fix endianness regardless of the host endianness.
Alex Deymoc1711e22014-08-08 13:16:23 -0700781 if (ei_data == ELFDATA2LSB)
782 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700783 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700784 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700785
786 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700787 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700788 *output += " x86";
789 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700790 case EM_MIPS:
791 *output += " mips";
792 break;
793 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700794 *output += " arm";
795 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700796 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700797 *output += " x86-64";
798 break;
799 default:
800 *output += " unknown-arch";
801 }
802 return true;
803}
804
805string GetFileFormat(const string& path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700806 brillo::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700807 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
808 return "File not found.";
809
810 string result;
811 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
812 return result;
813
814 return "data";
815}
816
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700817int FuzzInt(int value, unsigned int range) {
818 int min = value - range / 2;
819 int max = value + range - range / 2;
820 return base::RandInt(min, max);
821}
822
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700823string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800824 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700825}
826
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800827string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400828 string str;
829
830 // Handle negative durations by prefixing with a minus.
831 if (delta.ToInternalValue() < 0) {
832 delta *= -1;
833 str = "-";
834 }
835
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700836 // Canonicalize into days, hours, minutes, seconds and microseconds.
837 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800838 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700839 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800840 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700841 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800842 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700843 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800844 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700845 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800846
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700847 if (days)
848 base::StringAppendF(&str, "%ud", days);
849 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800850 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700851 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800852 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700853 base::StringAppendF(&str, "%u", secs);
854 if (usecs) {
855 int width = 6;
856 while ((usecs / 10) * 10 == usecs) {
857 usecs /= 10;
858 width--;
859 }
860 base::StringAppendF(&str, ".%0*u", width, usecs);
861 }
862 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800863 return str;
864}
865
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700866string ToString(const Time utc_time) {
867 Time::Exploded exp_time;
868 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700869 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700870 exp_time.month,
871 exp_time.day_of_month,
872 exp_time.year,
873 exp_time.hour,
874 exp_time.minute,
875 exp_time.second);
876}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000877
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700878string ToString(bool b) {
879 return (b ? "true" : "false");
880}
881
Alex Deymo1c656c42013-06-28 11:02:14 -0700882string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700883 switch (source) {
884 case kDownloadSourceHttpsServer: return "HttpsServer";
885 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700886 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700887 case kNumDownloadSources: return "Unknown";
888 // Don't add a default case to let the compiler warn about newly added
889 // download sources which should be added here.
890 }
891
892 return "Unknown";
893}
894
Alex Deymo1c656c42013-06-28 11:02:14 -0700895string ToString(PayloadType payload_type) {
896 switch (payload_type) {
897 case kPayloadTypeDelta: return "Delta";
898 case kPayloadTypeFull: return "Full";
899 case kPayloadTypeForcedFull: return "ForcedFull";
900 case kNumPayloadTypes: return "Unknown";
901 // Don't add a default case to let the compiler warn about newly added
902 // payload types which should be added here.
903 }
904
905 return "Unknown";
906}
907
David Zeuthena99981f2013-04-29 13:42:47 -0700908ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700909 // Ignore the higher order bits in the code by applying the mask as
910 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700911 // with values less than ErrorCode::kUmaReportedMax.
912 ErrorCode base_code = static_cast<ErrorCode>(
913 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700914
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800915 // Make additional adjustments required for UMA and error classification.
916 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
917 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700918 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700919 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800920 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800921 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700922 << " to ErrorCode::kOmahaErrorInHTTPResponse";
923 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700924 }
925
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800926 return base_code;
927}
928
David Zeuthen27a48bc2013-08-06 12:06:29 -0700929Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -0700930 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
931 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700932 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
933}
934
Alex Deymof329b932014-10-30 01:37:48 -0700935string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700936 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -0700937 for (vector<string>::const_iterator i = vec_str.begin();
938 i != vec_str.end(); ++i) {
939 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -0700940 str += ", ";
941 str += '"';
942 str += *i;
943 str += '"';
944 }
945 str += "]";
946 return str;
947}
948
Sen Jiang2703ef42017-03-16 13:36:21 -0700949// The P2P file id should be the same for devices running new version and old
950// version so that they can share it with each other. The hash in the response
951// was base64 encoded, but now that we switched to use "hash_sha256" field which
952// is hex encoded, we have to convert them back to base64 for P2P. However, the
953// base64 encoded hash was base64 encoded here again historically for some
954// reason, so we keep the same behavior here.
955string CalculateP2PFileId(const brillo::Blob& payload_hash,
956 size_t payload_size) {
957 string encoded_hash = brillo::data_encoding::Base64Encode(
958 brillo::data_encoding::Base64Encode(payload_hash));
Alex Deymoc00c98a2015-03-17 17:38:00 -0700959 return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800960 payload_size,
961 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -0700962}
963
Alex Deymof329b932014-10-30 01:37:48 -0700964bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -0700965 base::FilePath *out_path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700966 brillo::Blob contents;
David Zeuthene7f89172013-10-31 10:21:04 -0700967
968 out_path->clear();
969
970 if (base64_encoded.size() == 0) {
971 LOG(ERROR) << "Can't decode empty string.";
972 return false;
973 }
974
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700975 if (!brillo::data_encoding::Base64Decode(base64_encoded, &contents) ||
David Zeuthene7f89172013-10-31 10:21:04 -0700976 contents.size() == 0) {
977 LOG(ERROR) << "Error decoding base64.";
978 return false;
979 }
980
Alex Vakulenko75039d72014-03-25 12:36:28 -0700981 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700982 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -0700983 LOG(ERROR) << "Error creating temporary file.";
984 return false;
985 }
986
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800987 if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
David Zeuthene7f89172013-10-31 10:21:04 -0700988 PLOG(ERROR) << "Error writing to temporary file.";
989 if (fclose(file) != 0)
990 PLOG(ERROR) << "Error closing temporary file.";
991 if (unlink(out_path->value().c_str()) != 0)
992 PLOG(ERROR) << "Error unlinking temporary file.";
993 out_path->clear();
994 return false;
995 }
996
997 if (fclose(file) != 0) {
998 PLOG(ERROR) << "Error closing temporary file.";
999 out_path->clear();
1000 return false;
1001 }
1002
1003 return true;
1004}
1005
Alex Deymof329b932014-10-30 01:37:48 -07001006bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -08001007 time_t unix_time = time.ToTimeT();
1008 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1009 const time_t kOmahaEpoch = 1167638400;
1010 const int64_t kNumSecondsPerWeek = 7*24*3600;
1011 const int64_t kNumDaysPerWeek = 7;
1012
1013 time_t omaha_time = unix_time - kOmahaEpoch;
1014
1015 if (omaha_time < 0)
1016 return false;
1017
1018 // Note, as per the comment in utils.h we are deliberately not
1019 // handling DST correctly.
1020
1021 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1022 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1023
1024 return true;
1025}
1026
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001027bool GetMinorVersion(const brillo::KeyValueStore& store,
Alex Deymob42b98d2015-07-06 17:42:38 -07001028 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001029 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -07001030 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -08001031 if (!base::StringToUint(result, minor_version)) {
1032 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
1033 return false;
1034 }
Allie Wood78750a42015-02-11 15:42:11 -08001035 return true;
1036 }
1037 return false;
1038}
1039
Alex Deymo60ca1a72015-06-18 18:19:15 -07001040bool ReadExtents(const string& path, const vector<Extent>& extents,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001041 brillo::Blob* out_data, ssize_t out_data_size,
Allie Wood56873452015-03-27 17:48:40 -07001042 size_t block_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001043 brillo::Blob data(out_data_size);
Allie Wood56873452015-03-27 17:48:40 -07001044 ssize_t bytes_read = 0;
1045 int fd = open(path.c_str(), O_RDONLY);
1046 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
1047 ScopedFdCloser fd_closer(&fd);
1048
Gilad Arnold41e34742015-05-11 11:31:50 -07001049 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001050 ssize_t bytes_read_this_iteration = 0;
1051 ssize_t bytes = extent.num_blocks() * block_size;
1052 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
1053 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1054 &data[bytes_read],
1055 bytes,
1056 extent.start_block() * block_size,
1057 &bytes_read_this_iteration));
1058 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1059 bytes_read += bytes_read_this_iteration;
1060 }
1061 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1062 *out_data = data;
1063 return true;
1064}
1065
Alex Deymodd132f32015-09-14 19:12:07 -07001066bool GetBootId(string* boot_id) {
1067 TEST_AND_RETURN_FALSE(
1068 base::ReadFileToString(base::FilePath(kBootIdPath), boot_id));
1069 base::TrimWhitespaceASCII(*boot_id, base::TRIM_TRAILING, boot_id);
1070 return true;
1071}
1072
Marton Hunyadya0302682018-05-16 18:52:13 +02001073int VersionPrefix(const std::string& version) {
1074 if (version.empty()) {
1075 return 0;
1076 }
1077 vector<string> tokens = base::SplitString(
1078 version, ".", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
1079 int value;
1080 if (tokens.empty() || !base::StringToInt(tokens[0], &value))
1081 return -1; // Target version is invalid.
1082 return value;
1083}
1084
adlr@google.com3defe6a2009-12-04 20:57:17 +00001085} // namespace utils
1086
1087} // namespace chromeos_update_engine