blob: dd08a89060759da3be91adbbc0403122e373bbc5 [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>
Alex Deymo192393b2014-11-10 15:58:38 -080025#include <ext2fs/ext2fs.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080026#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000027#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
Alex Deymoc4acdf42014-05-28 21:07:10 -070030#include <sys/mount.h>
31#include <sys/resource.h>
32#include <sys/stat.h>
33#include <sys/types.h>
34#include <sys/wait.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000035#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070036
adlr@google.com3defe6a2009-12-04 20:57:17 +000037#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070038#include <utility>
Chris Sosac1972482013-04-30 22:31:10 -070039#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070040
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070041#include <base/callback.h>
Ben Chan736fcb52014-05-21 18:28:22 -070042#include <base/files/file_path.h>
Alex Deymo192393b2014-11-10 15:58:38 -080043#include <base/files/file_util.h>
Ben Chan736fcb52014-05-21 18:28:22 -070044#include <base/files/scoped_file.h>
Alex Deymoc00c98a2015-03-17 17:38:00 -070045#include <base/format_macros.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070046#include <base/location.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040047#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080048#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050049#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070050#include <base/strings/string_number_conversions.h>
51#include <base/strings/string_split.h>
52#include <base/strings/string_util.h>
53#include <base/strings/stringprintf.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070054#include <brillo/data_encoding.h>
55#include <brillo/message_loops/message_loop.h>
Will Drewry8f71da82010-08-30 14:07:11 -050056
Alex Deymo39910dc2015-11-09 17:04:30 -080057#include "update_engine/common/clock_interface.h"
58#include "update_engine/common/constants.h"
59#include "update_engine/common/prefs_interface.h"
60#include "update_engine/common/subprocess.h"
Darin Petkov33d30642010-08-04 10:18:57 -070061#include "update_engine/omaha_request_params.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080062#include "update_engine/payload_consumer/file_descriptor.h"
63#include "update_engine/payload_consumer/file_writer.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080064#include "update_engine/system_state.h"
65#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000066
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070067using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080068using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000069using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070070using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000071using std::string;
72using std::vector;
73
74namespace chromeos_update_engine {
75
Ben Chan77a1eba2012-10-07 22:54:55 -070076namespace {
77
78// The following constants control how UnmountFilesystem should retry if
79// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
80// one second.
81const int kUnmountMaxNumOfRetries = 5;
82const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070083
84// Number of bytes to read from a file to attempt to detect its contents. Used
85// in GetFileFormat.
86const int kGetFileFormatMaxHeaderSize = 32;
87
Alex Deymodd132f32015-09-14 19:12:07 -070088// The path to the kernel's boot_id.
89const char kBootIdPath[] = "/proc/sys/kernel/random/boot_id";
90
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080091// Return true if |disk_name| is an MTD or a UBI device. Note that this test is
92// simply based on the name of the device.
93bool IsMtdDeviceName(const string& disk_name) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070094 return base::StartsWithASCII(disk_name, "/dev/ubi", true) ||
95 base::StartsWithASCII(disk_name, "/dev/mtd", true);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080096}
97
98// Return the device name for the corresponding partition on a NAND device.
99// WARNING: This function returns device names that are not mountable.
100string MakeNandPartitionName(int partition_num) {
101 switch (partition_num) {
102 case 2:
103 case 4:
104 case 6: {
105 return base::StringPrintf("/dev/mtd%d", partition_num);
106 }
107 default: {
108 return base::StringPrintf("/dev/ubi%d_0", partition_num);
109 }
110 }
111}
112
113// Return the device name for the corresponding partition on a NAND device that
114// may be mountable (but may not be writable).
115string MakeNandPartitionNameForMount(int partition_num) {
116 switch (partition_num) {
117 case 2:
118 case 4:
119 case 6: {
120 return base::StringPrintf("/dev/mtd%d", partition_num);
121 }
122 case 3:
123 case 5:
124 case 7: {
125 return base::StringPrintf("/dev/ubiblock%d_0", partition_num);
126 }
127 default: {
128 return base::StringPrintf("/dev/ubi%d_0", partition_num);
129 }
130 }
131}
132
Alex Deymo5aa1c542015-09-18 01:02:33 -0700133// If |path| is absolute, or explicit relative to the current working directory,
134// leaves it as is. Otherwise, uses the system's temp directory, as defined by
135// base::GetTempDir() and prepends it to |path|. On success stores the full
136// temporary path in |template_path| and returns true.
137bool GetTempName(const string& path, base::FilePath* template_path) {
138 if (path[0] == '/' || base::StartsWithASCII(path, "./", true) ||
139 base::StartsWithASCII(path, "../", true)) {
140 *template_path = base::FilePath(path);
141 return true;
142 }
143
144 base::FilePath temp_dir;
145 TEST_AND_RETURN_FALSE(base::GetTempDir(&temp_dir));
146 *template_path = temp_dir.Append(path);
147 return true;
148}
149
Ben Chan77a1eba2012-10-07 22:54:55 -0700150} // namespace
151
adlr@google.com3defe6a2009-12-04 20:57:17 +0000152namespace utils {
153
Chris Sosa4f8ee272012-11-30 13:01:54 -0800154// Cgroup container is created in update-engine's upstart script located at
155// /etc/init/update-engine.conf.
156static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
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 Vakulenko6a9d3492015-06-15 12:53:22 -0700431 if (!base::StartsWithASCII(partition_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800432 LOG(ERROR) << "Invalid partition device name: " << partition_name;
433 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700434 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800435
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700436 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
437 if (last_nondigit_pos == string::npos ||
438 (last_nondigit_pos + 1) == partition_name.size()) {
439 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800440 return false;
441 }
442
Alex Deymof329b932014-10-30 01:37:48 -0700443 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700444 if (partition_name[last_nondigit_pos] == '_') {
445 // NAND block devices have weird naming which could be something
446 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
447 size_t prev_nondigit_pos =
448 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
449 if (prev_nondigit_pos == string::npos ||
450 (prev_nondigit_pos + 1) == last_nondigit_pos) {
451 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
452 return false;
453 }
454
455 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
456 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800457 }
458
459 if (out_disk_name) {
460 // Special case for MMC devices which have the following naming scheme:
461 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700462 size_t disk_name_len = last_nondigit_pos;
463 if (partition_name[last_nondigit_pos] != 'p' ||
464 last_nondigit_pos == 0 ||
465 !isdigit(partition_name[last_nondigit_pos - 1])) {
466 disk_name_len++;
467 }
468 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800469 }
470
471 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700472 string partition_str = partition_name.substr(last_nondigit_pos + 1,
473 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800474 *out_partition_num = atoi(partition_str.c_str());
475 }
476 return true;
477}
478
Alex Deymof329b932014-10-30 01:37:48 -0700479string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800480 if (partition_num < 1) {
481 LOG(ERROR) << "Invalid partition number: " << partition_num;
482 return string();
483 }
484
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700485 if (!base::StartsWithASCII(disk_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800486 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700487 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800488 }
489
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800490 if (IsMtdDeviceName(disk_name)) {
491 // Special case for UBI block devices.
492 // 1. ubiblock is not writable, we need to use plain "ubi".
493 // 2. There is a "_0" suffix.
494 return MakeNandPartitionName(partition_num);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800495 }
496
Alex Deymof329b932014-10-30 01:37:48 -0700497 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700498 if (isdigit(partition_name.back())) {
499 // Special case for devices with names ending with a digit.
500 // Add "p" to separate the disk name from partition number,
501 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800502 partition_name += 'p';
503 }
504
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700505 partition_name += std::to_string(partition_num);
506
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800507 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700508}
509
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800510string MakePartitionNameForMount(const string& part_name) {
511 if (IsMtdDeviceName(part_name)) {
512 int partition_num;
513 if (!SplitPartitionName(part_name, nullptr, &partition_num)) {
514 return "";
515 }
516 return MakeNandPartitionNameForMount(partition_num);
517 }
518 return part_name;
519}
520
Alex Deymof329b932014-10-30 01:37:48 -0700521string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000522 char buf[100];
523 buf[0] = '\0';
524 return strerror_r(err, buf, sizeof(buf));
525}
526
adlr@google.com3defe6a2009-12-04 20:57:17 +0000527bool FileExists(const char* path) {
528 struct stat stbuf;
529 return 0 == lstat(path, &stbuf);
530}
531
Darin Petkov30291ed2010-11-12 10:23:06 -0800532bool IsSymlink(const char* path) {
533 struct stat stbuf;
534 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
535}
536
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800537bool TryAttachingUbiVolume(int volume_num, int timeout) {
538 const string volume_path = base::StringPrintf("/dev/ubi%d_0", volume_num);
539 if (FileExists(volume_path.c_str())) {
540 return true;
541 }
542
543 int exit_code;
544 vector<string> cmd = {
545 "ubiattach",
546 "-m",
547 base::StringPrintf("%d", volume_num),
548 "-d",
549 base::StringPrintf("%d", volume_num)
550 };
551 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
552 TEST_AND_RETURN_FALSE(exit_code == 0);
553
554 cmd = {
555 "ubiblock",
556 "--create",
557 volume_path
558 };
559 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
560 TEST_AND_RETURN_FALSE(exit_code == 0);
561
562 while (timeout > 0 && !FileExists(volume_path.c_str())) {
563 sleep(1);
564 timeout--;
565 }
566
567 return FileExists(volume_path.c_str());
568}
569
Alex Deymof329b932014-10-30 01:37:48 -0700570bool MakeTempFile(const string& base_filename_template,
571 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700572 int* fd) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700573 base::FilePath filename_template;
574 TEST_AND_RETURN_FALSE(
575 GetTempName(base_filename_template, &filename_template));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700576 DCHECK(filename || fd);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700577 vector<char> buf(filename_template.value().size() + 1);
578 memcpy(buf.data(), filename_template.value().data(),
579 filename_template.value().size());
580 buf[filename_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700581
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800582 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700583 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
584 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800585 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700586 }
587 if (fd) {
588 *fd = mkstemp_fd;
589 } else {
590 close(mkstemp_fd);
591 }
592 return true;
593}
594
Alex Deymof329b932014-10-30 01:37:48 -0700595bool MakeTempDirectory(const string& base_dirname_template,
596 string* dirname) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700597 base::FilePath dirname_template;
598 TEST_AND_RETURN_FALSE(GetTempName(base_dirname_template, &dirname_template));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700599 DCHECK(dirname);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700600 vector<char> buf(dirname_template.value().size() + 1);
601 memcpy(buf.data(), dirname_template.value().data(),
602 dirname_template.value().size());
603 buf[dirname_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700604
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800605 char* return_code = mkdtemp(buf.data());
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700606 TEST_AND_RETURN_FALSE_ERRNO(return_code != nullptr);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800607 *dirname = buf.data();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700608 return true;
609}
610
adlr@google.com3defe6a2009-12-04 20:57:17 +0000611bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700612 const string& mountpoint,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700613 unsigned long mountflags) { // NOLINT(runtime/int)
Alex Deymo4c82df32014-11-10 22:25:57 -0800614 // TODO(sosa): Remove "ext3" once crbug.com/208022 is resolved.
Alex Deymo5fc5e102015-09-18 10:36:21 -0700615 const vector<const char*> fstypes{"ext2", "ext3", "ext4", "squashfs"};
Alex Deymo4c82df32014-11-10 22:25:57 -0800616 for (const char* fstype : fstypes) {
617 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
618 nullptr);
619 if (rc == 0)
620 return true;
621
622 PLOG(WARNING) << "Unable to mount destination device " << device
623 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000624 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800625 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
626 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000627}
628
629bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700630 for (int num_retries = 0; ; ++num_retries) {
631 if (umount(mountpoint.c_str()) == 0)
632 break;
633
634 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
635 num_retries < kUnmountMaxNumOfRetries);
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700636 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700637 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000638 return true;
639}
640
Alex Deymof329b932014-10-30 01:37:48 -0700641bool GetFilesystemSize(const string& device,
Darin Petkovd3f8c892010-10-12 21:38:45 -0700642 int* out_block_count,
643 int* out_block_size) {
644 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
Alex Deymoe7141c62014-10-17 14:03:01 -0700645 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700646 ScopedFdCloser fd_closer(&fd);
647 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
648}
649
650bool GetFilesystemSizeFromFD(int fd,
651 int* out_block_count,
652 int* out_block_size) {
653 TEST_AND_RETURN_FALSE(fd >= 0);
654
Alex Deymo192393b2014-11-10 15:58:38 -0800655 // Determine the filesystem size by directly reading the block count and
656 // block size information from the superblock. Supported FS are ext3 and
657 // squashfs.
658
659 // Read from the fd only once and detect in memory. The first 2 KiB is enough
660 // to read the ext2 superblock (located at offset 1024) and the squashfs
661 // superblock (located at offset 0).
662 const ssize_t kBufferSize = 2048;
663
664 uint8_t buffer[kBufferSize];
665 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, 0)) != kBufferSize) {
666 PLOG(ERROR) << "Unable to read the file system header:";
Darin Petkovd3f8c892010-10-12 21:38:45 -0700667 return false;
668 }
Alex Deymo192393b2014-11-10 15:58:38 -0800669
670 if (GetSquashfs4Size(buffer, kBufferSize, out_block_count, out_block_size))
671 return true;
672 if (GetExt3Size(buffer, kBufferSize, out_block_count, out_block_size))
673 return true;
674
675 LOG(ERROR) << "Unable to determine file system type.";
676 return false;
677}
678
679bool GetExt3Size(const uint8_t* buffer, size_t buffer_size,
680 int* out_block_count,
681 int* out_block_size) {
682 // See include/linux/ext2_fs.h for more details on the structure. We obtain
683 // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
684 // library.
685 if (buffer_size < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
686 return false;
687
688 const uint8_t* superblock = buffer + SUPERBLOCK_OFFSET;
689
690 // ext3_fs.h: ext3_super_block.s_blocks_count
691 uint32_t block_count =
692 *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
693
694 // ext3_fs.h: ext3_super_block.s_log_block_size
695 uint32_t log_block_size =
696 *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
697
698 // ext3_fs.h: ext3_super_block.s_magic
699 uint16_t magic =
700 *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
701
Darin Petkovd3f8c892010-10-12 21:38:45 -0700702 block_count = le32toh(block_count);
Alex Deymo192393b2014-11-10 15:58:38 -0800703 log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700704 magic = le16toh(magic);
705
706 // Sanity check the parameters.
Alex Deymo192393b2014-11-10 15:58:38 -0800707 TEST_AND_RETURN_FALSE(magic == EXT2_SUPER_MAGIC);
708 TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
709 log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700710 TEST_AND_RETURN_FALSE(block_count > 0);
711
Alex Deymo192393b2014-11-10 15:58:38 -0800712 if (out_block_count)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700713 *out_block_count = block_count;
Alex Deymo192393b2014-11-10 15:58:38 -0800714 if (out_block_size)
715 *out_block_size = 1 << log_block_size;
716 return true;
717}
718
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800719bool GetSquashfs4Size(const uint8_t* buffer, size_t buffer_size,
Alex Deymo192393b2014-11-10 15:58:38 -0800720 int* out_block_count,
721 int* out_block_size) {
722 // See fs/squashfs/squashfs_fs.h for format details. We only support
723 // Squashfs 4.x little endian.
724
725 // sizeof(struct squashfs_super_block)
726 const size_t kSquashfsSuperBlockSize = 96;
727 if (buffer_size < kSquashfsSuperBlockSize)
728 return false;
729
730 // Check magic, squashfs_fs.h: SQUASHFS_MAGIC
731 if (memcmp(buffer, "hsqs", 4) != 0)
732 return false; // Only little endian is supported.
733
734 // squashfs_fs.h: struct squashfs_super_block.s_major
735 uint16_t s_major = *reinterpret_cast<const uint16_t*>(
736 buffer + 5 * sizeof(uint32_t) + 4 * sizeof(uint16_t));
737
738 if (s_major != 4) {
739 LOG(ERROR) << "Found unsupported squashfs major version " << s_major;
740 return false;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700741 }
Alex Deymo192393b2014-11-10 15:58:38 -0800742
743 // squashfs_fs.h: struct squashfs_super_block.bytes_used
744 uint64_t bytes_used = *reinterpret_cast<const int64_t*>(
745 buffer + 5 * sizeof(uint32_t) + 6 * sizeof(uint16_t) + sizeof(uint64_t));
746
747 const int block_size = 4096;
748
749 // The squashfs' bytes_used doesn't need to be aligned with the block boundary
750 // so we round up to the nearest blocksize.
751 if (out_block_count)
752 *out_block_count = (bytes_used + block_size - 1) / block_size;
753 if (out_block_size)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700754 *out_block_size = block_size;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700755 return true;
756}
757
Alex Deymo60ca1a72015-06-18 18:19:15 -0700758bool IsExtFilesystem(const string& device) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700759 brillo::Blob header;
Alex Deymode942f32015-03-13 11:57:15 -0700760 // The first 2 KiB is enough to read the ext2 superblock (located at offset
761 // 1024).
762 if (!ReadFileChunk(device, 0, 2048, &header))
763 return false;
764 return GetExt3Size(header.data(), header.size(), nullptr, nullptr);
765}
766
Alex Deymo60ca1a72015-06-18 18:19:15 -0700767bool IsSquashfsFilesystem(const string& device) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700768 brillo::Blob header;
Alex Deymode942f32015-03-13 11:57:15 -0700769 // The first 96 is enough to read the squashfs superblock.
770 const ssize_t kSquashfsSuperBlockSize = 96;
771 if (!ReadFileChunk(device, 0, kSquashfsSuperBlockSize, &header))
772 return false;
773 return GetSquashfs4Size(header.data(), header.size(), nullptr, nullptr);
774}
775
Alex Deymo032e7722014-03-25 17:53:56 -0700776// Tries to parse the header of an ELF file to obtain a human-readable
777// description of it on the |output| string.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800778static bool GetFileFormatELF(const uint8_t* buffer, size_t size,
779 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700780 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700781 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700782 return false;
783 *output = "ELF";
784
785 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700786 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700787 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700788 switch (buffer[EI_CLASS]) {
789 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700790 *output += " 32-bit";
791 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700792 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700793 *output += " 64-bit";
794 break;
795 default:
796 *output += " ?-bit";
797 }
798
799 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700800 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700801 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800802 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700803 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700804 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700805 *output += " little-endian";
806 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700807 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700808 *output += " big-endian";
809 break;
810 default:
811 *output += " ?-endian";
812 // Don't parse anything after the 0x10 offset if endianness is unknown.
813 return true;
814 }
815
Alex Deymoc1711e22014-08-08 13:16:23 -0700816 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
817 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
818 // and size is the same for both 32 and 64 bits.
819 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700820 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700821 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700822 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700823 if (ei_data == ELFDATA2LSB)
824 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700825 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700826 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700827
828 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700829 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700830 *output += " x86";
831 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700832 case EM_MIPS:
833 *output += " mips";
834 break;
835 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700836 *output += " arm";
837 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700838 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700839 *output += " x86-64";
840 break;
841 default:
842 *output += " unknown-arch";
843 }
844 return true;
845}
846
847string GetFileFormat(const string& path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700848 brillo::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700849 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
850 return "File not found.";
851
852 string result;
853 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
854 return result;
855
856 return "data";
857}
858
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800859namespace {
860// Do the actual trigger. We do it as a main-loop callback to (try to) get a
861// consistent stack trace.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700862void TriggerCrashReporterUpload() {
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800863 pid_t pid = fork();
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700864 CHECK_GE(pid, 0) << "fork failed"; // fork() failed. Something is very wrong.
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800865 if (pid == 0) {
866 // We are the child. Crash.
867 abort(); // never returns
868 }
869 // We are the parent. Wait for child to terminate.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700870 pid_t result = waitpid(pid, nullptr, 0);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800871 LOG_IF(ERROR, result < 0) << "waitpid() failed";
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800872}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700873} // namespace
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800874
875void ScheduleCrashReporterUpload() {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700876 brillo::MessageLoop::current()->PostTask(
Alex Deymo60ca1a72015-06-18 18:19:15 -0700877 FROM_HERE,
878 base::Bind(&TriggerCrashReporterUpload));
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800879}
880
Chris Sosa4f8ee272012-11-30 13:01:54 -0800881bool SetCpuShares(CpuShares shares) {
882 string string_shares = base::IntToString(static_cast<int>(shares));
883 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
884 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700885 if (utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
886 string_shares.size())) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800887 return true;
888 } else {
889 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
890 << " using " << cpu_shares_file;
891 return false;
892 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700893}
894
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700895int FuzzInt(int value, unsigned int range) {
896 int min = value - range / 2;
897 int max = value + range - range / 2;
898 return base::RandInt(min, max);
899}
900
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700901string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800902 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700903}
904
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800905string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400906 string str;
907
908 // Handle negative durations by prefixing with a minus.
909 if (delta.ToInternalValue() < 0) {
910 delta *= -1;
911 str = "-";
912 }
913
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700914 // Canonicalize into days, hours, minutes, seconds and microseconds.
915 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800916 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700917 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800918 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700919 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800920 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700921 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800922 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700923 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800924
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700925 if (days)
926 base::StringAppendF(&str, "%ud", days);
927 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800928 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700929 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800930 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700931 base::StringAppendF(&str, "%u", secs);
932 if (usecs) {
933 int width = 6;
934 while ((usecs / 10) * 10 == usecs) {
935 usecs /= 10;
936 width--;
937 }
938 base::StringAppendF(&str, ".%0*u", width, usecs);
939 }
940 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800941 return str;
942}
943
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700944string ToString(const Time utc_time) {
945 Time::Exploded exp_time;
946 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700947 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700948 exp_time.month,
949 exp_time.day_of_month,
950 exp_time.year,
951 exp_time.hour,
952 exp_time.minute,
953 exp_time.second);
954}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000955
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700956string ToString(bool b) {
957 return (b ? "true" : "false");
958}
959
Alex Deymo1c656c42013-06-28 11:02:14 -0700960string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700961 switch (source) {
962 case kDownloadSourceHttpsServer: return "HttpsServer";
963 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700964 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700965 case kNumDownloadSources: return "Unknown";
966 // Don't add a default case to let the compiler warn about newly added
967 // download sources which should be added here.
968 }
969
970 return "Unknown";
971}
972
Alex Deymo1c656c42013-06-28 11:02:14 -0700973string ToString(PayloadType payload_type) {
974 switch (payload_type) {
975 case kPayloadTypeDelta: return "Delta";
976 case kPayloadTypeFull: return "Full";
977 case kPayloadTypeForcedFull: return "ForcedFull";
978 case kNumPayloadTypes: return "Unknown";
979 // Don't add a default case to let the compiler warn about newly added
980 // payload types which should be added here.
981 }
982
983 return "Unknown";
984}
985
David Zeuthena99981f2013-04-29 13:42:47 -0700986ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700987 // Ignore the higher order bits in the code by applying the mask as
988 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700989 // with values less than ErrorCode::kUmaReportedMax.
990 ErrorCode base_code = static_cast<ErrorCode>(
991 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700992
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800993 // Make additional adjustments required for UMA and error classification.
994 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
995 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700996 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700997 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800998 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800999 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001000 << " to ErrorCode::kOmahaErrorInHTTPResponse";
1001 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001002 }
1003
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001004 return base_code;
1005}
1006
David Zeuthen33bae492014-02-25 16:16:18 -08001007metrics::AttemptResult GetAttemptResult(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001008 ErrorCode base_code = static_cast<ErrorCode>(
1009 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001010
1011 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001012 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001013 return metrics::AttemptResult::kUpdateSucceeded;
1014
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001015 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001016 return metrics::AttemptResult::kPayloadDownloadError;
1017
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001018 case ErrorCode::kDownloadInvalidMetadataSize:
1019 case ErrorCode::kDownloadInvalidMetadataMagicString:
1020 case ErrorCode::kDownloadMetadataSignatureError:
1021 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1022 case ErrorCode::kPayloadMismatchedType:
1023 case ErrorCode::kUnsupportedMajorPayloadVersion:
1024 case ErrorCode::kUnsupportedMinorPayloadVersion:
1025 case ErrorCode::kDownloadNewPartitionInfoError:
1026 case ErrorCode::kDownloadSignatureMissingInManifest:
1027 case ErrorCode::kDownloadManifestParseError:
1028 case ErrorCode::kDownloadOperationHashMissingError:
David Zeuthen33bae492014-02-25 16:16:18 -08001029 return metrics::AttemptResult::kMetadataMalformed;
1030
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001031 case ErrorCode::kDownloadOperationHashMismatch:
1032 case ErrorCode::kDownloadOperationHashVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001033 return metrics::AttemptResult::kOperationMalformed;
1034
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001035 case ErrorCode::kDownloadOperationExecutionError:
1036 case ErrorCode::kInstallDeviceOpenError:
1037 case ErrorCode::kKernelDeviceOpenError:
1038 case ErrorCode::kDownloadWriteError:
1039 case ErrorCode::kFilesystemCopierError:
Allie Woodeb9e6d82015-04-17 13:55:30 -07001040 case ErrorCode::kFilesystemVerifierError:
David Zeuthen33bae492014-02-25 16:16:18 -08001041 return metrics::AttemptResult::kOperationExecutionError;
1042
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001043 case ErrorCode::kDownloadMetadataSignatureMismatch:
David Zeuthen33bae492014-02-25 16:16:18 -08001044 return metrics::AttemptResult::kMetadataVerificationFailed;
1045
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001046 case ErrorCode::kPayloadSizeMismatchError:
1047 case ErrorCode::kPayloadHashMismatchError:
1048 case ErrorCode::kDownloadPayloadVerificationError:
1049 case ErrorCode::kSignedDeltaPayloadExpectedError:
1050 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001051 return metrics::AttemptResult::kPayloadVerificationFailed;
1052
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001053 case ErrorCode::kNewRootfsVerificationError:
1054 case ErrorCode::kNewKernelVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001055 return metrics::AttemptResult::kVerificationFailed;
1056
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001057 case ErrorCode::kPostinstallRunnerError:
1058 case ErrorCode::kPostinstallBootedFromFirmwareB:
1059 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
David Zeuthen33bae492014-02-25 16:16:18 -08001060 return metrics::AttemptResult::kPostInstallFailed;
1061
1062 // We should never get these errors in the update-attempt stage so
1063 // return internal error if this happens.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001064 case ErrorCode::kError:
1065 case ErrorCode::kOmahaRequestXMLParseError:
1066 case ErrorCode::kOmahaRequestError:
1067 case ErrorCode::kOmahaResponseHandlerError:
1068 case ErrorCode::kDownloadStateInitializationError:
1069 case ErrorCode::kOmahaRequestEmptyResponseError:
1070 case ErrorCode::kDownloadInvalidMetadataSignature:
1071 case ErrorCode::kOmahaResponseInvalid:
1072 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1073 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1074 case ErrorCode::kOmahaErrorInHTTPResponse:
1075 case ErrorCode::kDownloadMetadataSignatureMissingError:
1076 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1077 case ErrorCode::kPostinstallPowerwashError:
1078 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -04001079 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
David Zeuthen33bae492014-02-25 16:16:18 -08001080 return metrics::AttemptResult::kInternalError;
1081
1082 // Special flags. These can't happen (we mask them out above) but
1083 // the compiler doesn't know that. Just break out so we can warn and
1084 // return |kInternalError|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001085 case ErrorCode::kUmaReportedMax:
1086 case ErrorCode::kOmahaRequestHTTPResponseBase:
1087 case ErrorCode::kDevModeFlag:
1088 case ErrorCode::kResumedFlag:
1089 case ErrorCode::kTestImageFlag:
1090 case ErrorCode::kTestOmahaUrlFlag:
1091 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001092 break;
1093 }
1094
1095 LOG(ERROR) << "Unexpected error code " << base_code;
1096 return metrics::AttemptResult::kInternalError;
1097}
1098
1099
1100metrics::DownloadErrorCode GetDownloadErrorCode(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001101 ErrorCode base_code = static_cast<ErrorCode>(
1102 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001103
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001104 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
1105 int http_status =
1106 static_cast<int>(base_code) -
1107 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase);
David Zeuthen33bae492014-02-25 16:16:18 -08001108 if (http_status >= 200 && http_status <= 599) {
1109 return static_cast<metrics::DownloadErrorCode>(
1110 static_cast<int>(metrics::DownloadErrorCode::kHttpStatus200) +
1111 http_status - 200);
1112 } else if (http_status == 0) {
1113 // The code is using HTTP Status 0 for "Unable to get http
1114 // response code."
1115 return metrics::DownloadErrorCode::kDownloadError;
1116 }
1117 LOG(WARNING) << "Unexpected HTTP status code " << http_status;
1118 return metrics::DownloadErrorCode::kHttpStatusOther;
1119 }
1120
1121 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001122 // Unfortunately, ErrorCode::kDownloadTransferError is returned for a wide
David Zeuthen33bae492014-02-25 16:16:18 -08001123 // variety of errors (proxy errors, host not reachable, timeouts etc.).
1124 //
1125 // For now just map that to kDownloading. See http://crbug.com/355745
1126 // for how we plan to add more detail in the future.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001127 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001128 return metrics::DownloadErrorCode::kDownloadError;
1129
1130 // All of these error codes are not related to downloading so break
1131 // out so we can warn and return InputMalformed.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001132 case ErrorCode::kSuccess:
1133 case ErrorCode::kError:
1134 case ErrorCode::kOmahaRequestError:
1135 case ErrorCode::kOmahaResponseHandlerError:
1136 case ErrorCode::kFilesystemCopierError:
1137 case ErrorCode::kPostinstallRunnerError:
1138 case ErrorCode::kPayloadMismatchedType:
1139 case ErrorCode::kInstallDeviceOpenError:
1140 case ErrorCode::kKernelDeviceOpenError:
1141 case ErrorCode::kPayloadHashMismatchError:
1142 case ErrorCode::kPayloadSizeMismatchError:
1143 case ErrorCode::kDownloadPayloadVerificationError:
1144 case ErrorCode::kDownloadNewPartitionInfoError:
1145 case ErrorCode::kDownloadWriteError:
1146 case ErrorCode::kNewRootfsVerificationError:
1147 case ErrorCode::kNewKernelVerificationError:
1148 case ErrorCode::kSignedDeltaPayloadExpectedError:
1149 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1150 case ErrorCode::kPostinstallBootedFromFirmwareB:
1151 case ErrorCode::kDownloadStateInitializationError:
1152 case ErrorCode::kDownloadInvalidMetadataMagicString:
1153 case ErrorCode::kDownloadSignatureMissingInManifest:
1154 case ErrorCode::kDownloadManifestParseError:
1155 case ErrorCode::kDownloadMetadataSignatureError:
1156 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1157 case ErrorCode::kDownloadMetadataSignatureMismatch:
1158 case ErrorCode::kDownloadOperationHashVerificationError:
1159 case ErrorCode::kDownloadOperationExecutionError:
1160 case ErrorCode::kDownloadOperationHashMismatch:
1161 case ErrorCode::kOmahaRequestEmptyResponseError:
1162 case ErrorCode::kOmahaRequestXMLParseError:
1163 case ErrorCode::kDownloadInvalidMetadataSize:
1164 case ErrorCode::kDownloadInvalidMetadataSignature:
1165 case ErrorCode::kOmahaResponseInvalid:
1166 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1167 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1168 case ErrorCode::kOmahaErrorInHTTPResponse:
1169 case ErrorCode::kDownloadOperationHashMissingError:
1170 case ErrorCode::kDownloadMetadataSignatureMissingError:
1171 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1172 case ErrorCode::kPostinstallPowerwashError:
1173 case ErrorCode::kUpdateCanceledByChannelChange:
1174 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1175 case ErrorCode::kUnsupportedMajorPayloadVersion:
1176 case ErrorCode::kUnsupportedMinorPayloadVersion:
David Zeuthenf3e28012014-08-26 18:23:52 -04001177 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -07001178 case ErrorCode::kFilesystemVerifierError:
David Zeuthen33bae492014-02-25 16:16:18 -08001179 break;
1180
1181 // Special flags. These can't happen (we mask them out above) but
1182 // the compiler doesn't know that. Just break out so we can warn and
1183 // return |kInputMalformed|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001184 case ErrorCode::kUmaReportedMax:
1185 case ErrorCode::kOmahaRequestHTTPResponseBase:
1186 case ErrorCode::kDevModeFlag:
1187 case ErrorCode::kResumedFlag:
1188 case ErrorCode::kTestImageFlag:
1189 case ErrorCode::kTestOmahaUrlFlag:
1190 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001191 LOG(ERROR) << "Unexpected error code " << base_code;
1192 break;
1193 }
1194
1195 return metrics::DownloadErrorCode::kInputMalformed;
1196}
1197
David Zeuthenb281f072014-04-02 10:20:19 -07001198metrics::ConnectionType GetConnectionType(
1199 NetworkConnectionType type,
1200 NetworkTethering tethering) {
1201 switch (type) {
Alex Deymo75eac7e2015-07-29 13:39:14 -07001202 case NetworkConnectionType::kUnknown:
David Zeuthenb281f072014-04-02 10:20:19 -07001203 return metrics::ConnectionType::kUnknown;
1204
Alex Deymo75eac7e2015-07-29 13:39:14 -07001205 case NetworkConnectionType::kEthernet:
David Zeuthenb281f072014-04-02 10:20:19 -07001206 if (tethering == NetworkTethering::kConfirmed)
1207 return metrics::ConnectionType::kTetheredEthernet;
1208 else
1209 return metrics::ConnectionType::kEthernet;
1210
Alex Deymo75eac7e2015-07-29 13:39:14 -07001211 case NetworkConnectionType::kWifi:
David Zeuthenb281f072014-04-02 10:20:19 -07001212 if (tethering == NetworkTethering::kConfirmed)
1213 return metrics::ConnectionType::kTetheredWifi;
1214 else
1215 return metrics::ConnectionType::kWifi;
1216
Alex Deymo75eac7e2015-07-29 13:39:14 -07001217 case NetworkConnectionType::kWimax:
David Zeuthenb281f072014-04-02 10:20:19 -07001218 return metrics::ConnectionType::kWimax;
1219
Alex Deymo75eac7e2015-07-29 13:39:14 -07001220 case NetworkConnectionType::kBluetooth:
David Zeuthenb281f072014-04-02 10:20:19 -07001221 return metrics::ConnectionType::kBluetooth;
1222
Alex Deymo75eac7e2015-07-29 13:39:14 -07001223 case NetworkConnectionType::kCellular:
David Zeuthenb281f072014-04-02 10:20:19 -07001224 return metrics::ConnectionType::kCellular;
1225 }
1226
Alex Deymo75eac7e2015-07-29 13:39:14 -07001227 LOG(ERROR) << "Unexpected network connection type: type="
1228 << static_cast<int>(type)
David Zeuthenb281f072014-04-02 10:20:19 -07001229 << ", tethering=" << static_cast<int>(tethering);
1230
1231 return metrics::ConnectionType::kUnknown;
1232}
1233
David Zeuthena99981f2013-04-29 13:42:47 -07001234string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001235 // If the given code has both parts (i.e. the error code part and the flags
1236 // part) then strip off the flags part since the switch statement below
1237 // has case statements only for the base error code or a single flag but
1238 // doesn't support any combinations of those.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001239 if ((static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags)) &&
1240 (static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags)))
1241 code = static_cast<ErrorCode>(
1242 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001243 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001244 case ErrorCode::kSuccess: return "ErrorCode::kSuccess";
1245 case ErrorCode::kError: return "ErrorCode::kError";
1246 case ErrorCode::kOmahaRequestError: return "ErrorCode::kOmahaRequestError";
1247 case ErrorCode::kOmahaResponseHandlerError:
1248 return "ErrorCode::kOmahaResponseHandlerError";
1249 case ErrorCode::kFilesystemCopierError:
1250 return "ErrorCode::kFilesystemCopierError";
1251 case ErrorCode::kPostinstallRunnerError:
1252 return "ErrorCode::kPostinstallRunnerError";
1253 case ErrorCode::kPayloadMismatchedType:
1254 return "ErrorCode::kPayloadMismatchedType";
1255 case ErrorCode::kInstallDeviceOpenError:
1256 return "ErrorCode::kInstallDeviceOpenError";
1257 case ErrorCode::kKernelDeviceOpenError:
1258 return "ErrorCode::kKernelDeviceOpenError";
1259 case ErrorCode::kDownloadTransferError:
1260 return "ErrorCode::kDownloadTransferError";
1261 case ErrorCode::kPayloadHashMismatchError:
1262 return "ErrorCode::kPayloadHashMismatchError";
1263 case ErrorCode::kPayloadSizeMismatchError:
1264 return "ErrorCode::kPayloadSizeMismatchError";
1265 case ErrorCode::kDownloadPayloadVerificationError:
1266 return "ErrorCode::kDownloadPayloadVerificationError";
1267 case ErrorCode::kDownloadNewPartitionInfoError:
1268 return "ErrorCode::kDownloadNewPartitionInfoError";
1269 case ErrorCode::kDownloadWriteError:
1270 return "ErrorCode::kDownloadWriteError";
1271 case ErrorCode::kNewRootfsVerificationError:
1272 return "ErrorCode::kNewRootfsVerificationError";
1273 case ErrorCode::kNewKernelVerificationError:
1274 return "ErrorCode::kNewKernelVerificationError";
1275 case ErrorCode::kSignedDeltaPayloadExpectedError:
1276 return "ErrorCode::kSignedDeltaPayloadExpectedError";
1277 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1278 return "ErrorCode::kDownloadPayloadPubKeyVerificationError";
1279 case ErrorCode::kPostinstallBootedFromFirmwareB:
1280 return "ErrorCode::kPostinstallBootedFromFirmwareB";
1281 case ErrorCode::kDownloadStateInitializationError:
1282 return "ErrorCode::kDownloadStateInitializationError";
1283 case ErrorCode::kDownloadInvalidMetadataMagicString:
1284 return "ErrorCode::kDownloadInvalidMetadataMagicString";
1285 case ErrorCode::kDownloadSignatureMissingInManifest:
1286 return "ErrorCode::kDownloadSignatureMissingInManifest";
1287 case ErrorCode::kDownloadManifestParseError:
1288 return "ErrorCode::kDownloadManifestParseError";
1289 case ErrorCode::kDownloadMetadataSignatureError:
1290 return "ErrorCode::kDownloadMetadataSignatureError";
1291 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1292 return "ErrorCode::kDownloadMetadataSignatureVerificationError";
1293 case ErrorCode::kDownloadMetadataSignatureMismatch:
1294 return "ErrorCode::kDownloadMetadataSignatureMismatch";
1295 case ErrorCode::kDownloadOperationHashVerificationError:
1296 return "ErrorCode::kDownloadOperationHashVerificationError";
1297 case ErrorCode::kDownloadOperationExecutionError:
1298 return "ErrorCode::kDownloadOperationExecutionError";
1299 case ErrorCode::kDownloadOperationHashMismatch:
1300 return "ErrorCode::kDownloadOperationHashMismatch";
1301 case ErrorCode::kOmahaRequestEmptyResponseError:
1302 return "ErrorCode::kOmahaRequestEmptyResponseError";
1303 case ErrorCode::kOmahaRequestXMLParseError:
1304 return "ErrorCode::kOmahaRequestXMLParseError";
1305 case ErrorCode::kDownloadInvalidMetadataSize:
1306 return "ErrorCode::kDownloadInvalidMetadataSize";
1307 case ErrorCode::kDownloadInvalidMetadataSignature:
1308 return "ErrorCode::kDownloadInvalidMetadataSignature";
1309 case ErrorCode::kOmahaResponseInvalid:
1310 return "ErrorCode::kOmahaResponseInvalid";
1311 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1312 return "ErrorCode::kOmahaUpdateIgnoredPerPolicy";
1313 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1314 return "ErrorCode::kOmahaUpdateDeferredPerPolicy";
1315 case ErrorCode::kOmahaErrorInHTTPResponse:
1316 return "ErrorCode::kOmahaErrorInHTTPResponse";
1317 case ErrorCode::kDownloadOperationHashMissingError:
1318 return "ErrorCode::kDownloadOperationHashMissingError";
1319 case ErrorCode::kDownloadMetadataSignatureMissingError:
1320 return "ErrorCode::kDownloadMetadataSignatureMissingError";
1321 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1322 return "ErrorCode::kOmahaUpdateDeferredForBackoff";
1323 case ErrorCode::kPostinstallPowerwashError:
1324 return "ErrorCode::kPostinstallPowerwashError";
1325 case ErrorCode::kUpdateCanceledByChannelChange:
1326 return "ErrorCode::kUpdateCanceledByChannelChange";
1327 case ErrorCode::kUmaReportedMax:
1328 return "ErrorCode::kUmaReportedMax";
1329 case ErrorCode::kOmahaRequestHTTPResponseBase:
1330 return "ErrorCode::kOmahaRequestHTTPResponseBase";
1331 case ErrorCode::kResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001332 return "Resumed";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001333 case ErrorCode::kDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001334 return "DevMode";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001335 case ErrorCode::kTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001336 return "TestImage";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001337 case ErrorCode::kTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001338 return "TestOmahaUrl";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001339 case ErrorCode::kSpecialFlags:
1340 return "ErrorCode::kSpecialFlags";
1341 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1342 return "ErrorCode::kPostinstallFirmwareRONotUpdatable";
1343 case ErrorCode::kUnsupportedMajorPayloadVersion:
1344 return "ErrorCode::kUnsupportedMajorPayloadVersion";
1345 case ErrorCode::kUnsupportedMinorPayloadVersion:
1346 return "ErrorCode::kUnsupportedMinorPayloadVersion";
David Zeuthenf3e28012014-08-26 18:23:52 -04001347 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
1348 return "ErrorCode::kOmahaRequestXMLHasEntityDecl";
Allie Woodeb9e6d82015-04-17 13:55:30 -07001349 case ErrorCode::kFilesystemVerifierError:
1350 return "ErrorCode::kFilesystemVerifierError";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001351 // Don't add a default case to let the compiler warn about newly added
1352 // error codes which should be added here.
1353 }
1354
1355 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1356}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001357
Gilad Arnold30dedd82013-07-03 06:19:09 -07001358bool CreatePowerwashMarkerFile(const char* file_path) {
1359 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1360 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001361 kPowerwashCommand,
1362 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001363 if (result) {
1364 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1365 } else {
1366 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1367 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001368
1369 return result;
1370}
1371
Gilad Arnold30dedd82013-07-03 06:19:09 -07001372bool DeletePowerwashMarkerFile(const char* file_path) {
1373 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001374 const base::FilePath kPowerwashMarkerPath(marker_file);
1375 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001376
1377 if (result)
1378 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001379 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001380 else
1381 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001382 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001383
1384 return result;
1385}
1386
David Zeuthen27a48bc2013-08-06 12:06:29 -07001387Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -07001388 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1389 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -07001390 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1391}
1392
Alex Deymof329b932014-10-30 01:37:48 -07001393string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001394 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -07001395 for (vector<string>::const_iterator i = vec_str.begin();
1396 i != vec_str.end(); ++i) {
1397 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -07001398 str += ", ";
1399 str += '"';
1400 str += *i;
1401 str += '"';
1402 }
1403 str += "]";
1404 return str;
1405}
1406
David Zeuthen8f191b22013-08-06 12:27:50 -07001407string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001408 string encoded_hash = brillo::data_encoding::Base64Encode(payload_hash);
Alex Deymoc00c98a2015-03-17 17:38:00 -07001409 return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001410 payload_size,
1411 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -07001412}
1413
Alex Deymof329b932014-10-30 01:37:48 -07001414bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -07001415 base::FilePath *out_path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001416 brillo::Blob contents;
David Zeuthene7f89172013-10-31 10:21:04 -07001417
1418 out_path->clear();
1419
1420 if (base64_encoded.size() == 0) {
1421 LOG(ERROR) << "Can't decode empty string.";
1422 return false;
1423 }
1424
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001425 if (!brillo::data_encoding::Base64Decode(base64_encoded, &contents) ||
David Zeuthene7f89172013-10-31 10:21:04 -07001426 contents.size() == 0) {
1427 LOG(ERROR) << "Error decoding base64.";
1428 return false;
1429 }
1430
Alex Vakulenko75039d72014-03-25 12:36:28 -07001431 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001432 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -07001433 LOG(ERROR) << "Error creating temporary file.";
1434 return false;
1435 }
1436
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001437 if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
David Zeuthene7f89172013-10-31 10:21:04 -07001438 PLOG(ERROR) << "Error writing to temporary file.";
1439 if (fclose(file) != 0)
1440 PLOG(ERROR) << "Error closing temporary file.";
1441 if (unlink(out_path->value().c_str()) != 0)
1442 PLOG(ERROR) << "Error unlinking temporary file.";
1443 out_path->clear();
1444 return false;
1445 }
1446
1447 if (fclose(file) != 0) {
1448 PLOG(ERROR) << "Error closing temporary file.";
1449 out_path->clear();
1450 return false;
1451 }
1452
1453 return true;
1454}
1455
Alex Deymof329b932014-10-30 01:37:48 -07001456bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -08001457 time_t unix_time = time.ToTimeT();
1458 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1459 const time_t kOmahaEpoch = 1167638400;
1460 const int64_t kNumSecondsPerWeek = 7*24*3600;
1461 const int64_t kNumDaysPerWeek = 7;
1462
1463 time_t omaha_time = unix_time - kOmahaEpoch;
1464
1465 if (omaha_time < 0)
1466 return false;
1467
1468 // Note, as per the comment in utils.h we are deliberately not
1469 // handling DST correctly.
1470
1471 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1472 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1473
1474 return true;
1475}
1476
David Zeuthen33bae492014-02-25 16:16:18 -08001477bool WallclockDurationHelper(SystemState* system_state,
Alex Deymof329b932014-10-30 01:37:48 -07001478 const string& state_variable_key,
1479 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001480 bool ret = false;
1481
Alex Deymof329b932014-10-30 01:37:48 -07001482 Time now = system_state->clock()->GetWallclockTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001483 int64_t stored_value;
1484 if (system_state->prefs()->GetInt64(state_variable_key, &stored_value)) {
Alex Deymof329b932014-10-30 01:37:48 -07001485 Time stored_time = Time::FromInternalValue(stored_value);
David Zeuthen33bae492014-02-25 16:16:18 -08001486 if (stored_time > now) {
1487 LOG(ERROR) << "Stored time-stamp used for " << state_variable_key
1488 << " is in the future.";
1489 } else {
1490 *out_duration = now - stored_time;
1491 ret = true;
1492 }
1493 }
1494
1495 if (!system_state->prefs()->SetInt64(state_variable_key,
1496 now.ToInternalValue())) {
1497 LOG(ERROR) << "Error storing time-stamp in " << state_variable_key;
1498 }
1499
1500 return ret;
1501}
1502
1503bool MonotonicDurationHelper(SystemState* system_state,
1504 int64_t* storage,
Alex Deymof329b932014-10-30 01:37:48 -07001505 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001506 bool ret = false;
1507
Alex Deymof329b932014-10-30 01:37:48 -07001508 Time now = system_state->clock()->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001509 if (*storage != 0) {
Alex Deymof329b932014-10-30 01:37:48 -07001510 Time stored_time = Time::FromInternalValue(*storage);
David Zeuthen33bae492014-02-25 16:16:18 -08001511 *out_duration = now - stored_time;
1512 ret = true;
1513 }
1514 *storage = now.ToInternalValue();
1515
1516 return ret;
1517}
1518
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001519bool GetMinorVersion(const brillo::KeyValueStore& store,
Alex Deymob42b98d2015-07-06 17:42:38 -07001520 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001521 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -07001522 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -08001523 if (!base::StringToUint(result, minor_version)) {
1524 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
1525 return false;
1526 }
Allie Wood78750a42015-02-11 15:42:11 -08001527 return true;
1528 }
1529 return false;
1530}
1531
Alex Deymo60ca1a72015-06-18 18:19:15 -07001532bool ReadExtents(const string& path, const vector<Extent>& extents,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001533 brillo::Blob* out_data, ssize_t out_data_size,
Allie Wood56873452015-03-27 17:48:40 -07001534 size_t block_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001535 brillo::Blob data(out_data_size);
Allie Wood56873452015-03-27 17:48:40 -07001536 ssize_t bytes_read = 0;
1537 int fd = open(path.c_str(), O_RDONLY);
1538 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
1539 ScopedFdCloser fd_closer(&fd);
1540
Gilad Arnold41e34742015-05-11 11:31:50 -07001541 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001542 ssize_t bytes_read_this_iteration = 0;
1543 ssize_t bytes = extent.num_blocks() * block_size;
1544 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
1545 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1546 &data[bytes_read],
1547 bytes,
1548 extent.start_block() * block_size,
1549 &bytes_read_this_iteration));
1550 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1551 bytes_read += bytes_read_this_iteration;
1552 }
1553 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1554 *out_data = data;
1555 return true;
1556}
1557
Alex Deymodd132f32015-09-14 19:12:07 -07001558bool GetBootId(string* boot_id) {
1559 TEST_AND_RETURN_FALSE(
1560 base::ReadFileToString(base::FilePath(kBootIdPath), boot_id));
1561 base::TrimWhitespaceASCII(*boot_id, base::TRIM_TRAILING, boot_id);
1562 return true;
1563}
1564
adlr@google.com3defe6a2009-12-04 20:57:17 +00001565} // namespace utils
1566
1567} // namespace chromeos_update_engine