blob: 8f1a12244748d906a36548f5039d8d4b59477167 [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
David Zeuthen910ec5b2013-09-26 12:10:58 -07007#include <attr/xattr.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +00008#include <dirent.h>
9#include <errno.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080010#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000011#include <stdio.h>
12#include <stdlib.h>
13#include <string.h>
Alex Deymoc4acdf42014-05-28 21:07:10 -070014#include <sys/mount.h>
15#include <sys/resource.h>
16#include <sys/stat.h>
17#include <sys/types.h>
18#include <sys/wait.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000019#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070020
adlr@google.com3defe6a2009-12-04 20:57:17 +000021#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070022#include <utility>
Chris Sosac1972482013-04-30 22:31:10 -070023#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070024
Will Drewry8f71da82010-08-30 14:07:11 -050025#include <base/file_util.h>
Ben Chan736fcb52014-05-21 18:28:22 -070026#include <base/files/file_path.h>
27#include <base/files/scoped_file.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040028#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080029#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050030#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070031#include <base/strings/string_number_conversions.h>
32#include <base/strings/string_split.h>
33#include <base/strings/string_util.h>
34#include <base/strings/stringprintf.h>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080035#include <glib.h>
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -080036#include <google/protobuf/stubs/common.h>
Will Drewry8f71da82010-08-30 14:07:11 -050037
David Zeuthen33bae492014-02-25 16:16:18 -080038#include "update_engine/clock_interface.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070039#include "update_engine/constants.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080040#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070041#include "update_engine/omaha_request_params.h"
David Zeuthen33bae492014-02-25 16:16:18 -080042#include "update_engine/prefs_interface.h"
Darin Petkov296889c2010-07-23 16:20:54 -070043#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080044#include "update_engine/system_state.h"
45#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000046
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070047using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080048using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000049using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070050using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000051using std::string;
52using std::vector;
53
54namespace chromeos_update_engine {
55
Ben Chan77a1eba2012-10-07 22:54:55 -070056namespace {
57
58// The following constants control how UnmountFilesystem should retry if
59// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
60// one second.
61const int kUnmountMaxNumOfRetries = 5;
62const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070063
64// Number of bytes to read from a file to attempt to detect its contents. Used
65// in GetFileFormat.
66const int kGetFileFormatMaxHeaderSize = 32;
67
Ben Chan77a1eba2012-10-07 22:54:55 -070068} // namespace
69
adlr@google.com3defe6a2009-12-04 20:57:17 +000070namespace utils {
71
Chris Sosa4f8ee272012-11-30 13:01:54 -080072// Cgroup container is created in update-engine's upstart script located at
73// /etc/init/update-engine.conf.
74static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
75
J. Richard Barnette63137e52013-10-28 10:57:29 -070076string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -070077 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -070078
Alex Vakulenko75039d72014-03-25 12:36:28 -070079 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -070080 // a vector of key value pairs.
81 vector<pair<string, string> > kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -070082 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Chris Sosac1972482013-04-30 22:31:10 -070083 for (vector<pair<string, string> >::iterator it = kv_pairs.begin();
84 it != kv_pairs.end(); ++it) {
85 // Finally match against the fw_verion which may have quotes.
86 if (it->first == "fw_version") {
87 string output;
88 // Trim any quotes.
Alex Vakulenko75039d72014-03-25 12:36:28 -070089 base::TrimString(it->second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -070090 return output;
91 }
92 }
93 }
94 LOG(ERROR) << "Unable to parse fwid from ec info.";
95 return "";
96}
97
98
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -070099const string KernelDeviceOfBootDevice(const string& boot_device) {
100 string kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700101
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700102 string disk_name;
103 int partition_num;
104 if (SplitPartitionName(boot_device, &disk_name, &partition_num)) {
105 if (disk_name == "/dev/ubiblock") {
106 // Special case for NAND devices.
107 // eg: /dev/ubiblock3_0 becomes /dev/mtdblock2
108 disk_name = "/dev/mtdblock";
109 }
110 // Currently this assumes the partition number of the boot device is
111 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
112 // get the kernel device.
113 if (partition_num == 3 || partition_num == 5 || partition_num == 7) {
114 kernel_partition_name = MakePartitionName(disk_name, partition_num - 1);
115 }
J. Richard Barnette30842932013-10-28 15:04:23 -0700116 }
117
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700118 return kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700119}
120
121
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800122bool WriteFile(const char* path, const char* data, int data_len) {
123 DirectFileWriter writer;
124 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
125 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700126 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800127 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800128 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800129 return true;
130}
131
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700132bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700133 const char* c_buf = static_cast<const char*>(buf);
134 ssize_t bytes_written = 0;
135 while (bytes_written < static_cast<ssize_t>(count)) {
136 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
137 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
138 bytes_written += rc;
139 }
140 return true;
141}
142
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700143bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
144 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700145 size_t bytes_written = 0;
146 int num_attempts = 0;
147 while (bytes_written < count) {
148 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700149 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
150 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700151 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
152 if (rc < 0) {
153 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
154 << " bytes_written=" << bytes_written
155 << " count=" << count << " offset=" << offset;
156 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700157 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
158 bytes_written += rc;
159 }
160 return true;
161}
162
163bool PReadAll(int fd, void* buf, size_t count, off_t offset,
164 ssize_t* out_bytes_read) {
165 char* c_buf = static_cast<char*>(buf);
166 ssize_t bytes_read = 0;
167 while (bytes_read < static_cast<ssize_t>(count)) {
168 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
169 offset + bytes_read);
170 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
171 if (rc == 0) {
172 break;
173 }
174 bytes_read += rc;
175 }
176 *out_bytes_read = bytes_read;
177 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700178}
179
Gilad Arnold19a45f02012-07-19 12:36:10 -0700180// Append |nbytes| of content from |buf| to the vector pointed to by either
181// |vec_p| or |str_p|.
182static void AppendBytes(const char* buf, size_t nbytes,
183 std::vector<char>* vec_p) {
184 CHECK(buf);
185 CHECK(vec_p);
186 vec_p->insert(vec_p->end(), buf, buf + nbytes);
187}
188static void AppendBytes(const char* buf, size_t nbytes,
189 std::string* str_p) {
190 CHECK(buf);
191 CHECK(str_p);
192 str_p->append(buf, nbytes);
193}
194
195// Reads from an open file |fp|, appending the read content to the container
196// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200197// file's content, false otherwise. If |size| is not -1, reads up to |size|
198// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700199template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200200static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700201 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200202 CHECK(size == -1 || size >= 0);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700203 char buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200204 while (size == -1 || size > 0) {
205 off_t bytes_to_read = sizeof(buf);
206 if (size > 0 && bytes_to_read > size) {
207 bytes_to_read = size;
208 }
209 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
210 if (!nbytes) {
211 break;
212 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700213 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200214 if (size != -1) {
215 CHECK(size >= static_cast<off_t>(nbytes));
216 size -= nbytes;
217 }
218 }
219 if (ferror(fp)) {
220 return false;
221 }
222 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700223}
224
Darin Petkov8e447e02013-04-16 16:23:50 +0200225// Opens a file |path| for reading and appends its the contents to a container
226// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
227// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700228template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200229static bool ReadFileChunkAndAppend(const std::string& path,
230 off_t offset,
231 off_t size,
232 T* out_p) {
233 CHECK_GE(offset, 0);
234 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700235 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200236 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000237 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200238 if (offset) {
239 // Return success without appending any data if a chunk beyond the end of
240 // the file is requested.
241 if (offset >= FileSize(path)) {
242 return true;
243 }
244 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
245 }
246 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000247}
248
Gilad Arnold19a45f02012-07-19 12:36:10 -0700249// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
250// container |out_p|.
251template <class T>
252static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
253 FILE* fp = popen(cmd.c_str(), "r");
254 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000255 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200256 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700257 return (success && pclose(fp) >= 0);
258}
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
274bool ReadPipe(const string& cmd, vector<char>* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700275 return ReadPipeAndAppend(cmd, out_p);
276}
277
Darin Petkov8e447e02013-04-16 16:23:50 +0200278bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700279 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000280}
281
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700282off_t FileSize(const string& path) {
283 struct stat stbuf;
284 int rc = stat(path.c_str(), &stbuf);
285 CHECK_EQ(rc, 0);
286 if (rc < 0)
287 return rc;
288 return stbuf.st_size;
289}
290
adlr@google.com3defe6a2009-12-04 20:57:17 +0000291void HexDumpArray(const unsigned char* const arr, const size_t length) {
292 const unsigned char* const char_arr =
293 reinterpret_cast<const unsigned char* const>(arr);
294 LOG(INFO) << "Logging array of length: " << length;
295 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700296 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000297 const unsigned int bytes_remaining = length - i;
298 const unsigned int bytes_per_this_line = min(bytes_per_line,
299 bytes_remaining);
300 char header[100];
301 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
302 TEST_AND_RETURN(r == 13);
303 string line = header;
304 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
305 char buf[20];
306 unsigned char c = char_arr[i + j];
307 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
308 TEST_AND_RETURN(r == 3);
309 line += buf;
310 }
311 LOG(INFO) << line;
312 }
313}
314
315namespace {
316class ScopedDirCloser {
317 public:
318 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
319 ~ScopedDirCloser() {
320 if (dir_ && *dir_) {
321 int r = closedir(*dir_);
322 TEST_AND_RETURN_ERRNO(r == 0);
323 *dir_ = NULL;
324 dir_ = NULL;
325 }
326 }
327 private:
328 DIR** dir_;
329};
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700330} // namespace
adlr@google.com3defe6a2009-12-04 20:57:17 +0000331
332bool RecursiveUnlinkDir(const std::string& path) {
333 struct stat stbuf;
334 int r = lstat(path.c_str(), &stbuf);
335 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
336 if ((r < 0) && (errno == ENOENT))
337 // path request is missing. that's fine.
338 return true;
339 if (!S_ISDIR(stbuf.st_mode)) {
340 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700341 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000342 // success or path disappeared before we could unlink.
343 return true;
344 }
345 {
346 // We have a dir, unlink all children, then delete dir
347 DIR *dir = opendir(path.c_str());
348 TEST_AND_RETURN_FALSE_ERRNO(dir);
349 ScopedDirCloser dir_closer(&dir);
350 struct dirent dir_entry;
351 struct dirent *dir_entry_p;
352 int err = 0;
353 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
354 if (dir_entry_p == NULL) {
355 // end of stream reached
356 break;
357 }
358 // Skip . and ..
359 if (!strcmp(dir_entry_p->d_name, ".") ||
360 !strcmp(dir_entry_p->d_name, ".."))
361 continue;
362 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700363 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000364 }
365 TEST_AND_RETURN_FALSE(err == 0);
366 }
367 // unlink dir
368 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
369 return true;
370}
371
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800372std::string GetDiskName(const string& partition_name) {
373 std::string disk_name;
374 return SplitPartitionName(partition_name, &disk_name, nullptr) ?
375 disk_name : std::string();
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700376}
377
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800378int GetPartitionNumber(const std::string& partition_name) {
379 int partition_num = 0;
380 return SplitPartitionName(partition_name, nullptr, &partition_num) ?
381 partition_num : 0;
382}
383
384bool SplitPartitionName(const std::string& partition_name,
385 std::string* out_disk_name,
386 int* out_partition_num) {
387 if (!StringHasPrefix(partition_name, "/dev/")) {
388 LOG(ERROR) << "Invalid partition device name: " << partition_name;
389 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700390 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800391
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700392 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
393 if (last_nondigit_pos == string::npos ||
394 (last_nondigit_pos + 1) == partition_name.size()) {
395 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800396 return false;
397 }
398
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700399 size_t partition_name_len = std::string::npos;
400 if (partition_name[last_nondigit_pos] == '_') {
401 // NAND block devices have weird naming which could be something
402 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
403 size_t prev_nondigit_pos =
404 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
405 if (prev_nondigit_pos == string::npos ||
406 (prev_nondigit_pos + 1) == last_nondigit_pos) {
407 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
408 return false;
409 }
410
411 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
412 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800413 }
414
415 if (out_disk_name) {
416 // Special case for MMC devices which have the following naming scheme:
417 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700418 size_t disk_name_len = last_nondigit_pos;
419 if (partition_name[last_nondigit_pos] != 'p' ||
420 last_nondigit_pos == 0 ||
421 !isdigit(partition_name[last_nondigit_pos - 1])) {
422 disk_name_len++;
423 }
424 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800425 }
426
427 if (out_partition_num) {
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700428 std::string partition_str = partition_name.substr(last_nondigit_pos + 1,
429 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800430 *out_partition_num = atoi(partition_str.c_str());
431 }
432 return true;
433}
434
435std::string MakePartitionName(const std::string& disk_name,
436 int partition_num) {
437 if (!StringHasPrefix(disk_name, "/dev/")) {
438 LOG(ERROR) << "Invalid disk name: " << disk_name;
439 return std::string();
440 }
441
442 if (partition_num < 1) {
443 LOG(ERROR) << "Invalid partition number: " << partition_num;
444 return std::string();
445 }
446
447 std::string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700448 if (isdigit(partition_name.back())) {
449 // Special case for devices with names ending with a digit.
450 // Add "p" to separate the disk name from partition number,
451 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800452 partition_name += 'p';
453 }
454
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700455 partition_name += std::to_string(partition_num);
456
457 if (StringHasPrefix(partition_name, "/dev/ubiblock")) {
458 // Special case for UBI block devieces that have "_0" suffix.
459 partition_name += "_0";
460 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800461 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700462}
463
Darin Petkovf74eb652010-08-04 12:08:38 -0700464string SysfsBlockDevice(const string& device) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700465 base::FilePath device_path(device);
Darin Petkovf74eb652010-08-04 12:08:38 -0700466 if (device_path.DirName().value() != "/dev") {
467 return "";
468 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700469 return base::FilePath("/sys/block").Append(device_path.BaseName()).value();
Darin Petkovf74eb652010-08-04 12:08:38 -0700470}
471
472bool IsRemovableDevice(const std::string& device) {
473 string sysfs_block = SysfsBlockDevice(device);
474 string removable;
475 if (sysfs_block.empty() ||
Alex Vakulenko75039d72014-03-25 12:36:28 -0700476 !base::ReadFileToString(base::FilePath(sysfs_block).Append("removable"),
Ben Chan736fcb52014-05-21 18:28:22 -0700477 &removable)) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700478 return false;
479 }
Ben Chan736fcb52014-05-21 18:28:22 -0700480 base::TrimWhitespaceASCII(removable, base::TRIM_ALL, &removable);
Darin Petkovf74eb652010-08-04 12:08:38 -0700481 return removable == "1";
482}
483
adlr@google.com3defe6a2009-12-04 20:57:17 +0000484std::string ErrnoNumberAsString(int err) {
485 char buf[100];
486 buf[0] = '\0';
487 return strerror_r(err, buf, sizeof(buf));
488}
489
490std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
491 string ret;
492 bool last_insert_was_slash = false;
493 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
494 if (*it == '/') {
495 if (last_insert_was_slash)
496 continue;
497 last_insert_was_slash = true;
498 } else {
499 last_insert_was_slash = false;
500 }
501 ret.push_back(*it);
502 }
503 if (strip_trailing_slash && last_insert_was_slash) {
504 string::size_type last_non_slash = ret.find_last_not_of('/');
505 if (last_non_slash != string::npos) {
506 ret.resize(last_non_slash + 1);
507 } else {
508 ret = "";
509 }
510 }
511 return ret;
512}
513
514bool FileExists(const char* path) {
515 struct stat stbuf;
516 return 0 == lstat(path, &stbuf);
517}
518
Darin Petkov30291ed2010-11-12 10:23:06 -0800519bool IsSymlink(const char* path) {
520 struct stat stbuf;
521 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
522}
523
Alex Deymo7dc4c502014-05-20 20:09:58 -0700524bool IsDir(const char* path) {
525 struct stat stbuf;
526 TEST_AND_RETURN_FALSE_ERRNO(lstat(path, &stbuf) == 0);
527 return S_ISDIR(stbuf.st_mode);
528}
529
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800530// If |path| is absolute, or explicit relative to the current working directory,
531// leaves it as is. Otherwise, if TMPDIR is defined in the environment and is
532// non-empty, prepends it to |path|. Otherwise, prepends /tmp. Returns the
533// resulting path.
534static const string PrependTmpdir(const string& path) {
535 if (path[0] == '/' || StartsWithASCII(path, "./", true) ||
536 StartsWithASCII(path, "../", true))
537 return path;
538
539 const char *tmpdir = getenv("TMPDIR");
540 const string prefix = (tmpdir && *tmpdir ? tmpdir : "/tmp");
541 return prefix + "/" + path;
542}
543
544bool MakeTempFile(const std::string& base_filename_template,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700545 std::string* filename,
546 int* fd) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800547 const string filename_template = PrependTmpdir(base_filename_template);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700548 DCHECK(filename || fd);
549 vector<char> buf(filename_template.size() + 1);
550 memcpy(&buf[0], filename_template.data(), filename_template.size());
551 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700552
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700553 int mkstemp_fd = mkstemp(&buf[0]);
554 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
555 if (filename) {
556 *filename = &buf[0];
557 }
558 if (fd) {
559 *fd = mkstemp_fd;
560 } else {
561 close(mkstemp_fd);
562 }
563 return true;
564}
565
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800566bool MakeTempDirectory(const std::string& base_dirname_template,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700567 std::string* dirname) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800568 const string dirname_template = PrependTmpdir(base_dirname_template);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700569 DCHECK(dirname);
570 vector<char> buf(dirname_template.size() + 1);
571 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
572 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700573
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700574 char* return_code = mkdtemp(&buf[0]);
575 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
576 *dirname = &buf[0];
577 return true;
578}
579
adlr@google.com3defe6a2009-12-04 20:57:17 +0000580bool StringHasSuffix(const std::string& str, const std::string& suffix) {
581 if (suffix.size() > str.size())
582 return false;
583 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
584}
585
586bool StringHasPrefix(const std::string& str, const std::string& prefix) {
587 if (prefix.size() > str.size())
588 return false;
589 return 0 == str.compare(0, prefix.size(), prefix);
590}
591
adlr@google.com3defe6a2009-12-04 20:57:17 +0000592bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700593 const string& mountpoint,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700594 unsigned long mountflags) { // NOLINT(runtime/int)
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700595 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000596 if (rc < 0) {
597 string msg = ErrnoNumberAsString(errno);
598 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
599 << device << " on " << mountpoint;
600 return false;
601 }
602 return true;
603}
604
605bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700606 for (int num_retries = 0; ; ++num_retries) {
607 if (umount(mountpoint.c_str()) == 0)
608 break;
609
610 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
611 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800612 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700613 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000614 return true;
615}
616
Darin Petkovd3f8c892010-10-12 21:38:45 -0700617bool GetFilesystemSize(const std::string& device,
618 int* out_block_count,
619 int* out_block_size) {
620 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
621 TEST_AND_RETURN_FALSE(fd >= 0);
622 ScopedFdCloser fd_closer(&fd);
623 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
624}
625
626bool GetFilesystemSizeFromFD(int fd,
627 int* out_block_count,
628 int* out_block_size) {
629 TEST_AND_RETURN_FALSE(fd >= 0);
630
631 // Determine the ext3 filesystem size by directly reading the block count and
632 // block size information from the superblock. See include/linux/ext3_fs.h for
633 // more details on the structure.
634 ssize_t kBufferSize = 16 * sizeof(uint32_t);
635 char buffer[kBufferSize];
636 const int kSuperblockOffset = 1024;
637 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
638 kBufferSize) {
639 PLOG(ERROR) << "Unable to determine file system size:";
640 return false;
641 }
642 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
643 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
644 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
645 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
646 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
647 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
648 block_count = le32toh(block_count);
649 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
650 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
651 magic = le16toh(magic);
652
653 // Sanity check the parameters.
654 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
655 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
656 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
657 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
658 int block_size = 1 << log_block_size;
659 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
660 block_size <= kExt3MaxBlockSize);
661 TEST_AND_RETURN_FALSE(block_count > 0);
662
663 if (out_block_count) {
664 *out_block_count = block_count;
665 }
666 if (out_block_size) {
667 *out_block_size = block_size;
668 }
669 return true;
670}
671
Alex Deymo719bfff2014-07-11 12:12:32 -0700672string GetPathOnBoard(const string& command) {
673 int return_code = 0;
674 string command_path;
675 // TODO(deymo): prepend SYSROOT to each PATH instead of the result.
676 if (!Subprocess::SynchronousExec(
677 {"which", command}, &return_code, &command_path)) {
678 return command;
679 }
680 if (return_code != 0)
681 return command;
682
683 base::TrimWhitespaceASCII(command_path, base::TRIM_ALL, &command_path);
684 const char* env_sysroot = getenv("SYSROOT");
685 if (env_sysroot) {
686 string sysroot_command_path = env_sysroot + command_path;
687 if (utils::FileExists(sysroot_command_path.c_str()))
688 return sysroot_command_path;
689 }
690 return command_path;
691}
692
Alex Deymo032e7722014-03-25 17:53:56 -0700693// Tries to parse the header of an ELF file to obtain a human-readable
694// description of it on the |output| string.
695static bool GetFileFormatELF(const char* buffer, size_t size, string* output) {
696 // 0x00: EI_MAG - ELF magic header, 4 bytes.
697 if (size < 4 || memcmp(buffer, "\x7F""ELF", 4) != 0)
698 return false;
699 *output = "ELF";
700
701 // 0x04: EI_CLASS, 1 byte.
702 if (size < 0x04 + 1)
703 return true;
704 switch (buffer[4]) {
705 case 1:
706 *output += " 32-bit";
707 break;
708 case 2:
709 *output += " 64-bit";
710 break;
711 default:
712 *output += " ?-bit";
713 }
714
715 // 0x05: EI_DATA, endianness, 1 byte.
716 if (size < 0x05 + 1)
717 return true;
718 char ei_data = buffer[5];
719 switch (ei_data) {
720 case 1:
721 *output += " little-endian";
722 break;
723 case 2:
724 *output += " big-endian";
725 break;
726 default:
727 *output += " ?-endian";
728 // Don't parse anything after the 0x10 offset if endianness is unknown.
729 return true;
730 }
731
732 // 0x12: e_machine, 2 byte endianness based on ei_data
733 if (size < 0x12 + 2)
734 return true;
735 uint16 e_machine = *reinterpret_cast<const uint16*>(buffer+0x12);
736 // Fix endianess regardless of the host endianess.
737 if (ei_data == 1)
738 e_machine = le16toh(e_machine);
739 else
740 e_machine = be16toh(e_machine);
741
742 switch (e_machine) {
743 case 0x03:
744 *output += " x86";
745 break;
746 case 0x28:
747 *output += " arm";
748 break;
749 case 0x3E:
750 *output += " x86-64";
751 break;
752 default:
753 *output += " unknown-arch";
754 }
755 return true;
756}
757
758string GetFileFormat(const string& path) {
759 vector<char> buffer;
760 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
761 return "File not found.";
762
763 string result;
764 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
765 return result;
766
767 return "data";
768}
769
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700770bool GetBootloader(BootLoader* out_bootloader) {
771 // For now, hardcode to syslinux.
772 *out_bootloader = BootLoader_SYSLINUX;
773 return true;
774}
775
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800776namespace {
777// Do the actual trigger. We do it as a main-loop callback to (try to) get a
778// consistent stack trace.
779gboolean TriggerCrashReporterUpload(void* unused) {
780 pid_t pid = fork();
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700781 CHECK_GE(pid, 0) << "fork failed"; // fork() failed. Something is very wrong.
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800782 if (pid == 0) {
783 // We are the child. Crash.
784 abort(); // never returns
785 }
786 // We are the parent. Wait for child to terminate.
787 pid_t result = waitpid(pid, NULL, 0);
788 LOG_IF(ERROR, result < 0) << "waitpid() failed";
789 return FALSE; // Don't call this callback again
790}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700791} // namespace
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800792
793void ScheduleCrashReporterUpload() {
794 g_idle_add(&TriggerCrashReporterUpload, NULL);
795}
796
Chris Sosa4f8ee272012-11-30 13:01:54 -0800797bool SetCpuShares(CpuShares shares) {
798 string string_shares = base::IntToString(static_cast<int>(shares));
799 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
800 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700801 if (utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
802 string_shares.size())) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800803 return true;
804 } else {
805 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
806 << " using " << cpu_shares_file;
807 return false;
808 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700809}
810
Chris Sosa4f8ee272012-11-30 13:01:54 -0800811int CompareCpuShares(CpuShares shares_lhs,
812 CpuShares shares_rhs) {
813 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700814}
815
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700816int FuzzInt(int value, unsigned int range) {
817 int min = value - range / 2;
818 int max = value + range - range / 2;
819 return base::RandInt(min, max);
820}
821
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800822gboolean GlibRunClosure(gpointer data) {
823 google::protobuf::Closure* callback =
824 reinterpret_cast<google::protobuf::Closure*>(data);
825 callback->Run();
826 return FALSE;
827}
828
Alex Deymoc4acdf42014-05-28 21:07:10 -0700829void GlibDestroyClosure(gpointer data) {
830 delete reinterpret_cast<google::protobuf::Closure*>(data);
831}
832
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700833string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800834 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700835}
836
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800837string FormatTimeDelta(TimeDelta delta) {
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700838 // Canonicalize into days, hours, minutes, seconds and microseconds.
839 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800840 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700841 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800842 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700843 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800844 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700845 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800846 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700847 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800848
849 // Construct and return string.
850 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700851 if (days)
852 base::StringAppendF(&str, "%ud", days);
853 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800854 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700855 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800856 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700857 base::StringAppendF(&str, "%u", secs);
858 if (usecs) {
859 int width = 6;
860 while ((usecs / 10) * 10 == usecs) {
861 usecs /= 10;
862 width--;
863 }
864 base::StringAppendF(&str, ".%0*u", width, usecs);
865 }
866 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800867 return str;
868}
869
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700870string ToString(const Time utc_time) {
871 Time::Exploded exp_time;
872 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700873 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700874 exp_time.month,
875 exp_time.day_of_month,
876 exp_time.year,
877 exp_time.hour,
878 exp_time.minute,
879 exp_time.second);
880}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000881
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700882string ToString(bool b) {
883 return (b ? "true" : "false");
884}
885
Alex Deymo1c656c42013-06-28 11:02:14 -0700886string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700887 switch (source) {
888 case kDownloadSourceHttpsServer: return "HttpsServer";
889 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700890 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700891 case kNumDownloadSources: return "Unknown";
892 // Don't add a default case to let the compiler warn about newly added
893 // download sources which should be added here.
894 }
895
896 return "Unknown";
897}
898
Alex Deymo1c656c42013-06-28 11:02:14 -0700899string ToString(PayloadType payload_type) {
900 switch (payload_type) {
901 case kPayloadTypeDelta: return "Delta";
902 case kPayloadTypeFull: return "Full";
903 case kPayloadTypeForcedFull: return "ForcedFull";
904 case kNumPayloadTypes: return "Unknown";
905 // Don't add a default case to let the compiler warn about newly added
906 // payload types which should be added here.
907 }
908
909 return "Unknown";
910}
911
David Zeuthena99981f2013-04-29 13:42:47 -0700912ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700913 // Ignore the higher order bits in the code by applying the mask as
914 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700915 // with values less than ErrorCode::kUmaReportedMax.
916 ErrorCode base_code = static_cast<ErrorCode>(
917 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700918
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800919 // Make additional adjustments required for UMA and error classification.
920 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
921 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700922 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700923 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800924 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800925 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700926 << " to ErrorCode::kOmahaErrorInHTTPResponse";
927 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700928 }
929
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800930 return base_code;
931}
932
David Zeuthen33bae492014-02-25 16:16:18 -0800933metrics::AttemptResult GetAttemptResult(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700934 ErrorCode base_code = static_cast<ErrorCode>(
935 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -0800936
937 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700938 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -0800939 return metrics::AttemptResult::kUpdateSucceeded;
940
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700941 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -0800942 return metrics::AttemptResult::kPayloadDownloadError;
943
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700944 case ErrorCode::kDownloadInvalidMetadataSize:
945 case ErrorCode::kDownloadInvalidMetadataMagicString:
946 case ErrorCode::kDownloadMetadataSignatureError:
947 case ErrorCode::kDownloadMetadataSignatureVerificationError:
948 case ErrorCode::kPayloadMismatchedType:
949 case ErrorCode::kUnsupportedMajorPayloadVersion:
950 case ErrorCode::kUnsupportedMinorPayloadVersion:
951 case ErrorCode::kDownloadNewPartitionInfoError:
952 case ErrorCode::kDownloadSignatureMissingInManifest:
953 case ErrorCode::kDownloadManifestParseError:
954 case ErrorCode::kDownloadOperationHashMissingError:
David Zeuthen33bae492014-02-25 16:16:18 -0800955 return metrics::AttemptResult::kMetadataMalformed;
956
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700957 case ErrorCode::kDownloadOperationHashMismatch:
958 case ErrorCode::kDownloadOperationHashVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -0800959 return metrics::AttemptResult::kOperationMalformed;
960
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700961 case ErrorCode::kDownloadOperationExecutionError:
962 case ErrorCode::kInstallDeviceOpenError:
963 case ErrorCode::kKernelDeviceOpenError:
964 case ErrorCode::kDownloadWriteError:
965 case ErrorCode::kFilesystemCopierError:
David Zeuthen33bae492014-02-25 16:16:18 -0800966 return metrics::AttemptResult::kOperationExecutionError;
967
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700968 case ErrorCode::kDownloadMetadataSignatureMismatch:
David Zeuthen33bae492014-02-25 16:16:18 -0800969 return metrics::AttemptResult::kMetadataVerificationFailed;
970
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700971 case ErrorCode::kPayloadSizeMismatchError:
972 case ErrorCode::kPayloadHashMismatchError:
973 case ErrorCode::kDownloadPayloadVerificationError:
974 case ErrorCode::kSignedDeltaPayloadExpectedError:
975 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -0800976 return metrics::AttemptResult::kPayloadVerificationFailed;
977
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700978 case ErrorCode::kNewRootfsVerificationError:
979 case ErrorCode::kNewKernelVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -0800980 return metrics::AttemptResult::kVerificationFailed;
981
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700982 case ErrorCode::kPostinstallRunnerError:
983 case ErrorCode::kPostinstallBootedFromFirmwareB:
984 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
David Zeuthen33bae492014-02-25 16:16:18 -0800985 return metrics::AttemptResult::kPostInstallFailed;
986
987 // We should never get these errors in the update-attempt stage so
988 // return internal error if this happens.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700989 case ErrorCode::kError:
990 case ErrorCode::kOmahaRequestXMLParseError:
991 case ErrorCode::kOmahaRequestError:
992 case ErrorCode::kOmahaResponseHandlerError:
993 case ErrorCode::kDownloadStateInitializationError:
994 case ErrorCode::kOmahaRequestEmptyResponseError:
995 case ErrorCode::kDownloadInvalidMetadataSignature:
996 case ErrorCode::kOmahaResponseInvalid:
997 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
998 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
999 case ErrorCode::kOmahaErrorInHTTPResponse:
1000 case ErrorCode::kDownloadMetadataSignatureMissingError:
1001 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1002 case ErrorCode::kPostinstallPowerwashError:
1003 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthen33bae492014-02-25 16:16:18 -08001004 return metrics::AttemptResult::kInternalError;
1005
1006 // Special flags. These can't happen (we mask them out above) but
1007 // the compiler doesn't know that. Just break out so we can warn and
1008 // return |kInternalError|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001009 case ErrorCode::kUmaReportedMax:
1010 case ErrorCode::kOmahaRequestHTTPResponseBase:
1011 case ErrorCode::kDevModeFlag:
1012 case ErrorCode::kResumedFlag:
1013 case ErrorCode::kTestImageFlag:
1014 case ErrorCode::kTestOmahaUrlFlag:
1015 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001016 break;
1017 }
1018
1019 LOG(ERROR) << "Unexpected error code " << base_code;
1020 return metrics::AttemptResult::kInternalError;
1021}
1022
1023
1024metrics::DownloadErrorCode GetDownloadErrorCode(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001025 ErrorCode base_code = static_cast<ErrorCode>(
1026 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001027
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001028 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
1029 int http_status =
1030 static_cast<int>(base_code) -
1031 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase);
David Zeuthen33bae492014-02-25 16:16:18 -08001032 if (http_status >= 200 && http_status <= 599) {
1033 return static_cast<metrics::DownloadErrorCode>(
1034 static_cast<int>(metrics::DownloadErrorCode::kHttpStatus200) +
1035 http_status - 200);
1036 } else if (http_status == 0) {
1037 // The code is using HTTP Status 0 for "Unable to get http
1038 // response code."
1039 return metrics::DownloadErrorCode::kDownloadError;
1040 }
1041 LOG(WARNING) << "Unexpected HTTP status code " << http_status;
1042 return metrics::DownloadErrorCode::kHttpStatusOther;
1043 }
1044
1045 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001046 // Unfortunately, ErrorCode::kDownloadTransferError is returned for a wide
David Zeuthen33bae492014-02-25 16:16:18 -08001047 // variety of errors (proxy errors, host not reachable, timeouts etc.).
1048 //
1049 // For now just map that to kDownloading. See http://crbug.com/355745
1050 // for how we plan to add more detail in the future.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001051 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001052 return metrics::DownloadErrorCode::kDownloadError;
1053
1054 // All of these error codes are not related to downloading so break
1055 // out so we can warn and return InputMalformed.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001056 case ErrorCode::kSuccess:
1057 case ErrorCode::kError:
1058 case ErrorCode::kOmahaRequestError:
1059 case ErrorCode::kOmahaResponseHandlerError:
1060 case ErrorCode::kFilesystemCopierError:
1061 case ErrorCode::kPostinstallRunnerError:
1062 case ErrorCode::kPayloadMismatchedType:
1063 case ErrorCode::kInstallDeviceOpenError:
1064 case ErrorCode::kKernelDeviceOpenError:
1065 case ErrorCode::kPayloadHashMismatchError:
1066 case ErrorCode::kPayloadSizeMismatchError:
1067 case ErrorCode::kDownloadPayloadVerificationError:
1068 case ErrorCode::kDownloadNewPartitionInfoError:
1069 case ErrorCode::kDownloadWriteError:
1070 case ErrorCode::kNewRootfsVerificationError:
1071 case ErrorCode::kNewKernelVerificationError:
1072 case ErrorCode::kSignedDeltaPayloadExpectedError:
1073 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1074 case ErrorCode::kPostinstallBootedFromFirmwareB:
1075 case ErrorCode::kDownloadStateInitializationError:
1076 case ErrorCode::kDownloadInvalidMetadataMagicString:
1077 case ErrorCode::kDownloadSignatureMissingInManifest:
1078 case ErrorCode::kDownloadManifestParseError:
1079 case ErrorCode::kDownloadMetadataSignatureError:
1080 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1081 case ErrorCode::kDownloadMetadataSignatureMismatch:
1082 case ErrorCode::kDownloadOperationHashVerificationError:
1083 case ErrorCode::kDownloadOperationExecutionError:
1084 case ErrorCode::kDownloadOperationHashMismatch:
1085 case ErrorCode::kOmahaRequestEmptyResponseError:
1086 case ErrorCode::kOmahaRequestXMLParseError:
1087 case ErrorCode::kDownloadInvalidMetadataSize:
1088 case ErrorCode::kDownloadInvalidMetadataSignature:
1089 case ErrorCode::kOmahaResponseInvalid:
1090 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1091 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1092 case ErrorCode::kOmahaErrorInHTTPResponse:
1093 case ErrorCode::kDownloadOperationHashMissingError:
1094 case ErrorCode::kDownloadMetadataSignatureMissingError:
1095 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1096 case ErrorCode::kPostinstallPowerwashError:
1097 case ErrorCode::kUpdateCanceledByChannelChange:
1098 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1099 case ErrorCode::kUnsupportedMajorPayloadVersion:
1100 case ErrorCode::kUnsupportedMinorPayloadVersion:
David Zeuthen33bae492014-02-25 16:16:18 -08001101 break;
1102
1103 // Special flags. These can't happen (we mask them out above) but
1104 // the compiler doesn't know that. Just break out so we can warn and
1105 // return |kInputMalformed|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001106 case ErrorCode::kUmaReportedMax:
1107 case ErrorCode::kOmahaRequestHTTPResponseBase:
1108 case ErrorCode::kDevModeFlag:
1109 case ErrorCode::kResumedFlag:
1110 case ErrorCode::kTestImageFlag:
1111 case ErrorCode::kTestOmahaUrlFlag:
1112 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001113 LOG(ERROR) << "Unexpected error code " << base_code;
1114 break;
1115 }
1116
1117 return metrics::DownloadErrorCode::kInputMalformed;
1118}
1119
David Zeuthenb281f072014-04-02 10:20:19 -07001120metrics::ConnectionType GetConnectionType(
1121 NetworkConnectionType type,
1122 NetworkTethering tethering) {
1123 switch (type) {
1124 case kNetUnknown:
1125 return metrics::ConnectionType::kUnknown;
1126
1127 case kNetEthernet:
1128 if (tethering == NetworkTethering::kConfirmed)
1129 return metrics::ConnectionType::kTetheredEthernet;
1130 else
1131 return metrics::ConnectionType::kEthernet;
1132
1133 case kNetWifi:
1134 if (tethering == NetworkTethering::kConfirmed)
1135 return metrics::ConnectionType::kTetheredWifi;
1136 else
1137 return metrics::ConnectionType::kWifi;
1138
1139 case kNetWimax:
1140 return metrics::ConnectionType::kWimax;
1141
1142 case kNetBluetooth:
1143 return metrics::ConnectionType::kBluetooth;
1144
1145 case kNetCellular:
1146 return metrics::ConnectionType::kCellular;
1147 }
1148
1149 LOG(ERROR) << "Unexpected network connection type: type=" << type
1150 << ", tethering=" << static_cast<int>(tethering);
1151
1152 return metrics::ConnectionType::kUnknown;
1153}
1154
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001155// Returns a printable version of the various flags denoted in the higher order
1156// bits of the given code. Returns an empty string if none of those bits are
1157// set.
1158string GetFlagNames(uint32_t code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001159 uint32_t flags = (static_cast<uint32_t>(code) &
1160 static_cast<uint32_t>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001161 string flag_names;
1162 string separator = "";
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001163 for (size_t i = 0; i < sizeof(flags) * 8; i++) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001164 uint32_t flag = flags & (1 << i);
1165 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -07001166 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001167 separator = ", ";
1168 }
1169 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001170
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001171 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001172}
1173
David Zeuthena99981f2013-04-29 13:42:47 -07001174void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001175 if (!system_state)
1176 return;
1177
David Zeuthena99981f2013-04-29 13:42:47 -07001178 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001179
1180 // If the code doesn't have flags computed already, compute them now based on
1181 // the state of the current update attempt.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001182 uint32_t flags =
1183 static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001184 if (!flags)
1185 flags = system_state->update_attempter()->GetErrorCodeFlags();
1186
1187 // Determine the UMA bucket depending on the flags. But, ignore the resumed
1188 // flag, as it's perfectly normal for production devices to resume their
1189 // downloads and so we want to record those cases also in NormalErrorCodes
1190 // bucket.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001191 string metric =
1192 flags & ~static_cast<uint32_t>(ErrorCode::kResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001193 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
1194
1195 LOG(INFO) << "Sending error code " << uma_error_code
1196 << " (" << CodeToString(uma_error_code) << ")"
1197 << " to UMA metric: " << metric
1198 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
1199
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001200 system_state->metrics_lib()->SendEnumToUMA(
1201 metric, static_cast<int>(uma_error_code),
1202 static_cast<int>(ErrorCode::kUmaReportedMax));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001203}
1204
David Zeuthena99981f2013-04-29 13:42:47 -07001205string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001206 // If the given code has both parts (i.e. the error code part and the flags
1207 // part) then strip off the flags part since the switch statement below
1208 // has case statements only for the base error code or a single flag but
1209 // doesn't support any combinations of those.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001210 if ((static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags)) &&
1211 (static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags)))
1212 code = static_cast<ErrorCode>(
1213 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001214 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001215 case ErrorCode::kSuccess: return "ErrorCode::kSuccess";
1216 case ErrorCode::kError: return "ErrorCode::kError";
1217 case ErrorCode::kOmahaRequestError: return "ErrorCode::kOmahaRequestError";
1218 case ErrorCode::kOmahaResponseHandlerError:
1219 return "ErrorCode::kOmahaResponseHandlerError";
1220 case ErrorCode::kFilesystemCopierError:
1221 return "ErrorCode::kFilesystemCopierError";
1222 case ErrorCode::kPostinstallRunnerError:
1223 return "ErrorCode::kPostinstallRunnerError";
1224 case ErrorCode::kPayloadMismatchedType:
1225 return "ErrorCode::kPayloadMismatchedType";
1226 case ErrorCode::kInstallDeviceOpenError:
1227 return "ErrorCode::kInstallDeviceOpenError";
1228 case ErrorCode::kKernelDeviceOpenError:
1229 return "ErrorCode::kKernelDeviceOpenError";
1230 case ErrorCode::kDownloadTransferError:
1231 return "ErrorCode::kDownloadTransferError";
1232 case ErrorCode::kPayloadHashMismatchError:
1233 return "ErrorCode::kPayloadHashMismatchError";
1234 case ErrorCode::kPayloadSizeMismatchError:
1235 return "ErrorCode::kPayloadSizeMismatchError";
1236 case ErrorCode::kDownloadPayloadVerificationError:
1237 return "ErrorCode::kDownloadPayloadVerificationError";
1238 case ErrorCode::kDownloadNewPartitionInfoError:
1239 return "ErrorCode::kDownloadNewPartitionInfoError";
1240 case ErrorCode::kDownloadWriteError:
1241 return "ErrorCode::kDownloadWriteError";
1242 case ErrorCode::kNewRootfsVerificationError:
1243 return "ErrorCode::kNewRootfsVerificationError";
1244 case ErrorCode::kNewKernelVerificationError:
1245 return "ErrorCode::kNewKernelVerificationError";
1246 case ErrorCode::kSignedDeltaPayloadExpectedError:
1247 return "ErrorCode::kSignedDeltaPayloadExpectedError";
1248 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1249 return "ErrorCode::kDownloadPayloadPubKeyVerificationError";
1250 case ErrorCode::kPostinstallBootedFromFirmwareB:
1251 return "ErrorCode::kPostinstallBootedFromFirmwareB";
1252 case ErrorCode::kDownloadStateInitializationError:
1253 return "ErrorCode::kDownloadStateInitializationError";
1254 case ErrorCode::kDownloadInvalidMetadataMagicString:
1255 return "ErrorCode::kDownloadInvalidMetadataMagicString";
1256 case ErrorCode::kDownloadSignatureMissingInManifest:
1257 return "ErrorCode::kDownloadSignatureMissingInManifest";
1258 case ErrorCode::kDownloadManifestParseError:
1259 return "ErrorCode::kDownloadManifestParseError";
1260 case ErrorCode::kDownloadMetadataSignatureError:
1261 return "ErrorCode::kDownloadMetadataSignatureError";
1262 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1263 return "ErrorCode::kDownloadMetadataSignatureVerificationError";
1264 case ErrorCode::kDownloadMetadataSignatureMismatch:
1265 return "ErrorCode::kDownloadMetadataSignatureMismatch";
1266 case ErrorCode::kDownloadOperationHashVerificationError:
1267 return "ErrorCode::kDownloadOperationHashVerificationError";
1268 case ErrorCode::kDownloadOperationExecutionError:
1269 return "ErrorCode::kDownloadOperationExecutionError";
1270 case ErrorCode::kDownloadOperationHashMismatch:
1271 return "ErrorCode::kDownloadOperationHashMismatch";
1272 case ErrorCode::kOmahaRequestEmptyResponseError:
1273 return "ErrorCode::kOmahaRequestEmptyResponseError";
1274 case ErrorCode::kOmahaRequestXMLParseError:
1275 return "ErrorCode::kOmahaRequestXMLParseError";
1276 case ErrorCode::kDownloadInvalidMetadataSize:
1277 return "ErrorCode::kDownloadInvalidMetadataSize";
1278 case ErrorCode::kDownloadInvalidMetadataSignature:
1279 return "ErrorCode::kDownloadInvalidMetadataSignature";
1280 case ErrorCode::kOmahaResponseInvalid:
1281 return "ErrorCode::kOmahaResponseInvalid";
1282 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1283 return "ErrorCode::kOmahaUpdateIgnoredPerPolicy";
1284 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1285 return "ErrorCode::kOmahaUpdateDeferredPerPolicy";
1286 case ErrorCode::kOmahaErrorInHTTPResponse:
1287 return "ErrorCode::kOmahaErrorInHTTPResponse";
1288 case ErrorCode::kDownloadOperationHashMissingError:
1289 return "ErrorCode::kDownloadOperationHashMissingError";
1290 case ErrorCode::kDownloadMetadataSignatureMissingError:
1291 return "ErrorCode::kDownloadMetadataSignatureMissingError";
1292 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1293 return "ErrorCode::kOmahaUpdateDeferredForBackoff";
1294 case ErrorCode::kPostinstallPowerwashError:
1295 return "ErrorCode::kPostinstallPowerwashError";
1296 case ErrorCode::kUpdateCanceledByChannelChange:
1297 return "ErrorCode::kUpdateCanceledByChannelChange";
1298 case ErrorCode::kUmaReportedMax:
1299 return "ErrorCode::kUmaReportedMax";
1300 case ErrorCode::kOmahaRequestHTTPResponseBase:
1301 return "ErrorCode::kOmahaRequestHTTPResponseBase";
1302 case ErrorCode::kResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001303 return "Resumed";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001304 case ErrorCode::kDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001305 return "DevMode";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001306 case ErrorCode::kTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001307 return "TestImage";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001308 case ErrorCode::kTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001309 return "TestOmahaUrl";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001310 case ErrorCode::kSpecialFlags:
1311 return "ErrorCode::kSpecialFlags";
1312 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1313 return "ErrorCode::kPostinstallFirmwareRONotUpdatable";
1314 case ErrorCode::kUnsupportedMajorPayloadVersion:
1315 return "ErrorCode::kUnsupportedMajorPayloadVersion";
1316 case ErrorCode::kUnsupportedMinorPayloadVersion:
1317 return "ErrorCode::kUnsupportedMinorPayloadVersion";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001318 // Don't add a default case to let the compiler warn about newly added
1319 // error codes which should be added here.
1320 }
1321
1322 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1323}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001324
Gilad Arnold30dedd82013-07-03 06:19:09 -07001325bool CreatePowerwashMarkerFile(const char* file_path) {
1326 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1327 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001328 kPowerwashCommand,
1329 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001330 if (result) {
1331 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1332 } else {
1333 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1334 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001335
1336 return result;
1337}
1338
Gilad Arnold30dedd82013-07-03 06:19:09 -07001339bool DeletePowerwashMarkerFile(const char* file_path) {
1340 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001341 const base::FilePath kPowerwashMarkerPath(marker_file);
1342 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001343
1344 if (result)
1345 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001346 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001347 else
1348 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001349 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001350
1351 return result;
1352}
1353
Chris Sosad317e402013-06-12 13:47:09 -07001354bool GetInstallDev(const std::string& boot_dev, std::string* install_dev) {
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001355 std::string disk_name;
1356 int partition_num;
1357 if (!SplitPartitionName(boot_dev, &disk_name, &partition_num))
1358 return false;
Liam McLoughlin049d1652013-07-31 18:47:46 -07001359
Chris Sosad317e402013-06-12 13:47:09 -07001360 // Right now, we just switch '3' and '5' partition numbers.
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001361 if (partition_num == 3) {
1362 partition_num = 5;
1363 } else if (partition_num == 5) {
1364 partition_num = 3;
1365 } else {
1366 return false;
1367 }
1368
1369 if (install_dev)
1370 *install_dev = MakePartitionName(disk_name, partition_num);
Liam McLoughlin049d1652013-07-31 18:47:46 -07001371
Chris Sosad317e402013-06-12 13:47:09 -07001372 return true;
1373}
1374
David Zeuthen27a48bc2013-08-06 12:06:29 -07001375Time TimeFromStructTimespec(struct timespec *ts) {
1376 int64 us = static_cast<int64>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1377 static_cast<int64>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
1378 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1379}
1380
1381gchar** StringVectorToGStrv(const vector<string> &vector) {
1382 GPtrArray *p = g_ptr_array_new();
1383 for (std::vector<string>::const_iterator i = vector.begin();
1384 i != vector.end(); ++i) {
1385 g_ptr_array_add(p, g_strdup(i->c_str()));
1386 }
1387 g_ptr_array_add(p, NULL);
1388 return reinterpret_cast<gchar**>(g_ptr_array_free(p, FALSE));
1389}
1390
1391string StringVectorToString(const vector<string> &vector) {
1392 string str = "[";
1393 for (std::vector<string>::const_iterator i = vector.begin();
1394 i != vector.end(); ++i) {
1395 if (i != vector.begin())
1396 str += ", ";
1397 str += '"';
1398 str += *i;
1399 str += '"';
1400 }
1401 str += "]";
1402 return str;
1403}
1404
David Zeuthen8f191b22013-08-06 12:27:50 -07001405string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
1406 string encoded_hash;
1407 OmahaHashCalculator::Base64Encode(payload_hash.c_str(),
1408 payload_hash.size(),
1409 &encoded_hash);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001410 return base::StringPrintf("cros_update_size_%zu_hash_%s",
David Zeuthen8f191b22013-08-06 12:27:50 -07001411 payload_size,
1412 encoded_hash.c_str());
1413}
1414
David Zeuthen910ec5b2013-09-26 12:10:58 -07001415bool IsXAttrSupported(const base::FilePath& dir_path) {
1416 char *path = strdup(dir_path.Append("xattr_test_XXXXXX").value().c_str());
1417
1418 int fd = mkstemp(path);
1419 if (fd == -1) {
1420 PLOG(ERROR) << "Error creating temporary file in " << dir_path.value();
1421 free(path);
1422 return false;
1423 }
1424
1425 if (unlink(path) != 0) {
1426 PLOG(ERROR) << "Error unlinking temporary file " << path;
1427 close(fd);
1428 free(path);
1429 return false;
1430 }
1431
1432 int xattr_res = fsetxattr(fd, "user.xattr-test", "value", strlen("value"), 0);
1433 if (xattr_res != 0) {
1434 if (errno == ENOTSUP) {
1435 // Leave it to call-sites to warn about non-support.
1436 } else {
1437 PLOG(ERROR) << "Error setting xattr on " << path;
1438 }
1439 }
1440 close(fd);
1441 free(path);
1442 return xattr_res == 0;
1443}
1444
David Zeuthene7f89172013-10-31 10:21:04 -07001445bool DecodeAndStoreBase64String(const std::string& base64_encoded,
1446 base::FilePath *out_path) {
1447 vector<char> contents;
1448
1449 out_path->clear();
1450
1451 if (base64_encoded.size() == 0) {
1452 LOG(ERROR) << "Can't decode empty string.";
1453 return false;
1454 }
1455
1456 if (!OmahaHashCalculator::Base64Decode(base64_encoded, &contents) ||
1457 contents.size() == 0) {
1458 LOG(ERROR) << "Error decoding base64.";
1459 return false;
1460 }
1461
Alex Vakulenko75039d72014-03-25 12:36:28 -07001462 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
David Zeuthene7f89172013-10-31 10:21:04 -07001463 if (file == NULL) {
1464 LOG(ERROR) << "Error creating temporary file.";
1465 return false;
1466 }
1467
1468 if (fwrite(&contents[0], 1, contents.size(), file) != contents.size()) {
1469 PLOG(ERROR) << "Error writing to temporary file.";
1470 if (fclose(file) != 0)
1471 PLOG(ERROR) << "Error closing temporary file.";
1472 if (unlink(out_path->value().c_str()) != 0)
1473 PLOG(ERROR) << "Error unlinking temporary file.";
1474 out_path->clear();
1475 return false;
1476 }
1477
1478 if (fclose(file) != 0) {
1479 PLOG(ERROR) << "Error closing temporary file.";
1480 out_path->clear();
1481 return false;
1482 }
1483
1484 return true;
1485}
1486
David Zeuthen639aa362014-02-03 16:23:44 -08001487bool ConvertToOmahaInstallDate(base::Time time, int *out_num_days) {
1488 time_t unix_time = time.ToTimeT();
1489 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1490 const time_t kOmahaEpoch = 1167638400;
1491 const int64_t kNumSecondsPerWeek = 7*24*3600;
1492 const int64_t kNumDaysPerWeek = 7;
1493
1494 time_t omaha_time = unix_time - kOmahaEpoch;
1495
1496 if (omaha_time < 0)
1497 return false;
1498
1499 // Note, as per the comment in utils.h we are deliberately not
1500 // handling DST correctly.
1501
1502 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1503 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1504
1505 return true;
1506}
1507
David Zeuthen33bae492014-02-25 16:16:18 -08001508bool WallclockDurationHelper(SystemState* system_state,
1509 const std::string& state_variable_key,
1510 base::TimeDelta* out_duration) {
1511 bool ret = false;
1512
1513 base::Time now = system_state->clock()->GetWallclockTime();
1514 int64_t stored_value;
1515 if (system_state->prefs()->GetInt64(state_variable_key, &stored_value)) {
1516 base::Time stored_time = base::Time::FromInternalValue(stored_value);
1517 if (stored_time > now) {
1518 LOG(ERROR) << "Stored time-stamp used for " << state_variable_key
1519 << " is in the future.";
1520 } else {
1521 *out_duration = now - stored_time;
1522 ret = true;
1523 }
1524 }
1525
1526 if (!system_state->prefs()->SetInt64(state_variable_key,
1527 now.ToInternalValue())) {
1528 LOG(ERROR) << "Error storing time-stamp in " << state_variable_key;
1529 }
1530
1531 return ret;
1532}
1533
1534bool MonotonicDurationHelper(SystemState* system_state,
1535 int64_t* storage,
1536 base::TimeDelta* out_duration) {
1537 bool ret = false;
1538
1539 base::Time now = system_state->clock()->GetMonotonicTime();
1540 if (*storage != 0) {
1541 base::Time stored_time = base::Time::FromInternalValue(*storage);
1542 *out_duration = now - stored_time;
1543 ret = true;
1544 }
1545 *storage = now.ToInternalValue();
1546
1547 return ret;
1548}
1549
adlr@google.com3defe6a2009-12-04 20:57:17 +00001550} // namespace utils
1551
1552} // namespace chromeos_update_engine