blob: b84eda035456567c64a9a878d18d1d14f746aa87 [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>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080039#include <glib.h>
Will Drewry8f71da82010-08-30 14:07:11 -050040
David Zeuthen33bae492014-02-25 16:16:18 -080041#include "update_engine/clock_interface.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070042#include "update_engine/constants.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080043#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070044#include "update_engine/omaha_request_params.h"
David Zeuthen33bae492014-02-25 16:16:18 -080045#include "update_engine/prefs_interface.h"
Darin Petkov296889c2010-07-23 16:20:54 -070046#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080047#include "update_engine/system_state.h"
48#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000049
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070050using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080051using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000052using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070053using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000054using std::string;
55using std::vector;
56
57namespace chromeos_update_engine {
58
Ben Chan77a1eba2012-10-07 22:54:55 -070059namespace {
60
61// The following constants control how UnmountFilesystem should retry if
62// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
63// one second.
64const int kUnmountMaxNumOfRetries = 5;
65const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070066
67// Number of bytes to read from a file to attempt to detect its contents. Used
68// in GetFileFormat.
69const int kGetFileFormatMaxHeaderSize = 32;
70
Ben Chan77a1eba2012-10-07 22:54:55 -070071} // namespace
72
adlr@google.com3defe6a2009-12-04 20:57:17 +000073namespace utils {
74
Chris Sosa4f8ee272012-11-30 13:01:54 -080075// Cgroup container is created in update-engine's upstart script located at
76// /etc/init/update-engine.conf.
77static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
78
J. Richard Barnette63137e52013-10-28 10:57:29 -070079string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -070080 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -070081
Alex Vakulenko75039d72014-03-25 12:36:28 -070082 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -070083 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -070084 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -070085 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -080086 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -070087 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -080088 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -070089 string output;
90 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -080091 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -070092 return output;
93 }
94 }
95 }
96 LOG(ERROR) << "Unable to parse fwid from ec info.";
97 return "";
98}
99
100
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700101const string KernelDeviceOfBootDevice(const string& boot_device) {
102 string kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700103
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700104 string disk_name;
105 int partition_num;
106 if (SplitPartitionName(boot_device, &disk_name, &partition_num)) {
107 if (disk_name == "/dev/ubiblock") {
108 // Special case for NAND devices.
109 // eg: /dev/ubiblock3_0 becomes /dev/mtdblock2
110 disk_name = "/dev/mtdblock";
111 }
112 // Currently this assumes the partition number of the boot device is
113 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
114 // get the kernel device.
115 if (partition_num == 3 || partition_num == 5 || partition_num == 7) {
116 kernel_partition_name = MakePartitionName(disk_name, partition_num - 1);
117 }
J. Richard Barnette30842932013-10-28 15:04:23 -0700118 }
119
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700120 return kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700121}
122
123
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800124bool WriteFile(const char* path, const char* data, int data_len) {
125 DirectFileWriter writer;
126 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
127 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700128 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800129 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800130 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800131 return true;
132}
133
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700134bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700135 const char* c_buf = static_cast<const char*>(buf);
136 ssize_t bytes_written = 0;
137 while (bytes_written < static_cast<ssize_t>(count)) {
138 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
139 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
140 bytes_written += rc;
141 }
142 return true;
143}
144
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700145bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
146 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700147 size_t bytes_written = 0;
148 int num_attempts = 0;
149 while (bytes_written < count) {
150 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700151 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
152 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700153 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
154 if (rc < 0) {
155 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
156 << " bytes_written=" << bytes_written
157 << " count=" << count << " offset=" << offset;
158 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700159 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
160 bytes_written += rc;
161 }
162 return true;
163}
164
165bool PReadAll(int fd, void* buf, size_t count, off_t offset,
166 ssize_t* out_bytes_read) {
167 char* c_buf = static_cast<char*>(buf);
168 ssize_t bytes_read = 0;
169 while (bytes_read < static_cast<ssize_t>(count)) {
170 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
171 offset + bytes_read);
172 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
173 if (rc == 0) {
174 break;
175 }
176 bytes_read += rc;
177 }
178 *out_bytes_read = bytes_read;
179 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700180}
181
Gilad Arnold19a45f02012-07-19 12:36:10 -0700182// Append |nbytes| of content from |buf| to the vector pointed to by either
183// |vec_p| or |str_p|.
184static void AppendBytes(const char* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700185 vector<char>* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700186 CHECK(buf);
187 CHECK(vec_p);
188 vec_p->insert(vec_p->end(), buf, buf + nbytes);
189}
190static void AppendBytes(const char* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700191 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700192 CHECK(buf);
193 CHECK(str_p);
194 str_p->append(buf, nbytes);
195}
196
197// Reads from an open file |fp|, appending the read content to the container
198// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200199// file's content, false otherwise. If |size| is not -1, reads up to |size|
200// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700201template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200202static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700203 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200204 CHECK(size == -1 || size >= 0);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700205 char buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200206 while (size == -1 || size > 0) {
207 off_t bytes_to_read = sizeof(buf);
208 if (size > 0 && bytes_to_read > size) {
209 bytes_to_read = size;
210 }
211 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
212 if (!nbytes) {
213 break;
214 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700215 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200216 if (size != -1) {
217 CHECK(size >= static_cast<off_t>(nbytes));
218 size -= nbytes;
219 }
220 }
221 if (ferror(fp)) {
222 return false;
223 }
224 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700225}
226
Darin Petkov8e447e02013-04-16 16:23:50 +0200227// Opens a file |path| for reading and appends its the contents to a container
228// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
229// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700230template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700231static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200232 off_t offset,
233 off_t size,
234 T* out_p) {
235 CHECK_GE(offset, 0);
236 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700237 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200238 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000239 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200240 if (offset) {
241 // Return success without appending any data if a chunk beyond the end of
242 // the file is requested.
243 if (offset >= FileSize(path)) {
244 return true;
245 }
246 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
247 }
248 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000249}
250
Alex Deymo10875d92014-11-10 21:52:57 -0800251// TODO(deymo): This is only used in unittest, but requires the private
252// Read<string>() defined here. Expose Read<string>() or move to base/ version.
253bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700254 FILE* fp = popen(cmd.c_str(), "r");
255 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000256 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200257 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700258 return (success && pclose(fp) >= 0);
259}
260
Darin Petkov8e447e02013-04-16 16:23:50 +0200261bool ReadFile(const string& path, vector<char>* out_p) {
262 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700263}
264
Darin Petkov8e447e02013-04-16 16:23:50 +0200265bool ReadFile(const string& path, string* out_p) {
266 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700267}
268
Darin Petkov8e447e02013-04-16 16:23:50 +0200269bool ReadFileChunk(const string& path, off_t offset, off_t size,
270 vector<char>* out_p) {
271 return ReadFileChunkAndAppend(path, offset, size, out_p);
272}
273
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700274off_t BlockDevSize(int fd) {
275 uint64_t dev_size;
276 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
277 if (rc == -1) {
278 dev_size = -1;
279 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
280 }
281 return dev_size;
282}
283
284off_t BlockDevSize(const string& path) {
285 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
286 if (fd == -1) {
287 PLOG(ERROR) << "Error opening " << path;
288 return fd;
289 }
290
291 off_t dev_size = BlockDevSize(fd);
292 if (dev_size == -1)
293 PLOG(ERROR) << "Error getting block device size on " << path;
294
295 close(fd);
296 return dev_size;
297}
298
299off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700300 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700301 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700302 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700303 if (rc < 0) {
304 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700305 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700306 }
307 if (S_ISREG(stbuf.st_mode))
308 return stbuf.st_size;
309 if (S_ISBLK(stbuf.st_mode))
310 return BlockDevSize(fd);
311 LOG(ERROR) << "Couldn't determine the type of " << fd;
312 return -1;
313}
314
315off_t FileSize(const string& path) {
316 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
317 if (fd == -1) {
318 PLOG(ERROR) << "Error opening " << path;
319 return fd;
320 }
321 off_t size = FileSize(fd);
322 if (size == -1)
323 PLOG(ERROR) << "Error getting file size of " << path;
324 close(fd);
325 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700326}
327
adlr@google.com3defe6a2009-12-04 20:57:17 +0000328void HexDumpArray(const unsigned char* const arr, const size_t length) {
329 const unsigned char* const char_arr =
330 reinterpret_cast<const unsigned char* const>(arr);
331 LOG(INFO) << "Logging array of length: " << length;
332 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700333 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000334 const unsigned int bytes_remaining = length - i;
335 const unsigned int bytes_per_this_line = min(bytes_per_line,
336 bytes_remaining);
337 char header[100];
338 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
339 TEST_AND_RETURN(r == 13);
340 string line = header;
341 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
342 char buf[20];
343 unsigned char c = char_arr[i + j];
344 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
345 TEST_AND_RETURN(r == 3);
346 line += buf;
347 }
348 LOG(INFO) << line;
349 }
350}
351
Alex Deymof329b932014-10-30 01:37:48 -0700352string GetDiskName(const string& partition_name) {
353 string disk_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800354 return SplitPartitionName(partition_name, &disk_name, nullptr) ?
Alex Deymof329b932014-10-30 01:37:48 -0700355 disk_name : string();
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700356}
357
Alex Deymof329b932014-10-30 01:37:48 -0700358int GetPartitionNumber(const string& partition_name) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800359 int partition_num = 0;
360 return SplitPartitionName(partition_name, nullptr, &partition_num) ?
361 partition_num : 0;
362}
363
Alex Deymof329b932014-10-30 01:37:48 -0700364bool SplitPartitionName(const string& partition_name,
365 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800366 int* out_partition_num) {
Alex Deymo10875d92014-11-10 21:52:57 -0800367 if (!StartsWithASCII(partition_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800368 LOG(ERROR) << "Invalid partition device name: " << partition_name;
369 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700370 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800371
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700372 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
373 if (last_nondigit_pos == string::npos ||
374 (last_nondigit_pos + 1) == partition_name.size()) {
375 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800376 return false;
377 }
378
Alex Deymof329b932014-10-30 01:37:48 -0700379 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700380 if (partition_name[last_nondigit_pos] == '_') {
381 // NAND block devices have weird naming which could be something
382 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
383 size_t prev_nondigit_pos =
384 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
385 if (prev_nondigit_pos == string::npos ||
386 (prev_nondigit_pos + 1) == last_nondigit_pos) {
387 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
388 return false;
389 }
390
391 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
392 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800393 }
394
395 if (out_disk_name) {
396 // Special case for MMC devices which have the following naming scheme:
397 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700398 size_t disk_name_len = last_nondigit_pos;
399 if (partition_name[last_nondigit_pos] != 'p' ||
400 last_nondigit_pos == 0 ||
401 !isdigit(partition_name[last_nondigit_pos - 1])) {
402 disk_name_len++;
403 }
404 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800405 }
406
407 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700408 string partition_str = partition_name.substr(last_nondigit_pos + 1,
409 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800410 *out_partition_num = atoi(partition_str.c_str());
411 }
412 return true;
413}
414
Alex Deymof329b932014-10-30 01:37:48 -0700415string MakePartitionName(const string& disk_name, int partition_num) {
Alex Deymo10875d92014-11-10 21:52:57 -0800416 if (!StartsWithASCII(disk_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800417 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700418 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800419 }
420
421 if (partition_num < 1) {
422 LOG(ERROR) << "Invalid partition number: " << partition_num;
Alex Deymof329b932014-10-30 01:37:48 -0700423 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800424 }
425
Alex Deymof329b932014-10-30 01:37:48 -0700426 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700427 if (isdigit(partition_name.back())) {
428 // Special case for devices with names ending with a digit.
429 // Add "p" to separate the disk name from partition number,
430 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800431 partition_name += 'p';
432 }
433
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700434 partition_name += std::to_string(partition_num);
435
Alex Deymo10875d92014-11-10 21:52:57 -0800436 if (StartsWithASCII(partition_name, "/dev/ubiblock", true)) {
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700437 // Special case for UBI block devieces that have "_0" suffix.
438 partition_name += "_0";
439 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800440 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700441}
442
Darin Petkovf74eb652010-08-04 12:08:38 -0700443string SysfsBlockDevice(const string& device) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700444 base::FilePath device_path(device);
Darin Petkovf74eb652010-08-04 12:08:38 -0700445 if (device_path.DirName().value() != "/dev") {
446 return "";
447 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700448 return base::FilePath("/sys/block").Append(device_path.BaseName()).value();
Darin Petkovf74eb652010-08-04 12:08:38 -0700449}
450
Alex Deymof329b932014-10-30 01:37:48 -0700451bool IsRemovableDevice(const string& device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700452 string sysfs_block = SysfsBlockDevice(device);
453 string removable;
454 if (sysfs_block.empty() ||
Alex Vakulenko75039d72014-03-25 12:36:28 -0700455 !base::ReadFileToString(base::FilePath(sysfs_block).Append("removable"),
Ben Chan736fcb52014-05-21 18:28:22 -0700456 &removable)) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700457 return false;
458 }
Ben Chan736fcb52014-05-21 18:28:22 -0700459 base::TrimWhitespaceASCII(removable, base::TRIM_ALL, &removable);
Darin Petkovf74eb652010-08-04 12:08:38 -0700460 return removable == "1";
461}
462
Alex Deymof329b932014-10-30 01:37:48 -0700463string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000464 char buf[100];
465 buf[0] = '\0';
466 return strerror_r(err, buf, sizeof(buf));
467}
468
Alex Deymof329b932014-10-30 01:37:48 -0700469string NormalizePath(const string& path, bool strip_trailing_slash) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000470 string ret;
Alex Deymo020600d2014-11-05 21:05:55 -0800471 std::unique_copy(path.begin(), path.end(), std::back_inserter(ret),
472 [](char c1, char c2) { return c1 == c2 && c1 == '/'; });
473 // The above code ensures no "//" is present in the string, so at most one
474 // '/' is present at the end of the line.
475 if (strip_trailing_slash && !ret.empty() && ret.back() == '/')
476 ret.pop_back();
adlr@google.com3defe6a2009-12-04 20:57:17 +0000477 return ret;
478}
479
480bool FileExists(const char* path) {
481 struct stat stbuf;
482 return 0 == lstat(path, &stbuf);
483}
484
Darin Petkov30291ed2010-11-12 10:23:06 -0800485bool IsSymlink(const char* path) {
486 struct stat stbuf;
487 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
488}
489
Alex Deymo7dc4c502014-05-20 20:09:58 -0700490bool IsDir(const char* path) {
491 struct stat stbuf;
492 TEST_AND_RETURN_FALSE_ERRNO(lstat(path, &stbuf) == 0);
493 return S_ISDIR(stbuf.st_mode);
494}
495
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800496// If |path| is absolute, or explicit relative to the current working directory,
497// leaves it as is. Otherwise, if TMPDIR is defined in the environment and is
498// non-empty, prepends it to |path|. Otherwise, prepends /tmp. Returns the
499// resulting path.
500static const string PrependTmpdir(const string& path) {
501 if (path[0] == '/' || StartsWithASCII(path, "./", true) ||
502 StartsWithASCII(path, "../", true))
503 return path;
504
505 const char *tmpdir = getenv("TMPDIR");
506 const string prefix = (tmpdir && *tmpdir ? tmpdir : "/tmp");
507 return prefix + "/" + path;
508}
509
Alex Deymof329b932014-10-30 01:37:48 -0700510bool MakeTempFile(const string& base_filename_template,
511 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700512 int* fd) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800513 const string filename_template = PrependTmpdir(base_filename_template);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700514 DCHECK(filename || fd);
515 vector<char> buf(filename_template.size() + 1);
516 memcpy(&buf[0], filename_template.data(), filename_template.size());
517 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700518
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700519 int mkstemp_fd = mkstemp(&buf[0]);
520 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
521 if (filename) {
522 *filename = &buf[0];
523 }
524 if (fd) {
525 *fd = mkstemp_fd;
526 } else {
527 close(mkstemp_fd);
528 }
529 return true;
530}
531
Alex Deymof329b932014-10-30 01:37:48 -0700532bool MakeTempDirectory(const string& base_dirname_template,
533 string* dirname) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800534 const string dirname_template = PrependTmpdir(base_dirname_template);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700535 DCHECK(dirname);
536 vector<char> buf(dirname_template.size() + 1);
537 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
538 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700539
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700540 char* return_code = mkdtemp(&buf[0]);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700541 TEST_AND_RETURN_FALSE_ERRNO(return_code != nullptr);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700542 *dirname = &buf[0];
543 return true;
544}
545
adlr@google.com3defe6a2009-12-04 20:57:17 +0000546bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700547 const string& mountpoint,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700548 unsigned long mountflags) { // NOLINT(runtime/int)
Alex Deymo4c82df32014-11-10 22:25:57 -0800549 // TODO(sosa): Remove "ext3" once crbug.com/208022 is resolved.
550 const vector<const char*> fstypes{"ext2", "ext3", "squashfs"};
551 for (const char* fstype : fstypes) {
552 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
553 nullptr);
554 if (rc == 0)
555 return true;
556
557 PLOG(WARNING) << "Unable to mount destination device " << device
558 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000559 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800560 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
561 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000562}
563
564bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700565 for (int num_retries = 0; ; ++num_retries) {
566 if (umount(mountpoint.c_str()) == 0)
567 break;
568
569 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
570 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800571 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700572 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000573 return true;
574}
575
Alex Deymof329b932014-10-30 01:37:48 -0700576bool GetFilesystemSize(const string& device,
Darin Petkovd3f8c892010-10-12 21:38:45 -0700577 int* out_block_count,
578 int* out_block_size) {
579 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
Alex Deymoe7141c62014-10-17 14:03:01 -0700580 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700581 ScopedFdCloser fd_closer(&fd);
582 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
583}
584
585bool GetFilesystemSizeFromFD(int fd,
586 int* out_block_count,
587 int* out_block_size) {
588 TEST_AND_RETURN_FALSE(fd >= 0);
589
Alex Deymo192393b2014-11-10 15:58:38 -0800590 // Determine the filesystem size by directly reading the block count and
591 // block size information from the superblock. Supported FS are ext3 and
592 // squashfs.
593
594 // Read from the fd only once and detect in memory. The first 2 KiB is enough
595 // to read the ext2 superblock (located at offset 1024) and the squashfs
596 // superblock (located at offset 0).
597 const ssize_t kBufferSize = 2048;
598
599 uint8_t buffer[kBufferSize];
600 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, 0)) != kBufferSize) {
601 PLOG(ERROR) << "Unable to read the file system header:";
Darin Petkovd3f8c892010-10-12 21:38:45 -0700602 return false;
603 }
Alex Deymo192393b2014-11-10 15:58:38 -0800604
605 if (GetSquashfs4Size(buffer, kBufferSize, out_block_count, out_block_size))
606 return true;
607 if (GetExt3Size(buffer, kBufferSize, out_block_count, out_block_size))
608 return true;
609
610 LOG(ERROR) << "Unable to determine file system type.";
611 return false;
612}
613
614bool GetExt3Size(const uint8_t* buffer, size_t buffer_size,
615 int* out_block_count,
616 int* out_block_size) {
617 // See include/linux/ext2_fs.h for more details on the structure. We obtain
618 // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
619 // library.
620 if (buffer_size < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
621 return false;
622
623 const uint8_t* superblock = buffer + SUPERBLOCK_OFFSET;
624
625 // ext3_fs.h: ext3_super_block.s_blocks_count
626 uint32_t block_count =
627 *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
628
629 // ext3_fs.h: ext3_super_block.s_log_block_size
630 uint32_t log_block_size =
631 *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
632
633 // ext3_fs.h: ext3_super_block.s_magic
634 uint16_t magic =
635 *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
636
Darin Petkovd3f8c892010-10-12 21:38:45 -0700637 block_count = le32toh(block_count);
Alex Deymo192393b2014-11-10 15:58:38 -0800638 log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700639 magic = le16toh(magic);
640
641 // Sanity check the parameters.
Alex Deymo192393b2014-11-10 15:58:38 -0800642 TEST_AND_RETURN_FALSE(magic == EXT2_SUPER_MAGIC);
643 TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
644 log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700645 TEST_AND_RETURN_FALSE(block_count > 0);
646
Alex Deymo192393b2014-11-10 15:58:38 -0800647 if (out_block_count)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700648 *out_block_count = block_count;
Alex Deymo192393b2014-11-10 15:58:38 -0800649 if (out_block_size)
650 *out_block_size = 1 << log_block_size;
651 return true;
652}
653
654bool GetSquashfs4Size(const unsigned char* buffer, size_t buffer_size,
655 int* out_block_count,
656 int* out_block_size) {
657 // See fs/squashfs/squashfs_fs.h for format details. We only support
658 // Squashfs 4.x little endian.
659
660 // sizeof(struct squashfs_super_block)
661 const size_t kSquashfsSuperBlockSize = 96;
662 if (buffer_size < kSquashfsSuperBlockSize)
663 return false;
664
665 // Check magic, squashfs_fs.h: SQUASHFS_MAGIC
666 if (memcmp(buffer, "hsqs", 4) != 0)
667 return false; // Only little endian is supported.
668
669 // squashfs_fs.h: struct squashfs_super_block.s_major
670 uint16_t s_major = *reinterpret_cast<const uint16_t*>(
671 buffer + 5 * sizeof(uint32_t) + 4 * sizeof(uint16_t));
672
673 if (s_major != 4) {
674 LOG(ERROR) << "Found unsupported squashfs major version " << s_major;
675 return false;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700676 }
Alex Deymo192393b2014-11-10 15:58:38 -0800677
678 // squashfs_fs.h: struct squashfs_super_block.bytes_used
679 uint64_t bytes_used = *reinterpret_cast<const int64_t*>(
680 buffer + 5 * sizeof(uint32_t) + 6 * sizeof(uint16_t) + sizeof(uint64_t));
681
682 const int block_size = 4096;
683
684 // The squashfs' bytes_used doesn't need to be aligned with the block boundary
685 // so we round up to the nearest blocksize.
686 if (out_block_count)
687 *out_block_count = (bytes_used + block_size - 1) / block_size;
688 if (out_block_size)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700689 *out_block_size = block_size;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700690 return true;
691}
692
Alex Deymo719bfff2014-07-11 12:12:32 -0700693string GetPathOnBoard(const string& command) {
694 int return_code = 0;
695 string command_path;
696 // TODO(deymo): prepend SYSROOT to each PATH instead of the result.
697 if (!Subprocess::SynchronousExec(
698 {"which", command}, &return_code, &command_path)) {
699 return command;
700 }
701 if (return_code != 0)
702 return command;
703
704 base::TrimWhitespaceASCII(command_path, base::TRIM_ALL, &command_path);
705 const char* env_sysroot = getenv("SYSROOT");
706 if (env_sysroot) {
707 string sysroot_command_path = env_sysroot + command_path;
708 if (utils::FileExists(sysroot_command_path.c_str()))
709 return sysroot_command_path;
710 }
711 return command_path;
712}
713
Alex Deymo032e7722014-03-25 17:53:56 -0700714// Tries to parse the header of an ELF file to obtain a human-readable
715// description of it on the |output| string.
716static bool GetFileFormatELF(const char* buffer, size_t size, string* output) {
717 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700718 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700719 return false;
720 *output = "ELF";
721
722 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700723 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700724 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700725 switch (buffer[EI_CLASS]) {
726 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700727 *output += " 32-bit";
728 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700729 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700730 *output += " 64-bit";
731 break;
732 default:
733 *output += " ?-bit";
734 }
735
736 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700737 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700738 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700739 char ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700740 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700741 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700742 *output += " little-endian";
743 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700744 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700745 *output += " big-endian";
746 break;
747 default:
748 *output += " ?-endian";
749 // Don't parse anything after the 0x10 offset if endianness is unknown.
750 return true;
751 }
752
Alex Deymoc1711e22014-08-08 13:16:23 -0700753 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
754 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
755 // and size is the same for both 32 and 64 bits.
756 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700757 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700758 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700759 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700760 if (ei_data == ELFDATA2LSB)
761 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700762 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700763 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700764
765 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700766 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700767 *output += " x86";
768 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700769 case EM_MIPS:
770 *output += " mips";
771 break;
772 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700773 *output += " arm";
774 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700775 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700776 *output += " x86-64";
777 break;
778 default:
779 *output += " unknown-arch";
780 }
781 return true;
782}
783
784string GetFileFormat(const string& path) {
785 vector<char> buffer;
786 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
787 return "File not found.";
788
789 string result;
790 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
791 return result;
792
793 return "data";
794}
795
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800796namespace {
797// Do the actual trigger. We do it as a main-loop callback to (try to) get a
798// consistent stack trace.
799gboolean TriggerCrashReporterUpload(void* unused) {
800 pid_t pid = fork();
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700801 CHECK_GE(pid, 0) << "fork failed"; // fork() failed. Something is very wrong.
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800802 if (pid == 0) {
803 // We are the child. Crash.
804 abort(); // never returns
805 }
806 // We are the parent. Wait for child to terminate.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700807 pid_t result = waitpid(pid, nullptr, 0);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800808 LOG_IF(ERROR, result < 0) << "waitpid() failed";
809 return FALSE; // Don't call this callback again
810}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700811} // namespace
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800812
813void ScheduleCrashReporterUpload() {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700814 g_idle_add(&TriggerCrashReporterUpload, nullptr);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800815}
816
Chris Sosa4f8ee272012-11-30 13:01:54 -0800817bool SetCpuShares(CpuShares shares) {
818 string string_shares = base::IntToString(static_cast<int>(shares));
819 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
820 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700821 if (utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
822 string_shares.size())) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800823 return true;
824 } else {
825 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
826 << " using " << cpu_shares_file;
827 return false;
828 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700829}
830
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700831int FuzzInt(int value, unsigned int range) {
832 int min = value - range / 2;
833 int max = value + range - range / 2;
834 return base::RandInt(min, max);
835}
836
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800837gboolean GlibRunClosure(gpointer data) {
Alex Vakulenko4906c1c2014-08-21 13:17:44 -0700838 base::Closure* callback = reinterpret_cast<base::Closure*>(data);
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800839 callback->Run();
840 return FALSE;
841}
842
Alex Deymoc4acdf42014-05-28 21:07:10 -0700843void GlibDestroyClosure(gpointer data) {
Alex Vakulenko4906c1c2014-08-21 13:17:44 -0700844 delete reinterpret_cast<base::Closure*>(data);
Alex Deymoc4acdf42014-05-28 21:07:10 -0700845}
846
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700847string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800848 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700849}
850
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800851string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400852 string str;
853
854 // Handle negative durations by prefixing with a minus.
855 if (delta.ToInternalValue() < 0) {
856 delta *= -1;
857 str = "-";
858 }
859
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700860 // Canonicalize into days, hours, minutes, seconds and microseconds.
861 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800862 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700863 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800864 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700865 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800866 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700867 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800868 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700869 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800870
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700871 if (days)
872 base::StringAppendF(&str, "%ud", days);
873 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800874 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700875 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800876 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700877 base::StringAppendF(&str, "%u", secs);
878 if (usecs) {
879 int width = 6;
880 while ((usecs / 10) * 10 == usecs) {
881 usecs /= 10;
882 width--;
883 }
884 base::StringAppendF(&str, ".%0*u", width, usecs);
885 }
886 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800887 return str;
888}
889
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700890string ToString(const Time utc_time) {
891 Time::Exploded exp_time;
892 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700893 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700894 exp_time.month,
895 exp_time.day_of_month,
896 exp_time.year,
897 exp_time.hour,
898 exp_time.minute,
899 exp_time.second);
900}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000901
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700902string ToString(bool b) {
903 return (b ? "true" : "false");
904}
905
Alex Deymo1c656c42013-06-28 11:02:14 -0700906string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700907 switch (source) {
908 case kDownloadSourceHttpsServer: return "HttpsServer";
909 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700910 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700911 case kNumDownloadSources: return "Unknown";
912 // Don't add a default case to let the compiler warn about newly added
913 // download sources which should be added here.
914 }
915
916 return "Unknown";
917}
918
Alex Deymo1c656c42013-06-28 11:02:14 -0700919string ToString(PayloadType payload_type) {
920 switch (payload_type) {
921 case kPayloadTypeDelta: return "Delta";
922 case kPayloadTypeFull: return "Full";
923 case kPayloadTypeForcedFull: return "ForcedFull";
924 case kNumPayloadTypes: return "Unknown";
925 // Don't add a default case to let the compiler warn about newly added
926 // payload types which should be added here.
927 }
928
929 return "Unknown";
930}
931
David Zeuthena99981f2013-04-29 13:42:47 -0700932ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700933 // Ignore the higher order bits in the code by applying the mask as
934 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700935 // with values less than ErrorCode::kUmaReportedMax.
936 ErrorCode base_code = static_cast<ErrorCode>(
937 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700938
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800939 // Make additional adjustments required for UMA and error classification.
940 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
941 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700942 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700943 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800944 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800945 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700946 << " to ErrorCode::kOmahaErrorInHTTPResponse";
947 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700948 }
949
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800950 return base_code;
951}
952
David Zeuthen33bae492014-02-25 16:16:18 -0800953metrics::AttemptResult GetAttemptResult(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700954 ErrorCode base_code = static_cast<ErrorCode>(
955 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -0800956
957 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700958 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -0800959 return metrics::AttemptResult::kUpdateSucceeded;
960
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700961 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -0800962 return metrics::AttemptResult::kPayloadDownloadError;
963
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700964 case ErrorCode::kDownloadInvalidMetadataSize:
965 case ErrorCode::kDownloadInvalidMetadataMagicString:
966 case ErrorCode::kDownloadMetadataSignatureError:
967 case ErrorCode::kDownloadMetadataSignatureVerificationError:
968 case ErrorCode::kPayloadMismatchedType:
969 case ErrorCode::kUnsupportedMajorPayloadVersion:
970 case ErrorCode::kUnsupportedMinorPayloadVersion:
971 case ErrorCode::kDownloadNewPartitionInfoError:
972 case ErrorCode::kDownloadSignatureMissingInManifest:
973 case ErrorCode::kDownloadManifestParseError:
974 case ErrorCode::kDownloadOperationHashMissingError:
David Zeuthen33bae492014-02-25 16:16:18 -0800975 return metrics::AttemptResult::kMetadataMalformed;
976
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700977 case ErrorCode::kDownloadOperationHashMismatch:
978 case ErrorCode::kDownloadOperationHashVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -0800979 return metrics::AttemptResult::kOperationMalformed;
980
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700981 case ErrorCode::kDownloadOperationExecutionError:
982 case ErrorCode::kInstallDeviceOpenError:
983 case ErrorCode::kKernelDeviceOpenError:
984 case ErrorCode::kDownloadWriteError:
985 case ErrorCode::kFilesystemCopierError:
David Zeuthen33bae492014-02-25 16:16:18 -0800986 return metrics::AttemptResult::kOperationExecutionError;
987
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700988 case ErrorCode::kDownloadMetadataSignatureMismatch:
David Zeuthen33bae492014-02-25 16:16:18 -0800989 return metrics::AttemptResult::kMetadataVerificationFailed;
990
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700991 case ErrorCode::kPayloadSizeMismatchError:
992 case ErrorCode::kPayloadHashMismatchError:
993 case ErrorCode::kDownloadPayloadVerificationError:
994 case ErrorCode::kSignedDeltaPayloadExpectedError:
995 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -0800996 return metrics::AttemptResult::kPayloadVerificationFailed;
997
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700998 case ErrorCode::kNewRootfsVerificationError:
999 case ErrorCode::kNewKernelVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001000 return metrics::AttemptResult::kVerificationFailed;
1001
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001002 case ErrorCode::kPostinstallRunnerError:
1003 case ErrorCode::kPostinstallBootedFromFirmwareB:
1004 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
David Zeuthen33bae492014-02-25 16:16:18 -08001005 return metrics::AttemptResult::kPostInstallFailed;
1006
1007 // We should never get these errors in the update-attempt stage so
1008 // return internal error if this happens.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001009 case ErrorCode::kError:
1010 case ErrorCode::kOmahaRequestXMLParseError:
1011 case ErrorCode::kOmahaRequestError:
1012 case ErrorCode::kOmahaResponseHandlerError:
1013 case ErrorCode::kDownloadStateInitializationError:
1014 case ErrorCode::kOmahaRequestEmptyResponseError:
1015 case ErrorCode::kDownloadInvalidMetadataSignature:
1016 case ErrorCode::kOmahaResponseInvalid:
1017 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1018 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1019 case ErrorCode::kOmahaErrorInHTTPResponse:
1020 case ErrorCode::kDownloadMetadataSignatureMissingError:
1021 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1022 case ErrorCode::kPostinstallPowerwashError:
1023 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -04001024 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
David Zeuthen33bae492014-02-25 16:16:18 -08001025 return metrics::AttemptResult::kInternalError;
1026
1027 // Special flags. These can't happen (we mask them out above) but
1028 // the compiler doesn't know that. Just break out so we can warn and
1029 // return |kInternalError|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001030 case ErrorCode::kUmaReportedMax:
1031 case ErrorCode::kOmahaRequestHTTPResponseBase:
1032 case ErrorCode::kDevModeFlag:
1033 case ErrorCode::kResumedFlag:
1034 case ErrorCode::kTestImageFlag:
1035 case ErrorCode::kTestOmahaUrlFlag:
1036 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001037 break;
1038 }
1039
1040 LOG(ERROR) << "Unexpected error code " << base_code;
1041 return metrics::AttemptResult::kInternalError;
1042}
1043
1044
1045metrics::DownloadErrorCode GetDownloadErrorCode(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001046 ErrorCode base_code = static_cast<ErrorCode>(
1047 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001048
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001049 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
1050 int http_status =
1051 static_cast<int>(base_code) -
1052 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase);
David Zeuthen33bae492014-02-25 16:16:18 -08001053 if (http_status >= 200 && http_status <= 599) {
1054 return static_cast<metrics::DownloadErrorCode>(
1055 static_cast<int>(metrics::DownloadErrorCode::kHttpStatus200) +
1056 http_status - 200);
1057 } else if (http_status == 0) {
1058 // The code is using HTTP Status 0 for "Unable to get http
1059 // response code."
1060 return metrics::DownloadErrorCode::kDownloadError;
1061 }
1062 LOG(WARNING) << "Unexpected HTTP status code " << http_status;
1063 return metrics::DownloadErrorCode::kHttpStatusOther;
1064 }
1065
1066 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001067 // Unfortunately, ErrorCode::kDownloadTransferError is returned for a wide
David Zeuthen33bae492014-02-25 16:16:18 -08001068 // variety of errors (proxy errors, host not reachable, timeouts etc.).
1069 //
1070 // For now just map that to kDownloading. See http://crbug.com/355745
1071 // for how we plan to add more detail in the future.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001072 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001073 return metrics::DownloadErrorCode::kDownloadError;
1074
1075 // All of these error codes are not related to downloading so break
1076 // out so we can warn and return InputMalformed.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001077 case ErrorCode::kSuccess:
1078 case ErrorCode::kError:
1079 case ErrorCode::kOmahaRequestError:
1080 case ErrorCode::kOmahaResponseHandlerError:
1081 case ErrorCode::kFilesystemCopierError:
1082 case ErrorCode::kPostinstallRunnerError:
1083 case ErrorCode::kPayloadMismatchedType:
1084 case ErrorCode::kInstallDeviceOpenError:
1085 case ErrorCode::kKernelDeviceOpenError:
1086 case ErrorCode::kPayloadHashMismatchError:
1087 case ErrorCode::kPayloadSizeMismatchError:
1088 case ErrorCode::kDownloadPayloadVerificationError:
1089 case ErrorCode::kDownloadNewPartitionInfoError:
1090 case ErrorCode::kDownloadWriteError:
1091 case ErrorCode::kNewRootfsVerificationError:
1092 case ErrorCode::kNewKernelVerificationError:
1093 case ErrorCode::kSignedDeltaPayloadExpectedError:
1094 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1095 case ErrorCode::kPostinstallBootedFromFirmwareB:
1096 case ErrorCode::kDownloadStateInitializationError:
1097 case ErrorCode::kDownloadInvalidMetadataMagicString:
1098 case ErrorCode::kDownloadSignatureMissingInManifest:
1099 case ErrorCode::kDownloadManifestParseError:
1100 case ErrorCode::kDownloadMetadataSignatureError:
1101 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1102 case ErrorCode::kDownloadMetadataSignatureMismatch:
1103 case ErrorCode::kDownloadOperationHashVerificationError:
1104 case ErrorCode::kDownloadOperationExecutionError:
1105 case ErrorCode::kDownloadOperationHashMismatch:
1106 case ErrorCode::kOmahaRequestEmptyResponseError:
1107 case ErrorCode::kOmahaRequestXMLParseError:
1108 case ErrorCode::kDownloadInvalidMetadataSize:
1109 case ErrorCode::kDownloadInvalidMetadataSignature:
1110 case ErrorCode::kOmahaResponseInvalid:
1111 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1112 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1113 case ErrorCode::kOmahaErrorInHTTPResponse:
1114 case ErrorCode::kDownloadOperationHashMissingError:
1115 case ErrorCode::kDownloadMetadataSignatureMissingError:
1116 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1117 case ErrorCode::kPostinstallPowerwashError:
1118 case ErrorCode::kUpdateCanceledByChannelChange:
1119 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1120 case ErrorCode::kUnsupportedMajorPayloadVersion:
1121 case ErrorCode::kUnsupportedMinorPayloadVersion:
David Zeuthenf3e28012014-08-26 18:23:52 -04001122 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
David Zeuthen33bae492014-02-25 16:16:18 -08001123 break;
1124
1125 // Special flags. These can't happen (we mask them out above) but
1126 // the compiler doesn't know that. Just break out so we can warn and
1127 // return |kInputMalformed|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001128 case ErrorCode::kUmaReportedMax:
1129 case ErrorCode::kOmahaRequestHTTPResponseBase:
1130 case ErrorCode::kDevModeFlag:
1131 case ErrorCode::kResumedFlag:
1132 case ErrorCode::kTestImageFlag:
1133 case ErrorCode::kTestOmahaUrlFlag:
1134 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001135 LOG(ERROR) << "Unexpected error code " << base_code;
1136 break;
1137 }
1138
1139 return metrics::DownloadErrorCode::kInputMalformed;
1140}
1141
David Zeuthenb281f072014-04-02 10:20:19 -07001142metrics::ConnectionType GetConnectionType(
1143 NetworkConnectionType type,
1144 NetworkTethering tethering) {
1145 switch (type) {
1146 case kNetUnknown:
1147 return metrics::ConnectionType::kUnknown;
1148
1149 case kNetEthernet:
1150 if (tethering == NetworkTethering::kConfirmed)
1151 return metrics::ConnectionType::kTetheredEthernet;
1152 else
1153 return metrics::ConnectionType::kEthernet;
1154
1155 case kNetWifi:
1156 if (tethering == NetworkTethering::kConfirmed)
1157 return metrics::ConnectionType::kTetheredWifi;
1158 else
1159 return metrics::ConnectionType::kWifi;
1160
1161 case kNetWimax:
1162 return metrics::ConnectionType::kWimax;
1163
1164 case kNetBluetooth:
1165 return metrics::ConnectionType::kBluetooth;
1166
1167 case kNetCellular:
1168 return metrics::ConnectionType::kCellular;
1169 }
1170
1171 LOG(ERROR) << "Unexpected network connection type: type=" << type
1172 << ", tethering=" << static_cast<int>(tethering);
1173
1174 return metrics::ConnectionType::kUnknown;
1175}
1176
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001177// Returns a printable version of the various flags denoted in the higher order
1178// bits of the given code. Returns an empty string if none of those bits are
1179// set.
1180string GetFlagNames(uint32_t code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001181 uint32_t flags = (static_cast<uint32_t>(code) &
1182 static_cast<uint32_t>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001183 string flag_names;
1184 string separator = "";
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001185 for (size_t i = 0; i < sizeof(flags) * 8; i++) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001186 uint32_t flag = flags & (1 << i);
1187 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -07001188 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001189 separator = ", ";
1190 }
1191 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001192
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001193 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001194}
1195
David Zeuthena99981f2013-04-29 13:42:47 -07001196void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001197 if (!system_state)
1198 return;
1199
David Zeuthena99981f2013-04-29 13:42:47 -07001200 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001201
1202 // If the code doesn't have flags computed already, compute them now based on
1203 // the state of the current update attempt.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001204 uint32_t flags =
1205 static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001206 if (!flags)
1207 flags = system_state->update_attempter()->GetErrorCodeFlags();
1208
1209 // Determine the UMA bucket depending on the flags. But, ignore the resumed
1210 // flag, as it's perfectly normal for production devices to resume their
1211 // downloads and so we want to record those cases also in NormalErrorCodes
1212 // bucket.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001213 string metric =
1214 flags & ~static_cast<uint32_t>(ErrorCode::kResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001215 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
1216
1217 LOG(INFO) << "Sending error code " << uma_error_code
1218 << " (" << CodeToString(uma_error_code) << ")"
1219 << " to UMA metric: " << metric
1220 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
1221
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001222 system_state->metrics_lib()->SendEnumToUMA(
1223 metric, static_cast<int>(uma_error_code),
1224 static_cast<int>(ErrorCode::kUmaReportedMax));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001225}
1226
David Zeuthena99981f2013-04-29 13:42:47 -07001227string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001228 // If the given code has both parts (i.e. the error code part and the flags
1229 // part) then strip off the flags part since the switch statement below
1230 // has case statements only for the base error code or a single flag but
1231 // doesn't support any combinations of those.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001232 if ((static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags)) &&
1233 (static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags)))
1234 code = static_cast<ErrorCode>(
1235 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001236 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001237 case ErrorCode::kSuccess: return "ErrorCode::kSuccess";
1238 case ErrorCode::kError: return "ErrorCode::kError";
1239 case ErrorCode::kOmahaRequestError: return "ErrorCode::kOmahaRequestError";
1240 case ErrorCode::kOmahaResponseHandlerError:
1241 return "ErrorCode::kOmahaResponseHandlerError";
1242 case ErrorCode::kFilesystemCopierError:
1243 return "ErrorCode::kFilesystemCopierError";
1244 case ErrorCode::kPostinstallRunnerError:
1245 return "ErrorCode::kPostinstallRunnerError";
1246 case ErrorCode::kPayloadMismatchedType:
1247 return "ErrorCode::kPayloadMismatchedType";
1248 case ErrorCode::kInstallDeviceOpenError:
1249 return "ErrorCode::kInstallDeviceOpenError";
1250 case ErrorCode::kKernelDeviceOpenError:
1251 return "ErrorCode::kKernelDeviceOpenError";
1252 case ErrorCode::kDownloadTransferError:
1253 return "ErrorCode::kDownloadTransferError";
1254 case ErrorCode::kPayloadHashMismatchError:
1255 return "ErrorCode::kPayloadHashMismatchError";
1256 case ErrorCode::kPayloadSizeMismatchError:
1257 return "ErrorCode::kPayloadSizeMismatchError";
1258 case ErrorCode::kDownloadPayloadVerificationError:
1259 return "ErrorCode::kDownloadPayloadVerificationError";
1260 case ErrorCode::kDownloadNewPartitionInfoError:
1261 return "ErrorCode::kDownloadNewPartitionInfoError";
1262 case ErrorCode::kDownloadWriteError:
1263 return "ErrorCode::kDownloadWriteError";
1264 case ErrorCode::kNewRootfsVerificationError:
1265 return "ErrorCode::kNewRootfsVerificationError";
1266 case ErrorCode::kNewKernelVerificationError:
1267 return "ErrorCode::kNewKernelVerificationError";
1268 case ErrorCode::kSignedDeltaPayloadExpectedError:
1269 return "ErrorCode::kSignedDeltaPayloadExpectedError";
1270 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1271 return "ErrorCode::kDownloadPayloadPubKeyVerificationError";
1272 case ErrorCode::kPostinstallBootedFromFirmwareB:
1273 return "ErrorCode::kPostinstallBootedFromFirmwareB";
1274 case ErrorCode::kDownloadStateInitializationError:
1275 return "ErrorCode::kDownloadStateInitializationError";
1276 case ErrorCode::kDownloadInvalidMetadataMagicString:
1277 return "ErrorCode::kDownloadInvalidMetadataMagicString";
1278 case ErrorCode::kDownloadSignatureMissingInManifest:
1279 return "ErrorCode::kDownloadSignatureMissingInManifest";
1280 case ErrorCode::kDownloadManifestParseError:
1281 return "ErrorCode::kDownloadManifestParseError";
1282 case ErrorCode::kDownloadMetadataSignatureError:
1283 return "ErrorCode::kDownloadMetadataSignatureError";
1284 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1285 return "ErrorCode::kDownloadMetadataSignatureVerificationError";
1286 case ErrorCode::kDownloadMetadataSignatureMismatch:
1287 return "ErrorCode::kDownloadMetadataSignatureMismatch";
1288 case ErrorCode::kDownloadOperationHashVerificationError:
1289 return "ErrorCode::kDownloadOperationHashVerificationError";
1290 case ErrorCode::kDownloadOperationExecutionError:
1291 return "ErrorCode::kDownloadOperationExecutionError";
1292 case ErrorCode::kDownloadOperationHashMismatch:
1293 return "ErrorCode::kDownloadOperationHashMismatch";
1294 case ErrorCode::kOmahaRequestEmptyResponseError:
1295 return "ErrorCode::kOmahaRequestEmptyResponseError";
1296 case ErrorCode::kOmahaRequestXMLParseError:
1297 return "ErrorCode::kOmahaRequestXMLParseError";
1298 case ErrorCode::kDownloadInvalidMetadataSize:
1299 return "ErrorCode::kDownloadInvalidMetadataSize";
1300 case ErrorCode::kDownloadInvalidMetadataSignature:
1301 return "ErrorCode::kDownloadInvalidMetadataSignature";
1302 case ErrorCode::kOmahaResponseInvalid:
1303 return "ErrorCode::kOmahaResponseInvalid";
1304 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1305 return "ErrorCode::kOmahaUpdateIgnoredPerPolicy";
1306 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1307 return "ErrorCode::kOmahaUpdateDeferredPerPolicy";
1308 case ErrorCode::kOmahaErrorInHTTPResponse:
1309 return "ErrorCode::kOmahaErrorInHTTPResponse";
1310 case ErrorCode::kDownloadOperationHashMissingError:
1311 return "ErrorCode::kDownloadOperationHashMissingError";
1312 case ErrorCode::kDownloadMetadataSignatureMissingError:
1313 return "ErrorCode::kDownloadMetadataSignatureMissingError";
1314 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1315 return "ErrorCode::kOmahaUpdateDeferredForBackoff";
1316 case ErrorCode::kPostinstallPowerwashError:
1317 return "ErrorCode::kPostinstallPowerwashError";
1318 case ErrorCode::kUpdateCanceledByChannelChange:
1319 return "ErrorCode::kUpdateCanceledByChannelChange";
1320 case ErrorCode::kUmaReportedMax:
1321 return "ErrorCode::kUmaReportedMax";
1322 case ErrorCode::kOmahaRequestHTTPResponseBase:
1323 return "ErrorCode::kOmahaRequestHTTPResponseBase";
1324 case ErrorCode::kResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001325 return "Resumed";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001326 case ErrorCode::kDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001327 return "DevMode";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001328 case ErrorCode::kTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001329 return "TestImage";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001330 case ErrorCode::kTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001331 return "TestOmahaUrl";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001332 case ErrorCode::kSpecialFlags:
1333 return "ErrorCode::kSpecialFlags";
1334 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1335 return "ErrorCode::kPostinstallFirmwareRONotUpdatable";
1336 case ErrorCode::kUnsupportedMajorPayloadVersion:
1337 return "ErrorCode::kUnsupportedMajorPayloadVersion";
1338 case ErrorCode::kUnsupportedMinorPayloadVersion:
1339 return "ErrorCode::kUnsupportedMinorPayloadVersion";
David Zeuthenf3e28012014-08-26 18:23:52 -04001340 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
1341 return "ErrorCode::kOmahaRequestXMLHasEntityDecl";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001342 // Don't add a default case to let the compiler warn about newly added
1343 // error codes which should be added here.
1344 }
1345
1346 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1347}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001348
Gilad Arnold30dedd82013-07-03 06:19:09 -07001349bool CreatePowerwashMarkerFile(const char* file_path) {
1350 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1351 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001352 kPowerwashCommand,
1353 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001354 if (result) {
1355 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1356 } else {
1357 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1358 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001359
1360 return result;
1361}
1362
Gilad Arnold30dedd82013-07-03 06:19:09 -07001363bool DeletePowerwashMarkerFile(const char* file_path) {
1364 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001365 const base::FilePath kPowerwashMarkerPath(marker_file);
1366 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001367
1368 if (result)
1369 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001370 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001371 else
1372 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001373 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001374
1375 return result;
1376}
1377
Alex Deymof329b932014-10-30 01:37:48 -07001378bool GetInstallDev(const string& boot_dev, string* install_dev) {
1379 string disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001380 int partition_num;
1381 if (!SplitPartitionName(boot_dev, &disk_name, &partition_num))
1382 return false;
Liam McLoughlin049d1652013-07-31 18:47:46 -07001383
Chris Sosad317e402013-06-12 13:47:09 -07001384 // Right now, we just switch '3' and '5' partition numbers.
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001385 if (partition_num == 3) {
1386 partition_num = 5;
1387 } else if (partition_num == 5) {
1388 partition_num = 3;
1389 } else {
1390 return false;
1391 }
1392
1393 if (install_dev)
1394 *install_dev = MakePartitionName(disk_name, partition_num);
Liam McLoughlin049d1652013-07-31 18:47:46 -07001395
Chris Sosad317e402013-06-12 13:47:09 -07001396 return true;
1397}
1398
David Zeuthen27a48bc2013-08-06 12:06:29 -07001399Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -07001400 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1401 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -07001402 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1403}
1404
Alex Deymof329b932014-10-30 01:37:48 -07001405gchar** StringVectorToGStrv(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001406 GPtrArray *p = g_ptr_array_new();
Alex Deymo020600d2014-11-05 21:05:55 -08001407 for (const string& str : vec_str) {
1408 g_ptr_array_add(p, g_strdup(str.c_str()));
David Zeuthen27a48bc2013-08-06 12:06:29 -07001409 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001410 g_ptr_array_add(p, nullptr);
David Zeuthen27a48bc2013-08-06 12:06:29 -07001411 return reinterpret_cast<gchar**>(g_ptr_array_free(p, FALSE));
1412}
1413
Alex Deymof329b932014-10-30 01:37:48 -07001414string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001415 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -07001416 for (vector<string>::const_iterator i = vec_str.begin();
1417 i != vec_str.end(); ++i) {
1418 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -07001419 str += ", ";
1420 str += '"';
1421 str += *i;
1422 str += '"';
1423 }
1424 str += "]";
1425 return str;
1426}
1427
David Zeuthen8f191b22013-08-06 12:27:50 -07001428string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
1429 string encoded_hash;
1430 OmahaHashCalculator::Base64Encode(payload_hash.c_str(),
1431 payload_hash.size(),
1432 &encoded_hash);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001433 return base::StringPrintf("cros_update_size_%zu_hash_%s",
David Zeuthen8f191b22013-08-06 12:27:50 -07001434 payload_size,
1435 encoded_hash.c_str());
1436}
1437
Alex Deymof329b932014-10-30 01:37:48 -07001438bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -07001439 base::FilePath *out_path) {
1440 vector<char> contents;
1441
1442 out_path->clear();
1443
1444 if (base64_encoded.size() == 0) {
1445 LOG(ERROR) << "Can't decode empty string.";
1446 return false;
1447 }
1448
1449 if (!OmahaHashCalculator::Base64Decode(base64_encoded, &contents) ||
1450 contents.size() == 0) {
1451 LOG(ERROR) << "Error decoding base64.";
1452 return false;
1453 }
1454
Alex Vakulenko75039d72014-03-25 12:36:28 -07001455 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001456 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -07001457 LOG(ERROR) << "Error creating temporary file.";
1458 return false;
1459 }
1460
1461 if (fwrite(&contents[0], 1, contents.size(), file) != contents.size()) {
1462 PLOG(ERROR) << "Error writing to temporary file.";
1463 if (fclose(file) != 0)
1464 PLOG(ERROR) << "Error closing temporary file.";
1465 if (unlink(out_path->value().c_str()) != 0)
1466 PLOG(ERROR) << "Error unlinking temporary file.";
1467 out_path->clear();
1468 return false;
1469 }
1470
1471 if (fclose(file) != 0) {
1472 PLOG(ERROR) << "Error closing temporary file.";
1473 out_path->clear();
1474 return false;
1475 }
1476
1477 return true;
1478}
1479
Alex Deymof329b932014-10-30 01:37:48 -07001480bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -08001481 time_t unix_time = time.ToTimeT();
1482 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1483 const time_t kOmahaEpoch = 1167638400;
1484 const int64_t kNumSecondsPerWeek = 7*24*3600;
1485 const int64_t kNumDaysPerWeek = 7;
1486
1487 time_t omaha_time = unix_time - kOmahaEpoch;
1488
1489 if (omaha_time < 0)
1490 return false;
1491
1492 // Note, as per the comment in utils.h we are deliberately not
1493 // handling DST correctly.
1494
1495 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1496 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1497
1498 return true;
1499}
1500
David Zeuthen33bae492014-02-25 16:16:18 -08001501bool WallclockDurationHelper(SystemState* system_state,
Alex Deymof329b932014-10-30 01:37:48 -07001502 const string& state_variable_key,
1503 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001504 bool ret = false;
1505
Alex Deymof329b932014-10-30 01:37:48 -07001506 Time now = system_state->clock()->GetWallclockTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001507 int64_t stored_value;
1508 if (system_state->prefs()->GetInt64(state_variable_key, &stored_value)) {
Alex Deymof329b932014-10-30 01:37:48 -07001509 Time stored_time = Time::FromInternalValue(stored_value);
David Zeuthen33bae492014-02-25 16:16:18 -08001510 if (stored_time > now) {
1511 LOG(ERROR) << "Stored time-stamp used for " << state_variable_key
1512 << " is in the future.";
1513 } else {
1514 *out_duration = now - stored_time;
1515 ret = true;
1516 }
1517 }
1518
1519 if (!system_state->prefs()->SetInt64(state_variable_key,
1520 now.ToInternalValue())) {
1521 LOG(ERROR) << "Error storing time-stamp in " << state_variable_key;
1522 }
1523
1524 return ret;
1525}
1526
1527bool MonotonicDurationHelper(SystemState* system_state,
1528 int64_t* storage,
Alex Deymof329b932014-10-30 01:37:48 -07001529 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001530 bool ret = false;
1531
Alex Deymof329b932014-10-30 01:37:48 -07001532 Time now = system_state->clock()->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001533 if (*storage != 0) {
Alex Deymof329b932014-10-30 01:37:48 -07001534 Time stored_time = Time::FromInternalValue(*storage);
David Zeuthen33bae492014-02-25 16:16:18 -08001535 *out_duration = now - stored_time;
1536 ret = true;
1537 }
1538 *storage = now.ToInternalValue();
1539
1540 return ret;
1541}
1542
adlr@google.com3defe6a2009-12-04 20:57:17 +00001543} // namespace utils
1544
1545} // namespace chromeos_update_engine