blob: 6c527b34d3c4b64f2bb0cfbd2503a40cdb7b9c23 [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>
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>
Will Drewry8f71da82010-08-30 14:07:11 -050029#include <base/file_util.h>
Ben Chan736fcb52014-05-21 18:28:22 -070030#include <base/files/file_path.h>
31#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.
84 vector<pair<string, string> > kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -070085 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Chris Sosac1972482013-04-30 22:31:10 -070086 for (vector<pair<string, string> >::iterator it = kv_pairs.begin();
87 it != kv_pairs.end(); ++it) {
88 // Finally match against the fw_verion which may have quotes.
89 if (it->first == "fw_version") {
90 string output;
91 // Trim any quotes.
Alex Vakulenko75039d72014-03-25 12:36:28 -070092 base::TrimString(it->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,
186 std::vector<char>* vec_p) {
187 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,
192 std::string* str_p) {
193 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>
Darin Petkov8e447e02013-04-16 16:23:50 +0200232static bool ReadFileChunkAndAppend(const std::string& path,
233 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>
255static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
256 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
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700285off_t FileSize(const string& path) {
286 struct stat stbuf;
287 int rc = stat(path.c_str(), &stbuf);
288 CHECK_EQ(rc, 0);
289 if (rc < 0)
290 return rc;
291 return stbuf.st_size;
292}
293
adlr@google.com3defe6a2009-12-04 20:57:17 +0000294void HexDumpArray(const unsigned char* const arr, const size_t length) {
295 const unsigned char* const char_arr =
296 reinterpret_cast<const unsigned char* const>(arr);
297 LOG(INFO) << "Logging array of length: " << length;
298 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700299 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000300 const unsigned int bytes_remaining = length - i;
301 const unsigned int bytes_per_this_line = min(bytes_per_line,
302 bytes_remaining);
303 char header[100];
304 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
305 TEST_AND_RETURN(r == 13);
306 string line = header;
307 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
308 char buf[20];
309 unsigned char c = char_arr[i + j];
310 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
311 TEST_AND_RETURN(r == 3);
312 line += buf;
313 }
314 LOG(INFO) << line;
315 }
316}
317
318namespace {
319class ScopedDirCloser {
320 public:
321 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
322 ~ScopedDirCloser() {
323 if (dir_ && *dir_) {
324 int r = closedir(*dir_);
325 TEST_AND_RETURN_ERRNO(r == 0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700326 *dir_ = nullptr;
327 dir_ = nullptr;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000328 }
329 }
330 private:
331 DIR** dir_;
332};
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700333} // namespace
adlr@google.com3defe6a2009-12-04 20:57:17 +0000334
335bool RecursiveUnlinkDir(const std::string& path) {
336 struct stat stbuf;
337 int r = lstat(path.c_str(), &stbuf);
338 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
339 if ((r < 0) && (errno == ENOENT))
340 // path request is missing. that's fine.
341 return true;
342 if (!S_ISDIR(stbuf.st_mode)) {
343 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700344 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000345 // success or path disappeared before we could unlink.
346 return true;
347 }
348 {
349 // We have a dir, unlink all children, then delete dir
350 DIR *dir = opendir(path.c_str());
351 TEST_AND_RETURN_FALSE_ERRNO(dir);
352 ScopedDirCloser dir_closer(&dir);
353 struct dirent dir_entry;
354 struct dirent *dir_entry_p;
355 int err = 0;
356 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700357 if (dir_entry_p == nullptr) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000358 // end of stream reached
359 break;
360 }
361 // Skip . and ..
362 if (!strcmp(dir_entry_p->d_name, ".") ||
363 !strcmp(dir_entry_p->d_name, ".."))
364 continue;
365 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700366 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000367 }
368 TEST_AND_RETURN_FALSE(err == 0);
369 }
370 // unlink dir
371 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
372 return true;
373}
374
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800375std::string GetDiskName(const string& partition_name) {
376 std::string disk_name;
377 return SplitPartitionName(partition_name, &disk_name, nullptr) ?
378 disk_name : std::string();
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700379}
380
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800381int GetPartitionNumber(const std::string& partition_name) {
382 int partition_num = 0;
383 return SplitPartitionName(partition_name, nullptr, &partition_num) ?
384 partition_num : 0;
385}
386
387bool SplitPartitionName(const std::string& partition_name,
388 std::string* out_disk_name,
389 int* out_partition_num) {
390 if (!StringHasPrefix(partition_name, "/dev/")) {
391 LOG(ERROR) << "Invalid partition device name: " << partition_name;
392 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700393 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800394
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700395 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
396 if (last_nondigit_pos == string::npos ||
397 (last_nondigit_pos + 1) == partition_name.size()) {
398 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800399 return false;
400 }
401
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700402 size_t partition_name_len = std::string::npos;
403 if (partition_name[last_nondigit_pos] == '_') {
404 // NAND block devices have weird naming which could be something
405 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
406 size_t prev_nondigit_pos =
407 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
408 if (prev_nondigit_pos == string::npos ||
409 (prev_nondigit_pos + 1) == last_nondigit_pos) {
410 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
411 return false;
412 }
413
414 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
415 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800416 }
417
418 if (out_disk_name) {
419 // Special case for MMC devices which have the following naming scheme:
420 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700421 size_t disk_name_len = last_nondigit_pos;
422 if (partition_name[last_nondigit_pos] != 'p' ||
423 last_nondigit_pos == 0 ||
424 !isdigit(partition_name[last_nondigit_pos - 1])) {
425 disk_name_len++;
426 }
427 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800428 }
429
430 if (out_partition_num) {
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700431 std::string partition_str = partition_name.substr(last_nondigit_pos + 1,
432 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800433 *out_partition_num = atoi(partition_str.c_str());
434 }
435 return true;
436}
437
438std::string MakePartitionName(const std::string& disk_name,
439 int partition_num) {
440 if (!StringHasPrefix(disk_name, "/dev/")) {
441 LOG(ERROR) << "Invalid disk name: " << disk_name;
442 return std::string();
443 }
444
445 if (partition_num < 1) {
446 LOG(ERROR) << "Invalid partition number: " << partition_num;
447 return std::string();
448 }
449
450 std::string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700451 if (isdigit(partition_name.back())) {
452 // Special case for devices with names ending with a digit.
453 // Add "p" to separate the disk name from partition number,
454 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800455 partition_name += 'p';
456 }
457
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700458 partition_name += std::to_string(partition_num);
459
460 if (StringHasPrefix(partition_name, "/dev/ubiblock")) {
461 // Special case for UBI block devieces that have "_0" suffix.
462 partition_name += "_0";
463 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800464 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700465}
466
Darin Petkovf74eb652010-08-04 12:08:38 -0700467string SysfsBlockDevice(const string& device) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700468 base::FilePath device_path(device);
Darin Petkovf74eb652010-08-04 12:08:38 -0700469 if (device_path.DirName().value() != "/dev") {
470 return "";
471 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700472 return base::FilePath("/sys/block").Append(device_path.BaseName()).value();
Darin Petkovf74eb652010-08-04 12:08:38 -0700473}
474
475bool IsRemovableDevice(const std::string& device) {
476 string sysfs_block = SysfsBlockDevice(device);
477 string removable;
478 if (sysfs_block.empty() ||
Alex Vakulenko75039d72014-03-25 12:36:28 -0700479 !base::ReadFileToString(base::FilePath(sysfs_block).Append("removable"),
Ben Chan736fcb52014-05-21 18:28:22 -0700480 &removable)) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700481 return false;
482 }
Ben Chan736fcb52014-05-21 18:28:22 -0700483 base::TrimWhitespaceASCII(removable, base::TRIM_ALL, &removable);
Darin Petkovf74eb652010-08-04 12:08:38 -0700484 return removable == "1";
485}
486
adlr@google.com3defe6a2009-12-04 20:57:17 +0000487std::string ErrnoNumberAsString(int err) {
488 char buf[100];
489 buf[0] = '\0';
490 return strerror_r(err, buf, sizeof(buf));
491}
492
493std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
494 string ret;
495 bool last_insert_was_slash = false;
496 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
497 if (*it == '/') {
498 if (last_insert_was_slash)
499 continue;
500 last_insert_was_slash = true;
501 } else {
502 last_insert_was_slash = false;
503 }
504 ret.push_back(*it);
505 }
506 if (strip_trailing_slash && last_insert_was_slash) {
507 string::size_type last_non_slash = ret.find_last_not_of('/');
508 if (last_non_slash != string::npos) {
509 ret.resize(last_non_slash + 1);
510 } else {
511 ret = "";
512 }
513 }
514 return ret;
515}
516
517bool FileExists(const char* path) {
518 struct stat stbuf;
519 return 0 == lstat(path, &stbuf);
520}
521
Darin Petkov30291ed2010-11-12 10:23:06 -0800522bool IsSymlink(const char* path) {
523 struct stat stbuf;
524 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
525}
526
Alex Deymo7dc4c502014-05-20 20:09:58 -0700527bool IsDir(const char* path) {
528 struct stat stbuf;
529 TEST_AND_RETURN_FALSE_ERRNO(lstat(path, &stbuf) == 0);
530 return S_ISDIR(stbuf.st_mode);
531}
532
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800533// If |path| is absolute, or explicit relative to the current working directory,
534// leaves it as is. Otherwise, if TMPDIR is defined in the environment and is
535// non-empty, prepends it to |path|. Otherwise, prepends /tmp. Returns the
536// resulting path.
537static const string PrependTmpdir(const string& path) {
538 if (path[0] == '/' || StartsWithASCII(path, "./", true) ||
539 StartsWithASCII(path, "../", true))
540 return path;
541
542 const char *tmpdir = getenv("TMPDIR");
543 const string prefix = (tmpdir && *tmpdir ? tmpdir : "/tmp");
544 return prefix + "/" + path;
545}
546
547bool MakeTempFile(const std::string& base_filename_template,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700548 std::string* filename,
549 int* fd) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800550 const string filename_template = PrependTmpdir(base_filename_template);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700551 DCHECK(filename || fd);
552 vector<char> buf(filename_template.size() + 1);
553 memcpy(&buf[0], filename_template.data(), filename_template.size());
554 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700555
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700556 int mkstemp_fd = mkstemp(&buf[0]);
557 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
558 if (filename) {
559 *filename = &buf[0];
560 }
561 if (fd) {
562 *fd = mkstemp_fd;
563 } else {
564 close(mkstemp_fd);
565 }
566 return true;
567}
568
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800569bool MakeTempDirectory(const std::string& base_dirname_template,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700570 std::string* dirname) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800571 const string dirname_template = PrependTmpdir(base_dirname_template);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700572 DCHECK(dirname);
573 vector<char> buf(dirname_template.size() + 1);
574 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
575 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700576
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700577 char* return_code = mkdtemp(&buf[0]);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700578 TEST_AND_RETURN_FALSE_ERRNO(return_code != nullptr);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700579 *dirname = &buf[0];
580 return true;
581}
582
adlr@google.com3defe6a2009-12-04 20:57:17 +0000583bool StringHasSuffix(const std::string& str, const std::string& suffix) {
584 if (suffix.size() > str.size())
585 return false;
586 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
587}
588
589bool StringHasPrefix(const std::string& str, const std::string& prefix) {
590 if (prefix.size() > str.size())
591 return false;
592 return 0 == str.compare(0, prefix.size(), prefix);
593}
594
adlr@google.com3defe6a2009-12-04 20:57:17 +0000595bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700596 const string& mountpoint,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700597 unsigned long mountflags) { // NOLINT(runtime/int)
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700598 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags,
599 nullptr);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000600 if (rc < 0) {
601 string msg = ErrnoNumberAsString(errno);
602 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
603 << device << " on " << mountpoint;
604 return false;
605 }
606 return true;
607}
608
609bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700610 for (int num_retries = 0; ; ++num_retries) {
611 if (umount(mountpoint.c_str()) == 0)
612 break;
613
614 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
615 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800616 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700617 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000618 return true;
619}
620
Darin Petkovd3f8c892010-10-12 21:38:45 -0700621bool GetFilesystemSize(const std::string& device,
622 int* out_block_count,
623 int* out_block_size) {
624 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
625 TEST_AND_RETURN_FALSE(fd >= 0);
626 ScopedFdCloser fd_closer(&fd);
627 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
628}
629
630bool GetFilesystemSizeFromFD(int fd,
631 int* out_block_count,
632 int* out_block_size) {
633 TEST_AND_RETURN_FALSE(fd >= 0);
634
635 // Determine the ext3 filesystem size by directly reading the block count and
636 // block size information from the superblock. See include/linux/ext3_fs.h for
637 // more details on the structure.
638 ssize_t kBufferSize = 16 * sizeof(uint32_t);
639 char buffer[kBufferSize];
640 const int kSuperblockOffset = 1024;
641 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
642 kBufferSize) {
643 PLOG(ERROR) << "Unable to determine file system size:";
644 return false;
645 }
646 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
647 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
648 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
649 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
650 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
651 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
652 block_count = le32toh(block_count);
653 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
654 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
655 magic = le16toh(magic);
656
657 // Sanity check the parameters.
658 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
659 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
660 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
661 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
662 int block_size = 1 << log_block_size;
663 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
664 block_size <= kExt3MaxBlockSize);
665 TEST_AND_RETURN_FALSE(block_count > 0);
666
667 if (out_block_count) {
668 *out_block_count = block_count;
669 }
670 if (out_block_size) {
671 *out_block_size = block_size;
672 }
673 return true;
674}
675
Alex Deymo719bfff2014-07-11 12:12:32 -0700676string GetPathOnBoard(const string& command) {
677 int return_code = 0;
678 string command_path;
679 // TODO(deymo): prepend SYSROOT to each PATH instead of the result.
680 if (!Subprocess::SynchronousExec(
681 {"which", command}, &return_code, &command_path)) {
682 return command;
683 }
684 if (return_code != 0)
685 return command;
686
687 base::TrimWhitespaceASCII(command_path, base::TRIM_ALL, &command_path);
688 const char* env_sysroot = getenv("SYSROOT");
689 if (env_sysroot) {
690 string sysroot_command_path = env_sysroot + command_path;
691 if (utils::FileExists(sysroot_command_path.c_str()))
692 return sysroot_command_path;
693 }
694 return command_path;
695}
696
Alex Deymo032e7722014-03-25 17:53:56 -0700697// Tries to parse the header of an ELF file to obtain a human-readable
698// description of it on the |output| string.
699static bool GetFileFormatELF(const char* buffer, size_t size, string* output) {
700 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700701 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700702 return false;
703 *output = "ELF";
704
705 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700706 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700707 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700708 switch (buffer[EI_CLASS]) {
709 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700710 *output += " 32-bit";
711 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700712 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700713 *output += " 64-bit";
714 break;
715 default:
716 *output += " ?-bit";
717 }
718
719 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700720 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700721 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700722 char ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700723 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700724 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700725 *output += " little-endian";
726 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700727 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700728 *output += " big-endian";
729 break;
730 default:
731 *output += " ?-endian";
732 // Don't parse anything after the 0x10 offset if endianness is unknown.
733 return true;
734 }
735
Alex Deymoc1711e22014-08-08 13:16:23 -0700736 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
737 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
738 // and size is the same for both 32 and 64 bits.
739 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700740 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700741 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700742 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700743 if (ei_data == ELFDATA2LSB)
744 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700745 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700746 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700747
748 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700749 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700750 *output += " x86";
751 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700752 case EM_MIPS:
753 *output += " mips";
754 break;
755 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700756 *output += " arm";
757 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700758 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700759 *output += " x86-64";
760 break;
761 default:
762 *output += " unknown-arch";
763 }
764 return true;
765}
766
767string GetFileFormat(const string& path) {
768 vector<char> buffer;
769 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
770 return "File not found.";
771
772 string result;
773 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
774 return result;
775
776 return "data";
777}
778
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700779bool GetBootloader(BootLoader* out_bootloader) {
780 // For now, hardcode to syslinux.
781 *out_bootloader = BootLoader_SYSLINUX;
782 return true;
783}
784
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800785namespace {
786// Do the actual trigger. We do it as a main-loop callback to (try to) get a
787// consistent stack trace.
788gboolean TriggerCrashReporterUpload(void* unused) {
789 pid_t pid = fork();
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700790 CHECK_GE(pid, 0) << "fork failed"; // fork() failed. Something is very wrong.
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800791 if (pid == 0) {
792 // We are the child. Crash.
793 abort(); // never returns
794 }
795 // We are the parent. Wait for child to terminate.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700796 pid_t result = waitpid(pid, nullptr, 0);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800797 LOG_IF(ERROR, result < 0) << "waitpid() failed";
798 return FALSE; // Don't call this callback again
799}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700800} // namespace
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800801
802void ScheduleCrashReporterUpload() {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700803 g_idle_add(&TriggerCrashReporterUpload, nullptr);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800804}
805
Chris Sosa4f8ee272012-11-30 13:01:54 -0800806bool SetCpuShares(CpuShares shares) {
807 string string_shares = base::IntToString(static_cast<int>(shares));
808 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
809 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700810 if (utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
811 string_shares.size())) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800812 return true;
813 } else {
814 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
815 << " using " << cpu_shares_file;
816 return false;
817 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700818}
819
Chris Sosa4f8ee272012-11-30 13:01:54 -0800820int CompareCpuShares(CpuShares shares_lhs,
821 CpuShares shares_rhs) {
822 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700823}
824
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700825int FuzzInt(int value, unsigned int range) {
826 int min = value - range / 2;
827 int max = value + range - range / 2;
828 return base::RandInt(min, max);
829}
830
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800831gboolean GlibRunClosure(gpointer data) {
Alex Vakulenko4906c1c2014-08-21 13:17:44 -0700832 base::Closure* callback = reinterpret_cast<base::Closure*>(data);
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800833 callback->Run();
834 return FALSE;
835}
836
Alex Deymoc4acdf42014-05-28 21:07:10 -0700837void GlibDestroyClosure(gpointer data) {
Alex Vakulenko4906c1c2014-08-21 13:17:44 -0700838 delete reinterpret_cast<base::Closure*>(data);
Alex Deymoc4acdf42014-05-28 21:07:10 -0700839}
840
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700841string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800842 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700843}
844
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800845string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400846 string str;
847
848 // Handle negative durations by prefixing with a minus.
849 if (delta.ToInternalValue() < 0) {
850 delta *= -1;
851 str = "-";
852 }
853
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700854 // Canonicalize into days, hours, minutes, seconds and microseconds.
855 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800856 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700857 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800858 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700859 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800860 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700861 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800862 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700863 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800864
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700865 if (days)
866 base::StringAppendF(&str, "%ud", days);
867 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800868 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700869 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800870 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700871 base::StringAppendF(&str, "%u", secs);
872 if (usecs) {
873 int width = 6;
874 while ((usecs / 10) * 10 == usecs) {
875 usecs /= 10;
876 width--;
877 }
878 base::StringAppendF(&str, ".%0*u", width, usecs);
879 }
880 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800881 return str;
882}
883
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700884string ToString(const Time utc_time) {
885 Time::Exploded exp_time;
886 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700887 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700888 exp_time.month,
889 exp_time.day_of_month,
890 exp_time.year,
891 exp_time.hour,
892 exp_time.minute,
893 exp_time.second);
894}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000895
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700896string ToString(bool b) {
897 return (b ? "true" : "false");
898}
899
Alex Deymo1c656c42013-06-28 11:02:14 -0700900string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700901 switch (source) {
902 case kDownloadSourceHttpsServer: return "HttpsServer";
903 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700904 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700905 case kNumDownloadSources: return "Unknown";
906 // Don't add a default case to let the compiler warn about newly added
907 // download sources which should be added here.
908 }
909
910 return "Unknown";
911}
912
Alex Deymo1c656c42013-06-28 11:02:14 -0700913string ToString(PayloadType payload_type) {
914 switch (payload_type) {
915 case kPayloadTypeDelta: return "Delta";
916 case kPayloadTypeFull: return "Full";
917 case kPayloadTypeForcedFull: return "ForcedFull";
918 case kNumPayloadTypes: return "Unknown";
919 // Don't add a default case to let the compiler warn about newly added
920 // payload types which should be added here.
921 }
922
923 return "Unknown";
924}
925
David Zeuthena99981f2013-04-29 13:42:47 -0700926ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700927 // Ignore the higher order bits in the code by applying the mask as
928 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700929 // with values less than ErrorCode::kUmaReportedMax.
930 ErrorCode base_code = static_cast<ErrorCode>(
931 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700932
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800933 // Make additional adjustments required for UMA and error classification.
934 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
935 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700936 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700937 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800938 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800939 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700940 << " to ErrorCode::kOmahaErrorInHTTPResponse";
941 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700942 }
943
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800944 return base_code;
945}
946
David Zeuthen33bae492014-02-25 16:16:18 -0800947metrics::AttemptResult GetAttemptResult(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700948 ErrorCode base_code = static_cast<ErrorCode>(
949 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -0800950
951 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700952 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -0800953 return metrics::AttemptResult::kUpdateSucceeded;
954
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700955 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -0800956 return metrics::AttemptResult::kPayloadDownloadError;
957
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700958 case ErrorCode::kDownloadInvalidMetadataSize:
959 case ErrorCode::kDownloadInvalidMetadataMagicString:
960 case ErrorCode::kDownloadMetadataSignatureError:
961 case ErrorCode::kDownloadMetadataSignatureVerificationError:
962 case ErrorCode::kPayloadMismatchedType:
963 case ErrorCode::kUnsupportedMajorPayloadVersion:
964 case ErrorCode::kUnsupportedMinorPayloadVersion:
965 case ErrorCode::kDownloadNewPartitionInfoError:
966 case ErrorCode::kDownloadSignatureMissingInManifest:
967 case ErrorCode::kDownloadManifestParseError:
968 case ErrorCode::kDownloadOperationHashMissingError:
David Zeuthen33bae492014-02-25 16:16:18 -0800969 return metrics::AttemptResult::kMetadataMalformed;
970
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700971 case ErrorCode::kDownloadOperationHashMismatch:
972 case ErrorCode::kDownloadOperationHashVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -0800973 return metrics::AttemptResult::kOperationMalformed;
974
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700975 case ErrorCode::kDownloadOperationExecutionError:
976 case ErrorCode::kInstallDeviceOpenError:
977 case ErrorCode::kKernelDeviceOpenError:
978 case ErrorCode::kDownloadWriteError:
979 case ErrorCode::kFilesystemCopierError:
David Zeuthen33bae492014-02-25 16:16:18 -0800980 return metrics::AttemptResult::kOperationExecutionError;
981
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700982 case ErrorCode::kDownloadMetadataSignatureMismatch:
David Zeuthen33bae492014-02-25 16:16:18 -0800983 return metrics::AttemptResult::kMetadataVerificationFailed;
984
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700985 case ErrorCode::kPayloadSizeMismatchError:
986 case ErrorCode::kPayloadHashMismatchError:
987 case ErrorCode::kDownloadPayloadVerificationError:
988 case ErrorCode::kSignedDeltaPayloadExpectedError:
989 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -0800990 return metrics::AttemptResult::kPayloadVerificationFailed;
991
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700992 case ErrorCode::kNewRootfsVerificationError:
993 case ErrorCode::kNewKernelVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -0800994 return metrics::AttemptResult::kVerificationFailed;
995
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700996 case ErrorCode::kPostinstallRunnerError:
997 case ErrorCode::kPostinstallBootedFromFirmwareB:
998 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
David Zeuthen33bae492014-02-25 16:16:18 -0800999 return metrics::AttemptResult::kPostInstallFailed;
1000
1001 // We should never get these errors in the update-attempt stage so
1002 // return internal error if this happens.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001003 case ErrorCode::kError:
1004 case ErrorCode::kOmahaRequestXMLParseError:
1005 case ErrorCode::kOmahaRequestError:
1006 case ErrorCode::kOmahaResponseHandlerError:
1007 case ErrorCode::kDownloadStateInitializationError:
1008 case ErrorCode::kOmahaRequestEmptyResponseError:
1009 case ErrorCode::kDownloadInvalidMetadataSignature:
1010 case ErrorCode::kOmahaResponseInvalid:
1011 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1012 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1013 case ErrorCode::kOmahaErrorInHTTPResponse:
1014 case ErrorCode::kDownloadMetadataSignatureMissingError:
1015 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1016 case ErrorCode::kPostinstallPowerwashError:
1017 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -04001018 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
David Zeuthen33bae492014-02-25 16:16:18 -08001019 return metrics::AttemptResult::kInternalError;
1020
1021 // Special flags. These can't happen (we mask them out above) but
1022 // the compiler doesn't know that. Just break out so we can warn and
1023 // return |kInternalError|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001024 case ErrorCode::kUmaReportedMax:
1025 case ErrorCode::kOmahaRequestHTTPResponseBase:
1026 case ErrorCode::kDevModeFlag:
1027 case ErrorCode::kResumedFlag:
1028 case ErrorCode::kTestImageFlag:
1029 case ErrorCode::kTestOmahaUrlFlag:
1030 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001031 break;
1032 }
1033
1034 LOG(ERROR) << "Unexpected error code " << base_code;
1035 return metrics::AttemptResult::kInternalError;
1036}
1037
1038
1039metrics::DownloadErrorCode GetDownloadErrorCode(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001040 ErrorCode base_code = static_cast<ErrorCode>(
1041 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001042
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001043 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
1044 int http_status =
1045 static_cast<int>(base_code) -
1046 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase);
David Zeuthen33bae492014-02-25 16:16:18 -08001047 if (http_status >= 200 && http_status <= 599) {
1048 return static_cast<metrics::DownloadErrorCode>(
1049 static_cast<int>(metrics::DownloadErrorCode::kHttpStatus200) +
1050 http_status - 200);
1051 } else if (http_status == 0) {
1052 // The code is using HTTP Status 0 for "Unable to get http
1053 // response code."
1054 return metrics::DownloadErrorCode::kDownloadError;
1055 }
1056 LOG(WARNING) << "Unexpected HTTP status code " << http_status;
1057 return metrics::DownloadErrorCode::kHttpStatusOther;
1058 }
1059
1060 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001061 // Unfortunately, ErrorCode::kDownloadTransferError is returned for a wide
David Zeuthen33bae492014-02-25 16:16:18 -08001062 // variety of errors (proxy errors, host not reachable, timeouts etc.).
1063 //
1064 // For now just map that to kDownloading. See http://crbug.com/355745
1065 // for how we plan to add more detail in the future.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001066 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001067 return metrics::DownloadErrorCode::kDownloadError;
1068
1069 // All of these error codes are not related to downloading so break
1070 // out so we can warn and return InputMalformed.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001071 case ErrorCode::kSuccess:
1072 case ErrorCode::kError:
1073 case ErrorCode::kOmahaRequestError:
1074 case ErrorCode::kOmahaResponseHandlerError:
1075 case ErrorCode::kFilesystemCopierError:
1076 case ErrorCode::kPostinstallRunnerError:
1077 case ErrorCode::kPayloadMismatchedType:
1078 case ErrorCode::kInstallDeviceOpenError:
1079 case ErrorCode::kKernelDeviceOpenError:
1080 case ErrorCode::kPayloadHashMismatchError:
1081 case ErrorCode::kPayloadSizeMismatchError:
1082 case ErrorCode::kDownloadPayloadVerificationError:
1083 case ErrorCode::kDownloadNewPartitionInfoError:
1084 case ErrorCode::kDownloadWriteError:
1085 case ErrorCode::kNewRootfsVerificationError:
1086 case ErrorCode::kNewKernelVerificationError:
1087 case ErrorCode::kSignedDeltaPayloadExpectedError:
1088 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1089 case ErrorCode::kPostinstallBootedFromFirmwareB:
1090 case ErrorCode::kDownloadStateInitializationError:
1091 case ErrorCode::kDownloadInvalidMetadataMagicString:
1092 case ErrorCode::kDownloadSignatureMissingInManifest:
1093 case ErrorCode::kDownloadManifestParseError:
1094 case ErrorCode::kDownloadMetadataSignatureError:
1095 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1096 case ErrorCode::kDownloadMetadataSignatureMismatch:
1097 case ErrorCode::kDownloadOperationHashVerificationError:
1098 case ErrorCode::kDownloadOperationExecutionError:
1099 case ErrorCode::kDownloadOperationHashMismatch:
1100 case ErrorCode::kOmahaRequestEmptyResponseError:
1101 case ErrorCode::kOmahaRequestXMLParseError:
1102 case ErrorCode::kDownloadInvalidMetadataSize:
1103 case ErrorCode::kDownloadInvalidMetadataSignature:
1104 case ErrorCode::kOmahaResponseInvalid:
1105 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1106 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1107 case ErrorCode::kOmahaErrorInHTTPResponse:
1108 case ErrorCode::kDownloadOperationHashMissingError:
1109 case ErrorCode::kDownloadMetadataSignatureMissingError:
1110 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1111 case ErrorCode::kPostinstallPowerwashError:
1112 case ErrorCode::kUpdateCanceledByChannelChange:
1113 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1114 case ErrorCode::kUnsupportedMajorPayloadVersion:
1115 case ErrorCode::kUnsupportedMinorPayloadVersion:
David Zeuthenf3e28012014-08-26 18:23:52 -04001116 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
David Zeuthen33bae492014-02-25 16:16:18 -08001117 break;
1118
1119 // Special flags. These can't happen (we mask them out above) but
1120 // the compiler doesn't know that. Just break out so we can warn and
1121 // return |kInputMalformed|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001122 case ErrorCode::kUmaReportedMax:
1123 case ErrorCode::kOmahaRequestHTTPResponseBase:
1124 case ErrorCode::kDevModeFlag:
1125 case ErrorCode::kResumedFlag:
1126 case ErrorCode::kTestImageFlag:
1127 case ErrorCode::kTestOmahaUrlFlag:
1128 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001129 LOG(ERROR) << "Unexpected error code " << base_code;
1130 break;
1131 }
1132
1133 return metrics::DownloadErrorCode::kInputMalformed;
1134}
1135
David Zeuthenb281f072014-04-02 10:20:19 -07001136metrics::ConnectionType GetConnectionType(
1137 NetworkConnectionType type,
1138 NetworkTethering tethering) {
1139 switch (type) {
1140 case kNetUnknown:
1141 return metrics::ConnectionType::kUnknown;
1142
1143 case kNetEthernet:
1144 if (tethering == NetworkTethering::kConfirmed)
1145 return metrics::ConnectionType::kTetheredEthernet;
1146 else
1147 return metrics::ConnectionType::kEthernet;
1148
1149 case kNetWifi:
1150 if (tethering == NetworkTethering::kConfirmed)
1151 return metrics::ConnectionType::kTetheredWifi;
1152 else
1153 return metrics::ConnectionType::kWifi;
1154
1155 case kNetWimax:
1156 return metrics::ConnectionType::kWimax;
1157
1158 case kNetBluetooth:
1159 return metrics::ConnectionType::kBluetooth;
1160
1161 case kNetCellular:
1162 return metrics::ConnectionType::kCellular;
1163 }
1164
1165 LOG(ERROR) << "Unexpected network connection type: type=" << type
1166 << ", tethering=" << static_cast<int>(tethering);
1167
1168 return metrics::ConnectionType::kUnknown;
1169}
1170
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001171// Returns a printable version of the various flags denoted in the higher order
1172// bits of the given code. Returns an empty string if none of those bits are
1173// set.
1174string GetFlagNames(uint32_t code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001175 uint32_t flags = (static_cast<uint32_t>(code) &
1176 static_cast<uint32_t>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001177 string flag_names;
1178 string separator = "";
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001179 for (size_t i = 0; i < sizeof(flags) * 8; i++) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001180 uint32_t flag = flags & (1 << i);
1181 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -07001182 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001183 separator = ", ";
1184 }
1185 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001186
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001187 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001188}
1189
David Zeuthena99981f2013-04-29 13:42:47 -07001190void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001191 if (!system_state)
1192 return;
1193
David Zeuthena99981f2013-04-29 13:42:47 -07001194 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001195
1196 // If the code doesn't have flags computed already, compute them now based on
1197 // the state of the current update attempt.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001198 uint32_t flags =
1199 static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001200 if (!flags)
1201 flags = system_state->update_attempter()->GetErrorCodeFlags();
1202
1203 // Determine the UMA bucket depending on the flags. But, ignore the resumed
1204 // flag, as it's perfectly normal for production devices to resume their
1205 // downloads and so we want to record those cases also in NormalErrorCodes
1206 // bucket.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001207 string metric =
1208 flags & ~static_cast<uint32_t>(ErrorCode::kResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001209 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
1210
1211 LOG(INFO) << "Sending error code " << uma_error_code
1212 << " (" << CodeToString(uma_error_code) << ")"
1213 << " to UMA metric: " << metric
1214 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
1215
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001216 system_state->metrics_lib()->SendEnumToUMA(
1217 metric, static_cast<int>(uma_error_code),
1218 static_cast<int>(ErrorCode::kUmaReportedMax));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001219}
1220
David Zeuthena99981f2013-04-29 13:42:47 -07001221string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001222 // If the given code has both parts (i.e. the error code part and the flags
1223 // part) then strip off the flags part since the switch statement below
1224 // has case statements only for the base error code or a single flag but
1225 // doesn't support any combinations of those.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001226 if ((static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags)) &&
1227 (static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags)))
1228 code = static_cast<ErrorCode>(
1229 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001230 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001231 case ErrorCode::kSuccess: return "ErrorCode::kSuccess";
1232 case ErrorCode::kError: return "ErrorCode::kError";
1233 case ErrorCode::kOmahaRequestError: return "ErrorCode::kOmahaRequestError";
1234 case ErrorCode::kOmahaResponseHandlerError:
1235 return "ErrorCode::kOmahaResponseHandlerError";
1236 case ErrorCode::kFilesystemCopierError:
1237 return "ErrorCode::kFilesystemCopierError";
1238 case ErrorCode::kPostinstallRunnerError:
1239 return "ErrorCode::kPostinstallRunnerError";
1240 case ErrorCode::kPayloadMismatchedType:
1241 return "ErrorCode::kPayloadMismatchedType";
1242 case ErrorCode::kInstallDeviceOpenError:
1243 return "ErrorCode::kInstallDeviceOpenError";
1244 case ErrorCode::kKernelDeviceOpenError:
1245 return "ErrorCode::kKernelDeviceOpenError";
1246 case ErrorCode::kDownloadTransferError:
1247 return "ErrorCode::kDownloadTransferError";
1248 case ErrorCode::kPayloadHashMismatchError:
1249 return "ErrorCode::kPayloadHashMismatchError";
1250 case ErrorCode::kPayloadSizeMismatchError:
1251 return "ErrorCode::kPayloadSizeMismatchError";
1252 case ErrorCode::kDownloadPayloadVerificationError:
1253 return "ErrorCode::kDownloadPayloadVerificationError";
1254 case ErrorCode::kDownloadNewPartitionInfoError:
1255 return "ErrorCode::kDownloadNewPartitionInfoError";
1256 case ErrorCode::kDownloadWriteError:
1257 return "ErrorCode::kDownloadWriteError";
1258 case ErrorCode::kNewRootfsVerificationError:
1259 return "ErrorCode::kNewRootfsVerificationError";
1260 case ErrorCode::kNewKernelVerificationError:
1261 return "ErrorCode::kNewKernelVerificationError";
1262 case ErrorCode::kSignedDeltaPayloadExpectedError:
1263 return "ErrorCode::kSignedDeltaPayloadExpectedError";
1264 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1265 return "ErrorCode::kDownloadPayloadPubKeyVerificationError";
1266 case ErrorCode::kPostinstallBootedFromFirmwareB:
1267 return "ErrorCode::kPostinstallBootedFromFirmwareB";
1268 case ErrorCode::kDownloadStateInitializationError:
1269 return "ErrorCode::kDownloadStateInitializationError";
1270 case ErrorCode::kDownloadInvalidMetadataMagicString:
1271 return "ErrorCode::kDownloadInvalidMetadataMagicString";
1272 case ErrorCode::kDownloadSignatureMissingInManifest:
1273 return "ErrorCode::kDownloadSignatureMissingInManifest";
1274 case ErrorCode::kDownloadManifestParseError:
1275 return "ErrorCode::kDownloadManifestParseError";
1276 case ErrorCode::kDownloadMetadataSignatureError:
1277 return "ErrorCode::kDownloadMetadataSignatureError";
1278 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1279 return "ErrorCode::kDownloadMetadataSignatureVerificationError";
1280 case ErrorCode::kDownloadMetadataSignatureMismatch:
1281 return "ErrorCode::kDownloadMetadataSignatureMismatch";
1282 case ErrorCode::kDownloadOperationHashVerificationError:
1283 return "ErrorCode::kDownloadOperationHashVerificationError";
1284 case ErrorCode::kDownloadOperationExecutionError:
1285 return "ErrorCode::kDownloadOperationExecutionError";
1286 case ErrorCode::kDownloadOperationHashMismatch:
1287 return "ErrorCode::kDownloadOperationHashMismatch";
1288 case ErrorCode::kOmahaRequestEmptyResponseError:
1289 return "ErrorCode::kOmahaRequestEmptyResponseError";
1290 case ErrorCode::kOmahaRequestXMLParseError:
1291 return "ErrorCode::kOmahaRequestXMLParseError";
1292 case ErrorCode::kDownloadInvalidMetadataSize:
1293 return "ErrorCode::kDownloadInvalidMetadataSize";
1294 case ErrorCode::kDownloadInvalidMetadataSignature:
1295 return "ErrorCode::kDownloadInvalidMetadataSignature";
1296 case ErrorCode::kOmahaResponseInvalid:
1297 return "ErrorCode::kOmahaResponseInvalid";
1298 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1299 return "ErrorCode::kOmahaUpdateIgnoredPerPolicy";
1300 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1301 return "ErrorCode::kOmahaUpdateDeferredPerPolicy";
1302 case ErrorCode::kOmahaErrorInHTTPResponse:
1303 return "ErrorCode::kOmahaErrorInHTTPResponse";
1304 case ErrorCode::kDownloadOperationHashMissingError:
1305 return "ErrorCode::kDownloadOperationHashMissingError";
1306 case ErrorCode::kDownloadMetadataSignatureMissingError:
1307 return "ErrorCode::kDownloadMetadataSignatureMissingError";
1308 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1309 return "ErrorCode::kOmahaUpdateDeferredForBackoff";
1310 case ErrorCode::kPostinstallPowerwashError:
1311 return "ErrorCode::kPostinstallPowerwashError";
1312 case ErrorCode::kUpdateCanceledByChannelChange:
1313 return "ErrorCode::kUpdateCanceledByChannelChange";
1314 case ErrorCode::kUmaReportedMax:
1315 return "ErrorCode::kUmaReportedMax";
1316 case ErrorCode::kOmahaRequestHTTPResponseBase:
1317 return "ErrorCode::kOmahaRequestHTTPResponseBase";
1318 case ErrorCode::kResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001319 return "Resumed";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001320 case ErrorCode::kDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001321 return "DevMode";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001322 case ErrorCode::kTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001323 return "TestImage";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001324 case ErrorCode::kTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001325 return "TestOmahaUrl";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001326 case ErrorCode::kSpecialFlags:
1327 return "ErrorCode::kSpecialFlags";
1328 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1329 return "ErrorCode::kPostinstallFirmwareRONotUpdatable";
1330 case ErrorCode::kUnsupportedMajorPayloadVersion:
1331 return "ErrorCode::kUnsupportedMajorPayloadVersion";
1332 case ErrorCode::kUnsupportedMinorPayloadVersion:
1333 return "ErrorCode::kUnsupportedMinorPayloadVersion";
David Zeuthenf3e28012014-08-26 18:23:52 -04001334 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
1335 return "ErrorCode::kOmahaRequestXMLHasEntityDecl";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001336 // Don't add a default case to let the compiler warn about newly added
1337 // error codes which should be added here.
1338 }
1339
1340 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1341}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001342
Gilad Arnold30dedd82013-07-03 06:19:09 -07001343bool CreatePowerwashMarkerFile(const char* file_path) {
1344 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1345 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001346 kPowerwashCommand,
1347 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001348 if (result) {
1349 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1350 } else {
1351 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1352 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001353
1354 return result;
1355}
1356
Gilad Arnold30dedd82013-07-03 06:19:09 -07001357bool DeletePowerwashMarkerFile(const char* file_path) {
1358 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001359 const base::FilePath kPowerwashMarkerPath(marker_file);
1360 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001361
1362 if (result)
1363 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001364 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001365 else
1366 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001367 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001368
1369 return result;
1370}
1371
Chris Sosad317e402013-06-12 13:47:09 -07001372bool GetInstallDev(const std::string& boot_dev, std::string* install_dev) {
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001373 std::string disk_name;
1374 int partition_num;
1375 if (!SplitPartitionName(boot_dev, &disk_name, &partition_num))
1376 return false;
Liam McLoughlin049d1652013-07-31 18:47:46 -07001377
Chris Sosad317e402013-06-12 13:47:09 -07001378 // Right now, we just switch '3' and '5' partition numbers.
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001379 if (partition_num == 3) {
1380 partition_num = 5;
1381 } else if (partition_num == 5) {
1382 partition_num = 3;
1383 } else {
1384 return false;
1385 }
1386
1387 if (install_dev)
1388 *install_dev = MakePartitionName(disk_name, partition_num);
Liam McLoughlin049d1652013-07-31 18:47:46 -07001389
Chris Sosad317e402013-06-12 13:47:09 -07001390 return true;
1391}
1392
David Zeuthen27a48bc2013-08-06 12:06:29 -07001393Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -07001394 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1395 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -07001396 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1397}
1398
1399gchar** StringVectorToGStrv(const vector<string> &vector) {
1400 GPtrArray *p = g_ptr_array_new();
1401 for (std::vector<string>::const_iterator i = vector.begin();
1402 i != vector.end(); ++i) {
1403 g_ptr_array_add(p, g_strdup(i->c_str()));
1404 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001405 g_ptr_array_add(p, nullptr);
David Zeuthen27a48bc2013-08-06 12:06:29 -07001406 return reinterpret_cast<gchar**>(g_ptr_array_free(p, FALSE));
1407}
1408
1409string StringVectorToString(const vector<string> &vector) {
1410 string str = "[";
1411 for (std::vector<string>::const_iterator i = vector.begin();
1412 i != vector.end(); ++i) {
1413 if (i != vector.begin())
1414 str += ", ";
1415 str += '"';
1416 str += *i;
1417 str += '"';
1418 }
1419 str += "]";
1420 return str;
1421}
1422
David Zeuthen8f191b22013-08-06 12:27:50 -07001423string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
1424 string encoded_hash;
1425 OmahaHashCalculator::Base64Encode(payload_hash.c_str(),
1426 payload_hash.size(),
1427 &encoded_hash);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001428 return base::StringPrintf("cros_update_size_%zu_hash_%s",
David Zeuthen8f191b22013-08-06 12:27:50 -07001429 payload_size,
1430 encoded_hash.c_str());
1431}
1432
David Zeuthen910ec5b2013-09-26 12:10:58 -07001433bool IsXAttrSupported(const base::FilePath& dir_path) {
1434 char *path = strdup(dir_path.Append("xattr_test_XXXXXX").value().c_str());
1435
1436 int fd = mkstemp(path);
1437 if (fd == -1) {
1438 PLOG(ERROR) << "Error creating temporary file in " << dir_path.value();
1439 free(path);
1440 return false;
1441 }
1442
1443 if (unlink(path) != 0) {
1444 PLOG(ERROR) << "Error unlinking temporary file " << path;
1445 close(fd);
1446 free(path);
1447 return false;
1448 }
1449
1450 int xattr_res = fsetxattr(fd, "user.xattr-test", "value", strlen("value"), 0);
1451 if (xattr_res != 0) {
1452 if (errno == ENOTSUP) {
1453 // Leave it to call-sites to warn about non-support.
1454 } else {
1455 PLOG(ERROR) << "Error setting xattr on " << path;
1456 }
1457 }
1458 close(fd);
1459 free(path);
1460 return xattr_res == 0;
1461}
1462
David Zeuthene7f89172013-10-31 10:21:04 -07001463bool DecodeAndStoreBase64String(const std::string& base64_encoded,
1464 base::FilePath *out_path) {
1465 vector<char> contents;
1466
1467 out_path->clear();
1468
1469 if (base64_encoded.size() == 0) {
1470 LOG(ERROR) << "Can't decode empty string.";
1471 return false;
1472 }
1473
1474 if (!OmahaHashCalculator::Base64Decode(base64_encoded, &contents) ||
1475 contents.size() == 0) {
1476 LOG(ERROR) << "Error decoding base64.";
1477 return false;
1478 }
1479
Alex Vakulenko75039d72014-03-25 12:36:28 -07001480 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001481 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -07001482 LOG(ERROR) << "Error creating temporary file.";
1483 return false;
1484 }
1485
1486 if (fwrite(&contents[0], 1, contents.size(), file) != contents.size()) {
1487 PLOG(ERROR) << "Error writing to temporary file.";
1488 if (fclose(file) != 0)
1489 PLOG(ERROR) << "Error closing temporary file.";
1490 if (unlink(out_path->value().c_str()) != 0)
1491 PLOG(ERROR) << "Error unlinking temporary file.";
1492 out_path->clear();
1493 return false;
1494 }
1495
1496 if (fclose(file) != 0) {
1497 PLOG(ERROR) << "Error closing temporary file.";
1498 out_path->clear();
1499 return false;
1500 }
1501
1502 return true;
1503}
1504
David Zeuthen639aa362014-02-03 16:23:44 -08001505bool ConvertToOmahaInstallDate(base::Time time, int *out_num_days) {
1506 time_t unix_time = time.ToTimeT();
1507 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1508 const time_t kOmahaEpoch = 1167638400;
1509 const int64_t kNumSecondsPerWeek = 7*24*3600;
1510 const int64_t kNumDaysPerWeek = 7;
1511
1512 time_t omaha_time = unix_time - kOmahaEpoch;
1513
1514 if (omaha_time < 0)
1515 return false;
1516
1517 // Note, as per the comment in utils.h we are deliberately not
1518 // handling DST correctly.
1519
1520 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1521 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1522
1523 return true;
1524}
1525
David Zeuthen33bae492014-02-25 16:16:18 -08001526bool WallclockDurationHelper(SystemState* system_state,
1527 const std::string& state_variable_key,
1528 base::TimeDelta* out_duration) {
1529 bool ret = false;
1530
1531 base::Time now = system_state->clock()->GetWallclockTime();
1532 int64_t stored_value;
1533 if (system_state->prefs()->GetInt64(state_variable_key, &stored_value)) {
1534 base::Time stored_time = base::Time::FromInternalValue(stored_value);
1535 if (stored_time > now) {
1536 LOG(ERROR) << "Stored time-stamp used for " << state_variable_key
1537 << " is in the future.";
1538 } else {
1539 *out_duration = now - stored_time;
1540 ret = true;
1541 }
1542 }
1543
1544 if (!system_state->prefs()->SetInt64(state_variable_key,
1545 now.ToInternalValue())) {
1546 LOG(ERROR) << "Error storing time-stamp in " << state_variable_key;
1547 }
1548
1549 return ret;
1550}
1551
1552bool MonotonicDurationHelper(SystemState* system_state,
1553 int64_t* storage,
1554 base::TimeDelta* out_duration) {
1555 bool ret = false;
1556
1557 base::Time now = system_state->clock()->GetMonotonicTime();
1558 if (*storage != 0) {
1559 base::Time stored_time = base::Time::FromInternalValue(*storage);
1560 *out_duration = now - stored_time;
1561 ret = true;
1562 }
1563 *storage = now.ToInternalValue();
1564
1565 return ret;
1566}
1567
adlr@google.com3defe6a2009-12-04 20:57:17 +00001568} // namespace utils
1569
1570} // namespace chromeos_update_engine