blob: c6c52264ba18931e911cbcf3e2d24acc88c3d3a0 [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
David Zeuthen910ec5b2013-09-26 12:10:58 -07009#include <attr/xattr.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000010#include <dirent.h>
Alex Deymoc1711e22014-08-08 13:16:23 -070011#include <elf.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000012#include <errno.h>
Alex Deymo192393b2014-11-10 15:58:38 -080013#include <ext2fs/ext2fs.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080014#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000015#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
Alex Deymoc4acdf42014-05-28 21:07:10 -070018#include <sys/mount.h>
19#include <sys/resource.h>
20#include <sys/stat.h>
21#include <sys/types.h>
22#include <sys/wait.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000023#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070024
adlr@google.com3defe6a2009-12-04 20:57:17 +000025#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070026#include <utility>
Chris Sosac1972482013-04-30 22:31:10 -070027#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070028
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070029#include <base/callback.h>
Ben Chan736fcb52014-05-21 18:28:22 -070030#include <base/files/file_path.h>
Alex Deymo192393b2014-11-10 15:58:38 -080031#include <base/files/file_util.h>
Ben Chan736fcb52014-05-21 18:28:22 -070032#include <base/files/scoped_file.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040033#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080034#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050035#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070036#include <base/strings/string_number_conversions.h>
37#include <base/strings/string_split.h>
38#include <base/strings/string_util.h>
39#include <base/strings/stringprintf.h>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080040#include <glib.h>
Will Drewry8f71da82010-08-30 14:07:11 -050041
David Zeuthen33bae492014-02-25 16:16:18 -080042#include "update_engine/clock_interface.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070043#include "update_engine/constants.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080044#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070045#include "update_engine/omaha_request_params.h"
David Zeuthen33bae492014-02-25 16:16:18 -080046#include "update_engine/prefs_interface.h"
Darin Petkov296889c2010-07-23 16:20:54 -070047#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080048#include "update_engine/system_state.h"
49#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000050
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070051using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080052using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000053using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070054using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000055using std::string;
56using std::vector;
57
58namespace chromeos_update_engine {
59
Ben Chan77a1eba2012-10-07 22:54:55 -070060namespace {
61
62// The following constants control how UnmountFilesystem should retry if
63// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
64// one second.
65const int kUnmountMaxNumOfRetries = 5;
66const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070067
68// Number of bytes to read from a file to attempt to detect its contents. Used
69// in GetFileFormat.
70const int kGetFileFormatMaxHeaderSize = 32;
71
Ben Chan77a1eba2012-10-07 22:54:55 -070072} // namespace
73
adlr@google.com3defe6a2009-12-04 20:57:17 +000074namespace utils {
75
Chris Sosa4f8ee272012-11-30 13:01:54 -080076// Cgroup container is created in update-engine's upstart script located at
77// /etc/init/update-engine.conf.
78static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
79
J. Richard Barnette63137e52013-10-28 10:57:29 -070080string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -070081 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -070082
Alex Vakulenko75039d72014-03-25 12:36:28 -070083 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -070084 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -070085 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -070086 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -080087 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -070088 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -080089 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -070090 string output;
91 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -080092 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -070093 return output;
94 }
95 }
96 }
97 LOG(ERROR) << "Unable to parse fwid from ec info.";
98 return "";
99}
100
101
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700102const string KernelDeviceOfBootDevice(const string& boot_device) {
103 string kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700104
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700105 string disk_name;
106 int partition_num;
107 if (SplitPartitionName(boot_device, &disk_name, &partition_num)) {
108 if (disk_name == "/dev/ubiblock") {
109 // Special case for NAND devices.
110 // eg: /dev/ubiblock3_0 becomes /dev/mtdblock2
111 disk_name = "/dev/mtdblock";
112 }
113 // Currently this assumes the partition number of the boot device is
114 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
115 // get the kernel device.
116 if (partition_num == 3 || partition_num == 5 || partition_num == 7) {
117 kernel_partition_name = MakePartitionName(disk_name, partition_num - 1);
118 }
J. Richard Barnette30842932013-10-28 15:04:23 -0700119 }
120
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700121 return kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700122}
123
124
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800125bool WriteFile(const char* path, const char* data, int data_len) {
126 DirectFileWriter writer;
127 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
128 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700129 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800130 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800131 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800132 return true;
133}
134
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700135bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700136 const char* c_buf = static_cast<const char*>(buf);
137 ssize_t bytes_written = 0;
138 while (bytes_written < static_cast<ssize_t>(count)) {
139 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
140 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
141 bytes_written += rc;
142 }
143 return true;
144}
145
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700146bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
147 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700148 size_t bytes_written = 0;
149 int num_attempts = 0;
150 while (bytes_written < count) {
151 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700152 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
153 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700154 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
155 if (rc < 0) {
156 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
157 << " bytes_written=" << bytes_written
158 << " count=" << count << " offset=" << offset;
159 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700160 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
161 bytes_written += rc;
162 }
163 return true;
164}
165
166bool PReadAll(int fd, void* buf, size_t count, off_t offset,
167 ssize_t* out_bytes_read) {
168 char* c_buf = static_cast<char*>(buf);
169 ssize_t bytes_read = 0;
170 while (bytes_read < static_cast<ssize_t>(count)) {
171 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
172 offset + bytes_read);
173 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
174 if (rc == 0) {
175 break;
176 }
177 bytes_read += rc;
178 }
179 *out_bytes_read = bytes_read;
180 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700181}
182
Gilad Arnold19a45f02012-07-19 12:36:10 -0700183// Append |nbytes| of content from |buf| to the vector pointed to by either
184// |vec_p| or |str_p|.
185static void AppendBytes(const char* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700186 vector<char>* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700187 CHECK(buf);
188 CHECK(vec_p);
189 vec_p->insert(vec_p->end(), buf, buf + nbytes);
190}
191static void AppendBytes(const char* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700192 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700193 CHECK(buf);
194 CHECK(str_p);
195 str_p->append(buf, nbytes);
196}
197
198// Reads from an open file |fp|, appending the read content to the container
199// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200200// file's content, false otherwise. If |size| is not -1, reads up to |size|
201// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700202template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200203static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700204 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200205 CHECK(size == -1 || size >= 0);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700206 char buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200207 while (size == -1 || size > 0) {
208 off_t bytes_to_read = sizeof(buf);
209 if (size > 0 && bytes_to_read > size) {
210 bytes_to_read = size;
211 }
212 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
213 if (!nbytes) {
214 break;
215 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700216 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200217 if (size != -1) {
218 CHECK(size >= static_cast<off_t>(nbytes));
219 size -= nbytes;
220 }
221 }
222 if (ferror(fp)) {
223 return false;
224 }
225 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700226}
227
Darin Petkov8e447e02013-04-16 16:23:50 +0200228// Opens a file |path| for reading and appends its the contents to a container
229// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
230// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700231template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700232static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200233 off_t offset,
234 off_t size,
235 T* out_p) {
236 CHECK_GE(offset, 0);
237 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700238 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200239 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000240 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200241 if (offset) {
242 // Return success without appending any data if a chunk beyond the end of
243 // the file is requested.
244 if (offset >= FileSize(path)) {
245 return true;
246 }
247 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
248 }
249 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000250}
251
Gilad Arnold19a45f02012-07-19 12:36:10 -0700252// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
253// container |out_p|.
254template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700255static bool ReadPipeAndAppend(const string& cmd, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700256 FILE* fp = popen(cmd.c_str(), "r");
257 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000258 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200259 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700260 return (success && pclose(fp) >= 0);
261}
262
263
Darin Petkov8e447e02013-04-16 16:23:50 +0200264bool ReadFile(const string& path, vector<char>* out_p) {
265 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700266}
267
Darin Petkov8e447e02013-04-16 16:23:50 +0200268bool ReadFile(const string& path, string* out_p) {
269 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700270}
271
Darin Petkov8e447e02013-04-16 16:23:50 +0200272bool ReadFileChunk(const string& path, off_t offset, off_t size,
273 vector<char>* out_p) {
274 return ReadFileChunkAndAppend(path, offset, size, out_p);
275}
276
277bool ReadPipe(const string& cmd, vector<char>* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700278 return ReadPipeAndAppend(cmd, out_p);
279}
280
Darin Petkov8e447e02013-04-16 16:23:50 +0200281bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700282 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000283}
284
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700285off_t BlockDevSize(int fd) {
286 uint64_t dev_size;
287 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
288 if (rc == -1) {
289 dev_size = -1;
290 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
291 }
292 return dev_size;
293}
294
295off_t BlockDevSize(const string& path) {
296 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
297 if (fd == -1) {
298 PLOG(ERROR) << "Error opening " << path;
299 return fd;
300 }
301
302 off_t dev_size = BlockDevSize(fd);
303 if (dev_size == -1)
304 PLOG(ERROR) << "Error getting block device size on " << path;
305
306 close(fd);
307 return dev_size;
308}
309
310off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700311 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700312 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700313 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700314 if (rc < 0) {
315 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700316 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700317 }
318 if (S_ISREG(stbuf.st_mode))
319 return stbuf.st_size;
320 if (S_ISBLK(stbuf.st_mode))
321 return BlockDevSize(fd);
322 LOG(ERROR) << "Couldn't determine the type of " << fd;
323 return -1;
324}
325
326off_t FileSize(const string& path) {
327 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
328 if (fd == -1) {
329 PLOG(ERROR) << "Error opening " << path;
330 return fd;
331 }
332 off_t size = FileSize(fd);
333 if (size == -1)
334 PLOG(ERROR) << "Error getting file size of " << path;
335 close(fd);
336 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700337}
338
adlr@google.com3defe6a2009-12-04 20:57:17 +0000339void HexDumpArray(const unsigned char* const arr, const size_t length) {
340 const unsigned char* const char_arr =
341 reinterpret_cast<const unsigned char* const>(arr);
342 LOG(INFO) << "Logging array of length: " << length;
343 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700344 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000345 const unsigned int bytes_remaining = length - i;
346 const unsigned int bytes_per_this_line = min(bytes_per_line,
347 bytes_remaining);
348 char header[100];
349 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
350 TEST_AND_RETURN(r == 13);
351 string line = header;
352 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
353 char buf[20];
354 unsigned char c = char_arr[i + j];
355 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
356 TEST_AND_RETURN(r == 3);
357 line += buf;
358 }
359 LOG(INFO) << line;
360 }
361}
362
363namespace {
364class ScopedDirCloser {
365 public:
366 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
367 ~ScopedDirCloser() {
368 if (dir_ && *dir_) {
369 int r = closedir(*dir_);
370 TEST_AND_RETURN_ERRNO(r == 0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700371 *dir_ = nullptr;
372 dir_ = nullptr;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000373 }
374 }
375 private:
376 DIR** dir_;
377};
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700378} // namespace
adlr@google.com3defe6a2009-12-04 20:57:17 +0000379
Alex Deymof329b932014-10-30 01:37:48 -0700380bool RecursiveUnlinkDir(const string& path) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000381 struct stat stbuf;
382 int r = lstat(path.c_str(), &stbuf);
383 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
384 if ((r < 0) && (errno == ENOENT))
385 // path request is missing. that's fine.
386 return true;
387 if (!S_ISDIR(stbuf.st_mode)) {
388 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700389 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000390 // success or path disappeared before we could unlink.
391 return true;
392 }
393 {
394 // We have a dir, unlink all children, then delete dir
395 DIR *dir = opendir(path.c_str());
396 TEST_AND_RETURN_FALSE_ERRNO(dir);
397 ScopedDirCloser dir_closer(&dir);
398 struct dirent dir_entry;
399 struct dirent *dir_entry_p;
400 int err = 0;
401 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700402 if (dir_entry_p == nullptr) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000403 // end of stream reached
404 break;
405 }
406 // Skip . and ..
407 if (!strcmp(dir_entry_p->d_name, ".") ||
408 !strcmp(dir_entry_p->d_name, ".."))
409 continue;
410 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700411 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000412 }
413 TEST_AND_RETURN_FALSE(err == 0);
414 }
415 // unlink dir
416 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
417 return true;
418}
419
Alex Deymof329b932014-10-30 01:37:48 -0700420string GetDiskName(const string& partition_name) {
421 string disk_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800422 return SplitPartitionName(partition_name, &disk_name, nullptr) ?
Alex Deymof329b932014-10-30 01:37:48 -0700423 disk_name : string();
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700424}
425
Alex Deymof329b932014-10-30 01:37:48 -0700426int GetPartitionNumber(const string& partition_name) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800427 int partition_num = 0;
428 return SplitPartitionName(partition_name, nullptr, &partition_num) ?
429 partition_num : 0;
430}
431
Alex Deymof329b932014-10-30 01:37:48 -0700432bool SplitPartitionName(const string& partition_name,
433 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800434 int* out_partition_num) {
435 if (!StringHasPrefix(partition_name, "/dev/")) {
436 LOG(ERROR) << "Invalid partition device name: " << partition_name;
437 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700438 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800439
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700440 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
441 if (last_nondigit_pos == string::npos ||
442 (last_nondigit_pos + 1) == partition_name.size()) {
443 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800444 return false;
445 }
446
Alex Deymof329b932014-10-30 01:37:48 -0700447 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700448 if (partition_name[last_nondigit_pos] == '_') {
449 // NAND block devices have weird naming which could be something
450 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
451 size_t prev_nondigit_pos =
452 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
453 if (prev_nondigit_pos == string::npos ||
454 (prev_nondigit_pos + 1) == last_nondigit_pos) {
455 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
456 return false;
457 }
458
459 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
460 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800461 }
462
463 if (out_disk_name) {
464 // Special case for MMC devices which have the following naming scheme:
465 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700466 size_t disk_name_len = last_nondigit_pos;
467 if (partition_name[last_nondigit_pos] != 'p' ||
468 last_nondigit_pos == 0 ||
469 !isdigit(partition_name[last_nondigit_pos - 1])) {
470 disk_name_len++;
471 }
472 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800473 }
474
475 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700476 string partition_str = partition_name.substr(last_nondigit_pos + 1,
477 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800478 *out_partition_num = atoi(partition_str.c_str());
479 }
480 return true;
481}
482
Alex Deymof329b932014-10-30 01:37:48 -0700483string MakePartitionName(const string& disk_name, int partition_num) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800484 if (!StringHasPrefix(disk_name, "/dev/")) {
485 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700486 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800487 }
488
489 if (partition_num < 1) {
490 LOG(ERROR) << "Invalid partition number: " << partition_num;
Alex Deymof329b932014-10-30 01:37:48 -0700491 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800492 }
493
Alex Deymof329b932014-10-30 01:37:48 -0700494 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700495 if (isdigit(partition_name.back())) {
496 // Special case for devices with names ending with a digit.
497 // Add "p" to separate the disk name from partition number,
498 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800499 partition_name += 'p';
500 }
501
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700502 partition_name += std::to_string(partition_num);
503
504 if (StringHasPrefix(partition_name, "/dev/ubiblock")) {
505 // Special case for UBI block devieces that have "_0" suffix.
506 partition_name += "_0";
507 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800508 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700509}
510
Darin Petkovf74eb652010-08-04 12:08:38 -0700511string SysfsBlockDevice(const string& device) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700512 base::FilePath device_path(device);
Darin Petkovf74eb652010-08-04 12:08:38 -0700513 if (device_path.DirName().value() != "/dev") {
514 return "";
515 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700516 return base::FilePath("/sys/block").Append(device_path.BaseName()).value();
Darin Petkovf74eb652010-08-04 12:08:38 -0700517}
518
Alex Deymof329b932014-10-30 01:37:48 -0700519bool IsRemovableDevice(const string& device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700520 string sysfs_block = SysfsBlockDevice(device);
521 string removable;
522 if (sysfs_block.empty() ||
Alex Vakulenko75039d72014-03-25 12:36:28 -0700523 !base::ReadFileToString(base::FilePath(sysfs_block).Append("removable"),
Ben Chan736fcb52014-05-21 18:28:22 -0700524 &removable)) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700525 return false;
526 }
Ben Chan736fcb52014-05-21 18:28:22 -0700527 base::TrimWhitespaceASCII(removable, base::TRIM_ALL, &removable);
Darin Petkovf74eb652010-08-04 12:08:38 -0700528 return removable == "1";
529}
530
Alex Deymof329b932014-10-30 01:37:48 -0700531string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000532 char buf[100];
533 buf[0] = '\0';
534 return strerror_r(err, buf, sizeof(buf));
535}
536
Alex Deymof329b932014-10-30 01:37:48 -0700537string NormalizePath(const string& path, bool strip_trailing_slash) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000538 string ret;
Alex Deymo020600d2014-11-05 21:05:55 -0800539 std::unique_copy(path.begin(), path.end(), std::back_inserter(ret),
540 [](char c1, char c2) { return c1 == c2 && c1 == '/'; });
541 // The above code ensures no "//" is present in the string, so at most one
542 // '/' is present at the end of the line.
543 if (strip_trailing_slash && !ret.empty() && ret.back() == '/')
544 ret.pop_back();
adlr@google.com3defe6a2009-12-04 20:57:17 +0000545 return ret;
546}
547
548bool FileExists(const char* path) {
549 struct stat stbuf;
550 return 0 == lstat(path, &stbuf);
551}
552
Darin Petkov30291ed2010-11-12 10:23:06 -0800553bool IsSymlink(const char* path) {
554 struct stat stbuf;
555 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
556}
557
Alex Deymo7dc4c502014-05-20 20:09:58 -0700558bool IsDir(const char* path) {
559 struct stat stbuf;
560 TEST_AND_RETURN_FALSE_ERRNO(lstat(path, &stbuf) == 0);
561 return S_ISDIR(stbuf.st_mode);
562}
563
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800564// If |path| is absolute, or explicit relative to the current working directory,
565// leaves it as is. Otherwise, if TMPDIR is defined in the environment and is
566// non-empty, prepends it to |path|. Otherwise, prepends /tmp. Returns the
567// resulting path.
568static const string PrependTmpdir(const string& path) {
569 if (path[0] == '/' || StartsWithASCII(path, "./", true) ||
570 StartsWithASCII(path, "../", true))
571 return path;
572
573 const char *tmpdir = getenv("TMPDIR");
574 const string prefix = (tmpdir && *tmpdir ? tmpdir : "/tmp");
575 return prefix + "/" + path;
576}
577
Alex Deymof329b932014-10-30 01:37:48 -0700578bool MakeTempFile(const string& base_filename_template,
579 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700580 int* fd) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800581 const string filename_template = PrependTmpdir(base_filename_template);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700582 DCHECK(filename || fd);
583 vector<char> buf(filename_template.size() + 1);
584 memcpy(&buf[0], filename_template.data(), filename_template.size());
585 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700586
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700587 int mkstemp_fd = mkstemp(&buf[0]);
588 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
589 if (filename) {
590 *filename = &buf[0];
591 }
592 if (fd) {
593 *fd = mkstemp_fd;
594 } else {
595 close(mkstemp_fd);
596 }
597 return true;
598}
599
Alex Deymof329b932014-10-30 01:37:48 -0700600bool MakeTempDirectory(const string& base_dirname_template,
601 string* dirname) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800602 const string dirname_template = PrependTmpdir(base_dirname_template);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700603 DCHECK(dirname);
604 vector<char> buf(dirname_template.size() + 1);
605 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
606 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700607
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700608 char* return_code = mkdtemp(&buf[0]);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700609 TEST_AND_RETURN_FALSE_ERRNO(return_code != nullptr);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700610 *dirname = &buf[0];
611 return true;
612}
613
Alex Deymof329b932014-10-30 01:37:48 -0700614bool StringHasSuffix(const string& str, const string& suffix) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000615 if (suffix.size() > str.size())
616 return false;
617 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
618}
619
Alex Deymof329b932014-10-30 01:37:48 -0700620bool StringHasPrefix(const string& str, const string& prefix) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000621 if (prefix.size() > str.size())
622 return false;
623 return 0 == str.compare(0, prefix.size(), prefix);
624}
625
adlr@google.com3defe6a2009-12-04 20:57:17 +0000626bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700627 const string& mountpoint,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700628 unsigned long mountflags) { // NOLINT(runtime/int)
Alex Deymo4c82df32014-11-10 22:25:57 -0800629 // TODO(sosa): Remove "ext3" once crbug.com/208022 is resolved.
630 const vector<const char*> fstypes{"ext2", "ext3", "squashfs"};
631 for (const char* fstype : fstypes) {
632 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
633 nullptr);
634 if (rc == 0)
635 return true;
636
637 PLOG(WARNING) << "Unable to mount destination device " << device
638 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000639 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800640 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
641 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000642}
643
644bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700645 for (int num_retries = 0; ; ++num_retries) {
646 if (umount(mountpoint.c_str()) == 0)
647 break;
648
649 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
650 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800651 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700652 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000653 return true;
654}
655
Alex Deymof329b932014-10-30 01:37:48 -0700656bool GetFilesystemSize(const string& device,
Darin Petkovd3f8c892010-10-12 21:38:45 -0700657 int* out_block_count,
658 int* out_block_size) {
659 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
Alex Deymoe7141c62014-10-17 14:03:01 -0700660 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700661 ScopedFdCloser fd_closer(&fd);
662 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
663}
664
665bool GetFilesystemSizeFromFD(int fd,
666 int* out_block_count,
667 int* out_block_size) {
668 TEST_AND_RETURN_FALSE(fd >= 0);
669
Alex Deymo192393b2014-11-10 15:58:38 -0800670 // Determine the filesystem size by directly reading the block count and
671 // block size information from the superblock. Supported FS are ext3 and
672 // squashfs.
673
674 // Read from the fd only once and detect in memory. The first 2 KiB is enough
675 // to read the ext2 superblock (located at offset 1024) and the squashfs
676 // superblock (located at offset 0).
677 const ssize_t kBufferSize = 2048;
678
679 uint8_t buffer[kBufferSize];
680 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, 0)) != kBufferSize) {
681 PLOG(ERROR) << "Unable to read the file system header:";
Darin Petkovd3f8c892010-10-12 21:38:45 -0700682 return false;
683 }
Alex Deymo192393b2014-11-10 15:58:38 -0800684
685 if (GetSquashfs4Size(buffer, kBufferSize, out_block_count, out_block_size))
686 return true;
687 if (GetExt3Size(buffer, kBufferSize, out_block_count, out_block_size))
688 return true;
689
690 LOG(ERROR) << "Unable to determine file system type.";
691 return false;
692}
693
694bool GetExt3Size(const uint8_t* buffer, size_t buffer_size,
695 int* out_block_count,
696 int* out_block_size) {
697 // See include/linux/ext2_fs.h for more details on the structure. We obtain
698 // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
699 // library.
700 if (buffer_size < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
701 return false;
702
703 const uint8_t* superblock = buffer + SUPERBLOCK_OFFSET;
704
705 // ext3_fs.h: ext3_super_block.s_blocks_count
706 uint32_t block_count =
707 *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
708
709 // ext3_fs.h: ext3_super_block.s_log_block_size
710 uint32_t log_block_size =
711 *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
712
713 // ext3_fs.h: ext3_super_block.s_magic
714 uint16_t magic =
715 *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
716
Darin Petkovd3f8c892010-10-12 21:38:45 -0700717 block_count = le32toh(block_count);
Alex Deymo192393b2014-11-10 15:58:38 -0800718 log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700719 magic = le16toh(magic);
720
721 // Sanity check the parameters.
Alex Deymo192393b2014-11-10 15:58:38 -0800722 TEST_AND_RETURN_FALSE(magic == EXT2_SUPER_MAGIC);
723 TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
724 log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700725 TEST_AND_RETURN_FALSE(block_count > 0);
726
Alex Deymo192393b2014-11-10 15:58:38 -0800727 if (out_block_count)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700728 *out_block_count = block_count;
Alex Deymo192393b2014-11-10 15:58:38 -0800729 if (out_block_size)
730 *out_block_size = 1 << log_block_size;
731 return true;
732}
733
734bool GetSquashfs4Size(const unsigned char* buffer, size_t buffer_size,
735 int* out_block_count,
736 int* out_block_size) {
737 // See fs/squashfs/squashfs_fs.h for format details. We only support
738 // Squashfs 4.x little endian.
739
740 // sizeof(struct squashfs_super_block)
741 const size_t kSquashfsSuperBlockSize = 96;
742 if (buffer_size < kSquashfsSuperBlockSize)
743 return false;
744
745 // Check magic, squashfs_fs.h: SQUASHFS_MAGIC
746 if (memcmp(buffer, "hsqs", 4) != 0)
747 return false; // Only little endian is supported.
748
749 // squashfs_fs.h: struct squashfs_super_block.s_major
750 uint16_t s_major = *reinterpret_cast<const uint16_t*>(
751 buffer + 5 * sizeof(uint32_t) + 4 * sizeof(uint16_t));
752
753 if (s_major != 4) {
754 LOG(ERROR) << "Found unsupported squashfs major version " << s_major;
755 return false;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700756 }
Alex Deymo192393b2014-11-10 15:58:38 -0800757
758 // squashfs_fs.h: struct squashfs_super_block.bytes_used
759 uint64_t bytes_used = *reinterpret_cast<const int64_t*>(
760 buffer + 5 * sizeof(uint32_t) + 6 * sizeof(uint16_t) + sizeof(uint64_t));
761
762 const int block_size = 4096;
763
764 // The squashfs' bytes_used doesn't need to be aligned with the block boundary
765 // so we round up to the nearest blocksize.
766 if (out_block_count)
767 *out_block_count = (bytes_used + block_size - 1) / block_size;
768 if (out_block_size)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700769 *out_block_size = block_size;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700770 return true;
771}
772
Alex Deymo719bfff2014-07-11 12:12:32 -0700773string GetPathOnBoard(const string& command) {
774 int return_code = 0;
775 string command_path;
776 // TODO(deymo): prepend SYSROOT to each PATH instead of the result.
777 if (!Subprocess::SynchronousExec(
778 {"which", command}, &return_code, &command_path)) {
779 return command;
780 }
781 if (return_code != 0)
782 return command;
783
784 base::TrimWhitespaceASCII(command_path, base::TRIM_ALL, &command_path);
785 const char* env_sysroot = getenv("SYSROOT");
786 if (env_sysroot) {
787 string sysroot_command_path = env_sysroot + command_path;
788 if (utils::FileExists(sysroot_command_path.c_str()))
789 return sysroot_command_path;
790 }
791 return command_path;
792}
793
Alex Deymo032e7722014-03-25 17:53:56 -0700794// Tries to parse the header of an ELF file to obtain a human-readable
795// description of it on the |output| string.
796static bool GetFileFormatELF(const char* buffer, size_t size, string* output) {
797 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700798 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700799 return false;
800 *output = "ELF";
801
802 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700803 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700804 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700805 switch (buffer[EI_CLASS]) {
806 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700807 *output += " 32-bit";
808 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700809 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700810 *output += " 64-bit";
811 break;
812 default:
813 *output += " ?-bit";
814 }
815
816 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700817 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700818 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700819 char ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700820 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700821 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700822 *output += " little-endian";
823 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700824 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700825 *output += " big-endian";
826 break;
827 default:
828 *output += " ?-endian";
829 // Don't parse anything after the 0x10 offset if endianness is unknown.
830 return true;
831 }
832
Alex Deymoc1711e22014-08-08 13:16:23 -0700833 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
834 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
835 // and size is the same for both 32 and 64 bits.
836 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700837 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700838 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700839 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700840 if (ei_data == ELFDATA2LSB)
841 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700842 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700843 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700844
845 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700846 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700847 *output += " x86";
848 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700849 case EM_MIPS:
850 *output += " mips";
851 break;
852 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700853 *output += " arm";
854 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700855 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700856 *output += " x86-64";
857 break;
858 default:
859 *output += " unknown-arch";
860 }
861 return true;
862}
863
864string GetFileFormat(const string& path) {
865 vector<char> buffer;
866 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
867 return "File not found.";
868
869 string result;
870 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
871 return result;
872
873 return "data";
874}
875
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800876namespace {
877// Do the actual trigger. We do it as a main-loop callback to (try to) get a
878// consistent stack trace.
879gboolean TriggerCrashReporterUpload(void* unused) {
880 pid_t pid = fork();
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700881 CHECK_GE(pid, 0) << "fork failed"; // fork() failed. Something is very wrong.
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800882 if (pid == 0) {
883 // We are the child. Crash.
884 abort(); // never returns
885 }
886 // We are the parent. Wait for child to terminate.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700887 pid_t result = waitpid(pid, nullptr, 0);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800888 LOG_IF(ERROR, result < 0) << "waitpid() failed";
889 return FALSE; // Don't call this callback again
890}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700891} // namespace
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800892
893void ScheduleCrashReporterUpload() {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700894 g_idle_add(&TriggerCrashReporterUpload, nullptr);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800895}
896
Chris Sosa4f8ee272012-11-30 13:01:54 -0800897bool SetCpuShares(CpuShares shares) {
898 string string_shares = base::IntToString(static_cast<int>(shares));
899 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
900 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700901 if (utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
902 string_shares.size())) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800903 return true;
904 } else {
905 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
906 << " using " << cpu_shares_file;
907 return false;
908 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700909}
910
Chris Sosa4f8ee272012-11-30 13:01:54 -0800911int CompareCpuShares(CpuShares shares_lhs,
912 CpuShares shares_rhs) {
913 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700914}
915
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700916int FuzzInt(int value, unsigned int range) {
917 int min = value - range / 2;
918 int max = value + range - range / 2;
919 return base::RandInt(min, max);
920}
921
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800922gboolean GlibRunClosure(gpointer data) {
Alex Vakulenko4906c1c2014-08-21 13:17:44 -0700923 base::Closure* callback = reinterpret_cast<base::Closure*>(data);
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800924 callback->Run();
925 return FALSE;
926}
927
Alex Deymoc4acdf42014-05-28 21:07:10 -0700928void GlibDestroyClosure(gpointer data) {
Alex Vakulenko4906c1c2014-08-21 13:17:44 -0700929 delete reinterpret_cast<base::Closure*>(data);
Alex Deymoc4acdf42014-05-28 21:07:10 -0700930}
931
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700932string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800933 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700934}
935
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800936string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400937 string str;
938
939 // Handle negative durations by prefixing with a minus.
940 if (delta.ToInternalValue() < 0) {
941 delta *= -1;
942 str = "-";
943 }
944
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700945 // Canonicalize into days, hours, minutes, seconds and microseconds.
946 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800947 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700948 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800949 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700950 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800951 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700952 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800953 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700954 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800955
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700956 if (days)
957 base::StringAppendF(&str, "%ud", days);
958 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800959 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700960 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800961 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700962 base::StringAppendF(&str, "%u", secs);
963 if (usecs) {
964 int width = 6;
965 while ((usecs / 10) * 10 == usecs) {
966 usecs /= 10;
967 width--;
968 }
969 base::StringAppendF(&str, ".%0*u", width, usecs);
970 }
971 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800972 return str;
973}
974
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700975string ToString(const Time utc_time) {
976 Time::Exploded exp_time;
977 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700978 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700979 exp_time.month,
980 exp_time.day_of_month,
981 exp_time.year,
982 exp_time.hour,
983 exp_time.minute,
984 exp_time.second);
985}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000986
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700987string ToString(bool b) {
988 return (b ? "true" : "false");
989}
990
Alex Deymo1c656c42013-06-28 11:02:14 -0700991string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700992 switch (source) {
993 case kDownloadSourceHttpsServer: return "HttpsServer";
994 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700995 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700996 case kNumDownloadSources: return "Unknown";
997 // Don't add a default case to let the compiler warn about newly added
998 // download sources which should be added here.
999 }
1000
1001 return "Unknown";
1002}
1003
Alex Deymo1c656c42013-06-28 11:02:14 -07001004string ToString(PayloadType payload_type) {
1005 switch (payload_type) {
1006 case kPayloadTypeDelta: return "Delta";
1007 case kPayloadTypeFull: return "Full";
1008 case kPayloadTypeForcedFull: return "ForcedFull";
1009 case kNumPayloadTypes: return "Unknown";
1010 // Don't add a default case to let the compiler warn about newly added
1011 // payload types which should be added here.
1012 }
1013
1014 return "Unknown";
1015}
1016
David Zeuthena99981f2013-04-29 13:42:47 -07001017ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -07001018 // Ignore the higher order bits in the code by applying the mask as
1019 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001020 // with values less than ErrorCode::kUmaReportedMax.
1021 ErrorCode base_code = static_cast<ErrorCode>(
1022 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -07001023
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001024 // Make additional adjustments required for UMA and error classification.
1025 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
1026 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001027 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -07001028 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001029 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001030 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001031 << " to ErrorCode::kOmahaErrorInHTTPResponse";
1032 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001033 }
1034
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001035 return base_code;
1036}
1037
David Zeuthen33bae492014-02-25 16:16:18 -08001038metrics::AttemptResult GetAttemptResult(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001039 ErrorCode base_code = static_cast<ErrorCode>(
1040 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001041
1042 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001043 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001044 return metrics::AttemptResult::kUpdateSucceeded;
1045
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001046 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001047 return metrics::AttemptResult::kPayloadDownloadError;
1048
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001049 case ErrorCode::kDownloadInvalidMetadataSize:
1050 case ErrorCode::kDownloadInvalidMetadataMagicString:
1051 case ErrorCode::kDownloadMetadataSignatureError:
1052 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1053 case ErrorCode::kPayloadMismatchedType:
1054 case ErrorCode::kUnsupportedMajorPayloadVersion:
1055 case ErrorCode::kUnsupportedMinorPayloadVersion:
1056 case ErrorCode::kDownloadNewPartitionInfoError:
1057 case ErrorCode::kDownloadSignatureMissingInManifest:
1058 case ErrorCode::kDownloadManifestParseError:
1059 case ErrorCode::kDownloadOperationHashMissingError:
David Zeuthen33bae492014-02-25 16:16:18 -08001060 return metrics::AttemptResult::kMetadataMalformed;
1061
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001062 case ErrorCode::kDownloadOperationHashMismatch:
1063 case ErrorCode::kDownloadOperationHashVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001064 return metrics::AttemptResult::kOperationMalformed;
1065
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001066 case ErrorCode::kDownloadOperationExecutionError:
1067 case ErrorCode::kInstallDeviceOpenError:
1068 case ErrorCode::kKernelDeviceOpenError:
1069 case ErrorCode::kDownloadWriteError:
1070 case ErrorCode::kFilesystemCopierError:
David Zeuthen33bae492014-02-25 16:16:18 -08001071 return metrics::AttemptResult::kOperationExecutionError;
1072
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001073 case ErrorCode::kDownloadMetadataSignatureMismatch:
David Zeuthen33bae492014-02-25 16:16:18 -08001074 return metrics::AttemptResult::kMetadataVerificationFailed;
1075
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001076 case ErrorCode::kPayloadSizeMismatchError:
1077 case ErrorCode::kPayloadHashMismatchError:
1078 case ErrorCode::kDownloadPayloadVerificationError:
1079 case ErrorCode::kSignedDeltaPayloadExpectedError:
1080 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001081 return metrics::AttemptResult::kPayloadVerificationFailed;
1082
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001083 case ErrorCode::kNewRootfsVerificationError:
1084 case ErrorCode::kNewKernelVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001085 return metrics::AttemptResult::kVerificationFailed;
1086
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001087 case ErrorCode::kPostinstallRunnerError:
1088 case ErrorCode::kPostinstallBootedFromFirmwareB:
1089 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
David Zeuthen33bae492014-02-25 16:16:18 -08001090 return metrics::AttemptResult::kPostInstallFailed;
1091
1092 // We should never get these errors in the update-attempt stage so
1093 // return internal error if this happens.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001094 case ErrorCode::kError:
1095 case ErrorCode::kOmahaRequestXMLParseError:
1096 case ErrorCode::kOmahaRequestError:
1097 case ErrorCode::kOmahaResponseHandlerError:
1098 case ErrorCode::kDownloadStateInitializationError:
1099 case ErrorCode::kOmahaRequestEmptyResponseError:
1100 case ErrorCode::kDownloadInvalidMetadataSignature:
1101 case ErrorCode::kOmahaResponseInvalid:
1102 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1103 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1104 case ErrorCode::kOmahaErrorInHTTPResponse:
1105 case ErrorCode::kDownloadMetadataSignatureMissingError:
1106 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1107 case ErrorCode::kPostinstallPowerwashError:
1108 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -04001109 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
David Zeuthen33bae492014-02-25 16:16:18 -08001110 return metrics::AttemptResult::kInternalError;
1111
1112 // Special flags. These can't happen (we mask them out above) but
1113 // the compiler doesn't know that. Just break out so we can warn and
1114 // return |kInternalError|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001115 case ErrorCode::kUmaReportedMax:
1116 case ErrorCode::kOmahaRequestHTTPResponseBase:
1117 case ErrorCode::kDevModeFlag:
1118 case ErrorCode::kResumedFlag:
1119 case ErrorCode::kTestImageFlag:
1120 case ErrorCode::kTestOmahaUrlFlag:
1121 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001122 break;
1123 }
1124
1125 LOG(ERROR) << "Unexpected error code " << base_code;
1126 return metrics::AttemptResult::kInternalError;
1127}
1128
1129
1130metrics::DownloadErrorCode GetDownloadErrorCode(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001131 ErrorCode base_code = static_cast<ErrorCode>(
1132 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001133
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001134 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
1135 int http_status =
1136 static_cast<int>(base_code) -
1137 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase);
David Zeuthen33bae492014-02-25 16:16:18 -08001138 if (http_status >= 200 && http_status <= 599) {
1139 return static_cast<metrics::DownloadErrorCode>(
1140 static_cast<int>(metrics::DownloadErrorCode::kHttpStatus200) +
1141 http_status - 200);
1142 } else if (http_status == 0) {
1143 // The code is using HTTP Status 0 for "Unable to get http
1144 // response code."
1145 return metrics::DownloadErrorCode::kDownloadError;
1146 }
1147 LOG(WARNING) << "Unexpected HTTP status code " << http_status;
1148 return metrics::DownloadErrorCode::kHttpStatusOther;
1149 }
1150
1151 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001152 // Unfortunately, ErrorCode::kDownloadTransferError is returned for a wide
David Zeuthen33bae492014-02-25 16:16:18 -08001153 // variety of errors (proxy errors, host not reachable, timeouts etc.).
1154 //
1155 // For now just map that to kDownloading. See http://crbug.com/355745
1156 // for how we plan to add more detail in the future.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001157 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001158 return metrics::DownloadErrorCode::kDownloadError;
1159
1160 // All of these error codes are not related to downloading so break
1161 // out so we can warn and return InputMalformed.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001162 case ErrorCode::kSuccess:
1163 case ErrorCode::kError:
1164 case ErrorCode::kOmahaRequestError:
1165 case ErrorCode::kOmahaResponseHandlerError:
1166 case ErrorCode::kFilesystemCopierError:
1167 case ErrorCode::kPostinstallRunnerError:
1168 case ErrorCode::kPayloadMismatchedType:
1169 case ErrorCode::kInstallDeviceOpenError:
1170 case ErrorCode::kKernelDeviceOpenError:
1171 case ErrorCode::kPayloadHashMismatchError:
1172 case ErrorCode::kPayloadSizeMismatchError:
1173 case ErrorCode::kDownloadPayloadVerificationError:
1174 case ErrorCode::kDownloadNewPartitionInfoError:
1175 case ErrorCode::kDownloadWriteError:
1176 case ErrorCode::kNewRootfsVerificationError:
1177 case ErrorCode::kNewKernelVerificationError:
1178 case ErrorCode::kSignedDeltaPayloadExpectedError:
1179 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1180 case ErrorCode::kPostinstallBootedFromFirmwareB:
1181 case ErrorCode::kDownloadStateInitializationError:
1182 case ErrorCode::kDownloadInvalidMetadataMagicString:
1183 case ErrorCode::kDownloadSignatureMissingInManifest:
1184 case ErrorCode::kDownloadManifestParseError:
1185 case ErrorCode::kDownloadMetadataSignatureError:
1186 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1187 case ErrorCode::kDownloadMetadataSignatureMismatch:
1188 case ErrorCode::kDownloadOperationHashVerificationError:
1189 case ErrorCode::kDownloadOperationExecutionError:
1190 case ErrorCode::kDownloadOperationHashMismatch:
1191 case ErrorCode::kOmahaRequestEmptyResponseError:
1192 case ErrorCode::kOmahaRequestXMLParseError:
1193 case ErrorCode::kDownloadInvalidMetadataSize:
1194 case ErrorCode::kDownloadInvalidMetadataSignature:
1195 case ErrorCode::kOmahaResponseInvalid:
1196 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1197 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1198 case ErrorCode::kOmahaErrorInHTTPResponse:
1199 case ErrorCode::kDownloadOperationHashMissingError:
1200 case ErrorCode::kDownloadMetadataSignatureMissingError:
1201 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1202 case ErrorCode::kPostinstallPowerwashError:
1203 case ErrorCode::kUpdateCanceledByChannelChange:
1204 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1205 case ErrorCode::kUnsupportedMajorPayloadVersion:
1206 case ErrorCode::kUnsupportedMinorPayloadVersion:
David Zeuthenf3e28012014-08-26 18:23:52 -04001207 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
David Zeuthen33bae492014-02-25 16:16:18 -08001208 break;
1209
1210 // Special flags. These can't happen (we mask them out above) but
1211 // the compiler doesn't know that. Just break out so we can warn and
1212 // return |kInputMalformed|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001213 case ErrorCode::kUmaReportedMax:
1214 case ErrorCode::kOmahaRequestHTTPResponseBase:
1215 case ErrorCode::kDevModeFlag:
1216 case ErrorCode::kResumedFlag:
1217 case ErrorCode::kTestImageFlag:
1218 case ErrorCode::kTestOmahaUrlFlag:
1219 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001220 LOG(ERROR) << "Unexpected error code " << base_code;
1221 break;
1222 }
1223
1224 return metrics::DownloadErrorCode::kInputMalformed;
1225}
1226
David Zeuthenb281f072014-04-02 10:20:19 -07001227metrics::ConnectionType GetConnectionType(
1228 NetworkConnectionType type,
1229 NetworkTethering tethering) {
1230 switch (type) {
1231 case kNetUnknown:
1232 return metrics::ConnectionType::kUnknown;
1233
1234 case kNetEthernet:
1235 if (tethering == NetworkTethering::kConfirmed)
1236 return metrics::ConnectionType::kTetheredEthernet;
1237 else
1238 return metrics::ConnectionType::kEthernet;
1239
1240 case kNetWifi:
1241 if (tethering == NetworkTethering::kConfirmed)
1242 return metrics::ConnectionType::kTetheredWifi;
1243 else
1244 return metrics::ConnectionType::kWifi;
1245
1246 case kNetWimax:
1247 return metrics::ConnectionType::kWimax;
1248
1249 case kNetBluetooth:
1250 return metrics::ConnectionType::kBluetooth;
1251
1252 case kNetCellular:
1253 return metrics::ConnectionType::kCellular;
1254 }
1255
1256 LOG(ERROR) << "Unexpected network connection type: type=" << type
1257 << ", tethering=" << static_cast<int>(tethering);
1258
1259 return metrics::ConnectionType::kUnknown;
1260}
1261
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001262// Returns a printable version of the various flags denoted in the higher order
1263// bits of the given code. Returns an empty string if none of those bits are
1264// set.
1265string GetFlagNames(uint32_t code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001266 uint32_t flags = (static_cast<uint32_t>(code) &
1267 static_cast<uint32_t>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001268 string flag_names;
1269 string separator = "";
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001270 for (size_t i = 0; i < sizeof(flags) * 8; i++) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001271 uint32_t flag = flags & (1 << i);
1272 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -07001273 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001274 separator = ", ";
1275 }
1276 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001277
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001278 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001279}
1280
David Zeuthena99981f2013-04-29 13:42:47 -07001281void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001282 if (!system_state)
1283 return;
1284
David Zeuthena99981f2013-04-29 13:42:47 -07001285 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001286
1287 // If the code doesn't have flags computed already, compute them now based on
1288 // the state of the current update attempt.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001289 uint32_t flags =
1290 static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001291 if (!flags)
1292 flags = system_state->update_attempter()->GetErrorCodeFlags();
1293
1294 // Determine the UMA bucket depending on the flags. But, ignore the resumed
1295 // flag, as it's perfectly normal for production devices to resume their
1296 // downloads and so we want to record those cases also in NormalErrorCodes
1297 // bucket.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001298 string metric =
1299 flags & ~static_cast<uint32_t>(ErrorCode::kResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001300 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
1301
1302 LOG(INFO) << "Sending error code " << uma_error_code
1303 << " (" << CodeToString(uma_error_code) << ")"
1304 << " to UMA metric: " << metric
1305 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
1306
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001307 system_state->metrics_lib()->SendEnumToUMA(
1308 metric, static_cast<int>(uma_error_code),
1309 static_cast<int>(ErrorCode::kUmaReportedMax));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001310}
1311
David Zeuthena99981f2013-04-29 13:42:47 -07001312string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001313 // If the given code has both parts (i.e. the error code part and the flags
1314 // part) then strip off the flags part since the switch statement below
1315 // has case statements only for the base error code or a single flag but
1316 // doesn't support any combinations of those.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001317 if ((static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags)) &&
1318 (static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags)))
1319 code = static_cast<ErrorCode>(
1320 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001321 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001322 case ErrorCode::kSuccess: return "ErrorCode::kSuccess";
1323 case ErrorCode::kError: return "ErrorCode::kError";
1324 case ErrorCode::kOmahaRequestError: return "ErrorCode::kOmahaRequestError";
1325 case ErrorCode::kOmahaResponseHandlerError:
1326 return "ErrorCode::kOmahaResponseHandlerError";
1327 case ErrorCode::kFilesystemCopierError:
1328 return "ErrorCode::kFilesystemCopierError";
1329 case ErrorCode::kPostinstallRunnerError:
1330 return "ErrorCode::kPostinstallRunnerError";
1331 case ErrorCode::kPayloadMismatchedType:
1332 return "ErrorCode::kPayloadMismatchedType";
1333 case ErrorCode::kInstallDeviceOpenError:
1334 return "ErrorCode::kInstallDeviceOpenError";
1335 case ErrorCode::kKernelDeviceOpenError:
1336 return "ErrorCode::kKernelDeviceOpenError";
1337 case ErrorCode::kDownloadTransferError:
1338 return "ErrorCode::kDownloadTransferError";
1339 case ErrorCode::kPayloadHashMismatchError:
1340 return "ErrorCode::kPayloadHashMismatchError";
1341 case ErrorCode::kPayloadSizeMismatchError:
1342 return "ErrorCode::kPayloadSizeMismatchError";
1343 case ErrorCode::kDownloadPayloadVerificationError:
1344 return "ErrorCode::kDownloadPayloadVerificationError";
1345 case ErrorCode::kDownloadNewPartitionInfoError:
1346 return "ErrorCode::kDownloadNewPartitionInfoError";
1347 case ErrorCode::kDownloadWriteError:
1348 return "ErrorCode::kDownloadWriteError";
1349 case ErrorCode::kNewRootfsVerificationError:
1350 return "ErrorCode::kNewRootfsVerificationError";
1351 case ErrorCode::kNewKernelVerificationError:
1352 return "ErrorCode::kNewKernelVerificationError";
1353 case ErrorCode::kSignedDeltaPayloadExpectedError:
1354 return "ErrorCode::kSignedDeltaPayloadExpectedError";
1355 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1356 return "ErrorCode::kDownloadPayloadPubKeyVerificationError";
1357 case ErrorCode::kPostinstallBootedFromFirmwareB:
1358 return "ErrorCode::kPostinstallBootedFromFirmwareB";
1359 case ErrorCode::kDownloadStateInitializationError:
1360 return "ErrorCode::kDownloadStateInitializationError";
1361 case ErrorCode::kDownloadInvalidMetadataMagicString:
1362 return "ErrorCode::kDownloadInvalidMetadataMagicString";
1363 case ErrorCode::kDownloadSignatureMissingInManifest:
1364 return "ErrorCode::kDownloadSignatureMissingInManifest";
1365 case ErrorCode::kDownloadManifestParseError:
1366 return "ErrorCode::kDownloadManifestParseError";
1367 case ErrorCode::kDownloadMetadataSignatureError:
1368 return "ErrorCode::kDownloadMetadataSignatureError";
1369 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1370 return "ErrorCode::kDownloadMetadataSignatureVerificationError";
1371 case ErrorCode::kDownloadMetadataSignatureMismatch:
1372 return "ErrorCode::kDownloadMetadataSignatureMismatch";
1373 case ErrorCode::kDownloadOperationHashVerificationError:
1374 return "ErrorCode::kDownloadOperationHashVerificationError";
1375 case ErrorCode::kDownloadOperationExecutionError:
1376 return "ErrorCode::kDownloadOperationExecutionError";
1377 case ErrorCode::kDownloadOperationHashMismatch:
1378 return "ErrorCode::kDownloadOperationHashMismatch";
1379 case ErrorCode::kOmahaRequestEmptyResponseError:
1380 return "ErrorCode::kOmahaRequestEmptyResponseError";
1381 case ErrorCode::kOmahaRequestXMLParseError:
1382 return "ErrorCode::kOmahaRequestXMLParseError";
1383 case ErrorCode::kDownloadInvalidMetadataSize:
1384 return "ErrorCode::kDownloadInvalidMetadataSize";
1385 case ErrorCode::kDownloadInvalidMetadataSignature:
1386 return "ErrorCode::kDownloadInvalidMetadataSignature";
1387 case ErrorCode::kOmahaResponseInvalid:
1388 return "ErrorCode::kOmahaResponseInvalid";
1389 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1390 return "ErrorCode::kOmahaUpdateIgnoredPerPolicy";
1391 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1392 return "ErrorCode::kOmahaUpdateDeferredPerPolicy";
1393 case ErrorCode::kOmahaErrorInHTTPResponse:
1394 return "ErrorCode::kOmahaErrorInHTTPResponse";
1395 case ErrorCode::kDownloadOperationHashMissingError:
1396 return "ErrorCode::kDownloadOperationHashMissingError";
1397 case ErrorCode::kDownloadMetadataSignatureMissingError:
1398 return "ErrorCode::kDownloadMetadataSignatureMissingError";
1399 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1400 return "ErrorCode::kOmahaUpdateDeferredForBackoff";
1401 case ErrorCode::kPostinstallPowerwashError:
1402 return "ErrorCode::kPostinstallPowerwashError";
1403 case ErrorCode::kUpdateCanceledByChannelChange:
1404 return "ErrorCode::kUpdateCanceledByChannelChange";
1405 case ErrorCode::kUmaReportedMax:
1406 return "ErrorCode::kUmaReportedMax";
1407 case ErrorCode::kOmahaRequestHTTPResponseBase:
1408 return "ErrorCode::kOmahaRequestHTTPResponseBase";
1409 case ErrorCode::kResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001410 return "Resumed";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001411 case ErrorCode::kDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001412 return "DevMode";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001413 case ErrorCode::kTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001414 return "TestImage";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001415 case ErrorCode::kTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001416 return "TestOmahaUrl";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001417 case ErrorCode::kSpecialFlags:
1418 return "ErrorCode::kSpecialFlags";
1419 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1420 return "ErrorCode::kPostinstallFirmwareRONotUpdatable";
1421 case ErrorCode::kUnsupportedMajorPayloadVersion:
1422 return "ErrorCode::kUnsupportedMajorPayloadVersion";
1423 case ErrorCode::kUnsupportedMinorPayloadVersion:
1424 return "ErrorCode::kUnsupportedMinorPayloadVersion";
David Zeuthenf3e28012014-08-26 18:23:52 -04001425 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
1426 return "ErrorCode::kOmahaRequestXMLHasEntityDecl";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001427 // Don't add a default case to let the compiler warn about newly added
1428 // error codes which should be added here.
1429 }
1430
1431 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1432}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001433
Gilad Arnold30dedd82013-07-03 06:19:09 -07001434bool CreatePowerwashMarkerFile(const char* file_path) {
1435 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1436 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001437 kPowerwashCommand,
1438 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001439 if (result) {
1440 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1441 } else {
1442 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1443 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001444
1445 return result;
1446}
1447
Gilad Arnold30dedd82013-07-03 06:19:09 -07001448bool DeletePowerwashMarkerFile(const char* file_path) {
1449 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001450 const base::FilePath kPowerwashMarkerPath(marker_file);
1451 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001452
1453 if (result)
1454 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001455 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001456 else
1457 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001458 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001459
1460 return result;
1461}
1462
Alex Deymof329b932014-10-30 01:37:48 -07001463bool GetInstallDev(const string& boot_dev, string* install_dev) {
1464 string disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001465 int partition_num;
1466 if (!SplitPartitionName(boot_dev, &disk_name, &partition_num))
1467 return false;
Liam McLoughlin049d1652013-07-31 18:47:46 -07001468
Chris Sosad317e402013-06-12 13:47:09 -07001469 // Right now, we just switch '3' and '5' partition numbers.
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001470 if (partition_num == 3) {
1471 partition_num = 5;
1472 } else if (partition_num == 5) {
1473 partition_num = 3;
1474 } else {
1475 return false;
1476 }
1477
1478 if (install_dev)
1479 *install_dev = MakePartitionName(disk_name, partition_num);
Liam McLoughlin049d1652013-07-31 18:47:46 -07001480
Chris Sosad317e402013-06-12 13:47:09 -07001481 return true;
1482}
1483
David Zeuthen27a48bc2013-08-06 12:06:29 -07001484Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -07001485 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1486 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -07001487 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1488}
1489
Alex Deymof329b932014-10-30 01:37:48 -07001490gchar** StringVectorToGStrv(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001491 GPtrArray *p = g_ptr_array_new();
Alex Deymo020600d2014-11-05 21:05:55 -08001492 for (const string& str : vec_str) {
1493 g_ptr_array_add(p, g_strdup(str.c_str()));
David Zeuthen27a48bc2013-08-06 12:06:29 -07001494 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001495 g_ptr_array_add(p, nullptr);
David Zeuthen27a48bc2013-08-06 12:06:29 -07001496 return reinterpret_cast<gchar**>(g_ptr_array_free(p, FALSE));
1497}
1498
Alex Deymof329b932014-10-30 01:37:48 -07001499string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001500 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -07001501 for (vector<string>::const_iterator i = vec_str.begin();
1502 i != vec_str.end(); ++i) {
1503 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -07001504 str += ", ";
1505 str += '"';
1506 str += *i;
1507 str += '"';
1508 }
1509 str += "]";
1510 return str;
1511}
1512
David Zeuthen8f191b22013-08-06 12:27:50 -07001513string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
1514 string encoded_hash;
1515 OmahaHashCalculator::Base64Encode(payload_hash.c_str(),
1516 payload_hash.size(),
1517 &encoded_hash);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001518 return base::StringPrintf("cros_update_size_%zu_hash_%s",
David Zeuthen8f191b22013-08-06 12:27:50 -07001519 payload_size,
1520 encoded_hash.c_str());
1521}
1522
David Zeuthen910ec5b2013-09-26 12:10:58 -07001523bool IsXAttrSupported(const base::FilePath& dir_path) {
1524 char *path = strdup(dir_path.Append("xattr_test_XXXXXX").value().c_str());
1525
1526 int fd = mkstemp(path);
1527 if (fd == -1) {
1528 PLOG(ERROR) << "Error creating temporary file in " << dir_path.value();
1529 free(path);
1530 return false;
1531 }
1532
1533 if (unlink(path) != 0) {
1534 PLOG(ERROR) << "Error unlinking temporary file " << path;
1535 close(fd);
1536 free(path);
1537 return false;
1538 }
1539
1540 int xattr_res = fsetxattr(fd, "user.xattr-test", "value", strlen("value"), 0);
1541 if (xattr_res != 0) {
1542 if (errno == ENOTSUP) {
1543 // Leave it to call-sites to warn about non-support.
1544 } else {
1545 PLOG(ERROR) << "Error setting xattr on " << path;
1546 }
1547 }
1548 close(fd);
1549 free(path);
1550 return xattr_res == 0;
1551}
1552
Alex Deymof329b932014-10-30 01:37:48 -07001553bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -07001554 base::FilePath *out_path) {
1555 vector<char> contents;
1556
1557 out_path->clear();
1558
1559 if (base64_encoded.size() == 0) {
1560 LOG(ERROR) << "Can't decode empty string.";
1561 return false;
1562 }
1563
1564 if (!OmahaHashCalculator::Base64Decode(base64_encoded, &contents) ||
1565 contents.size() == 0) {
1566 LOG(ERROR) << "Error decoding base64.";
1567 return false;
1568 }
1569
Alex Vakulenko75039d72014-03-25 12:36:28 -07001570 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001571 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -07001572 LOG(ERROR) << "Error creating temporary file.";
1573 return false;
1574 }
1575
1576 if (fwrite(&contents[0], 1, contents.size(), file) != contents.size()) {
1577 PLOG(ERROR) << "Error writing to temporary file.";
1578 if (fclose(file) != 0)
1579 PLOG(ERROR) << "Error closing temporary file.";
1580 if (unlink(out_path->value().c_str()) != 0)
1581 PLOG(ERROR) << "Error unlinking temporary file.";
1582 out_path->clear();
1583 return false;
1584 }
1585
1586 if (fclose(file) != 0) {
1587 PLOG(ERROR) << "Error closing temporary file.";
1588 out_path->clear();
1589 return false;
1590 }
1591
1592 return true;
1593}
1594
Alex Deymof329b932014-10-30 01:37:48 -07001595bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -08001596 time_t unix_time = time.ToTimeT();
1597 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1598 const time_t kOmahaEpoch = 1167638400;
1599 const int64_t kNumSecondsPerWeek = 7*24*3600;
1600 const int64_t kNumDaysPerWeek = 7;
1601
1602 time_t omaha_time = unix_time - kOmahaEpoch;
1603
1604 if (omaha_time < 0)
1605 return false;
1606
1607 // Note, as per the comment in utils.h we are deliberately not
1608 // handling DST correctly.
1609
1610 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1611 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1612
1613 return true;
1614}
1615
David Zeuthen33bae492014-02-25 16:16:18 -08001616bool WallclockDurationHelper(SystemState* system_state,
Alex Deymof329b932014-10-30 01:37:48 -07001617 const string& state_variable_key,
1618 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001619 bool ret = false;
1620
Alex Deymof329b932014-10-30 01:37:48 -07001621 Time now = system_state->clock()->GetWallclockTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001622 int64_t stored_value;
1623 if (system_state->prefs()->GetInt64(state_variable_key, &stored_value)) {
Alex Deymof329b932014-10-30 01:37:48 -07001624 Time stored_time = Time::FromInternalValue(stored_value);
David Zeuthen33bae492014-02-25 16:16:18 -08001625 if (stored_time > now) {
1626 LOG(ERROR) << "Stored time-stamp used for " << state_variable_key
1627 << " is in the future.";
1628 } else {
1629 *out_duration = now - stored_time;
1630 ret = true;
1631 }
1632 }
1633
1634 if (!system_state->prefs()->SetInt64(state_variable_key,
1635 now.ToInternalValue())) {
1636 LOG(ERROR) << "Error storing time-stamp in " << state_variable_key;
1637 }
1638
1639 return ret;
1640}
1641
1642bool MonotonicDurationHelper(SystemState* system_state,
1643 int64_t* storage,
Alex Deymof329b932014-10-30 01:37:48 -07001644 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001645 bool ret = false;
1646
Alex Deymof329b932014-10-30 01:37:48 -07001647 Time now = system_state->clock()->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001648 if (*storage != 0) {
Alex Deymof329b932014-10-30 01:37:48 -07001649 Time stored_time = Time::FromInternalValue(*storage);
David Zeuthen33bae492014-02-25 16:16:18 -08001650 *out_duration = now - stored_time;
1651 ret = true;
1652 }
1653 *storage = now.ToInternalValue();
1654
1655 return ret;
1656}
1657
adlr@google.com3defe6a2009-12-04 20:57:17 +00001658} // namespace utils
1659
1660} // namespace chromeos_update_engine