blob: c512414f77b12459468f689c83b1fa9ef91aaf3e [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>
Mike Frysinger8155d082012-04-06 15:23:18 -040032#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080033#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050034#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070035#include <base/strings/string_number_conversions.h>
36#include <base/strings/string_split.h>
37#include <base/strings/string_util.h>
38#include <base/strings/stringprintf.h>
Alex Vakulenko981a9fb2015-02-09 12:51:24 -080039#include <chromeos/data_encoding.h>
Allie Wood78750a42015-02-11 15:42:11 -080040#include <chromeos/key_value_store.h>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080041#include <glib.h>
Will Drewry8f71da82010-08-30 14:07:11 -050042
David Zeuthen33bae492014-02-25 16:16:18 -080043#include "update_engine/clock_interface.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070044#include "update_engine/constants.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080045#include "update_engine/file_descriptor.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080046#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070047#include "update_engine/omaha_request_params.h"
David Zeuthen33bae492014-02-25 16:16:18 -080048#include "update_engine/prefs_interface.h"
Darin Petkov296889c2010-07-23 16:20:54 -070049#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080050#include "update_engine/system_state.h"
51#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000052
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070053using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080054using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000055using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070056using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000057using std::string;
58using std::vector;
59
60namespace chromeos_update_engine {
61
Ben Chan77a1eba2012-10-07 22:54:55 -070062namespace {
63
64// The following constants control how UnmountFilesystem should retry if
65// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
66// one second.
67const int kUnmountMaxNumOfRetries = 5;
68const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070069
70// Number of bytes to read from a file to attempt to detect its contents. Used
71// in GetFileFormat.
72const int kGetFileFormatMaxHeaderSize = 32;
73
Ben Chan77a1eba2012-10-07 22:54:55 -070074} // namespace
75
adlr@google.com3defe6a2009-12-04 20:57:17 +000076namespace utils {
77
Chris Sosa4f8ee272012-11-30 13:01:54 -080078// Cgroup container is created in update-engine's upstart script located at
79// /etc/init/update-engine.conf.
80static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
81
J. Richard Barnette63137e52013-10-28 10:57:29 -070082string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -070083 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -070084
Alex Vakulenko75039d72014-03-25 12:36:28 -070085 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -070086 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -070087 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -070088 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -080089 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -070090 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -080091 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -070092 string output;
93 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -080094 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -070095 return output;
96 }
97 }
98 }
99 LOG(ERROR) << "Unable to parse fwid from ec info.";
100 return "";
101}
102
103
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700104const string KernelDeviceOfBootDevice(const string& boot_device) {
105 string kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700106
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700107 string disk_name;
108 int partition_num;
109 if (SplitPartitionName(boot_device, &disk_name, &partition_num)) {
110 if (disk_name == "/dev/ubiblock") {
111 // Special case for NAND devices.
112 // eg: /dev/ubiblock3_0 becomes /dev/mtdblock2
113 disk_name = "/dev/mtdblock";
114 }
115 // Currently this assumes the partition number of the boot device is
116 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
117 // get the kernel device.
118 if (partition_num == 3 || partition_num == 5 || partition_num == 7) {
119 kernel_partition_name = MakePartitionName(disk_name, partition_num - 1);
120 }
J. Richard Barnette30842932013-10-28 15:04:23 -0700121 }
122
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700123 return kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700124}
125
126
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800127bool WriteFile(const char* path, const void* data, int data_len) {
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800128 DirectFileWriter writer;
129 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
130 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700131 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800132 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800133 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800134 return true;
135}
136
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700137bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700138 const char* c_buf = static_cast<const char*>(buf);
139 ssize_t bytes_written = 0;
140 while (bytes_written < static_cast<ssize_t>(count)) {
141 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
142 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
143 bytes_written += rc;
144 }
145 return true;
146}
147
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700148bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
149 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700150 size_t bytes_written = 0;
151 int num_attempts = 0;
152 while (bytes_written < count) {
153 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700154 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
155 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700156 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
157 if (rc < 0) {
158 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
159 << " bytes_written=" << bytes_written
160 << " count=" << count << " offset=" << offset;
161 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700162 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
163 bytes_written += rc;
164 }
165 return true;
166}
167
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800168bool WriteAll(FileDescriptorPtr fd, const void* buf, size_t count) {
169 const char* c_buf = static_cast<const char*>(buf);
170 ssize_t bytes_written = 0;
171 while (bytes_written < static_cast<ssize_t>(count)) {
172 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
173 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
174 bytes_written += rc;
175 }
176 return true;
177}
178
179bool PWriteAll(FileDescriptorPtr fd,
180 const void* buf,
181 size_t count,
182 off_t offset) {
183 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET));
184 return WriteAll(fd, buf, count);
185}
186
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700187bool PReadAll(int fd, void* buf, size_t count, off_t offset,
188 ssize_t* out_bytes_read) {
189 char* c_buf = static_cast<char*>(buf);
190 ssize_t bytes_read = 0;
191 while (bytes_read < static_cast<ssize_t>(count)) {
192 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
193 offset + bytes_read);
194 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
195 if (rc == 0) {
196 break;
197 }
198 bytes_read += rc;
199 }
200 *out_bytes_read = bytes_read;
201 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700202}
203
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800204bool PReadAll(FileDescriptorPtr fd, void* buf, size_t count, off_t offset,
205 ssize_t* out_bytes_read) {
206 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET));
207 char* c_buf = static_cast<char*>(buf);
208 ssize_t bytes_read = 0;
209 while (bytes_read < static_cast<ssize_t>(count)) {
210 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
211 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
212 if (rc == 0) {
213 break;
214 }
215 bytes_read += rc;
216 }
217 *out_bytes_read = bytes_read;
218 return true;
219}
220
Gilad Arnold19a45f02012-07-19 12:36:10 -0700221// Append |nbytes| of content from |buf| to the vector pointed to by either
222// |vec_p| or |str_p|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800223static void AppendBytes(const uint8_t* buf, size_t nbytes,
224 chromeos::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700225 CHECK(buf);
226 CHECK(vec_p);
227 vec_p->insert(vec_p->end(), buf, buf + nbytes);
228}
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800229static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700230 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700231 CHECK(buf);
232 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800233 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700234}
235
236// Reads from an open file |fp|, appending the read content to the container
237// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200238// file's content, false otherwise. If |size| is not -1, reads up to |size|
239// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700240template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200241static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700242 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200243 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800244 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200245 while (size == -1 || size > 0) {
246 off_t bytes_to_read = sizeof(buf);
247 if (size > 0 && bytes_to_read > size) {
248 bytes_to_read = size;
249 }
250 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
251 if (!nbytes) {
252 break;
253 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700254 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200255 if (size != -1) {
256 CHECK(size >= static_cast<off_t>(nbytes));
257 size -= nbytes;
258 }
259 }
260 if (ferror(fp)) {
261 return false;
262 }
263 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700264}
265
Darin Petkov8e447e02013-04-16 16:23:50 +0200266// Opens a file |path| for reading and appends its the contents to a container
267// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
268// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700269template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700270static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200271 off_t offset,
272 off_t size,
273 T* out_p) {
274 CHECK_GE(offset, 0);
275 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700276 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200277 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000278 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200279 if (offset) {
280 // Return success without appending any data if a chunk beyond the end of
281 // the file is requested.
282 if (offset >= FileSize(path)) {
283 return true;
284 }
285 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
286 }
287 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000288}
289
Alex Deymo10875d92014-11-10 21:52:57 -0800290// TODO(deymo): This is only used in unittest, but requires the private
291// Read<string>() defined here. Expose Read<string>() or move to base/ version.
292bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700293 FILE* fp = popen(cmd.c_str(), "r");
294 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000295 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200296 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700297 return (success && pclose(fp) >= 0);
298}
299
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800300bool ReadFile(const string& path, chromeos::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200301 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700302}
303
Darin Petkov8e447e02013-04-16 16:23:50 +0200304bool ReadFile(const string& path, string* out_p) {
305 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700306}
307
Darin Petkov8e447e02013-04-16 16:23:50 +0200308bool ReadFileChunk(const string& path, off_t offset, off_t size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800309 chromeos::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200310 return ReadFileChunkAndAppend(path, offset, size, out_p);
311}
312
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700313off_t BlockDevSize(int fd) {
314 uint64_t dev_size;
315 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
316 if (rc == -1) {
317 dev_size = -1;
318 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
319 }
320 return dev_size;
321}
322
323off_t BlockDevSize(const string& path) {
324 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
325 if (fd == -1) {
326 PLOG(ERROR) << "Error opening " << path;
327 return fd;
328 }
329
330 off_t dev_size = BlockDevSize(fd);
331 if (dev_size == -1)
332 PLOG(ERROR) << "Error getting block device size on " << path;
333
334 close(fd);
335 return dev_size;
336}
337
338off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700339 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700340 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700341 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700342 if (rc < 0) {
343 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700344 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700345 }
346 if (S_ISREG(stbuf.st_mode))
347 return stbuf.st_size;
348 if (S_ISBLK(stbuf.st_mode))
349 return BlockDevSize(fd);
350 LOG(ERROR) << "Couldn't determine the type of " << fd;
351 return -1;
352}
353
354off_t FileSize(const string& path) {
355 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
356 if (fd == -1) {
357 PLOG(ERROR) << "Error opening " << path;
358 return fd;
359 }
360 off_t size = FileSize(fd);
361 if (size == -1)
362 PLOG(ERROR) << "Error getting file size of " << path;
363 close(fd);
364 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700365}
366
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800367void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000368 LOG(INFO) << "Logging array of length: " << length;
369 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700370 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000371 const unsigned int bytes_remaining = length - i;
372 const unsigned int bytes_per_this_line = min(bytes_per_line,
373 bytes_remaining);
374 char header[100];
375 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
376 TEST_AND_RETURN(r == 13);
377 string line = header;
378 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
379 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800380 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000381 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
382 TEST_AND_RETURN(r == 3);
383 line += buf;
384 }
385 LOG(INFO) << line;
386 }
387}
388
Alex Deymof329b932014-10-30 01:37:48 -0700389string GetDiskName(const string& partition_name) {
390 string disk_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800391 return SplitPartitionName(partition_name, &disk_name, nullptr) ?
Alex Deymof329b932014-10-30 01:37:48 -0700392 disk_name : string();
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700393}
394
Alex Deymof329b932014-10-30 01:37:48 -0700395int GetPartitionNumber(const string& partition_name) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800396 int partition_num = 0;
397 return SplitPartitionName(partition_name, nullptr, &partition_num) ?
398 partition_num : 0;
399}
400
Alex Deymof329b932014-10-30 01:37:48 -0700401bool SplitPartitionName(const string& partition_name,
402 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800403 int* out_partition_num) {
Alex Deymo10875d92014-11-10 21:52:57 -0800404 if (!StartsWithASCII(partition_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800405 LOG(ERROR) << "Invalid partition device name: " << partition_name;
406 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700407 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800408
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700409 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
410 if (last_nondigit_pos == string::npos ||
411 (last_nondigit_pos + 1) == partition_name.size()) {
412 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800413 return false;
414 }
415
Alex Deymof329b932014-10-30 01:37:48 -0700416 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700417 if (partition_name[last_nondigit_pos] == '_') {
418 // NAND block devices have weird naming which could be something
419 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
420 size_t prev_nondigit_pos =
421 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
422 if (prev_nondigit_pos == string::npos ||
423 (prev_nondigit_pos + 1) == last_nondigit_pos) {
424 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
425 return false;
426 }
427
428 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
429 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800430 }
431
432 if (out_disk_name) {
433 // Special case for MMC devices which have the following naming scheme:
434 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700435 size_t disk_name_len = last_nondigit_pos;
436 if (partition_name[last_nondigit_pos] != 'p' ||
437 last_nondigit_pos == 0 ||
438 !isdigit(partition_name[last_nondigit_pos - 1])) {
439 disk_name_len++;
440 }
441 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800442 }
443
444 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700445 string partition_str = partition_name.substr(last_nondigit_pos + 1,
446 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800447 *out_partition_num = atoi(partition_str.c_str());
448 }
449 return true;
450}
451
Alex Deymof329b932014-10-30 01:37:48 -0700452string MakePartitionName(const string& disk_name, int partition_num) {
Alex Deymo10875d92014-11-10 21:52:57 -0800453 if (!StartsWithASCII(disk_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800454 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700455 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800456 }
457
458 if (partition_num < 1) {
459 LOG(ERROR) << "Invalid partition number: " << partition_num;
Alex Deymof329b932014-10-30 01:37:48 -0700460 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800461 }
462
Alex Deymof329b932014-10-30 01:37:48 -0700463 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700464 if (isdigit(partition_name.back())) {
465 // Special case for devices with names ending with a digit.
466 // Add "p" to separate the disk name from partition number,
467 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800468 partition_name += 'p';
469 }
470
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700471 partition_name += std::to_string(partition_num);
472
Alex Deymo10875d92014-11-10 21:52:57 -0800473 if (StartsWithASCII(partition_name, "/dev/ubiblock", true)) {
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700474 // Special case for UBI block devieces that have "_0" suffix.
475 partition_name += "_0";
476 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800477 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700478}
479
Darin Petkovf74eb652010-08-04 12:08:38 -0700480string SysfsBlockDevice(const string& device) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700481 base::FilePath device_path(device);
Darin Petkovf74eb652010-08-04 12:08:38 -0700482 if (device_path.DirName().value() != "/dev") {
483 return "";
484 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700485 return base::FilePath("/sys/block").Append(device_path.BaseName()).value();
Darin Petkovf74eb652010-08-04 12:08:38 -0700486}
487
Alex Deymof329b932014-10-30 01:37:48 -0700488bool IsRemovableDevice(const string& device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700489 string sysfs_block = SysfsBlockDevice(device);
490 string removable;
491 if (sysfs_block.empty() ||
Alex Vakulenko75039d72014-03-25 12:36:28 -0700492 !base::ReadFileToString(base::FilePath(sysfs_block).Append("removable"),
Ben Chan736fcb52014-05-21 18:28:22 -0700493 &removable)) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700494 return false;
495 }
Ben Chan736fcb52014-05-21 18:28:22 -0700496 base::TrimWhitespaceASCII(removable, base::TRIM_ALL, &removable);
Darin Petkovf74eb652010-08-04 12:08:38 -0700497 return removable == "1";
498}
499
Alex Deymof329b932014-10-30 01:37:48 -0700500string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000501 char buf[100];
502 buf[0] = '\0';
503 return strerror_r(err, buf, sizeof(buf));
504}
505
Alex Deymof329b932014-10-30 01:37:48 -0700506string NormalizePath(const string& path, bool strip_trailing_slash) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000507 string ret;
Alex Deymo020600d2014-11-05 21:05:55 -0800508 std::unique_copy(path.begin(), path.end(), std::back_inserter(ret),
509 [](char c1, char c2) { return c1 == c2 && c1 == '/'; });
510 // The above code ensures no "//" is present in the string, so at most one
511 // '/' is present at the end of the line.
512 if (strip_trailing_slash && !ret.empty() && ret.back() == '/')
513 ret.pop_back();
adlr@google.com3defe6a2009-12-04 20:57:17 +0000514 return ret;
515}
516
517bool FileExists(const char* path) {
518 struct stat stbuf;
519 return 0 == lstat(path, &stbuf);
520}
521
Darin Petkov30291ed2010-11-12 10:23:06 -0800522bool IsSymlink(const char* path) {
523 struct stat stbuf;
524 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
525}
526
Alex Deymo7dc4c502014-05-20 20:09:58 -0700527bool IsDir(const char* path) {
528 struct stat stbuf;
529 TEST_AND_RETURN_FALSE_ERRNO(lstat(path, &stbuf) == 0);
530 return S_ISDIR(stbuf.st_mode);
531}
532
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800533// If |path| is absolute, or explicit relative to the current working directory,
534// leaves it as is. Otherwise, if TMPDIR is defined in the environment and is
535// non-empty, prepends it to |path|. Otherwise, prepends /tmp. Returns the
536// resulting path.
537static const string PrependTmpdir(const string& path) {
538 if (path[0] == '/' || StartsWithASCII(path, "./", true) ||
539 StartsWithASCII(path, "../", true))
540 return path;
541
542 const char *tmpdir = getenv("TMPDIR");
543 const string prefix = (tmpdir && *tmpdir ? tmpdir : "/tmp");
544 return prefix + "/" + path;
545}
546
Alex Deymof329b932014-10-30 01:37:48 -0700547bool MakeTempFile(const string& base_filename_template,
548 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700549 int* fd) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800550 const string filename_template = PrependTmpdir(base_filename_template);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700551 DCHECK(filename || fd);
552 vector<char> buf(filename_template.size() + 1);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800553 memcpy(buf.data(), filename_template.data(), filename_template.size());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700554 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700555
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800556 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700557 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
558 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800559 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700560 }
561 if (fd) {
562 *fd = mkstemp_fd;
563 } else {
564 close(mkstemp_fd);
565 }
566 return true;
567}
568
Alex Deymof329b932014-10-30 01:37:48 -0700569bool MakeTempDirectory(const string& base_dirname_template,
570 string* dirname) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800571 const string dirname_template = PrependTmpdir(base_dirname_template);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700572 DCHECK(dirname);
573 vector<char> buf(dirname_template.size() + 1);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800574 memcpy(buf.data(), dirname_template.data(), dirname_template.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700575 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700576
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800577 char* return_code = mkdtemp(buf.data());
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700578 TEST_AND_RETURN_FALSE_ERRNO(return_code != nullptr);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800579 *dirname = buf.data();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700580 return true;
581}
582
adlr@google.com3defe6a2009-12-04 20:57:17 +0000583bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700584 const string& mountpoint,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700585 unsigned long mountflags) { // NOLINT(runtime/int)
Alex Deymo4c82df32014-11-10 22:25:57 -0800586 // TODO(sosa): Remove "ext3" once crbug.com/208022 is resolved.
587 const vector<const char*> fstypes{"ext2", "ext3", "squashfs"};
588 for (const char* fstype : fstypes) {
589 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
590 nullptr);
591 if (rc == 0)
592 return true;
593
594 PLOG(WARNING) << "Unable to mount destination device " << device
595 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000596 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800597 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
598 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000599}
600
601bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700602 for (int num_retries = 0; ; ++num_retries) {
603 if (umount(mountpoint.c_str()) == 0)
604 break;
605
606 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
607 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800608 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700609 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000610 return true;
611}
612
Alex Deymof329b932014-10-30 01:37:48 -0700613bool GetFilesystemSize(const string& device,
Darin Petkovd3f8c892010-10-12 21:38:45 -0700614 int* out_block_count,
615 int* out_block_size) {
616 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
Alex Deymoe7141c62014-10-17 14:03:01 -0700617 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700618 ScopedFdCloser fd_closer(&fd);
619 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
620}
621
622bool GetFilesystemSizeFromFD(int fd,
623 int* out_block_count,
624 int* out_block_size) {
625 TEST_AND_RETURN_FALSE(fd >= 0);
626
Alex Deymo192393b2014-11-10 15:58:38 -0800627 // Determine the filesystem size by directly reading the block count and
628 // block size information from the superblock. Supported FS are ext3 and
629 // squashfs.
630
631 // Read from the fd only once and detect in memory. The first 2 KiB is enough
632 // to read the ext2 superblock (located at offset 1024) and the squashfs
633 // superblock (located at offset 0).
634 const ssize_t kBufferSize = 2048;
635
636 uint8_t buffer[kBufferSize];
637 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, 0)) != kBufferSize) {
638 PLOG(ERROR) << "Unable to read the file system header:";
Darin Petkovd3f8c892010-10-12 21:38:45 -0700639 return false;
640 }
Alex Deymo192393b2014-11-10 15:58:38 -0800641
642 if (GetSquashfs4Size(buffer, kBufferSize, out_block_count, out_block_size))
643 return true;
644 if (GetExt3Size(buffer, kBufferSize, out_block_count, out_block_size))
645 return true;
646
647 LOG(ERROR) << "Unable to determine file system type.";
648 return false;
649}
650
651bool GetExt3Size(const uint8_t* buffer, size_t buffer_size,
652 int* out_block_count,
653 int* out_block_size) {
654 // See include/linux/ext2_fs.h for more details on the structure. We obtain
655 // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
656 // library.
657 if (buffer_size < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
658 return false;
659
660 const uint8_t* superblock = buffer + SUPERBLOCK_OFFSET;
661
662 // ext3_fs.h: ext3_super_block.s_blocks_count
663 uint32_t block_count =
664 *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
665
666 // ext3_fs.h: ext3_super_block.s_log_block_size
667 uint32_t log_block_size =
668 *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
669
670 // ext3_fs.h: ext3_super_block.s_magic
671 uint16_t magic =
672 *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
673
Darin Petkovd3f8c892010-10-12 21:38:45 -0700674 block_count = le32toh(block_count);
Alex Deymo192393b2014-11-10 15:58:38 -0800675 log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700676 magic = le16toh(magic);
677
678 // Sanity check the parameters.
Alex Deymo192393b2014-11-10 15:58:38 -0800679 TEST_AND_RETURN_FALSE(magic == EXT2_SUPER_MAGIC);
680 TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
681 log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700682 TEST_AND_RETURN_FALSE(block_count > 0);
683
Alex Deymo192393b2014-11-10 15:58:38 -0800684 if (out_block_count)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700685 *out_block_count = block_count;
Alex Deymo192393b2014-11-10 15:58:38 -0800686 if (out_block_size)
687 *out_block_size = 1 << log_block_size;
688 return true;
689}
690
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800691bool GetSquashfs4Size(const uint8_t* buffer, size_t buffer_size,
Alex Deymo192393b2014-11-10 15:58:38 -0800692 int* out_block_count,
693 int* out_block_size) {
694 // See fs/squashfs/squashfs_fs.h for format details. We only support
695 // Squashfs 4.x little endian.
696
697 // sizeof(struct squashfs_super_block)
698 const size_t kSquashfsSuperBlockSize = 96;
699 if (buffer_size < kSquashfsSuperBlockSize)
700 return false;
701
702 // Check magic, squashfs_fs.h: SQUASHFS_MAGIC
703 if (memcmp(buffer, "hsqs", 4) != 0)
704 return false; // Only little endian is supported.
705
706 // squashfs_fs.h: struct squashfs_super_block.s_major
707 uint16_t s_major = *reinterpret_cast<const uint16_t*>(
708 buffer + 5 * sizeof(uint32_t) + 4 * sizeof(uint16_t));
709
710 if (s_major != 4) {
711 LOG(ERROR) << "Found unsupported squashfs major version " << s_major;
712 return false;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700713 }
Alex Deymo192393b2014-11-10 15:58:38 -0800714
715 // squashfs_fs.h: struct squashfs_super_block.bytes_used
716 uint64_t bytes_used = *reinterpret_cast<const int64_t*>(
717 buffer + 5 * sizeof(uint32_t) + 6 * sizeof(uint16_t) + sizeof(uint64_t));
718
719 const int block_size = 4096;
720
721 // The squashfs' bytes_used doesn't need to be aligned with the block boundary
722 // so we round up to the nearest blocksize.
723 if (out_block_count)
724 *out_block_count = (bytes_used + block_size - 1) / block_size;
725 if (out_block_size)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700726 *out_block_size = block_size;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700727 return true;
728}
729
Alex Deymo719bfff2014-07-11 12:12:32 -0700730string GetPathOnBoard(const string& command) {
731 int return_code = 0;
732 string command_path;
733 // TODO(deymo): prepend SYSROOT to each PATH instead of the result.
734 if (!Subprocess::SynchronousExec(
735 {"which", command}, &return_code, &command_path)) {
736 return command;
737 }
738 if (return_code != 0)
739 return command;
740
741 base::TrimWhitespaceASCII(command_path, base::TRIM_ALL, &command_path);
742 const char* env_sysroot = getenv("SYSROOT");
743 if (env_sysroot) {
744 string sysroot_command_path = env_sysroot + command_path;
745 if (utils::FileExists(sysroot_command_path.c_str()))
746 return sysroot_command_path;
747 }
748 return command_path;
749}
750
Alex Deymo032e7722014-03-25 17:53:56 -0700751// Tries to parse the header of an ELF file to obtain a human-readable
752// description of it on the |output| string.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800753static bool GetFileFormatELF(const uint8_t* buffer, size_t size,
754 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700755 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700756 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700757 return false;
758 *output = "ELF";
759
760 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700761 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700762 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700763 switch (buffer[EI_CLASS]) {
764 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700765 *output += " 32-bit";
766 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700767 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700768 *output += " 64-bit";
769 break;
770 default:
771 *output += " ?-bit";
772 }
773
774 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700775 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700776 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800777 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700778 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700779 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700780 *output += " little-endian";
781 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700782 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700783 *output += " big-endian";
784 break;
785 default:
786 *output += " ?-endian";
787 // Don't parse anything after the 0x10 offset if endianness is unknown.
788 return true;
789 }
790
Alex Deymoc1711e22014-08-08 13:16:23 -0700791 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
792 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
793 // and size is the same for both 32 and 64 bits.
794 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700795 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700796 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700797 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700798 if (ei_data == ELFDATA2LSB)
799 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700800 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700801 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700802
803 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700804 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700805 *output += " x86";
806 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700807 case EM_MIPS:
808 *output += " mips";
809 break;
810 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700811 *output += " arm";
812 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700813 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700814 *output += " x86-64";
815 break;
816 default:
817 *output += " unknown-arch";
818 }
819 return true;
820}
821
822string GetFileFormat(const string& path) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800823 chromeos::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700824 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
825 return "File not found.";
826
827 string result;
828 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
829 return result;
830
831 return "data";
832}
833
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800834namespace {
835// Do the actual trigger. We do it as a main-loop callback to (try to) get a
836// consistent stack trace.
837gboolean TriggerCrashReporterUpload(void* unused) {
838 pid_t pid = fork();
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700839 CHECK_GE(pid, 0) << "fork failed"; // fork() failed. Something is very wrong.
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800840 if (pid == 0) {
841 // We are the child. Crash.
842 abort(); // never returns
843 }
844 // We are the parent. Wait for child to terminate.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700845 pid_t result = waitpid(pid, nullptr, 0);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800846 LOG_IF(ERROR, result < 0) << "waitpid() failed";
847 return FALSE; // Don't call this callback again
848}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700849} // namespace
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800850
851void ScheduleCrashReporterUpload() {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700852 g_idle_add(&TriggerCrashReporterUpload, nullptr);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800853}
854
Chris Sosa4f8ee272012-11-30 13:01:54 -0800855bool SetCpuShares(CpuShares shares) {
856 string string_shares = base::IntToString(static_cast<int>(shares));
857 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
858 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700859 if (utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
860 string_shares.size())) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800861 return true;
862 } else {
863 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
864 << " using " << cpu_shares_file;
865 return false;
866 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700867}
868
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700869int FuzzInt(int value, unsigned int range) {
870 int min = value - range / 2;
871 int max = value + range - range / 2;
872 return base::RandInt(min, max);
873}
874
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800875gboolean GlibRunClosure(gpointer data) {
Alex Vakulenko4906c1c2014-08-21 13:17:44 -0700876 base::Closure* callback = reinterpret_cast<base::Closure*>(data);
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800877 callback->Run();
878 return FALSE;
879}
880
Alex Deymoc4acdf42014-05-28 21:07:10 -0700881void GlibDestroyClosure(gpointer data) {
Alex Vakulenko4906c1c2014-08-21 13:17:44 -0700882 delete reinterpret_cast<base::Closure*>(data);
Alex Deymoc4acdf42014-05-28 21:07:10 -0700883}
884
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700885string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800886 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700887}
888
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800889string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400890 string str;
891
892 // Handle negative durations by prefixing with a minus.
893 if (delta.ToInternalValue() < 0) {
894 delta *= -1;
895 str = "-";
896 }
897
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700898 // Canonicalize into days, hours, minutes, seconds and microseconds.
899 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800900 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700901 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800902 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700903 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800904 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700905 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800906 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700907 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800908
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700909 if (days)
910 base::StringAppendF(&str, "%ud", days);
911 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800912 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700913 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800914 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700915 base::StringAppendF(&str, "%u", secs);
916 if (usecs) {
917 int width = 6;
918 while ((usecs / 10) * 10 == usecs) {
919 usecs /= 10;
920 width--;
921 }
922 base::StringAppendF(&str, ".%0*u", width, usecs);
923 }
924 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800925 return str;
926}
927
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700928string ToString(const Time utc_time) {
929 Time::Exploded exp_time;
930 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700931 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700932 exp_time.month,
933 exp_time.day_of_month,
934 exp_time.year,
935 exp_time.hour,
936 exp_time.minute,
937 exp_time.second);
938}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000939
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700940string ToString(bool b) {
941 return (b ? "true" : "false");
942}
943
Alex Deymo1c656c42013-06-28 11:02:14 -0700944string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700945 switch (source) {
946 case kDownloadSourceHttpsServer: return "HttpsServer";
947 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700948 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700949 case kNumDownloadSources: return "Unknown";
950 // Don't add a default case to let the compiler warn about newly added
951 // download sources which should be added here.
952 }
953
954 return "Unknown";
955}
956
Alex Deymo1c656c42013-06-28 11:02:14 -0700957string ToString(PayloadType payload_type) {
958 switch (payload_type) {
959 case kPayloadTypeDelta: return "Delta";
960 case kPayloadTypeFull: return "Full";
961 case kPayloadTypeForcedFull: return "ForcedFull";
962 case kNumPayloadTypes: return "Unknown";
963 // Don't add a default case to let the compiler warn about newly added
964 // payload types which should be added here.
965 }
966
967 return "Unknown";
968}
969
David Zeuthena99981f2013-04-29 13:42:47 -0700970ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700971 // Ignore the higher order bits in the code by applying the mask as
972 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700973 // with values less than ErrorCode::kUmaReportedMax.
974 ErrorCode base_code = static_cast<ErrorCode>(
975 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700976
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800977 // Make additional adjustments required for UMA and error classification.
978 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
979 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700980 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700981 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800982 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800983 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700984 << " to ErrorCode::kOmahaErrorInHTTPResponse";
985 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700986 }
987
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800988 return base_code;
989}
990
David Zeuthen33bae492014-02-25 16:16:18 -0800991metrics::AttemptResult GetAttemptResult(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700992 ErrorCode base_code = static_cast<ErrorCode>(
993 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -0800994
995 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700996 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -0800997 return metrics::AttemptResult::kUpdateSucceeded;
998
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700999 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001000 return metrics::AttemptResult::kPayloadDownloadError;
1001
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001002 case ErrorCode::kDownloadInvalidMetadataSize:
1003 case ErrorCode::kDownloadInvalidMetadataMagicString:
1004 case ErrorCode::kDownloadMetadataSignatureError:
1005 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1006 case ErrorCode::kPayloadMismatchedType:
1007 case ErrorCode::kUnsupportedMajorPayloadVersion:
1008 case ErrorCode::kUnsupportedMinorPayloadVersion:
1009 case ErrorCode::kDownloadNewPartitionInfoError:
1010 case ErrorCode::kDownloadSignatureMissingInManifest:
1011 case ErrorCode::kDownloadManifestParseError:
1012 case ErrorCode::kDownloadOperationHashMissingError:
David Zeuthen33bae492014-02-25 16:16:18 -08001013 return metrics::AttemptResult::kMetadataMalformed;
1014
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001015 case ErrorCode::kDownloadOperationHashMismatch:
1016 case ErrorCode::kDownloadOperationHashVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001017 return metrics::AttemptResult::kOperationMalformed;
1018
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001019 case ErrorCode::kDownloadOperationExecutionError:
1020 case ErrorCode::kInstallDeviceOpenError:
1021 case ErrorCode::kKernelDeviceOpenError:
1022 case ErrorCode::kDownloadWriteError:
1023 case ErrorCode::kFilesystemCopierError:
David Zeuthen33bae492014-02-25 16:16:18 -08001024 return metrics::AttemptResult::kOperationExecutionError;
1025
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001026 case ErrorCode::kDownloadMetadataSignatureMismatch:
David Zeuthen33bae492014-02-25 16:16:18 -08001027 return metrics::AttemptResult::kMetadataVerificationFailed;
1028
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001029 case ErrorCode::kPayloadSizeMismatchError:
1030 case ErrorCode::kPayloadHashMismatchError:
1031 case ErrorCode::kDownloadPayloadVerificationError:
1032 case ErrorCode::kSignedDeltaPayloadExpectedError:
1033 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001034 return metrics::AttemptResult::kPayloadVerificationFailed;
1035
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001036 case ErrorCode::kNewRootfsVerificationError:
1037 case ErrorCode::kNewKernelVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001038 return metrics::AttemptResult::kVerificationFailed;
1039
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001040 case ErrorCode::kPostinstallRunnerError:
1041 case ErrorCode::kPostinstallBootedFromFirmwareB:
1042 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
David Zeuthen33bae492014-02-25 16:16:18 -08001043 return metrics::AttemptResult::kPostInstallFailed;
1044
1045 // We should never get these errors in the update-attempt stage so
1046 // return internal error if this happens.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001047 case ErrorCode::kError:
1048 case ErrorCode::kOmahaRequestXMLParseError:
1049 case ErrorCode::kOmahaRequestError:
1050 case ErrorCode::kOmahaResponseHandlerError:
1051 case ErrorCode::kDownloadStateInitializationError:
1052 case ErrorCode::kOmahaRequestEmptyResponseError:
1053 case ErrorCode::kDownloadInvalidMetadataSignature:
1054 case ErrorCode::kOmahaResponseInvalid:
1055 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1056 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1057 case ErrorCode::kOmahaErrorInHTTPResponse:
1058 case ErrorCode::kDownloadMetadataSignatureMissingError:
1059 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1060 case ErrorCode::kPostinstallPowerwashError:
1061 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -04001062 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
David Zeuthen33bae492014-02-25 16:16:18 -08001063 return metrics::AttemptResult::kInternalError;
1064
1065 // Special flags. These can't happen (we mask them out above) but
1066 // the compiler doesn't know that. Just break out so we can warn and
1067 // return |kInternalError|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001068 case ErrorCode::kUmaReportedMax:
1069 case ErrorCode::kOmahaRequestHTTPResponseBase:
1070 case ErrorCode::kDevModeFlag:
1071 case ErrorCode::kResumedFlag:
1072 case ErrorCode::kTestImageFlag:
1073 case ErrorCode::kTestOmahaUrlFlag:
1074 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001075 break;
1076 }
1077
1078 LOG(ERROR) << "Unexpected error code " << base_code;
1079 return metrics::AttemptResult::kInternalError;
1080}
1081
1082
1083metrics::DownloadErrorCode GetDownloadErrorCode(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001084 ErrorCode base_code = static_cast<ErrorCode>(
1085 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001086
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001087 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
1088 int http_status =
1089 static_cast<int>(base_code) -
1090 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase);
David Zeuthen33bae492014-02-25 16:16:18 -08001091 if (http_status >= 200 && http_status <= 599) {
1092 return static_cast<metrics::DownloadErrorCode>(
1093 static_cast<int>(metrics::DownloadErrorCode::kHttpStatus200) +
1094 http_status - 200);
1095 } else if (http_status == 0) {
1096 // The code is using HTTP Status 0 for "Unable to get http
1097 // response code."
1098 return metrics::DownloadErrorCode::kDownloadError;
1099 }
1100 LOG(WARNING) << "Unexpected HTTP status code " << http_status;
1101 return metrics::DownloadErrorCode::kHttpStatusOther;
1102 }
1103
1104 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001105 // Unfortunately, ErrorCode::kDownloadTransferError is returned for a wide
David Zeuthen33bae492014-02-25 16:16:18 -08001106 // variety of errors (proxy errors, host not reachable, timeouts etc.).
1107 //
1108 // For now just map that to kDownloading. See http://crbug.com/355745
1109 // for how we plan to add more detail in the future.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001110 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001111 return metrics::DownloadErrorCode::kDownloadError;
1112
1113 // All of these error codes are not related to downloading so break
1114 // out so we can warn and return InputMalformed.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001115 case ErrorCode::kSuccess:
1116 case ErrorCode::kError:
1117 case ErrorCode::kOmahaRequestError:
1118 case ErrorCode::kOmahaResponseHandlerError:
1119 case ErrorCode::kFilesystemCopierError:
1120 case ErrorCode::kPostinstallRunnerError:
1121 case ErrorCode::kPayloadMismatchedType:
1122 case ErrorCode::kInstallDeviceOpenError:
1123 case ErrorCode::kKernelDeviceOpenError:
1124 case ErrorCode::kPayloadHashMismatchError:
1125 case ErrorCode::kPayloadSizeMismatchError:
1126 case ErrorCode::kDownloadPayloadVerificationError:
1127 case ErrorCode::kDownloadNewPartitionInfoError:
1128 case ErrorCode::kDownloadWriteError:
1129 case ErrorCode::kNewRootfsVerificationError:
1130 case ErrorCode::kNewKernelVerificationError:
1131 case ErrorCode::kSignedDeltaPayloadExpectedError:
1132 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1133 case ErrorCode::kPostinstallBootedFromFirmwareB:
1134 case ErrorCode::kDownloadStateInitializationError:
1135 case ErrorCode::kDownloadInvalidMetadataMagicString:
1136 case ErrorCode::kDownloadSignatureMissingInManifest:
1137 case ErrorCode::kDownloadManifestParseError:
1138 case ErrorCode::kDownloadMetadataSignatureError:
1139 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1140 case ErrorCode::kDownloadMetadataSignatureMismatch:
1141 case ErrorCode::kDownloadOperationHashVerificationError:
1142 case ErrorCode::kDownloadOperationExecutionError:
1143 case ErrorCode::kDownloadOperationHashMismatch:
1144 case ErrorCode::kOmahaRequestEmptyResponseError:
1145 case ErrorCode::kOmahaRequestXMLParseError:
1146 case ErrorCode::kDownloadInvalidMetadataSize:
1147 case ErrorCode::kDownloadInvalidMetadataSignature:
1148 case ErrorCode::kOmahaResponseInvalid:
1149 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1150 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1151 case ErrorCode::kOmahaErrorInHTTPResponse:
1152 case ErrorCode::kDownloadOperationHashMissingError:
1153 case ErrorCode::kDownloadMetadataSignatureMissingError:
1154 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1155 case ErrorCode::kPostinstallPowerwashError:
1156 case ErrorCode::kUpdateCanceledByChannelChange:
1157 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1158 case ErrorCode::kUnsupportedMajorPayloadVersion:
1159 case ErrorCode::kUnsupportedMinorPayloadVersion:
David Zeuthenf3e28012014-08-26 18:23:52 -04001160 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
David Zeuthen33bae492014-02-25 16:16:18 -08001161 break;
1162
1163 // Special flags. These can't happen (we mask them out above) but
1164 // the compiler doesn't know that. Just break out so we can warn and
1165 // return |kInputMalformed|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001166 case ErrorCode::kUmaReportedMax:
1167 case ErrorCode::kOmahaRequestHTTPResponseBase:
1168 case ErrorCode::kDevModeFlag:
1169 case ErrorCode::kResumedFlag:
1170 case ErrorCode::kTestImageFlag:
1171 case ErrorCode::kTestOmahaUrlFlag:
1172 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001173 LOG(ERROR) << "Unexpected error code " << base_code;
1174 break;
1175 }
1176
1177 return metrics::DownloadErrorCode::kInputMalformed;
1178}
1179
David Zeuthenb281f072014-04-02 10:20:19 -07001180metrics::ConnectionType GetConnectionType(
1181 NetworkConnectionType type,
1182 NetworkTethering tethering) {
1183 switch (type) {
1184 case kNetUnknown:
1185 return metrics::ConnectionType::kUnknown;
1186
1187 case kNetEthernet:
1188 if (tethering == NetworkTethering::kConfirmed)
1189 return metrics::ConnectionType::kTetheredEthernet;
1190 else
1191 return metrics::ConnectionType::kEthernet;
1192
1193 case kNetWifi:
1194 if (tethering == NetworkTethering::kConfirmed)
1195 return metrics::ConnectionType::kTetheredWifi;
1196 else
1197 return metrics::ConnectionType::kWifi;
1198
1199 case kNetWimax:
1200 return metrics::ConnectionType::kWimax;
1201
1202 case kNetBluetooth:
1203 return metrics::ConnectionType::kBluetooth;
1204
1205 case kNetCellular:
1206 return metrics::ConnectionType::kCellular;
1207 }
1208
1209 LOG(ERROR) << "Unexpected network connection type: type=" << type
1210 << ", tethering=" << static_cast<int>(tethering);
1211
1212 return metrics::ConnectionType::kUnknown;
1213}
1214
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001215// Returns a printable version of the various flags denoted in the higher order
1216// bits of the given code. Returns an empty string if none of those bits are
1217// set.
1218string GetFlagNames(uint32_t code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001219 uint32_t flags = (static_cast<uint32_t>(code) &
1220 static_cast<uint32_t>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001221 string flag_names;
1222 string separator = "";
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001223 for (size_t i = 0; i < sizeof(flags) * 8; i++) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001224 uint32_t flag = flags & (1 << i);
1225 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -07001226 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001227 separator = ", ";
1228 }
1229 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001230
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001231 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001232}
1233
David Zeuthena99981f2013-04-29 13:42:47 -07001234void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001235 if (!system_state)
1236 return;
1237
David Zeuthena99981f2013-04-29 13:42:47 -07001238 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001239
1240 // If the code doesn't have flags computed already, compute them now based on
1241 // the state of the current update attempt.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001242 uint32_t flags =
1243 static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001244 if (!flags)
1245 flags = system_state->update_attempter()->GetErrorCodeFlags();
1246
1247 // Determine the UMA bucket depending on the flags. But, ignore the resumed
1248 // flag, as it's perfectly normal for production devices to resume their
1249 // downloads and so we want to record those cases also in NormalErrorCodes
1250 // bucket.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001251 string metric =
1252 flags & ~static_cast<uint32_t>(ErrorCode::kResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001253 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
1254
1255 LOG(INFO) << "Sending error code " << uma_error_code
1256 << " (" << CodeToString(uma_error_code) << ")"
1257 << " to UMA metric: " << metric
1258 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
1259
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001260 system_state->metrics_lib()->SendEnumToUMA(
1261 metric, static_cast<int>(uma_error_code),
1262 static_cast<int>(ErrorCode::kUmaReportedMax));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001263}
1264
David Zeuthena99981f2013-04-29 13:42:47 -07001265string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001266 // If the given code has both parts (i.e. the error code part and the flags
1267 // part) then strip off the flags part since the switch statement below
1268 // has case statements only for the base error code or a single flag but
1269 // doesn't support any combinations of those.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001270 if ((static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags)) &&
1271 (static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags)))
1272 code = static_cast<ErrorCode>(
1273 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001274 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001275 case ErrorCode::kSuccess: return "ErrorCode::kSuccess";
1276 case ErrorCode::kError: return "ErrorCode::kError";
1277 case ErrorCode::kOmahaRequestError: return "ErrorCode::kOmahaRequestError";
1278 case ErrorCode::kOmahaResponseHandlerError:
1279 return "ErrorCode::kOmahaResponseHandlerError";
1280 case ErrorCode::kFilesystemCopierError:
1281 return "ErrorCode::kFilesystemCopierError";
1282 case ErrorCode::kPostinstallRunnerError:
1283 return "ErrorCode::kPostinstallRunnerError";
1284 case ErrorCode::kPayloadMismatchedType:
1285 return "ErrorCode::kPayloadMismatchedType";
1286 case ErrorCode::kInstallDeviceOpenError:
1287 return "ErrorCode::kInstallDeviceOpenError";
1288 case ErrorCode::kKernelDeviceOpenError:
1289 return "ErrorCode::kKernelDeviceOpenError";
1290 case ErrorCode::kDownloadTransferError:
1291 return "ErrorCode::kDownloadTransferError";
1292 case ErrorCode::kPayloadHashMismatchError:
1293 return "ErrorCode::kPayloadHashMismatchError";
1294 case ErrorCode::kPayloadSizeMismatchError:
1295 return "ErrorCode::kPayloadSizeMismatchError";
1296 case ErrorCode::kDownloadPayloadVerificationError:
1297 return "ErrorCode::kDownloadPayloadVerificationError";
1298 case ErrorCode::kDownloadNewPartitionInfoError:
1299 return "ErrorCode::kDownloadNewPartitionInfoError";
1300 case ErrorCode::kDownloadWriteError:
1301 return "ErrorCode::kDownloadWriteError";
1302 case ErrorCode::kNewRootfsVerificationError:
1303 return "ErrorCode::kNewRootfsVerificationError";
1304 case ErrorCode::kNewKernelVerificationError:
1305 return "ErrorCode::kNewKernelVerificationError";
1306 case ErrorCode::kSignedDeltaPayloadExpectedError:
1307 return "ErrorCode::kSignedDeltaPayloadExpectedError";
1308 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1309 return "ErrorCode::kDownloadPayloadPubKeyVerificationError";
1310 case ErrorCode::kPostinstallBootedFromFirmwareB:
1311 return "ErrorCode::kPostinstallBootedFromFirmwareB";
1312 case ErrorCode::kDownloadStateInitializationError:
1313 return "ErrorCode::kDownloadStateInitializationError";
1314 case ErrorCode::kDownloadInvalidMetadataMagicString:
1315 return "ErrorCode::kDownloadInvalidMetadataMagicString";
1316 case ErrorCode::kDownloadSignatureMissingInManifest:
1317 return "ErrorCode::kDownloadSignatureMissingInManifest";
1318 case ErrorCode::kDownloadManifestParseError:
1319 return "ErrorCode::kDownloadManifestParseError";
1320 case ErrorCode::kDownloadMetadataSignatureError:
1321 return "ErrorCode::kDownloadMetadataSignatureError";
1322 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1323 return "ErrorCode::kDownloadMetadataSignatureVerificationError";
1324 case ErrorCode::kDownloadMetadataSignatureMismatch:
1325 return "ErrorCode::kDownloadMetadataSignatureMismatch";
1326 case ErrorCode::kDownloadOperationHashVerificationError:
1327 return "ErrorCode::kDownloadOperationHashVerificationError";
1328 case ErrorCode::kDownloadOperationExecutionError:
1329 return "ErrorCode::kDownloadOperationExecutionError";
1330 case ErrorCode::kDownloadOperationHashMismatch:
1331 return "ErrorCode::kDownloadOperationHashMismatch";
1332 case ErrorCode::kOmahaRequestEmptyResponseError:
1333 return "ErrorCode::kOmahaRequestEmptyResponseError";
1334 case ErrorCode::kOmahaRequestXMLParseError:
1335 return "ErrorCode::kOmahaRequestXMLParseError";
1336 case ErrorCode::kDownloadInvalidMetadataSize:
1337 return "ErrorCode::kDownloadInvalidMetadataSize";
1338 case ErrorCode::kDownloadInvalidMetadataSignature:
1339 return "ErrorCode::kDownloadInvalidMetadataSignature";
1340 case ErrorCode::kOmahaResponseInvalid:
1341 return "ErrorCode::kOmahaResponseInvalid";
1342 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1343 return "ErrorCode::kOmahaUpdateIgnoredPerPolicy";
1344 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1345 return "ErrorCode::kOmahaUpdateDeferredPerPolicy";
1346 case ErrorCode::kOmahaErrorInHTTPResponse:
1347 return "ErrorCode::kOmahaErrorInHTTPResponse";
1348 case ErrorCode::kDownloadOperationHashMissingError:
1349 return "ErrorCode::kDownloadOperationHashMissingError";
1350 case ErrorCode::kDownloadMetadataSignatureMissingError:
1351 return "ErrorCode::kDownloadMetadataSignatureMissingError";
1352 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1353 return "ErrorCode::kOmahaUpdateDeferredForBackoff";
1354 case ErrorCode::kPostinstallPowerwashError:
1355 return "ErrorCode::kPostinstallPowerwashError";
1356 case ErrorCode::kUpdateCanceledByChannelChange:
1357 return "ErrorCode::kUpdateCanceledByChannelChange";
1358 case ErrorCode::kUmaReportedMax:
1359 return "ErrorCode::kUmaReportedMax";
1360 case ErrorCode::kOmahaRequestHTTPResponseBase:
1361 return "ErrorCode::kOmahaRequestHTTPResponseBase";
1362 case ErrorCode::kResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001363 return "Resumed";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001364 case ErrorCode::kDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001365 return "DevMode";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001366 case ErrorCode::kTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001367 return "TestImage";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001368 case ErrorCode::kTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001369 return "TestOmahaUrl";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001370 case ErrorCode::kSpecialFlags:
1371 return "ErrorCode::kSpecialFlags";
1372 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1373 return "ErrorCode::kPostinstallFirmwareRONotUpdatable";
1374 case ErrorCode::kUnsupportedMajorPayloadVersion:
1375 return "ErrorCode::kUnsupportedMajorPayloadVersion";
1376 case ErrorCode::kUnsupportedMinorPayloadVersion:
1377 return "ErrorCode::kUnsupportedMinorPayloadVersion";
David Zeuthenf3e28012014-08-26 18:23:52 -04001378 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
1379 return "ErrorCode::kOmahaRequestXMLHasEntityDecl";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001380 // Don't add a default case to let the compiler warn about newly added
1381 // error codes which should be added here.
1382 }
1383
1384 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1385}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001386
Gilad Arnold30dedd82013-07-03 06:19:09 -07001387bool CreatePowerwashMarkerFile(const char* file_path) {
1388 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1389 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001390 kPowerwashCommand,
1391 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001392 if (result) {
1393 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1394 } else {
1395 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1396 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001397
1398 return result;
1399}
1400
Gilad Arnold30dedd82013-07-03 06:19:09 -07001401bool DeletePowerwashMarkerFile(const char* file_path) {
1402 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001403 const base::FilePath kPowerwashMarkerPath(marker_file);
1404 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001405
1406 if (result)
1407 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001408 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001409 else
1410 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001411 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001412
1413 return result;
1414}
1415
Alex Deymof329b932014-10-30 01:37:48 -07001416bool GetInstallDev(const string& boot_dev, string* install_dev) {
1417 string disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001418 int partition_num;
1419 if (!SplitPartitionName(boot_dev, &disk_name, &partition_num))
1420 return false;
Liam McLoughlin049d1652013-07-31 18:47:46 -07001421
Chris Sosad317e402013-06-12 13:47:09 -07001422 // Right now, we just switch '3' and '5' partition numbers.
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001423 if (partition_num == 3) {
1424 partition_num = 5;
1425 } else if (partition_num == 5) {
1426 partition_num = 3;
1427 } else {
1428 return false;
1429 }
1430
1431 if (install_dev)
1432 *install_dev = MakePartitionName(disk_name, partition_num);
Liam McLoughlin049d1652013-07-31 18:47:46 -07001433
Chris Sosad317e402013-06-12 13:47:09 -07001434 return true;
1435}
1436
David Zeuthen27a48bc2013-08-06 12:06:29 -07001437Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -07001438 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1439 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -07001440 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1441}
1442
Alex Deymof329b932014-10-30 01:37:48 -07001443gchar** StringVectorToGStrv(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001444 GPtrArray *p = g_ptr_array_new();
Alex Deymo020600d2014-11-05 21:05:55 -08001445 for (const string& str : vec_str) {
1446 g_ptr_array_add(p, g_strdup(str.c_str()));
David Zeuthen27a48bc2013-08-06 12:06:29 -07001447 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001448 g_ptr_array_add(p, nullptr);
David Zeuthen27a48bc2013-08-06 12:06:29 -07001449 return reinterpret_cast<gchar**>(g_ptr_array_free(p, FALSE));
1450}
1451
Alex Deymof329b932014-10-30 01:37:48 -07001452string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001453 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -07001454 for (vector<string>::const_iterator i = vec_str.begin();
1455 i != vec_str.end(); ++i) {
1456 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -07001457 str += ", ";
1458 str += '"';
1459 str += *i;
1460 str += '"';
1461 }
1462 str += "]";
1463 return str;
1464}
1465
David Zeuthen8f191b22013-08-06 12:27:50 -07001466string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001467 string encoded_hash = chromeos::data_encoding::Base64Encode(payload_hash);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001468 return base::StringPrintf("cros_update_size_%zu_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001469 payload_size,
1470 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -07001471}
1472
Alex Deymof329b932014-10-30 01:37:48 -07001473bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -07001474 base::FilePath *out_path) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001475 chromeos::Blob contents;
David Zeuthene7f89172013-10-31 10:21:04 -07001476
1477 out_path->clear();
1478
1479 if (base64_encoded.size() == 0) {
1480 LOG(ERROR) << "Can't decode empty string.";
1481 return false;
1482 }
1483
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001484 if (!chromeos::data_encoding::Base64Decode(base64_encoded, &contents) ||
David Zeuthene7f89172013-10-31 10:21:04 -07001485 contents.size() == 0) {
1486 LOG(ERROR) << "Error decoding base64.";
1487 return false;
1488 }
1489
Alex Vakulenko75039d72014-03-25 12:36:28 -07001490 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001491 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -07001492 LOG(ERROR) << "Error creating temporary file.";
1493 return false;
1494 }
1495
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001496 if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
David Zeuthene7f89172013-10-31 10:21:04 -07001497 PLOG(ERROR) << "Error writing to temporary file.";
1498 if (fclose(file) != 0)
1499 PLOG(ERROR) << "Error closing temporary file.";
1500 if (unlink(out_path->value().c_str()) != 0)
1501 PLOG(ERROR) << "Error unlinking temporary file.";
1502 out_path->clear();
1503 return false;
1504 }
1505
1506 if (fclose(file) != 0) {
1507 PLOG(ERROR) << "Error closing temporary file.";
1508 out_path->clear();
1509 return false;
1510 }
1511
1512 return true;
1513}
1514
Alex Deymof329b932014-10-30 01:37:48 -07001515bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -08001516 time_t unix_time = time.ToTimeT();
1517 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1518 const time_t kOmahaEpoch = 1167638400;
1519 const int64_t kNumSecondsPerWeek = 7*24*3600;
1520 const int64_t kNumDaysPerWeek = 7;
1521
1522 time_t omaha_time = unix_time - kOmahaEpoch;
1523
1524 if (omaha_time < 0)
1525 return false;
1526
1527 // Note, as per the comment in utils.h we are deliberately not
1528 // handling DST correctly.
1529
1530 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1531 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1532
1533 return true;
1534}
1535
David Zeuthen33bae492014-02-25 16:16:18 -08001536bool WallclockDurationHelper(SystemState* system_state,
Alex Deymof329b932014-10-30 01:37:48 -07001537 const string& state_variable_key,
1538 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001539 bool ret = false;
1540
Alex Deymof329b932014-10-30 01:37:48 -07001541 Time now = system_state->clock()->GetWallclockTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001542 int64_t stored_value;
1543 if (system_state->prefs()->GetInt64(state_variable_key, &stored_value)) {
Alex Deymof329b932014-10-30 01:37:48 -07001544 Time stored_time = Time::FromInternalValue(stored_value);
David Zeuthen33bae492014-02-25 16:16:18 -08001545 if (stored_time > now) {
1546 LOG(ERROR) << "Stored time-stamp used for " << state_variable_key
1547 << " is in the future.";
1548 } else {
1549 *out_duration = now - stored_time;
1550 ret = true;
1551 }
1552 }
1553
1554 if (!system_state->prefs()->SetInt64(state_variable_key,
1555 now.ToInternalValue())) {
1556 LOG(ERROR) << "Error storing time-stamp in " << state_variable_key;
1557 }
1558
1559 return ret;
1560}
1561
1562bool MonotonicDurationHelper(SystemState* system_state,
1563 int64_t* storage,
Alex Deymof329b932014-10-30 01:37:48 -07001564 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001565 bool ret = false;
1566
Alex Deymof329b932014-10-30 01:37:48 -07001567 Time now = system_state->clock()->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001568 if (*storage != 0) {
Alex Deymof329b932014-10-30 01:37:48 -07001569 Time stored_time = Time::FromInternalValue(*storage);
David Zeuthen33bae492014-02-25 16:16:18 -08001570 *out_duration = now - stored_time;
1571 ret = true;
1572 }
1573 *storage = now.ToInternalValue();
1574
1575 return ret;
1576}
1577
Allie Wood78750a42015-02-11 15:42:11 -08001578bool GetMinorVersion(base::FilePath path, uint32_t* minor_version) {
1579 chromeos::KeyValueStore store;
1580 std::string result;
1581 if (base::PathExists(path) && store.Load(path) &&
1582 store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
1583 *minor_version = atoi(result.c_str());
1584 return true;
1585 }
1586 return false;
1587}
1588
adlr@google.com3defe6a2009-12-04 20:57:17 +00001589} // namespace utils
1590
1591} // namespace chromeos_update_engine