blob: 2ac63b93e61b8fdf01cc382179e6eb953acbf897 [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"
60#include "update_engine/payload_consumer/file_writer.h"
Sen Jiange0d04282016-03-01 14:22:52 -080061#include "update_engine/payload_consumer/payload_constants.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000062
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070063using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080064using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000065using std::min;
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) {
Alex Vakulenko0103c362016-01-20 07:56:15 -080090 return base::StartsWith(disk_name, "/dev/ubi",
91 base::CompareCase::SENSITIVE) ||
92 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__
144 temp_dir = base::FilePath(constants::kNonVolatileDirectory).Append("tmp");
145 if (!base::PathExists(temp_dir))
146 TEST_AND_RETURN_FALSE(base::CreateDirectory(temp_dir));
147#else
Alex Deymo5aa1c542015-09-18 01:02:33 -0700148 TEST_AND_RETURN_FALSE(base::GetTempDir(&temp_dir));
Sen Jiang9c123462015-11-19 13:16:23 -0800149#endif // __ANDROID__
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 Vakulenkof68bbbc2015-02-09 12:53:18 -0800179bool WriteFile(const char* path, const void* data, int data_len) {
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800180 DirectFileWriter writer;
181 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
182 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700183 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800184 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800185 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800186 return true;
187}
188
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700189bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700190 const char* c_buf = static_cast<const char*>(buf);
191 ssize_t bytes_written = 0;
192 while (bytes_written < static_cast<ssize_t>(count)) {
193 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
194 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
195 bytes_written += rc;
196 }
197 return true;
198}
199
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700200bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
201 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700202 size_t bytes_written = 0;
203 int num_attempts = 0;
204 while (bytes_written < count) {
205 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700206 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
207 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700208 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
209 if (rc < 0) {
210 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
211 << " bytes_written=" << bytes_written
212 << " count=" << count << " offset=" << offset;
213 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700214 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
215 bytes_written += rc;
216 }
217 return true;
218}
219
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800220bool WriteAll(FileDescriptorPtr fd, const void* buf, size_t count) {
221 const char* c_buf = static_cast<const char*>(buf);
222 ssize_t bytes_written = 0;
223 while (bytes_written < static_cast<ssize_t>(count)) {
224 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
225 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
226 bytes_written += rc;
227 }
228 return true;
229}
230
231bool PWriteAll(FileDescriptorPtr fd,
232 const void* buf,
233 size_t count,
234 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700235 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
236 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800237 return WriteAll(fd, buf, count);
238}
239
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700240bool PReadAll(int fd, void* buf, size_t count, off_t offset,
241 ssize_t* out_bytes_read) {
242 char* c_buf = static_cast<char*>(buf);
243 ssize_t bytes_read = 0;
244 while (bytes_read < static_cast<ssize_t>(count)) {
245 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
246 offset + bytes_read);
247 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
248 if (rc == 0) {
249 break;
250 }
251 bytes_read += rc;
252 }
253 *out_bytes_read = bytes_read;
254 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700255}
256
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800257bool PReadAll(FileDescriptorPtr fd, void* buf, size_t count, off_t offset,
258 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700259 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
260 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800261 char* c_buf = static_cast<char*>(buf);
262 ssize_t bytes_read = 0;
263 while (bytes_read < static_cast<ssize_t>(count)) {
264 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
265 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
266 if (rc == 0) {
267 break;
268 }
269 bytes_read += rc;
270 }
271 *out_bytes_read = bytes_read;
272 return true;
273}
274
Gilad Arnold19a45f02012-07-19 12:36:10 -0700275// Append |nbytes| of content from |buf| to the vector pointed to by either
276// |vec_p| or |str_p|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800277static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700278 brillo::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700279 CHECK(buf);
280 CHECK(vec_p);
281 vec_p->insert(vec_p->end(), buf, buf + nbytes);
282}
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800283static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700284 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700285 CHECK(buf);
286 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800287 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700288}
289
290// Reads from an open file |fp|, appending the read content to the container
291// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200292// file's content, false otherwise. If |size| is not -1, reads up to |size|
293// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700294template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200295static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700296 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200297 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800298 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200299 while (size == -1 || size > 0) {
300 off_t bytes_to_read = sizeof(buf);
301 if (size > 0 && bytes_to_read > size) {
302 bytes_to_read = size;
303 }
304 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
305 if (!nbytes) {
306 break;
307 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700308 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200309 if (size != -1) {
310 CHECK(size >= static_cast<off_t>(nbytes));
311 size -= nbytes;
312 }
313 }
314 if (ferror(fp)) {
315 return false;
316 }
317 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700318}
319
Darin Petkov8e447e02013-04-16 16:23:50 +0200320// Opens a file |path| for reading and appends its the contents to a container
321// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
322// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700323template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700324static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200325 off_t offset,
326 off_t size,
327 T* out_p) {
328 CHECK_GE(offset, 0);
329 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700330 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200331 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000332 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200333 if (offset) {
334 // Return success without appending any data if a chunk beyond the end of
335 // the file is requested.
336 if (offset >= FileSize(path)) {
337 return true;
338 }
339 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
340 }
341 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000342}
343
Alex Deymo10875d92014-11-10 21:52:57 -0800344// TODO(deymo): This is only used in unittest, but requires the private
345// Read<string>() defined here. Expose Read<string>() or move to base/ version.
346bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700347 FILE* fp = popen(cmd.c_str(), "r");
348 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000349 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200350 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700351 return (success && pclose(fp) >= 0);
352}
353
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700354bool ReadFile(const string& path, brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200355 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700356}
357
Darin Petkov8e447e02013-04-16 16:23:50 +0200358bool ReadFile(const string& path, string* out_p) {
359 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700360}
361
Darin Petkov8e447e02013-04-16 16:23:50 +0200362bool ReadFileChunk(const string& path, off_t offset, off_t size,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700363 brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200364 return ReadFileChunkAndAppend(path, offset, size, out_p);
365}
366
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700367off_t BlockDevSize(int fd) {
368 uint64_t dev_size;
369 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
370 if (rc == -1) {
371 dev_size = -1;
372 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
373 }
374 return dev_size;
375}
376
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700377off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700378 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700379 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700380 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700381 if (rc < 0) {
382 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700383 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700384 }
385 if (S_ISREG(stbuf.st_mode))
386 return stbuf.st_size;
387 if (S_ISBLK(stbuf.st_mode))
388 return BlockDevSize(fd);
389 LOG(ERROR) << "Couldn't determine the type of " << fd;
390 return -1;
391}
392
393off_t FileSize(const string& path) {
394 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
395 if (fd == -1) {
396 PLOG(ERROR) << "Error opening " << path;
397 return fd;
398 }
399 off_t size = FileSize(fd);
400 if (size == -1)
401 PLOG(ERROR) << "Error getting file size of " << path;
402 close(fd);
403 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700404}
405
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800406void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000407 LOG(INFO) << "Logging array of length: " << length;
408 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700409 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000410 const unsigned int bytes_remaining = length - i;
411 const unsigned int bytes_per_this_line = min(bytes_per_line,
412 bytes_remaining);
413 char header[100];
414 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
415 TEST_AND_RETURN(r == 13);
416 string line = header;
417 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
418 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800419 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000420 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
421 TEST_AND_RETURN(r == 3);
422 line += buf;
423 }
424 LOG(INFO) << line;
425 }
426}
427
Alex Deymof329b932014-10-30 01:37:48 -0700428bool SplitPartitionName(const string& partition_name,
429 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800430 int* out_partition_num) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800431 if (!base::StartsWith(partition_name, "/dev/",
432 base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800433 LOG(ERROR) << "Invalid partition device name: " << partition_name;
434 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700435 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800436
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700437 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
438 if (last_nondigit_pos == string::npos ||
439 (last_nondigit_pos + 1) == partition_name.size()) {
440 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800441 return false;
442 }
443
Alex Deymof329b932014-10-30 01:37:48 -0700444 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700445 if (partition_name[last_nondigit_pos] == '_') {
446 // NAND block devices have weird naming which could be something
447 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
448 size_t prev_nondigit_pos =
449 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
450 if (prev_nondigit_pos == string::npos ||
451 (prev_nondigit_pos + 1) == last_nondigit_pos) {
452 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
453 return false;
454 }
455
456 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
457 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800458 }
459
460 if (out_disk_name) {
461 // Special case for MMC devices which have the following naming scheme:
462 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700463 size_t disk_name_len = last_nondigit_pos;
464 if (partition_name[last_nondigit_pos] != 'p' ||
465 last_nondigit_pos == 0 ||
466 !isdigit(partition_name[last_nondigit_pos - 1])) {
467 disk_name_len++;
468 }
469 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800470 }
471
472 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700473 string partition_str = partition_name.substr(last_nondigit_pos + 1,
474 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800475 *out_partition_num = atoi(partition_str.c_str());
476 }
477 return true;
478}
479
Alex Deymof329b932014-10-30 01:37:48 -0700480string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800481 if (partition_num < 1) {
482 LOG(ERROR) << "Invalid partition number: " << partition_num;
483 return string();
484 }
485
Alex Vakulenko0103c362016-01-20 07:56:15 -0800486 if (!base::StartsWith(disk_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800487 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700488 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800489 }
490
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800491 if (IsMtdDeviceName(disk_name)) {
492 // Special case for UBI block devices.
493 // 1. ubiblock is not writable, we need to use plain "ubi".
494 // 2. There is a "_0" suffix.
495 return MakeNandPartitionName(partition_num);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800496 }
497
Alex Deymof329b932014-10-30 01:37:48 -0700498 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700499 if (isdigit(partition_name.back())) {
500 // Special case for devices with names ending with a digit.
501 // Add "p" to separate the disk name from partition number,
502 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800503 partition_name += 'p';
504 }
505
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700506 partition_name += std::to_string(partition_num);
507
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800508 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700509}
510
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800511string MakePartitionNameForMount(const string& part_name) {
512 if (IsMtdDeviceName(part_name)) {
513 int partition_num;
514 if (!SplitPartitionName(part_name, nullptr, &partition_num)) {
515 return "";
516 }
517 return MakeNandPartitionNameForMount(partition_num);
518 }
519 return part_name;
520}
521
Alex Deymof329b932014-10-30 01:37:48 -0700522string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000523 char buf[100];
524 buf[0] = '\0';
525 return strerror_r(err, buf, sizeof(buf));
526}
527
adlr@google.com3defe6a2009-12-04 20:57:17 +0000528bool FileExists(const char* path) {
529 struct stat stbuf;
530 return 0 == lstat(path, &stbuf);
531}
532
Darin Petkov30291ed2010-11-12 10:23:06 -0800533bool IsSymlink(const char* path) {
534 struct stat stbuf;
535 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
536}
537
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800538bool TryAttachingUbiVolume(int volume_num, int timeout) {
539 const string volume_path = base::StringPrintf("/dev/ubi%d_0", volume_num);
540 if (FileExists(volume_path.c_str())) {
541 return true;
542 }
543
544 int exit_code;
545 vector<string> cmd = {
546 "ubiattach",
547 "-m",
548 base::StringPrintf("%d", volume_num),
549 "-d",
550 base::StringPrintf("%d", volume_num)
551 };
552 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
553 TEST_AND_RETURN_FALSE(exit_code == 0);
554
555 cmd = {
556 "ubiblock",
557 "--create",
558 volume_path
559 };
560 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
561 TEST_AND_RETURN_FALSE(exit_code == 0);
562
563 while (timeout > 0 && !FileExists(volume_path.c_str())) {
564 sleep(1);
565 timeout--;
566 }
567
568 return FileExists(volume_path.c_str());
569}
570
Alex Deymof329b932014-10-30 01:37:48 -0700571bool MakeTempFile(const string& base_filename_template,
572 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700573 int* fd) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700574 base::FilePath filename_template;
575 TEST_AND_RETURN_FALSE(
576 GetTempName(base_filename_template, &filename_template));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700577 DCHECK(filename || fd);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700578 vector<char> buf(filename_template.value().size() + 1);
579 memcpy(buf.data(), filename_template.value().data(),
580 filename_template.value().size());
581 buf[filename_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700582
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800583 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700584 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
585 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800586 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700587 }
588 if (fd) {
589 *fd = mkstemp_fd;
590 } else {
591 close(mkstemp_fd);
592 }
593 return true;
594}
595
Alex Deymof329b932014-10-30 01:37:48 -0700596bool MakeTempDirectory(const string& base_dirname_template,
597 string* dirname) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700598 base::FilePath dirname_template;
599 TEST_AND_RETURN_FALSE(GetTempName(base_dirname_template, &dirname_template));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700600 DCHECK(dirname);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700601 vector<char> buf(dirname_template.value().size() + 1);
602 memcpy(buf.data(), dirname_template.value().data(),
603 dirname_template.value().size());
604 buf[dirname_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700605
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800606 char* return_code = mkdtemp(buf.data());
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700607 TEST_AND_RETURN_FALSE_ERRNO(return_code != nullptr);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800608 *dirname = buf.data();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700609 return true;
610}
611
adlr@google.com3defe6a2009-12-04 20:57:17 +0000612bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700613 const string& mountpoint,
Alex Deymo390efed2016-02-18 11:00:40 -0800614 unsigned long mountflags, // NOLINT(runtime/int)
Alex Deymo14dbd332016-03-01 18:55:54 -0800615 const string& type,
616 const string& fs_mount_options) {
Alex Deymo390efed2016-02-18 11:00:40 -0800617 vector<const char*> fstypes;
618 if (type.empty()) {
619 fstypes = {"ext2", "ext3", "ext4", "squashfs"};
620 } else {
621 fstypes = {type.c_str()};
622 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800623 for (const char* fstype : fstypes) {
624 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
Alex Deymo14dbd332016-03-01 18:55:54 -0800625 fs_mount_options.c_str());
Alex Deymo4c82df32014-11-10 22:25:57 -0800626 if (rc == 0)
627 return true;
628
629 PLOG(WARNING) << "Unable to mount destination device " << device
630 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000631 }
Alex Deymo390efed2016-02-18 11:00:40 -0800632 if (!type.empty()) {
633 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
634 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800635 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000636}
637
638bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700639 for (int num_retries = 0; ; ++num_retries) {
640 if (umount(mountpoint.c_str()) == 0)
641 break;
642
643 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
644 num_retries < kUnmountMaxNumOfRetries);
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700645 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700646 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000647 return true;
648}
649
Alex Deymo032e7722014-03-25 17:53:56 -0700650// Tries to parse the header of an ELF file to obtain a human-readable
651// description of it on the |output| string.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800652static bool GetFileFormatELF(const uint8_t* buffer, size_t size,
653 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700654 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700655 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700656 return false;
657 *output = "ELF";
658
659 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700660 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700661 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700662 switch (buffer[EI_CLASS]) {
663 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700664 *output += " 32-bit";
665 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700666 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700667 *output += " 64-bit";
668 break;
669 default:
670 *output += " ?-bit";
671 }
672
673 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700674 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700675 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800676 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700677 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700678 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700679 *output += " little-endian";
680 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700681 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700682 *output += " big-endian";
683 break;
684 default:
685 *output += " ?-endian";
686 // Don't parse anything after the 0x10 offset if endianness is unknown.
687 return true;
688 }
689
Alex Deymoc1711e22014-08-08 13:16:23 -0700690 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
691 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
692 // and size is the same for both 32 and 64 bits.
693 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700694 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700695 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700696 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700697 if (ei_data == ELFDATA2LSB)
698 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700699 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700700 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700701
702 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700703 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700704 *output += " x86";
705 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700706 case EM_MIPS:
707 *output += " mips";
708 break;
709 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700710 *output += " arm";
711 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700712 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700713 *output += " x86-64";
714 break;
715 default:
716 *output += " unknown-arch";
717 }
718 return true;
719}
720
721string GetFileFormat(const string& path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700722 brillo::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700723 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
724 return "File not found.";
725
726 string result;
727 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
728 return result;
729
730 return "data";
731}
732
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700733int FuzzInt(int value, unsigned int range) {
734 int min = value - range / 2;
735 int max = value + range - range / 2;
736 return base::RandInt(min, max);
737}
738
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700739string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800740 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700741}
742
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800743string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400744 string str;
745
746 // Handle negative durations by prefixing with a minus.
747 if (delta.ToInternalValue() < 0) {
748 delta *= -1;
749 str = "-";
750 }
751
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700752 // Canonicalize into days, hours, minutes, seconds and microseconds.
753 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800754 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700755 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800756 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700757 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800758 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700759 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800760 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700761 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800762
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700763 if (days)
764 base::StringAppendF(&str, "%ud", days);
765 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800766 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700767 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800768 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700769 base::StringAppendF(&str, "%u", secs);
770 if (usecs) {
771 int width = 6;
772 while ((usecs / 10) * 10 == usecs) {
773 usecs /= 10;
774 width--;
775 }
776 base::StringAppendF(&str, ".%0*u", width, usecs);
777 }
778 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800779 return str;
780}
781
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700782string ToString(const Time utc_time) {
783 Time::Exploded exp_time;
784 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700785 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700786 exp_time.month,
787 exp_time.day_of_month,
788 exp_time.year,
789 exp_time.hour,
790 exp_time.minute,
791 exp_time.second);
792}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000793
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700794string ToString(bool b) {
795 return (b ? "true" : "false");
796}
797
Alex Deymo1c656c42013-06-28 11:02:14 -0700798string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700799 switch (source) {
800 case kDownloadSourceHttpsServer: return "HttpsServer";
801 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700802 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700803 case kNumDownloadSources: return "Unknown";
804 // Don't add a default case to let the compiler warn about newly added
805 // download sources which should be added here.
806 }
807
808 return "Unknown";
809}
810
Alex Deymo1c656c42013-06-28 11:02:14 -0700811string ToString(PayloadType payload_type) {
812 switch (payload_type) {
813 case kPayloadTypeDelta: return "Delta";
814 case kPayloadTypeFull: return "Full";
815 case kPayloadTypeForcedFull: return "ForcedFull";
816 case kNumPayloadTypes: return "Unknown";
817 // Don't add a default case to let the compiler warn about newly added
818 // payload types which should be added here.
819 }
820
821 return "Unknown";
822}
823
David Zeuthena99981f2013-04-29 13:42:47 -0700824ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700825 // Ignore the higher order bits in the code by applying the mask as
826 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700827 // with values less than ErrorCode::kUmaReportedMax.
828 ErrorCode base_code = static_cast<ErrorCode>(
829 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700830
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800831 // Make additional adjustments required for UMA and error classification.
832 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
833 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700834 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700835 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800836 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800837 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700838 << " to ErrorCode::kOmahaErrorInHTTPResponse";
839 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700840 }
841
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800842 return base_code;
843}
844
Gilad Arnold30dedd82013-07-03 06:19:09 -0700845bool CreatePowerwashMarkerFile(const char* file_path) {
846 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
847 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700848 kPowerwashCommand,
849 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -0700850 if (result) {
851 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
852 } else {
853 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
854 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700855
856 return result;
857}
858
Gilad Arnold30dedd82013-07-03 06:19:09 -0700859bool DeletePowerwashMarkerFile(const char* file_path) {
860 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -0700861 const base::FilePath kPowerwashMarkerPath(marker_file);
862 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700863
864 if (result)
865 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -0700866 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700867 else
868 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -0700869 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700870
871 return result;
872}
873
David Zeuthen27a48bc2013-08-06 12:06:29 -0700874Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -0700875 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
876 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700877 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
878}
879
Alex Deymof329b932014-10-30 01:37:48 -0700880string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700881 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -0700882 for (vector<string>::const_iterator i = vec_str.begin();
883 i != vec_str.end(); ++i) {
884 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -0700885 str += ", ";
886 str += '"';
887 str += *i;
888 str += '"';
889 }
890 str += "]";
891 return str;
892}
893
David Zeuthen8f191b22013-08-06 12:27:50 -0700894string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700895 string encoded_hash = brillo::data_encoding::Base64Encode(payload_hash);
Alex Deymoc00c98a2015-03-17 17:38:00 -0700896 return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800897 payload_size,
898 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -0700899}
900
Alex Deymof329b932014-10-30 01:37:48 -0700901bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -0700902 base::FilePath *out_path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700903 brillo::Blob contents;
David Zeuthene7f89172013-10-31 10:21:04 -0700904
905 out_path->clear();
906
907 if (base64_encoded.size() == 0) {
908 LOG(ERROR) << "Can't decode empty string.";
909 return false;
910 }
911
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700912 if (!brillo::data_encoding::Base64Decode(base64_encoded, &contents) ||
David Zeuthene7f89172013-10-31 10:21:04 -0700913 contents.size() == 0) {
914 LOG(ERROR) << "Error decoding base64.";
915 return false;
916 }
917
Alex Vakulenko75039d72014-03-25 12:36:28 -0700918 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700919 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -0700920 LOG(ERROR) << "Error creating temporary file.";
921 return false;
922 }
923
Alex Vakulenko981a9fb2015-02-09 12:51:24 -0800924 if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
David Zeuthene7f89172013-10-31 10:21:04 -0700925 PLOG(ERROR) << "Error writing to temporary file.";
926 if (fclose(file) != 0)
927 PLOG(ERROR) << "Error closing temporary file.";
928 if (unlink(out_path->value().c_str()) != 0)
929 PLOG(ERROR) << "Error unlinking temporary file.";
930 out_path->clear();
931 return false;
932 }
933
934 if (fclose(file) != 0) {
935 PLOG(ERROR) << "Error closing temporary file.";
936 out_path->clear();
937 return false;
938 }
939
940 return true;
941}
942
Alex Deymof329b932014-10-30 01:37:48 -0700943bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -0800944 time_t unix_time = time.ToTimeT();
945 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
946 const time_t kOmahaEpoch = 1167638400;
947 const int64_t kNumSecondsPerWeek = 7*24*3600;
948 const int64_t kNumDaysPerWeek = 7;
949
950 time_t omaha_time = unix_time - kOmahaEpoch;
951
952 if (omaha_time < 0)
953 return false;
954
955 // Note, as per the comment in utils.h we are deliberately not
956 // handling DST correctly.
957
958 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
959 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
960
961 return true;
962}
963
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700964bool GetMinorVersion(const brillo::KeyValueStore& store,
Alex Deymob42b98d2015-07-06 17:42:38 -0700965 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700966 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -0700967 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -0800968 if (!base::StringToUint(result, minor_version)) {
969 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
970 return false;
971 }
Allie Wood78750a42015-02-11 15:42:11 -0800972 return true;
973 }
974 return false;
975}
976
Sen Jiange0d04282016-03-01 14:22:52 -0800977bool IsZlibCompatible(const string& fingerprint) {
978 if (fingerprint.size() != sizeof(kCompatibleZlibFingerprint[0]) - 1) {
979 LOG(ERROR) << "Invalid fingerprint: " << fingerprint;
980 return false;
981 }
982 for (auto& f : kCompatibleZlibFingerprint) {
983 if (base::CompareCaseInsensitiveASCII(fingerprint, f) == 0) {
984 return true;
985 }
986 }
987 return false;
988}
989
Alex Deymo60ca1a72015-06-18 18:19:15 -0700990bool ReadExtents(const string& path, const vector<Extent>& extents,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700991 brillo::Blob* out_data, ssize_t out_data_size,
Allie Wood56873452015-03-27 17:48:40 -0700992 size_t block_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700993 brillo::Blob data(out_data_size);
Allie Wood56873452015-03-27 17:48:40 -0700994 ssize_t bytes_read = 0;
995 int fd = open(path.c_str(), O_RDONLY);
996 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
997 ScopedFdCloser fd_closer(&fd);
998
Gilad Arnold41e34742015-05-11 11:31:50 -0700999 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001000 ssize_t bytes_read_this_iteration = 0;
1001 ssize_t bytes = extent.num_blocks() * block_size;
1002 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
1003 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1004 &data[bytes_read],
1005 bytes,
1006 extent.start_block() * block_size,
1007 &bytes_read_this_iteration));
1008 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1009 bytes_read += bytes_read_this_iteration;
1010 }
1011 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1012 *out_data = data;
1013 return true;
1014}
1015
Alex Deymodd132f32015-09-14 19:12:07 -07001016bool GetBootId(string* boot_id) {
1017 TEST_AND_RETURN_FALSE(
1018 base::ReadFileToString(base::FilePath(kBootIdPath), boot_id));
1019 base::TrimWhitespaceASCII(*boot_id, base::TRIM_TRAILING, boot_id);
1020 return true;
1021}
1022
adlr@google.com3defe6a2009-12-04 20:57:17 +00001023} // namespace utils
1024
1025} // namespace chromeos_update_engine