blob: f36cbec956bc3d94b1e5f8877b6340e62bb4f8b8 [file] [log] [blame]
Mike Frysinger8155d082012-04-06 15:23:18 -04001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
adlr@google.com3defe6a2009-12-04 20:57:17 +00002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/utils.h"
Darin Petkovf74eb652010-08-04 12:08:38 -07006
Ben Chan9abb7632014-08-07 00:10:53 -07007#include <stdint.h>
8
adlr@google.com3defe6a2009-12-04 20:57:17 +00009#include <dirent.h>
Alex Deymoc1711e22014-08-08 13:16:23 -070010#include <elf.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000011#include <errno.h>
Alex Deymo192393b2014-11-10 15:58:38 -080012#include <ext2fs/ext2fs.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080013#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000014#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
Alex Deymoc4acdf42014-05-28 21:07:10 -070017#include <sys/mount.h>
18#include <sys/resource.h>
19#include <sys/stat.h>
20#include <sys/types.h>
21#include <sys/wait.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000022#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070023
adlr@google.com3defe6a2009-12-04 20:57:17 +000024#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070025#include <utility>
Chris Sosac1972482013-04-30 22:31:10 -070026#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070027
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070028#include <base/callback.h>
Ben Chan736fcb52014-05-21 18:28:22 -070029#include <base/files/file_path.h>
Alex Deymo192393b2014-11-10 15:58:38 -080030#include <base/files/file_util.h>
Ben Chan736fcb52014-05-21 18:28:22 -070031#include <base/files/scoped_file.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070032#include <base/location.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040033#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080034#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050035#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070036#include <base/strings/string_number_conversions.h>
37#include <base/strings/string_split.h>
38#include <base/strings/string_util.h>
39#include <base/strings/stringprintf.h>
Alex Vakulenko981a9fb2015-02-09 12:51:24 -080040#include <chromeos/data_encoding.h>
Allie Wood78750a42015-02-11 15:42:11 -080041#include <chromeos/key_value_store.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070042#include <chromeos/message_loops/message_loop.h>
Will Drewry8f71da82010-08-30 14:07:11 -050043
David Zeuthen33bae492014-02-25 16:16:18 -080044#include "update_engine/clock_interface.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070045#include "update_engine/constants.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080046#include "update_engine/file_descriptor.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080047#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070048#include "update_engine/omaha_request_params.h"
David Zeuthen33bae492014-02-25 16:16:18 -080049#include "update_engine/prefs_interface.h"
Darin Petkov296889c2010-07-23 16:20:54 -070050#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080051#include "update_engine/system_state.h"
52#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000053
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070054using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080055using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000056using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070057using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000058using std::string;
59using std::vector;
60
61namespace chromeos_update_engine {
62
Ben Chan77a1eba2012-10-07 22:54:55 -070063namespace {
64
65// The following constants control how UnmountFilesystem should retry if
66// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
67// one second.
68const int kUnmountMaxNumOfRetries = 5;
69const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070070
71// Number of bytes to read from a file to attempt to detect its contents. Used
72// in GetFileFormat.
73const int kGetFileFormatMaxHeaderSize = 32;
74
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080075// Return true if |disk_name| is an MTD or a UBI device. Note that this test is
76// simply based on the name of the device.
77bool IsMtdDeviceName(const string& disk_name) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070078 return base::StartsWithASCII(disk_name, "/dev/ubi", true) ||
79 base::StartsWithASCII(disk_name, "/dev/mtd", true);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080080}
81
82// Return the device name for the corresponding partition on a NAND device.
83// WARNING: This function returns device names that are not mountable.
84string MakeNandPartitionName(int partition_num) {
85 switch (partition_num) {
86 case 2:
87 case 4:
88 case 6: {
89 return base::StringPrintf("/dev/mtd%d", partition_num);
90 }
91 default: {
92 return base::StringPrintf("/dev/ubi%d_0", partition_num);
93 }
94 }
95}
96
97// Return the device name for the corresponding partition on a NAND device that
98// may be mountable (but may not be writable).
99string MakeNandPartitionNameForMount(int partition_num) {
100 switch (partition_num) {
101 case 2:
102 case 4:
103 case 6: {
104 return base::StringPrintf("/dev/mtd%d", partition_num);
105 }
106 case 3:
107 case 5:
108 case 7: {
109 return base::StringPrintf("/dev/ubiblock%d_0", partition_num);
110 }
111 default: {
112 return base::StringPrintf("/dev/ubi%d_0", partition_num);
113 }
114 }
115}
116
Ben Chan77a1eba2012-10-07 22:54:55 -0700117} // namespace
118
adlr@google.com3defe6a2009-12-04 20:57:17 +0000119namespace utils {
120
Chris Sosa4f8ee272012-11-30 13:01:54 -0800121// Cgroup container is created in update-engine's upstart script located at
122// /etc/init/update-engine.conf.
123static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
124
J. Richard Barnette63137e52013-10-28 10:57:29 -0700125string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -0700126 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -0700127
Alex Vakulenko75039d72014-03-25 12:36:28 -0700128 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -0700129 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -0700130 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -0700131 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -0800132 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -0700133 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800134 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -0700135 string output;
136 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800137 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -0700138 return output;
139 }
140 }
141 }
142 LOG(ERROR) << "Unable to parse fwid from ec info.";
143 return "";
144}
145
146
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700147const string KernelDeviceOfBootDevice(const string& boot_device) {
148 string kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700149
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700150 string disk_name;
151 int partition_num;
152 if (SplitPartitionName(boot_device, &disk_name, &partition_num)) {
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700153 // Currently this assumes the partition number of the boot device is
154 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
155 // get the kernel device.
156 if (partition_num == 3 || partition_num == 5 || partition_num == 7) {
157 kernel_partition_name = MakePartitionName(disk_name, partition_num - 1);
158 }
J. Richard Barnette30842932013-10-28 15:04:23 -0700159 }
160
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700161 return kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700162}
163
164
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800165bool WriteFile(const char* path, const void* data, int data_len) {
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800166 DirectFileWriter writer;
167 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
168 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700169 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800170 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800171 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800172 return true;
173}
174
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700175bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700176 const char* c_buf = static_cast<const char*>(buf);
177 ssize_t bytes_written = 0;
178 while (bytes_written < static_cast<ssize_t>(count)) {
179 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
180 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
181 bytes_written += rc;
182 }
183 return true;
184}
185
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700186bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
187 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700188 size_t bytes_written = 0;
189 int num_attempts = 0;
190 while (bytes_written < count) {
191 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700192 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
193 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700194 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
195 if (rc < 0) {
196 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
197 << " bytes_written=" << bytes_written
198 << " count=" << count << " offset=" << offset;
199 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700200 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
201 bytes_written += rc;
202 }
203 return true;
204}
205
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800206bool WriteAll(FileDescriptorPtr fd, const void* buf, size_t count) {
207 const char* c_buf = static_cast<const char*>(buf);
208 ssize_t bytes_written = 0;
209 while (bytes_written < static_cast<ssize_t>(count)) {
210 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
211 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
212 bytes_written += rc;
213 }
214 return true;
215}
216
217bool PWriteAll(FileDescriptorPtr fd,
218 const void* buf,
219 size_t count,
220 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700221 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
222 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800223 return WriteAll(fd, buf, count);
224}
225
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700226bool PReadAll(int fd, void* buf, size_t count, off_t offset,
227 ssize_t* out_bytes_read) {
228 char* c_buf = static_cast<char*>(buf);
229 ssize_t bytes_read = 0;
230 while (bytes_read < static_cast<ssize_t>(count)) {
231 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
232 offset + bytes_read);
233 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
234 if (rc == 0) {
235 break;
236 }
237 bytes_read += rc;
238 }
239 *out_bytes_read = bytes_read;
240 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700241}
242
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800243bool PReadAll(FileDescriptorPtr fd, void* buf, size_t count, off_t offset,
244 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700245 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
246 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800247 char* c_buf = static_cast<char*>(buf);
248 ssize_t bytes_read = 0;
249 while (bytes_read < static_cast<ssize_t>(count)) {
250 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
251 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
252 if (rc == 0) {
253 break;
254 }
255 bytes_read += rc;
256 }
257 *out_bytes_read = bytes_read;
258 return true;
259}
260
Gilad Arnold19a45f02012-07-19 12:36:10 -0700261// Append |nbytes| of content from |buf| to the vector pointed to by either
262// |vec_p| or |str_p|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800263static void AppendBytes(const uint8_t* buf, size_t nbytes,
264 chromeos::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700265 CHECK(buf);
266 CHECK(vec_p);
267 vec_p->insert(vec_p->end(), buf, buf + nbytes);
268}
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800269static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700270 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700271 CHECK(buf);
272 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800273 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700274}
275
276// Reads from an open file |fp|, appending the read content to the container
277// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200278// file's content, false otherwise. If |size| is not -1, reads up to |size|
279// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700280template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200281static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700282 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200283 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800284 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200285 while (size == -1 || size > 0) {
286 off_t bytes_to_read = sizeof(buf);
287 if (size > 0 && bytes_to_read > size) {
288 bytes_to_read = size;
289 }
290 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
291 if (!nbytes) {
292 break;
293 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700294 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200295 if (size != -1) {
296 CHECK(size >= static_cast<off_t>(nbytes));
297 size -= nbytes;
298 }
299 }
300 if (ferror(fp)) {
301 return false;
302 }
303 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700304}
305
Darin Petkov8e447e02013-04-16 16:23:50 +0200306// Opens a file |path| for reading and appends its the contents to a container
307// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
308// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700309template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700310static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200311 off_t offset,
312 off_t size,
313 T* out_p) {
314 CHECK_GE(offset, 0);
315 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700316 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200317 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000318 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200319 if (offset) {
320 // Return success without appending any data if a chunk beyond the end of
321 // the file is requested.
322 if (offset >= FileSize(path)) {
323 return true;
324 }
325 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
326 }
327 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000328}
329
Alex Deymo10875d92014-11-10 21:52:57 -0800330// TODO(deymo): This is only used in unittest, but requires the private
331// Read<string>() defined here. Expose Read<string>() or move to base/ version.
332bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700333 FILE* fp = popen(cmd.c_str(), "r");
334 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000335 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200336 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700337 return (success && pclose(fp) >= 0);
338}
339
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800340bool ReadFile(const string& path, chromeos::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200341 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700342}
343
Darin Petkov8e447e02013-04-16 16:23:50 +0200344bool ReadFile(const string& path, string* out_p) {
345 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700346}
347
Darin Petkov8e447e02013-04-16 16:23:50 +0200348bool ReadFileChunk(const string& path, off_t offset, off_t size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800349 chromeos::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200350 return ReadFileChunkAndAppend(path, offset, size, out_p);
351}
352
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700353off_t BlockDevSize(int fd) {
354 uint64_t dev_size;
355 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
356 if (rc == -1) {
357 dev_size = -1;
358 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
359 }
360 return dev_size;
361}
362
363off_t BlockDevSize(const string& path) {
364 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
365 if (fd == -1) {
366 PLOG(ERROR) << "Error opening " << path;
367 return fd;
368 }
369
370 off_t dev_size = BlockDevSize(fd);
371 if (dev_size == -1)
372 PLOG(ERROR) << "Error getting block device size on " << path;
373
374 close(fd);
375 return dev_size;
376}
377
378off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700379 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700380 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700381 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700382 if (rc < 0) {
383 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700384 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700385 }
386 if (S_ISREG(stbuf.st_mode))
387 return stbuf.st_size;
388 if (S_ISBLK(stbuf.st_mode))
389 return BlockDevSize(fd);
390 LOG(ERROR) << "Couldn't determine the type of " << fd;
391 return -1;
392}
393
394off_t FileSize(const string& path) {
395 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
396 if (fd == -1) {
397 PLOG(ERROR) << "Error opening " << path;
398 return fd;
399 }
400 off_t size = FileSize(fd);
401 if (size == -1)
402 PLOG(ERROR) << "Error getting file size of " << path;
403 close(fd);
404 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700405}
406
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800407void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000408 LOG(INFO) << "Logging array of length: " << length;
409 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700410 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000411 const unsigned int bytes_remaining = length - i;
412 const unsigned int bytes_per_this_line = min(bytes_per_line,
413 bytes_remaining);
414 char header[100];
415 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
416 TEST_AND_RETURN(r == 13);
417 string line = header;
418 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
419 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800420 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000421 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
422 TEST_AND_RETURN(r == 3);
423 line += buf;
424 }
425 LOG(INFO) << line;
426 }
427}
428
Alex Deymof329b932014-10-30 01:37:48 -0700429string GetDiskName(const string& partition_name) {
430 string disk_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800431 return SplitPartitionName(partition_name, &disk_name, nullptr) ?
Alex Deymof329b932014-10-30 01:37:48 -0700432 disk_name : string();
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700433}
434
Alex Deymof329b932014-10-30 01:37:48 -0700435int GetPartitionNumber(const string& partition_name) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800436 int partition_num = 0;
437 return SplitPartitionName(partition_name, nullptr, &partition_num) ?
438 partition_num : 0;
439}
440
Alex Deymof329b932014-10-30 01:37:48 -0700441bool SplitPartitionName(const string& partition_name,
442 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800443 int* out_partition_num) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700444 if (!base::StartsWithASCII(partition_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800445 LOG(ERROR) << "Invalid partition device name: " << partition_name;
446 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700447 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800448
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700449 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
450 if (last_nondigit_pos == string::npos ||
451 (last_nondigit_pos + 1) == partition_name.size()) {
452 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800453 return false;
454 }
455
Alex Deymof329b932014-10-30 01:37:48 -0700456 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700457 if (partition_name[last_nondigit_pos] == '_') {
458 // NAND block devices have weird naming which could be something
459 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
460 size_t prev_nondigit_pos =
461 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
462 if (prev_nondigit_pos == string::npos ||
463 (prev_nondigit_pos + 1) == last_nondigit_pos) {
464 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
465 return false;
466 }
467
468 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
469 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800470 }
471
472 if (out_disk_name) {
473 // Special case for MMC devices which have the following naming scheme:
474 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700475 size_t disk_name_len = last_nondigit_pos;
476 if (partition_name[last_nondigit_pos] != 'p' ||
477 last_nondigit_pos == 0 ||
478 !isdigit(partition_name[last_nondigit_pos - 1])) {
479 disk_name_len++;
480 }
481 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800482 }
483
484 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700485 string partition_str = partition_name.substr(last_nondigit_pos + 1,
486 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800487 *out_partition_num = atoi(partition_str.c_str());
488 }
489 return true;
490}
491
Alex Deymof329b932014-10-30 01:37:48 -0700492string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800493 if (partition_num < 1) {
494 LOG(ERROR) << "Invalid partition number: " << partition_num;
495 return string();
496 }
497
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700498 if (!base::StartsWithASCII(disk_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800499 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700500 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800501 }
502
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800503 if (IsMtdDeviceName(disk_name)) {
504 // Special case for UBI block devices.
505 // 1. ubiblock is not writable, we need to use plain "ubi".
506 // 2. There is a "_0" suffix.
507 return MakeNandPartitionName(partition_num);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800508 }
509
Alex Deymof329b932014-10-30 01:37:48 -0700510 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700511 if (isdigit(partition_name.back())) {
512 // Special case for devices with names ending with a digit.
513 // Add "p" to separate the disk name from partition number,
514 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800515 partition_name += 'p';
516 }
517
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700518 partition_name += std::to_string(partition_num);
519
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800520 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700521}
522
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800523string MakePartitionNameForMount(const string& part_name) {
524 if (IsMtdDeviceName(part_name)) {
525 int partition_num;
526 if (!SplitPartitionName(part_name, nullptr, &partition_num)) {
527 return "";
528 }
529 return MakeNandPartitionNameForMount(partition_num);
530 }
531 return part_name;
532}
533
Darin Petkovf74eb652010-08-04 12:08:38 -0700534string SysfsBlockDevice(const string& device) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700535 base::FilePath device_path(device);
Darin Petkovf74eb652010-08-04 12:08:38 -0700536 if (device_path.DirName().value() != "/dev") {
537 return "";
538 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700539 return base::FilePath("/sys/block").Append(device_path.BaseName()).value();
Darin Petkovf74eb652010-08-04 12:08:38 -0700540}
541
Alex Deymof329b932014-10-30 01:37:48 -0700542bool IsRemovableDevice(const string& device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700543 string sysfs_block = SysfsBlockDevice(device);
544 string removable;
545 if (sysfs_block.empty() ||
Alex Vakulenko75039d72014-03-25 12:36:28 -0700546 !base::ReadFileToString(base::FilePath(sysfs_block).Append("removable"),
Ben Chan736fcb52014-05-21 18:28:22 -0700547 &removable)) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700548 return false;
549 }
Ben Chan736fcb52014-05-21 18:28:22 -0700550 base::TrimWhitespaceASCII(removable, base::TRIM_ALL, &removable);
Darin Petkovf74eb652010-08-04 12:08:38 -0700551 return removable == "1";
552}
553
Alex Deymof329b932014-10-30 01:37:48 -0700554string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000555 char buf[100];
556 buf[0] = '\0';
557 return strerror_r(err, buf, sizeof(buf));
558}
559
adlr@google.com3defe6a2009-12-04 20:57:17 +0000560bool FileExists(const char* path) {
561 struct stat stbuf;
562 return 0 == lstat(path, &stbuf);
563}
564
Darin Petkov30291ed2010-11-12 10:23:06 -0800565bool IsSymlink(const char* path) {
566 struct stat stbuf;
567 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
568}
569
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800570bool TryAttachingUbiVolume(int volume_num, int timeout) {
571 const string volume_path = base::StringPrintf("/dev/ubi%d_0", volume_num);
572 if (FileExists(volume_path.c_str())) {
573 return true;
574 }
575
576 int exit_code;
577 vector<string> cmd = {
578 "ubiattach",
579 "-m",
580 base::StringPrintf("%d", volume_num),
581 "-d",
582 base::StringPrintf("%d", volume_num)
583 };
584 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
585 TEST_AND_RETURN_FALSE(exit_code == 0);
586
587 cmd = {
588 "ubiblock",
589 "--create",
590 volume_path
591 };
592 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
593 TEST_AND_RETURN_FALSE(exit_code == 0);
594
595 while (timeout > 0 && !FileExists(volume_path.c_str())) {
596 sleep(1);
597 timeout--;
598 }
599
600 return FileExists(volume_path.c_str());
601}
602
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800603// If |path| is absolute, or explicit relative to the current working directory,
604// leaves it as is. Otherwise, if TMPDIR is defined in the environment and is
605// non-empty, prepends it to |path|. Otherwise, prepends /tmp. Returns the
606// resulting path.
607static const string PrependTmpdir(const string& path) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700608 if (path[0] == '/' || base::StartsWithASCII(path, "./", true) ||
609 base::StartsWithASCII(path, "../", true))
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800610 return path;
611
612 const char *tmpdir = getenv("TMPDIR");
613 const string prefix = (tmpdir && *tmpdir ? tmpdir : "/tmp");
614 return prefix + "/" + path;
615}
616
Alex Deymof329b932014-10-30 01:37:48 -0700617bool MakeTempFile(const string& base_filename_template,
618 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700619 int* fd) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800620 const string filename_template = PrependTmpdir(base_filename_template);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700621 DCHECK(filename || fd);
622 vector<char> buf(filename_template.size() + 1);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800623 memcpy(buf.data(), filename_template.data(), filename_template.size());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700624 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700625
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800626 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700627 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
628 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800629 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700630 }
631 if (fd) {
632 *fd = mkstemp_fd;
633 } else {
634 close(mkstemp_fd);
635 }
636 return true;
637}
638
Alex Deymof329b932014-10-30 01:37:48 -0700639bool MakeTempDirectory(const string& base_dirname_template,
640 string* dirname) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800641 const string dirname_template = PrependTmpdir(base_dirname_template);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700642 DCHECK(dirname);
643 vector<char> buf(dirname_template.size() + 1);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800644 memcpy(buf.data(), dirname_template.data(), dirname_template.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700645 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700646
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800647 char* return_code = mkdtemp(buf.data());
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700648 TEST_AND_RETURN_FALSE_ERRNO(return_code != nullptr);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800649 *dirname = buf.data();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700650 return true;
651}
652
adlr@google.com3defe6a2009-12-04 20:57:17 +0000653bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700654 const string& mountpoint,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700655 unsigned long mountflags) { // NOLINT(runtime/int)
Alex Deymo4c82df32014-11-10 22:25:57 -0800656 // TODO(sosa): Remove "ext3" once crbug.com/208022 is resolved.
657 const vector<const char*> fstypes{"ext2", "ext3", "squashfs"};
658 for (const char* fstype : fstypes) {
659 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
660 nullptr);
661 if (rc == 0)
662 return true;
663
664 PLOG(WARNING) << "Unable to mount destination device " << device
665 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000666 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800667 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
668 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000669}
670
671bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700672 for (int num_retries = 0; ; ++num_retries) {
673 if (umount(mountpoint.c_str()) == 0)
674 break;
675
676 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
677 num_retries < kUnmountMaxNumOfRetries);
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700678 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700679 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000680 return true;
681}
682
Alex Deymof329b932014-10-30 01:37:48 -0700683bool GetFilesystemSize(const string& device,
Darin Petkovd3f8c892010-10-12 21:38:45 -0700684 int* out_block_count,
685 int* out_block_size) {
686 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
Alex Deymoe7141c62014-10-17 14:03:01 -0700687 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700688 ScopedFdCloser fd_closer(&fd);
689 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
690}
691
692bool GetFilesystemSizeFromFD(int fd,
693 int* out_block_count,
694 int* out_block_size) {
695 TEST_AND_RETURN_FALSE(fd >= 0);
696
Alex Deymo192393b2014-11-10 15:58:38 -0800697 // Determine the filesystem size by directly reading the block count and
698 // block size information from the superblock. Supported FS are ext3 and
699 // squashfs.
700
701 // Read from the fd only once and detect in memory. The first 2 KiB is enough
702 // to read the ext2 superblock (located at offset 1024) and the squashfs
703 // superblock (located at offset 0).
704 const ssize_t kBufferSize = 2048;
705
706 uint8_t buffer[kBufferSize];
707 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, 0)) != kBufferSize) {
708 PLOG(ERROR) << "Unable to read the file system header:";
Darin Petkovd3f8c892010-10-12 21:38:45 -0700709 return false;
710 }
Alex Deymo192393b2014-11-10 15:58:38 -0800711
712 if (GetSquashfs4Size(buffer, kBufferSize, out_block_count, out_block_size))
713 return true;
714 if (GetExt3Size(buffer, kBufferSize, out_block_count, out_block_size))
715 return true;
716
717 LOG(ERROR) << "Unable to determine file system type.";
718 return false;
719}
720
721bool GetExt3Size(const uint8_t* buffer, size_t buffer_size,
722 int* out_block_count,
723 int* out_block_size) {
724 // See include/linux/ext2_fs.h for more details on the structure. We obtain
725 // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
726 // library.
727 if (buffer_size < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
728 return false;
729
730 const uint8_t* superblock = buffer + SUPERBLOCK_OFFSET;
731
732 // ext3_fs.h: ext3_super_block.s_blocks_count
733 uint32_t block_count =
734 *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
735
736 // ext3_fs.h: ext3_super_block.s_log_block_size
737 uint32_t log_block_size =
738 *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
739
740 // ext3_fs.h: ext3_super_block.s_magic
741 uint16_t magic =
742 *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
743
Darin Petkovd3f8c892010-10-12 21:38:45 -0700744 block_count = le32toh(block_count);
Alex Deymo192393b2014-11-10 15:58:38 -0800745 log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700746 magic = le16toh(magic);
747
748 // Sanity check the parameters.
Alex Deymo192393b2014-11-10 15:58:38 -0800749 TEST_AND_RETURN_FALSE(magic == EXT2_SUPER_MAGIC);
750 TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
751 log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700752 TEST_AND_RETURN_FALSE(block_count > 0);
753
Alex Deymo192393b2014-11-10 15:58:38 -0800754 if (out_block_count)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700755 *out_block_count = block_count;
Alex Deymo192393b2014-11-10 15:58:38 -0800756 if (out_block_size)
757 *out_block_size = 1 << log_block_size;
758 return true;
759}
760
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800761bool GetSquashfs4Size(const uint8_t* buffer, size_t buffer_size,
Alex Deymo192393b2014-11-10 15:58:38 -0800762 int* out_block_count,
763 int* out_block_size) {
764 // See fs/squashfs/squashfs_fs.h for format details. We only support
765 // Squashfs 4.x little endian.
766
767 // sizeof(struct squashfs_super_block)
768 const size_t kSquashfsSuperBlockSize = 96;
769 if (buffer_size < kSquashfsSuperBlockSize)
770 return false;
771
772 // Check magic, squashfs_fs.h: SQUASHFS_MAGIC
773 if (memcmp(buffer, "hsqs", 4) != 0)
774 return false; // Only little endian is supported.
775
776 // squashfs_fs.h: struct squashfs_super_block.s_major
777 uint16_t s_major = *reinterpret_cast<const uint16_t*>(
778 buffer + 5 * sizeof(uint32_t) + 4 * sizeof(uint16_t));
779
780 if (s_major != 4) {
781 LOG(ERROR) << "Found unsupported squashfs major version " << s_major;
782 return false;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700783 }
Alex Deymo192393b2014-11-10 15:58:38 -0800784
785 // squashfs_fs.h: struct squashfs_super_block.bytes_used
786 uint64_t bytes_used = *reinterpret_cast<const int64_t*>(
787 buffer + 5 * sizeof(uint32_t) + 6 * sizeof(uint16_t) + sizeof(uint64_t));
788
789 const int block_size = 4096;
790
791 // The squashfs' bytes_used doesn't need to be aligned with the block boundary
792 // so we round up to the nearest blocksize.
793 if (out_block_count)
794 *out_block_count = (bytes_used + block_size - 1) / block_size;
795 if (out_block_size)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700796 *out_block_size = block_size;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700797 return true;
798}
799
Alex Deymo60ca1a72015-06-18 18:19:15 -0700800bool IsExtFilesystem(const string& device) {
Alex Deymode942f32015-03-13 11:57:15 -0700801 chromeos::Blob header;
802 // The first 2 KiB is enough to read the ext2 superblock (located at offset
803 // 1024).
804 if (!ReadFileChunk(device, 0, 2048, &header))
805 return false;
806 return GetExt3Size(header.data(), header.size(), nullptr, nullptr);
807}
808
Alex Deymo60ca1a72015-06-18 18:19:15 -0700809bool IsSquashfsFilesystem(const string& device) {
Alex Deymode942f32015-03-13 11:57:15 -0700810 chromeos::Blob header;
811 // The first 96 is enough to read the squashfs superblock.
812 const ssize_t kSquashfsSuperBlockSize = 96;
813 if (!ReadFileChunk(device, 0, kSquashfsSuperBlockSize, &header))
814 return false;
815 return GetSquashfs4Size(header.data(), header.size(), nullptr, nullptr);
816}
817
Alex Deymo032e7722014-03-25 17:53:56 -0700818// Tries to parse the header of an ELF file to obtain a human-readable
819// description of it on the |output| string.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800820static bool GetFileFormatELF(const uint8_t* buffer, size_t size,
821 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700822 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700823 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700824 return false;
825 *output = "ELF";
826
827 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700828 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700829 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700830 switch (buffer[EI_CLASS]) {
831 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700832 *output += " 32-bit";
833 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700834 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700835 *output += " 64-bit";
836 break;
837 default:
838 *output += " ?-bit";
839 }
840
841 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700842 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700843 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800844 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700845 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700846 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700847 *output += " little-endian";
848 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700849 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700850 *output += " big-endian";
851 break;
852 default:
853 *output += " ?-endian";
854 // Don't parse anything after the 0x10 offset if endianness is unknown.
855 return true;
856 }
857
Alex Deymoc1711e22014-08-08 13:16:23 -0700858 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
859 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
860 // and size is the same for both 32 and 64 bits.
861 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700862 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700863 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700864 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700865 if (ei_data == ELFDATA2LSB)
866 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700867 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700868 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700869
870 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700871 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700872 *output += " x86";
873 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700874 case EM_MIPS:
875 *output += " mips";
876 break;
877 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700878 *output += " arm";
879 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700880 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700881 *output += " x86-64";
882 break;
883 default:
884 *output += " unknown-arch";
885 }
886 return true;
887}
888
889string GetFileFormat(const string& path) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800890 chromeos::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700891 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
892 return "File not found.";
893
894 string result;
895 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
896 return result;
897
898 return "data";
899}
900
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800901namespace {
902// Do the actual trigger. We do it as a main-loop callback to (try to) get a
903// consistent stack trace.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700904void TriggerCrashReporterUpload() {
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800905 pid_t pid = fork();
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700906 CHECK_GE(pid, 0) << "fork failed"; // fork() failed. Something is very wrong.
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800907 if (pid == 0) {
908 // We are the child. Crash.
909 abort(); // never returns
910 }
911 // We are the parent. Wait for child to terminate.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700912 pid_t result = waitpid(pid, nullptr, 0);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800913 LOG_IF(ERROR, result < 0) << "waitpid() failed";
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800914}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700915} // namespace
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800916
917void ScheduleCrashReporterUpload() {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700918 chromeos::MessageLoop::current()->PostTask(
919 FROM_HERE,
920 base::Bind(&TriggerCrashReporterUpload));
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800921}
922
Chris Sosa4f8ee272012-11-30 13:01:54 -0800923bool SetCpuShares(CpuShares shares) {
924 string string_shares = base::IntToString(static_cast<int>(shares));
925 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
926 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700927 if (utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
928 string_shares.size())) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800929 return true;
930 } else {
931 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
932 << " using " << cpu_shares_file;
933 return false;
934 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700935}
936
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700937int FuzzInt(int value, unsigned int range) {
938 int min = value - range / 2;
939 int max = value + range - range / 2;
940 return base::RandInt(min, max);
941}
942
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700943string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800944 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700945}
946
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800947string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400948 string str;
949
950 // Handle negative durations by prefixing with a minus.
951 if (delta.ToInternalValue() < 0) {
952 delta *= -1;
953 str = "-";
954 }
955
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700956 // Canonicalize into days, hours, minutes, seconds and microseconds.
957 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800958 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700959 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800960 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700961 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800962 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700963 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800964 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700965 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800966
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700967 if (days)
968 base::StringAppendF(&str, "%ud", days);
969 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800970 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700971 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800972 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700973 base::StringAppendF(&str, "%u", secs);
974 if (usecs) {
975 int width = 6;
976 while ((usecs / 10) * 10 == usecs) {
977 usecs /= 10;
978 width--;
979 }
980 base::StringAppendF(&str, ".%0*u", width, usecs);
981 }
982 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800983 return str;
984}
985
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700986string ToString(const Time utc_time) {
987 Time::Exploded exp_time;
988 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700989 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700990 exp_time.month,
991 exp_time.day_of_month,
992 exp_time.year,
993 exp_time.hour,
994 exp_time.minute,
995 exp_time.second);
996}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000997
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700998string ToString(bool b) {
999 return (b ? "true" : "false");
1000}
1001
Alex Deymo1c656c42013-06-28 11:02:14 -07001002string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -07001003 switch (source) {
1004 case kDownloadSourceHttpsServer: return "HttpsServer";
1005 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -07001006 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -07001007 case kNumDownloadSources: return "Unknown";
1008 // Don't add a default case to let the compiler warn about newly added
1009 // download sources which should be added here.
1010 }
1011
1012 return "Unknown";
1013}
1014
Alex Deymo1c656c42013-06-28 11:02:14 -07001015string ToString(PayloadType payload_type) {
1016 switch (payload_type) {
1017 case kPayloadTypeDelta: return "Delta";
1018 case kPayloadTypeFull: return "Full";
1019 case kPayloadTypeForcedFull: return "ForcedFull";
1020 case kNumPayloadTypes: return "Unknown";
1021 // Don't add a default case to let the compiler warn about newly added
1022 // payload types which should be added here.
1023 }
1024
1025 return "Unknown";
1026}
1027
David Zeuthena99981f2013-04-29 13:42:47 -07001028ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -07001029 // Ignore the higher order bits in the code by applying the mask as
1030 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001031 // with values less than ErrorCode::kUmaReportedMax.
1032 ErrorCode base_code = static_cast<ErrorCode>(
1033 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -07001034
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001035 // Make additional adjustments required for UMA and error classification.
1036 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
1037 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001038 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -07001039 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001040 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001041 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001042 << " to ErrorCode::kOmahaErrorInHTTPResponse";
1043 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001044 }
1045
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001046 return base_code;
1047}
1048
David Zeuthen33bae492014-02-25 16:16:18 -08001049metrics::AttemptResult GetAttemptResult(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001050 ErrorCode base_code = static_cast<ErrorCode>(
1051 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001052
1053 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001054 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001055 return metrics::AttemptResult::kUpdateSucceeded;
1056
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001057 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001058 return metrics::AttemptResult::kPayloadDownloadError;
1059
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001060 case ErrorCode::kDownloadInvalidMetadataSize:
1061 case ErrorCode::kDownloadInvalidMetadataMagicString:
1062 case ErrorCode::kDownloadMetadataSignatureError:
1063 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1064 case ErrorCode::kPayloadMismatchedType:
1065 case ErrorCode::kUnsupportedMajorPayloadVersion:
1066 case ErrorCode::kUnsupportedMinorPayloadVersion:
1067 case ErrorCode::kDownloadNewPartitionInfoError:
1068 case ErrorCode::kDownloadSignatureMissingInManifest:
1069 case ErrorCode::kDownloadManifestParseError:
1070 case ErrorCode::kDownloadOperationHashMissingError:
David Zeuthen33bae492014-02-25 16:16:18 -08001071 return metrics::AttemptResult::kMetadataMalformed;
1072
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001073 case ErrorCode::kDownloadOperationHashMismatch:
1074 case ErrorCode::kDownloadOperationHashVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001075 return metrics::AttemptResult::kOperationMalformed;
1076
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001077 case ErrorCode::kDownloadOperationExecutionError:
1078 case ErrorCode::kInstallDeviceOpenError:
1079 case ErrorCode::kKernelDeviceOpenError:
1080 case ErrorCode::kDownloadWriteError:
1081 case ErrorCode::kFilesystemCopierError:
Allie Woodeb9e6d82015-04-17 13:55:30 -07001082 case ErrorCode::kFilesystemVerifierError:
David Zeuthen33bae492014-02-25 16:16:18 -08001083 return metrics::AttemptResult::kOperationExecutionError;
1084
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001085 case ErrorCode::kDownloadMetadataSignatureMismatch:
David Zeuthen33bae492014-02-25 16:16:18 -08001086 return metrics::AttemptResult::kMetadataVerificationFailed;
1087
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001088 case ErrorCode::kPayloadSizeMismatchError:
1089 case ErrorCode::kPayloadHashMismatchError:
1090 case ErrorCode::kDownloadPayloadVerificationError:
1091 case ErrorCode::kSignedDeltaPayloadExpectedError:
1092 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001093 return metrics::AttemptResult::kPayloadVerificationFailed;
1094
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001095 case ErrorCode::kNewRootfsVerificationError:
1096 case ErrorCode::kNewKernelVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001097 return metrics::AttemptResult::kVerificationFailed;
1098
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001099 case ErrorCode::kPostinstallRunnerError:
1100 case ErrorCode::kPostinstallBootedFromFirmwareB:
1101 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
David Zeuthen33bae492014-02-25 16:16:18 -08001102 return metrics::AttemptResult::kPostInstallFailed;
1103
1104 // We should never get these errors in the update-attempt stage so
1105 // return internal error if this happens.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001106 case ErrorCode::kError:
1107 case ErrorCode::kOmahaRequestXMLParseError:
1108 case ErrorCode::kOmahaRequestError:
1109 case ErrorCode::kOmahaResponseHandlerError:
1110 case ErrorCode::kDownloadStateInitializationError:
1111 case ErrorCode::kOmahaRequestEmptyResponseError:
1112 case ErrorCode::kDownloadInvalidMetadataSignature:
1113 case ErrorCode::kOmahaResponseInvalid:
1114 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1115 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1116 case ErrorCode::kOmahaErrorInHTTPResponse:
1117 case ErrorCode::kDownloadMetadataSignatureMissingError:
1118 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1119 case ErrorCode::kPostinstallPowerwashError:
1120 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -04001121 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
David Zeuthen33bae492014-02-25 16:16:18 -08001122 return metrics::AttemptResult::kInternalError;
1123
1124 // Special flags. These can't happen (we mask them out above) but
1125 // the compiler doesn't know that. Just break out so we can warn and
1126 // return |kInternalError|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001127 case ErrorCode::kUmaReportedMax:
1128 case ErrorCode::kOmahaRequestHTTPResponseBase:
1129 case ErrorCode::kDevModeFlag:
1130 case ErrorCode::kResumedFlag:
1131 case ErrorCode::kTestImageFlag:
1132 case ErrorCode::kTestOmahaUrlFlag:
1133 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001134 break;
1135 }
1136
1137 LOG(ERROR) << "Unexpected error code " << base_code;
1138 return metrics::AttemptResult::kInternalError;
1139}
1140
1141
1142metrics::DownloadErrorCode GetDownloadErrorCode(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001143 ErrorCode base_code = static_cast<ErrorCode>(
1144 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001145
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001146 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
1147 int http_status =
1148 static_cast<int>(base_code) -
1149 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase);
David Zeuthen33bae492014-02-25 16:16:18 -08001150 if (http_status >= 200 && http_status <= 599) {
1151 return static_cast<metrics::DownloadErrorCode>(
1152 static_cast<int>(metrics::DownloadErrorCode::kHttpStatus200) +
1153 http_status - 200);
1154 } else if (http_status == 0) {
1155 // The code is using HTTP Status 0 for "Unable to get http
1156 // response code."
1157 return metrics::DownloadErrorCode::kDownloadError;
1158 }
1159 LOG(WARNING) << "Unexpected HTTP status code " << http_status;
1160 return metrics::DownloadErrorCode::kHttpStatusOther;
1161 }
1162
1163 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001164 // Unfortunately, ErrorCode::kDownloadTransferError is returned for a wide
David Zeuthen33bae492014-02-25 16:16:18 -08001165 // variety of errors (proxy errors, host not reachable, timeouts etc.).
1166 //
1167 // For now just map that to kDownloading. See http://crbug.com/355745
1168 // for how we plan to add more detail in the future.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001169 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001170 return metrics::DownloadErrorCode::kDownloadError;
1171
1172 // All of these error codes are not related to downloading so break
1173 // out so we can warn and return InputMalformed.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001174 case ErrorCode::kSuccess:
1175 case ErrorCode::kError:
1176 case ErrorCode::kOmahaRequestError:
1177 case ErrorCode::kOmahaResponseHandlerError:
1178 case ErrorCode::kFilesystemCopierError:
1179 case ErrorCode::kPostinstallRunnerError:
1180 case ErrorCode::kPayloadMismatchedType:
1181 case ErrorCode::kInstallDeviceOpenError:
1182 case ErrorCode::kKernelDeviceOpenError:
1183 case ErrorCode::kPayloadHashMismatchError:
1184 case ErrorCode::kPayloadSizeMismatchError:
1185 case ErrorCode::kDownloadPayloadVerificationError:
1186 case ErrorCode::kDownloadNewPartitionInfoError:
1187 case ErrorCode::kDownloadWriteError:
1188 case ErrorCode::kNewRootfsVerificationError:
1189 case ErrorCode::kNewKernelVerificationError:
1190 case ErrorCode::kSignedDeltaPayloadExpectedError:
1191 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1192 case ErrorCode::kPostinstallBootedFromFirmwareB:
1193 case ErrorCode::kDownloadStateInitializationError:
1194 case ErrorCode::kDownloadInvalidMetadataMagicString:
1195 case ErrorCode::kDownloadSignatureMissingInManifest:
1196 case ErrorCode::kDownloadManifestParseError:
1197 case ErrorCode::kDownloadMetadataSignatureError:
1198 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1199 case ErrorCode::kDownloadMetadataSignatureMismatch:
1200 case ErrorCode::kDownloadOperationHashVerificationError:
1201 case ErrorCode::kDownloadOperationExecutionError:
1202 case ErrorCode::kDownloadOperationHashMismatch:
1203 case ErrorCode::kOmahaRequestEmptyResponseError:
1204 case ErrorCode::kOmahaRequestXMLParseError:
1205 case ErrorCode::kDownloadInvalidMetadataSize:
1206 case ErrorCode::kDownloadInvalidMetadataSignature:
1207 case ErrorCode::kOmahaResponseInvalid:
1208 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1209 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1210 case ErrorCode::kOmahaErrorInHTTPResponse:
1211 case ErrorCode::kDownloadOperationHashMissingError:
1212 case ErrorCode::kDownloadMetadataSignatureMissingError:
1213 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1214 case ErrorCode::kPostinstallPowerwashError:
1215 case ErrorCode::kUpdateCanceledByChannelChange:
1216 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1217 case ErrorCode::kUnsupportedMajorPayloadVersion:
1218 case ErrorCode::kUnsupportedMinorPayloadVersion:
David Zeuthenf3e28012014-08-26 18:23:52 -04001219 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -07001220 case ErrorCode::kFilesystemVerifierError:
David Zeuthen33bae492014-02-25 16:16:18 -08001221 break;
1222
1223 // Special flags. These can't happen (we mask them out above) but
1224 // the compiler doesn't know that. Just break out so we can warn and
1225 // return |kInputMalformed|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001226 case ErrorCode::kUmaReportedMax:
1227 case ErrorCode::kOmahaRequestHTTPResponseBase:
1228 case ErrorCode::kDevModeFlag:
1229 case ErrorCode::kResumedFlag:
1230 case ErrorCode::kTestImageFlag:
1231 case ErrorCode::kTestOmahaUrlFlag:
1232 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001233 LOG(ERROR) << "Unexpected error code " << base_code;
1234 break;
1235 }
1236
1237 return metrics::DownloadErrorCode::kInputMalformed;
1238}
1239
David Zeuthenb281f072014-04-02 10:20:19 -07001240metrics::ConnectionType GetConnectionType(
1241 NetworkConnectionType type,
1242 NetworkTethering tethering) {
1243 switch (type) {
1244 case kNetUnknown:
1245 return metrics::ConnectionType::kUnknown;
1246
1247 case kNetEthernet:
1248 if (tethering == NetworkTethering::kConfirmed)
1249 return metrics::ConnectionType::kTetheredEthernet;
1250 else
1251 return metrics::ConnectionType::kEthernet;
1252
1253 case kNetWifi:
1254 if (tethering == NetworkTethering::kConfirmed)
1255 return metrics::ConnectionType::kTetheredWifi;
1256 else
1257 return metrics::ConnectionType::kWifi;
1258
1259 case kNetWimax:
1260 return metrics::ConnectionType::kWimax;
1261
1262 case kNetBluetooth:
1263 return metrics::ConnectionType::kBluetooth;
1264
1265 case kNetCellular:
1266 return metrics::ConnectionType::kCellular;
1267 }
1268
1269 LOG(ERROR) << "Unexpected network connection type: type=" << type
1270 << ", tethering=" << static_cast<int>(tethering);
1271
1272 return metrics::ConnectionType::kUnknown;
1273}
1274
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001275// Returns a printable version of the various flags denoted in the higher order
1276// bits of the given code. Returns an empty string if none of those bits are
1277// set.
1278string GetFlagNames(uint32_t code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001279 uint32_t flags = (static_cast<uint32_t>(code) &
1280 static_cast<uint32_t>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001281 string flag_names;
1282 string separator = "";
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001283 for (size_t i = 0; i < sizeof(flags) * 8; i++) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001284 uint32_t flag = flags & (1 << i);
1285 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -07001286 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001287 separator = ", ";
1288 }
1289 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001290
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001291 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001292}
1293
David Zeuthena99981f2013-04-29 13:42:47 -07001294void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001295 if (!system_state)
1296 return;
1297
David Zeuthena99981f2013-04-29 13:42:47 -07001298 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001299
1300 // If the code doesn't have flags computed already, compute them now based on
1301 // the state of the current update attempt.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001302 uint32_t flags =
1303 static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001304 if (!flags)
1305 flags = system_state->update_attempter()->GetErrorCodeFlags();
1306
1307 // Determine the UMA bucket depending on the flags. But, ignore the resumed
1308 // flag, as it's perfectly normal for production devices to resume their
1309 // downloads and so we want to record those cases also in NormalErrorCodes
1310 // bucket.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001311 string metric =
1312 flags & ~static_cast<uint32_t>(ErrorCode::kResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001313 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
1314
1315 LOG(INFO) << "Sending error code " << uma_error_code
1316 << " (" << CodeToString(uma_error_code) << ")"
1317 << " to UMA metric: " << metric
1318 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
1319
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001320 system_state->metrics_lib()->SendEnumToUMA(
1321 metric, static_cast<int>(uma_error_code),
1322 static_cast<int>(ErrorCode::kUmaReportedMax));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001323}
1324
David Zeuthena99981f2013-04-29 13:42:47 -07001325string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001326 // If the given code has both parts (i.e. the error code part and the flags
1327 // part) then strip off the flags part since the switch statement below
1328 // has case statements only for the base error code or a single flag but
1329 // doesn't support any combinations of those.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001330 if ((static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags)) &&
1331 (static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags)))
1332 code = static_cast<ErrorCode>(
1333 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001334 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001335 case ErrorCode::kSuccess: return "ErrorCode::kSuccess";
1336 case ErrorCode::kError: return "ErrorCode::kError";
1337 case ErrorCode::kOmahaRequestError: return "ErrorCode::kOmahaRequestError";
1338 case ErrorCode::kOmahaResponseHandlerError:
1339 return "ErrorCode::kOmahaResponseHandlerError";
1340 case ErrorCode::kFilesystemCopierError:
1341 return "ErrorCode::kFilesystemCopierError";
1342 case ErrorCode::kPostinstallRunnerError:
1343 return "ErrorCode::kPostinstallRunnerError";
1344 case ErrorCode::kPayloadMismatchedType:
1345 return "ErrorCode::kPayloadMismatchedType";
1346 case ErrorCode::kInstallDeviceOpenError:
1347 return "ErrorCode::kInstallDeviceOpenError";
1348 case ErrorCode::kKernelDeviceOpenError:
1349 return "ErrorCode::kKernelDeviceOpenError";
1350 case ErrorCode::kDownloadTransferError:
1351 return "ErrorCode::kDownloadTransferError";
1352 case ErrorCode::kPayloadHashMismatchError:
1353 return "ErrorCode::kPayloadHashMismatchError";
1354 case ErrorCode::kPayloadSizeMismatchError:
1355 return "ErrorCode::kPayloadSizeMismatchError";
1356 case ErrorCode::kDownloadPayloadVerificationError:
1357 return "ErrorCode::kDownloadPayloadVerificationError";
1358 case ErrorCode::kDownloadNewPartitionInfoError:
1359 return "ErrorCode::kDownloadNewPartitionInfoError";
1360 case ErrorCode::kDownloadWriteError:
1361 return "ErrorCode::kDownloadWriteError";
1362 case ErrorCode::kNewRootfsVerificationError:
1363 return "ErrorCode::kNewRootfsVerificationError";
1364 case ErrorCode::kNewKernelVerificationError:
1365 return "ErrorCode::kNewKernelVerificationError";
1366 case ErrorCode::kSignedDeltaPayloadExpectedError:
1367 return "ErrorCode::kSignedDeltaPayloadExpectedError";
1368 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1369 return "ErrorCode::kDownloadPayloadPubKeyVerificationError";
1370 case ErrorCode::kPostinstallBootedFromFirmwareB:
1371 return "ErrorCode::kPostinstallBootedFromFirmwareB";
1372 case ErrorCode::kDownloadStateInitializationError:
1373 return "ErrorCode::kDownloadStateInitializationError";
1374 case ErrorCode::kDownloadInvalidMetadataMagicString:
1375 return "ErrorCode::kDownloadInvalidMetadataMagicString";
1376 case ErrorCode::kDownloadSignatureMissingInManifest:
1377 return "ErrorCode::kDownloadSignatureMissingInManifest";
1378 case ErrorCode::kDownloadManifestParseError:
1379 return "ErrorCode::kDownloadManifestParseError";
1380 case ErrorCode::kDownloadMetadataSignatureError:
1381 return "ErrorCode::kDownloadMetadataSignatureError";
1382 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1383 return "ErrorCode::kDownloadMetadataSignatureVerificationError";
1384 case ErrorCode::kDownloadMetadataSignatureMismatch:
1385 return "ErrorCode::kDownloadMetadataSignatureMismatch";
1386 case ErrorCode::kDownloadOperationHashVerificationError:
1387 return "ErrorCode::kDownloadOperationHashVerificationError";
1388 case ErrorCode::kDownloadOperationExecutionError:
1389 return "ErrorCode::kDownloadOperationExecutionError";
1390 case ErrorCode::kDownloadOperationHashMismatch:
1391 return "ErrorCode::kDownloadOperationHashMismatch";
1392 case ErrorCode::kOmahaRequestEmptyResponseError:
1393 return "ErrorCode::kOmahaRequestEmptyResponseError";
1394 case ErrorCode::kOmahaRequestXMLParseError:
1395 return "ErrorCode::kOmahaRequestXMLParseError";
1396 case ErrorCode::kDownloadInvalidMetadataSize:
1397 return "ErrorCode::kDownloadInvalidMetadataSize";
1398 case ErrorCode::kDownloadInvalidMetadataSignature:
1399 return "ErrorCode::kDownloadInvalidMetadataSignature";
1400 case ErrorCode::kOmahaResponseInvalid:
1401 return "ErrorCode::kOmahaResponseInvalid";
1402 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1403 return "ErrorCode::kOmahaUpdateIgnoredPerPolicy";
1404 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1405 return "ErrorCode::kOmahaUpdateDeferredPerPolicy";
1406 case ErrorCode::kOmahaErrorInHTTPResponse:
1407 return "ErrorCode::kOmahaErrorInHTTPResponse";
1408 case ErrorCode::kDownloadOperationHashMissingError:
1409 return "ErrorCode::kDownloadOperationHashMissingError";
1410 case ErrorCode::kDownloadMetadataSignatureMissingError:
1411 return "ErrorCode::kDownloadMetadataSignatureMissingError";
1412 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1413 return "ErrorCode::kOmahaUpdateDeferredForBackoff";
1414 case ErrorCode::kPostinstallPowerwashError:
1415 return "ErrorCode::kPostinstallPowerwashError";
1416 case ErrorCode::kUpdateCanceledByChannelChange:
1417 return "ErrorCode::kUpdateCanceledByChannelChange";
1418 case ErrorCode::kUmaReportedMax:
1419 return "ErrorCode::kUmaReportedMax";
1420 case ErrorCode::kOmahaRequestHTTPResponseBase:
1421 return "ErrorCode::kOmahaRequestHTTPResponseBase";
1422 case ErrorCode::kResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001423 return "Resumed";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001424 case ErrorCode::kDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001425 return "DevMode";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001426 case ErrorCode::kTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001427 return "TestImage";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001428 case ErrorCode::kTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001429 return "TestOmahaUrl";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001430 case ErrorCode::kSpecialFlags:
1431 return "ErrorCode::kSpecialFlags";
1432 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1433 return "ErrorCode::kPostinstallFirmwareRONotUpdatable";
1434 case ErrorCode::kUnsupportedMajorPayloadVersion:
1435 return "ErrorCode::kUnsupportedMajorPayloadVersion";
1436 case ErrorCode::kUnsupportedMinorPayloadVersion:
1437 return "ErrorCode::kUnsupportedMinorPayloadVersion";
David Zeuthenf3e28012014-08-26 18:23:52 -04001438 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
1439 return "ErrorCode::kOmahaRequestXMLHasEntityDecl";
Allie Woodeb9e6d82015-04-17 13:55:30 -07001440 case ErrorCode::kFilesystemVerifierError:
1441 return "ErrorCode::kFilesystemVerifierError";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001442 // Don't add a default case to let the compiler warn about newly added
1443 // error codes which should be added here.
1444 }
1445
1446 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1447}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001448
Gilad Arnold30dedd82013-07-03 06:19:09 -07001449bool CreatePowerwashMarkerFile(const char* file_path) {
1450 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1451 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001452 kPowerwashCommand,
1453 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001454 if (result) {
1455 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1456 } else {
1457 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1458 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001459
1460 return result;
1461}
1462
Gilad Arnold30dedd82013-07-03 06:19:09 -07001463bool DeletePowerwashMarkerFile(const char* file_path) {
1464 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001465 const base::FilePath kPowerwashMarkerPath(marker_file);
1466 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001467
1468 if (result)
1469 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001470 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001471 else
1472 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001473 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001474
1475 return result;
1476}
1477
Alex Deymof329b932014-10-30 01:37:48 -07001478bool GetInstallDev(const string& boot_dev, string* install_dev) {
1479 string disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001480 int partition_num;
1481 if (!SplitPartitionName(boot_dev, &disk_name, &partition_num))
1482 return false;
Liam McLoughlin049d1652013-07-31 18:47:46 -07001483
Chris Sosad317e402013-06-12 13:47:09 -07001484 // Right now, we just switch '3' and '5' partition numbers.
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001485 if (partition_num == 3) {
1486 partition_num = 5;
1487 } else if (partition_num == 5) {
1488 partition_num = 3;
1489 } else {
1490 return false;
1491 }
1492
1493 if (install_dev)
1494 *install_dev = MakePartitionName(disk_name, partition_num);
Liam McLoughlin049d1652013-07-31 18:47:46 -07001495
Chris Sosad317e402013-06-12 13:47:09 -07001496 return true;
1497}
1498
David Zeuthen27a48bc2013-08-06 12:06:29 -07001499Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -07001500 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1501 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -07001502 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1503}
1504
Alex Deymof329b932014-10-30 01:37:48 -07001505string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001506 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -07001507 for (vector<string>::const_iterator i = vec_str.begin();
1508 i != vec_str.end(); ++i) {
1509 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -07001510 str += ", ";
1511 str += '"';
1512 str += *i;
1513 str += '"';
1514 }
1515 str += "]";
1516 return str;
1517}
1518
David Zeuthen8f191b22013-08-06 12:27:50 -07001519string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001520 string encoded_hash = chromeos::data_encoding::Base64Encode(payload_hash);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001521 return base::StringPrintf("cros_update_size_%zu_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001522 payload_size,
1523 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -07001524}
1525
Alex Deymof329b932014-10-30 01:37:48 -07001526bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -07001527 base::FilePath *out_path) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001528 chromeos::Blob contents;
David Zeuthene7f89172013-10-31 10:21:04 -07001529
1530 out_path->clear();
1531
1532 if (base64_encoded.size() == 0) {
1533 LOG(ERROR) << "Can't decode empty string.";
1534 return false;
1535 }
1536
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001537 if (!chromeos::data_encoding::Base64Decode(base64_encoded, &contents) ||
David Zeuthene7f89172013-10-31 10:21:04 -07001538 contents.size() == 0) {
1539 LOG(ERROR) << "Error decoding base64.";
1540 return false;
1541 }
1542
Alex Vakulenko75039d72014-03-25 12:36:28 -07001543 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001544 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -07001545 LOG(ERROR) << "Error creating temporary file.";
1546 return false;
1547 }
1548
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001549 if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
David Zeuthene7f89172013-10-31 10:21:04 -07001550 PLOG(ERROR) << "Error writing to temporary file.";
1551 if (fclose(file) != 0)
1552 PLOG(ERROR) << "Error closing temporary file.";
1553 if (unlink(out_path->value().c_str()) != 0)
1554 PLOG(ERROR) << "Error unlinking temporary file.";
1555 out_path->clear();
1556 return false;
1557 }
1558
1559 if (fclose(file) != 0) {
1560 PLOG(ERROR) << "Error closing temporary file.";
1561 out_path->clear();
1562 return false;
1563 }
1564
1565 return true;
1566}
1567
Alex Deymof329b932014-10-30 01:37:48 -07001568bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -08001569 time_t unix_time = time.ToTimeT();
1570 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1571 const time_t kOmahaEpoch = 1167638400;
1572 const int64_t kNumSecondsPerWeek = 7*24*3600;
1573 const int64_t kNumDaysPerWeek = 7;
1574
1575 time_t omaha_time = unix_time - kOmahaEpoch;
1576
1577 if (omaha_time < 0)
1578 return false;
1579
1580 // Note, as per the comment in utils.h we are deliberately not
1581 // handling DST correctly.
1582
1583 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1584 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1585
1586 return true;
1587}
1588
David Zeuthen33bae492014-02-25 16:16:18 -08001589bool WallclockDurationHelper(SystemState* system_state,
Alex Deymof329b932014-10-30 01:37:48 -07001590 const string& state_variable_key,
1591 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001592 bool ret = false;
1593
Alex Deymof329b932014-10-30 01:37:48 -07001594 Time now = system_state->clock()->GetWallclockTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001595 int64_t stored_value;
1596 if (system_state->prefs()->GetInt64(state_variable_key, &stored_value)) {
Alex Deymof329b932014-10-30 01:37:48 -07001597 Time stored_time = Time::FromInternalValue(stored_value);
David Zeuthen33bae492014-02-25 16:16:18 -08001598 if (stored_time > now) {
1599 LOG(ERROR) << "Stored time-stamp used for " << state_variable_key
1600 << " is in the future.";
1601 } else {
1602 *out_duration = now - stored_time;
1603 ret = true;
1604 }
1605 }
1606
1607 if (!system_state->prefs()->SetInt64(state_variable_key,
1608 now.ToInternalValue())) {
1609 LOG(ERROR) << "Error storing time-stamp in " << state_variable_key;
1610 }
1611
1612 return ret;
1613}
1614
1615bool MonotonicDurationHelper(SystemState* system_state,
1616 int64_t* storage,
Alex Deymof329b932014-10-30 01:37:48 -07001617 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001618 bool ret = false;
1619
Alex Deymof329b932014-10-30 01:37:48 -07001620 Time now = system_state->clock()->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001621 if (*storage != 0) {
Alex Deymof329b932014-10-30 01:37:48 -07001622 Time stored_time = Time::FromInternalValue(*storage);
David Zeuthen33bae492014-02-25 16:16:18 -08001623 *out_duration = now - stored_time;
1624 ret = true;
1625 }
1626 *storage = now.ToInternalValue();
1627
1628 return ret;
1629}
1630
Allie Wood78750a42015-02-11 15:42:11 -08001631bool GetMinorVersion(base::FilePath path, uint32_t* minor_version) {
1632 chromeos::KeyValueStore store;
Alex Deymo60ca1a72015-06-18 18:19:15 -07001633 string result;
Allie Wood78750a42015-02-11 15:42:11 -08001634 if (base::PathExists(path) && store.Load(path) &&
1635 store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -08001636 if (!base::StringToUint(result, minor_version)) {
1637 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
1638 return false;
1639 }
Allie Wood78750a42015-02-11 15:42:11 -08001640 return true;
1641 }
1642 return false;
1643}
1644
Alex Deymo60ca1a72015-06-18 18:19:15 -07001645bool ReadExtents(const string& path, const vector<Extent>& extents,
Allie Wood56873452015-03-27 17:48:40 -07001646 chromeos::Blob* out_data, ssize_t out_data_size,
1647 size_t block_size) {
1648 chromeos::Blob data(out_data_size);
1649 ssize_t bytes_read = 0;
1650 int fd = open(path.c_str(), O_RDONLY);
1651 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
1652 ScopedFdCloser fd_closer(&fd);
1653
Gilad Arnold41e34742015-05-11 11:31:50 -07001654 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001655 ssize_t bytes_read_this_iteration = 0;
1656 ssize_t bytes = extent.num_blocks() * block_size;
1657 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
1658 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1659 &data[bytes_read],
1660 bytes,
1661 extent.start_block() * block_size,
1662 &bytes_read_this_iteration));
1663 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1664 bytes_read += bytes_read_this_iteration;
1665 }
1666 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1667 *out_data = data;
1668 return true;
1669}
1670
adlr@google.com3defe6a2009-12-04 20:57:17 +00001671} // namespace utils
1672
1673} // namespace chromeos_update_engine