blob: f69dab4f44eee465ff0886ee6e69e13f2536cfc7 [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>
11#include <errno.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080012#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000013#include <stdio.h>
14#include <stdlib.h>
15#include <string.h>
Alex Deymoc4acdf42014-05-28 21:07:10 -070016#include <sys/mount.h>
17#include <sys/resource.h>
18#include <sys/stat.h>
19#include <sys/types.h>
20#include <sys/wait.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000021#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070022
adlr@google.com3defe6a2009-12-04 20:57:17 +000023#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070024#include <utility>
Chris Sosac1972482013-04-30 22:31:10 -070025#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070026
Will Drewry8f71da82010-08-30 14:07:11 -050027#include <base/file_util.h>
Ben Chan736fcb52014-05-21 18:28:22 -070028#include <base/files/file_path.h>
29#include <base/files/scoped_file.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040030#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080031#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050032#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070033#include <base/strings/string_number_conversions.h>
34#include <base/strings/string_split.h>
35#include <base/strings/string_util.h>
36#include <base/strings/stringprintf.h>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080037#include <glib.h>
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -080038#include <google/protobuf/stubs/common.h>
Will Drewry8f71da82010-08-30 14:07:11 -050039
David Zeuthen33bae492014-02-25 16:16:18 -080040#include "update_engine/clock_interface.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070041#include "update_engine/constants.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080042#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070043#include "update_engine/omaha_request_params.h"
David Zeuthen33bae492014-02-25 16:16:18 -080044#include "update_engine/prefs_interface.h"
Darin Petkov296889c2010-07-23 16:20:54 -070045#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080046#include "update_engine/system_state.h"
47#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000048
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070049using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080050using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000051using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070052using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000053using std::string;
54using std::vector;
55
56namespace chromeos_update_engine {
57
Ben Chan77a1eba2012-10-07 22:54:55 -070058namespace {
59
60// The following constants control how UnmountFilesystem should retry if
61// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
62// one second.
63const int kUnmountMaxNumOfRetries = 5;
64const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070065
66// Number of bytes to read from a file to attempt to detect its contents. Used
67// in GetFileFormat.
68const int kGetFileFormatMaxHeaderSize = 32;
69
Ben Chan77a1eba2012-10-07 22:54:55 -070070} // namespace
71
adlr@google.com3defe6a2009-12-04 20:57:17 +000072namespace utils {
73
Chris Sosa4f8ee272012-11-30 13:01:54 -080074// Cgroup container is created in update-engine's upstart script located at
75// /etc/init/update-engine.conf.
76static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
77
J. Richard Barnette63137e52013-10-28 10:57:29 -070078string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -070079 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -070080
Alex Vakulenko75039d72014-03-25 12:36:28 -070081 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -070082 // a vector of key value pairs.
83 vector<pair<string, string> > kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -070084 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Chris Sosac1972482013-04-30 22:31:10 -070085 for (vector<pair<string, string> >::iterator it = kv_pairs.begin();
86 it != kv_pairs.end(); ++it) {
87 // Finally match against the fw_verion which may have quotes.
88 if (it->first == "fw_version") {
89 string output;
90 // Trim any quotes.
Alex Vakulenko75039d72014-03-25 12:36:28 -070091 base::TrimString(it->second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -070092 return output;
93 }
94 }
95 }
96 LOG(ERROR) << "Unable to parse fwid from ec info.";
97 return "";
98}
99
100
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700101const string KernelDeviceOfBootDevice(const string& boot_device) {
102 string kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700103
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700104 string disk_name;
105 int partition_num;
106 if (SplitPartitionName(boot_device, &disk_name, &partition_num)) {
107 if (disk_name == "/dev/ubiblock") {
108 // Special case for NAND devices.
109 // eg: /dev/ubiblock3_0 becomes /dev/mtdblock2
110 disk_name = "/dev/mtdblock";
111 }
112 // Currently this assumes the partition number of the boot device is
113 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
114 // get the kernel device.
115 if (partition_num == 3 || partition_num == 5 || partition_num == 7) {
116 kernel_partition_name = MakePartitionName(disk_name, partition_num - 1);
117 }
J. Richard Barnette30842932013-10-28 15:04:23 -0700118 }
119
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700120 return kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700121}
122
123
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800124bool WriteFile(const char* path, const char* data, int data_len) {
125 DirectFileWriter writer;
126 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
127 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700128 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800129 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800130 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800131 return true;
132}
133
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700134bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700135 const char* c_buf = static_cast<const char*>(buf);
136 ssize_t bytes_written = 0;
137 while (bytes_written < static_cast<ssize_t>(count)) {
138 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
139 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
140 bytes_written += rc;
141 }
142 return true;
143}
144
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700145bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
146 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700147 size_t bytes_written = 0;
148 int num_attempts = 0;
149 while (bytes_written < count) {
150 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700151 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
152 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700153 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
154 if (rc < 0) {
155 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
156 << " bytes_written=" << bytes_written
157 << " count=" << count << " offset=" << offset;
158 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700159 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
160 bytes_written += rc;
161 }
162 return true;
163}
164
165bool PReadAll(int fd, void* buf, size_t count, off_t offset,
166 ssize_t* out_bytes_read) {
167 char* c_buf = static_cast<char*>(buf);
168 ssize_t bytes_read = 0;
169 while (bytes_read < static_cast<ssize_t>(count)) {
170 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
171 offset + bytes_read);
172 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
173 if (rc == 0) {
174 break;
175 }
176 bytes_read += rc;
177 }
178 *out_bytes_read = bytes_read;
179 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700180}
181
Gilad Arnold19a45f02012-07-19 12:36:10 -0700182// Append |nbytes| of content from |buf| to the vector pointed to by either
183// |vec_p| or |str_p|.
184static void AppendBytes(const char* buf, size_t nbytes,
185 std::vector<char>* vec_p) {
186 CHECK(buf);
187 CHECK(vec_p);
188 vec_p->insert(vec_p->end(), buf, buf + nbytes);
189}
190static void AppendBytes(const char* buf, size_t nbytes,
191 std::string* str_p) {
192 CHECK(buf);
193 CHECK(str_p);
194 str_p->append(buf, nbytes);
195}
196
197// Reads from an open file |fp|, appending the read content to the container
198// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200199// file's content, false otherwise. If |size| is not -1, reads up to |size|
200// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700201template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200202static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700203 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200204 CHECK(size == -1 || size >= 0);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700205 char buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200206 while (size == -1 || size > 0) {
207 off_t bytes_to_read = sizeof(buf);
208 if (size > 0 && bytes_to_read > size) {
209 bytes_to_read = size;
210 }
211 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
212 if (!nbytes) {
213 break;
214 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700215 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200216 if (size != -1) {
217 CHECK(size >= static_cast<off_t>(nbytes));
218 size -= nbytes;
219 }
220 }
221 if (ferror(fp)) {
222 return false;
223 }
224 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700225}
226
Darin Petkov8e447e02013-04-16 16:23:50 +0200227// Opens a file |path| for reading and appends its the contents to a container
228// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
229// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700230template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200231static bool ReadFileChunkAndAppend(const std::string& path,
232 off_t offset,
233 off_t size,
234 T* out_p) {
235 CHECK_GE(offset, 0);
236 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700237 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200238 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000239 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200240 if (offset) {
241 // Return success without appending any data if a chunk beyond the end of
242 // the file is requested.
243 if (offset >= FileSize(path)) {
244 return true;
245 }
246 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
247 }
248 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000249}
250
Gilad Arnold19a45f02012-07-19 12:36:10 -0700251// Invokes a pipe |cmd|, then uses |append_func| to append its stdout to a
252// container |out_p|.
253template <class T>
254static bool ReadPipeAndAppend(const std::string& cmd, T* out_p) {
255 FILE* fp = popen(cmd.c_str(), "r");
256 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000257 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200258 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700259 return (success && pclose(fp) >= 0);
260}
261
262
Darin Petkov8e447e02013-04-16 16:23:50 +0200263bool ReadFile(const string& path, vector<char>* out_p) {
264 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700265}
266
Darin Petkov8e447e02013-04-16 16:23:50 +0200267bool ReadFile(const string& path, string* out_p) {
268 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700269}
270
Darin Petkov8e447e02013-04-16 16:23:50 +0200271bool ReadFileChunk(const string& path, off_t offset, off_t size,
272 vector<char>* out_p) {
273 return ReadFileChunkAndAppend(path, offset, size, out_p);
274}
275
276bool ReadPipe(const string& cmd, vector<char>* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700277 return ReadPipeAndAppend(cmd, out_p);
278}
279
Darin Petkov8e447e02013-04-16 16:23:50 +0200280bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700281 return ReadPipeAndAppend(cmd, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000282}
283
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700284off_t FileSize(const string& path) {
285 struct stat stbuf;
286 int rc = stat(path.c_str(), &stbuf);
287 CHECK_EQ(rc, 0);
288 if (rc < 0)
289 return rc;
290 return stbuf.st_size;
291}
292
adlr@google.com3defe6a2009-12-04 20:57:17 +0000293void HexDumpArray(const unsigned char* const arr, const size_t length) {
294 const unsigned char* const char_arr =
295 reinterpret_cast<const unsigned char* const>(arr);
296 LOG(INFO) << "Logging array of length: " << length;
297 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700298 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000299 const unsigned int bytes_remaining = length - i;
300 const unsigned int bytes_per_this_line = min(bytes_per_line,
301 bytes_remaining);
302 char header[100];
303 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
304 TEST_AND_RETURN(r == 13);
305 string line = header;
306 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
307 char buf[20];
308 unsigned char c = char_arr[i + j];
309 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
310 TEST_AND_RETURN(r == 3);
311 line += buf;
312 }
313 LOG(INFO) << line;
314 }
315}
316
317namespace {
318class ScopedDirCloser {
319 public:
320 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
321 ~ScopedDirCloser() {
322 if (dir_ && *dir_) {
323 int r = closedir(*dir_);
324 TEST_AND_RETURN_ERRNO(r == 0);
325 *dir_ = NULL;
326 dir_ = NULL;
327 }
328 }
329 private:
330 DIR** dir_;
331};
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700332} // namespace
adlr@google.com3defe6a2009-12-04 20:57:17 +0000333
334bool RecursiveUnlinkDir(const std::string& path) {
335 struct stat stbuf;
336 int r = lstat(path.c_str(), &stbuf);
337 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
338 if ((r < 0) && (errno == ENOENT))
339 // path request is missing. that's fine.
340 return true;
341 if (!S_ISDIR(stbuf.st_mode)) {
342 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700343 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000344 // success or path disappeared before we could unlink.
345 return true;
346 }
347 {
348 // We have a dir, unlink all children, then delete dir
349 DIR *dir = opendir(path.c_str());
350 TEST_AND_RETURN_FALSE_ERRNO(dir);
351 ScopedDirCloser dir_closer(&dir);
352 struct dirent dir_entry;
353 struct dirent *dir_entry_p;
354 int err = 0;
355 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
356 if (dir_entry_p == NULL) {
357 // end of stream reached
358 break;
359 }
360 // Skip . and ..
361 if (!strcmp(dir_entry_p->d_name, ".") ||
362 !strcmp(dir_entry_p->d_name, ".."))
363 continue;
364 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700365 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000366 }
367 TEST_AND_RETURN_FALSE(err == 0);
368 }
369 // unlink dir
370 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
371 return true;
372}
373
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800374std::string GetDiskName(const string& partition_name) {
375 std::string disk_name;
376 return SplitPartitionName(partition_name, &disk_name, nullptr) ?
377 disk_name : std::string();
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700378}
379
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800380int GetPartitionNumber(const std::string& partition_name) {
381 int partition_num = 0;
382 return SplitPartitionName(partition_name, nullptr, &partition_num) ?
383 partition_num : 0;
384}
385
386bool SplitPartitionName(const std::string& partition_name,
387 std::string* out_disk_name,
388 int* out_partition_num) {
389 if (!StringHasPrefix(partition_name, "/dev/")) {
390 LOG(ERROR) << "Invalid partition device name: " << partition_name;
391 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700392 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800393
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700394 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
395 if (last_nondigit_pos == string::npos ||
396 (last_nondigit_pos + 1) == partition_name.size()) {
397 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800398 return false;
399 }
400
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700401 size_t partition_name_len = std::string::npos;
402 if (partition_name[last_nondigit_pos] == '_') {
403 // NAND block devices have weird naming which could be something
404 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
405 size_t prev_nondigit_pos =
406 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
407 if (prev_nondigit_pos == string::npos ||
408 (prev_nondigit_pos + 1) == last_nondigit_pos) {
409 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
410 return false;
411 }
412
413 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
414 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800415 }
416
417 if (out_disk_name) {
418 // Special case for MMC devices which have the following naming scheme:
419 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700420 size_t disk_name_len = last_nondigit_pos;
421 if (partition_name[last_nondigit_pos] != 'p' ||
422 last_nondigit_pos == 0 ||
423 !isdigit(partition_name[last_nondigit_pos - 1])) {
424 disk_name_len++;
425 }
426 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800427 }
428
429 if (out_partition_num) {
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700430 std::string partition_str = partition_name.substr(last_nondigit_pos + 1,
431 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800432 *out_partition_num = atoi(partition_str.c_str());
433 }
434 return true;
435}
436
437std::string MakePartitionName(const std::string& disk_name,
438 int partition_num) {
439 if (!StringHasPrefix(disk_name, "/dev/")) {
440 LOG(ERROR) << "Invalid disk name: " << disk_name;
441 return std::string();
442 }
443
444 if (partition_num < 1) {
445 LOG(ERROR) << "Invalid partition number: " << partition_num;
446 return std::string();
447 }
448
449 std::string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700450 if (isdigit(partition_name.back())) {
451 // Special case for devices with names ending with a digit.
452 // Add "p" to separate the disk name from partition number,
453 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800454 partition_name += 'p';
455 }
456
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700457 partition_name += std::to_string(partition_num);
458
459 if (StringHasPrefix(partition_name, "/dev/ubiblock")) {
460 // Special case for UBI block devieces that have "_0" suffix.
461 partition_name += "_0";
462 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800463 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700464}
465
Darin Petkovf74eb652010-08-04 12:08:38 -0700466string SysfsBlockDevice(const string& device) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700467 base::FilePath device_path(device);
Darin Petkovf74eb652010-08-04 12:08:38 -0700468 if (device_path.DirName().value() != "/dev") {
469 return "";
470 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700471 return base::FilePath("/sys/block").Append(device_path.BaseName()).value();
Darin Petkovf74eb652010-08-04 12:08:38 -0700472}
473
474bool IsRemovableDevice(const std::string& device) {
475 string sysfs_block = SysfsBlockDevice(device);
476 string removable;
477 if (sysfs_block.empty() ||
Alex Vakulenko75039d72014-03-25 12:36:28 -0700478 !base::ReadFileToString(base::FilePath(sysfs_block).Append("removable"),
Ben Chan736fcb52014-05-21 18:28:22 -0700479 &removable)) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700480 return false;
481 }
Ben Chan736fcb52014-05-21 18:28:22 -0700482 base::TrimWhitespaceASCII(removable, base::TRIM_ALL, &removable);
Darin Petkovf74eb652010-08-04 12:08:38 -0700483 return removable == "1";
484}
485
adlr@google.com3defe6a2009-12-04 20:57:17 +0000486std::string ErrnoNumberAsString(int err) {
487 char buf[100];
488 buf[0] = '\0';
489 return strerror_r(err, buf, sizeof(buf));
490}
491
492std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
493 string ret;
494 bool last_insert_was_slash = false;
495 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
496 if (*it == '/') {
497 if (last_insert_was_slash)
498 continue;
499 last_insert_was_slash = true;
500 } else {
501 last_insert_was_slash = false;
502 }
503 ret.push_back(*it);
504 }
505 if (strip_trailing_slash && last_insert_was_slash) {
506 string::size_type last_non_slash = ret.find_last_not_of('/');
507 if (last_non_slash != string::npos) {
508 ret.resize(last_non_slash + 1);
509 } else {
510 ret = "";
511 }
512 }
513 return ret;
514}
515
516bool FileExists(const char* path) {
517 struct stat stbuf;
518 return 0 == lstat(path, &stbuf);
519}
520
Darin Petkov30291ed2010-11-12 10:23:06 -0800521bool IsSymlink(const char* path) {
522 struct stat stbuf;
523 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
524}
525
Alex Deymo7dc4c502014-05-20 20:09:58 -0700526bool IsDir(const char* path) {
527 struct stat stbuf;
528 TEST_AND_RETURN_FALSE_ERRNO(lstat(path, &stbuf) == 0);
529 return S_ISDIR(stbuf.st_mode);
530}
531
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800532// If |path| is absolute, or explicit relative to the current working directory,
533// leaves it as is. Otherwise, if TMPDIR is defined in the environment and is
534// non-empty, prepends it to |path|. Otherwise, prepends /tmp. Returns the
535// resulting path.
536static const string PrependTmpdir(const string& path) {
537 if (path[0] == '/' || StartsWithASCII(path, "./", true) ||
538 StartsWithASCII(path, "../", true))
539 return path;
540
541 const char *tmpdir = getenv("TMPDIR");
542 const string prefix = (tmpdir && *tmpdir ? tmpdir : "/tmp");
543 return prefix + "/" + path;
544}
545
546bool MakeTempFile(const std::string& base_filename_template,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700547 std::string* filename,
548 int* fd) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800549 const string filename_template = PrependTmpdir(base_filename_template);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700550 DCHECK(filename || fd);
551 vector<char> buf(filename_template.size() + 1);
552 memcpy(&buf[0], filename_template.data(), filename_template.size());
553 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700554
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700555 int mkstemp_fd = mkstemp(&buf[0]);
556 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
557 if (filename) {
558 *filename = &buf[0];
559 }
560 if (fd) {
561 *fd = mkstemp_fd;
562 } else {
563 close(mkstemp_fd);
564 }
565 return true;
566}
567
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800568bool MakeTempDirectory(const std::string& base_dirname_template,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700569 std::string* dirname) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800570 const string dirname_template = PrependTmpdir(base_dirname_template);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700571 DCHECK(dirname);
572 vector<char> buf(dirname_template.size() + 1);
573 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
574 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700575
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700576 char* return_code = mkdtemp(&buf[0]);
577 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
578 *dirname = &buf[0];
579 return true;
580}
581
adlr@google.com3defe6a2009-12-04 20:57:17 +0000582bool StringHasSuffix(const std::string& str, const std::string& suffix) {
583 if (suffix.size() > str.size())
584 return false;
585 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
586}
587
588bool StringHasPrefix(const std::string& str, const std::string& prefix) {
589 if (prefix.size() > str.size())
590 return false;
591 return 0 == str.compare(0, prefix.size(), prefix);
592}
593
adlr@google.com3defe6a2009-12-04 20:57:17 +0000594bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700595 const string& mountpoint,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700596 unsigned long mountflags) { // NOLINT(runtime/int)
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700597 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000598 if (rc < 0) {
599 string msg = ErrnoNumberAsString(errno);
600 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
601 << device << " on " << mountpoint;
602 return false;
603 }
604 return true;
605}
606
607bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700608 for (int num_retries = 0; ; ++num_retries) {
609 if (umount(mountpoint.c_str()) == 0)
610 break;
611
612 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
613 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800614 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700615 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000616 return true;
617}
618
Darin Petkovd3f8c892010-10-12 21:38:45 -0700619bool GetFilesystemSize(const std::string& device,
620 int* out_block_count,
621 int* out_block_size) {
622 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
623 TEST_AND_RETURN_FALSE(fd >= 0);
624 ScopedFdCloser fd_closer(&fd);
625 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
626}
627
628bool GetFilesystemSizeFromFD(int fd,
629 int* out_block_count,
630 int* out_block_size) {
631 TEST_AND_RETURN_FALSE(fd >= 0);
632
633 // Determine the ext3 filesystem size by directly reading the block count and
634 // block size information from the superblock. See include/linux/ext3_fs.h for
635 // more details on the structure.
636 ssize_t kBufferSize = 16 * sizeof(uint32_t);
637 char buffer[kBufferSize];
638 const int kSuperblockOffset = 1024;
639 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
640 kBufferSize) {
641 PLOG(ERROR) << "Unable to determine file system size:";
642 return false;
643 }
644 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
645 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
646 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
647 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
648 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
649 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
650 block_count = le32toh(block_count);
651 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
652 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
653 magic = le16toh(magic);
654
655 // Sanity check the parameters.
656 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
657 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
658 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
659 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
660 int block_size = 1 << log_block_size;
661 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
662 block_size <= kExt3MaxBlockSize);
663 TEST_AND_RETURN_FALSE(block_count > 0);
664
665 if (out_block_count) {
666 *out_block_count = block_count;
667 }
668 if (out_block_size) {
669 *out_block_size = block_size;
670 }
671 return true;
672}
673
Alex Deymo719bfff2014-07-11 12:12:32 -0700674string GetPathOnBoard(const string& command) {
675 int return_code = 0;
676 string command_path;
677 // TODO(deymo): prepend SYSROOT to each PATH instead of the result.
678 if (!Subprocess::SynchronousExec(
679 {"which", command}, &return_code, &command_path)) {
680 return command;
681 }
682 if (return_code != 0)
683 return command;
684
685 base::TrimWhitespaceASCII(command_path, base::TRIM_ALL, &command_path);
686 const char* env_sysroot = getenv("SYSROOT");
687 if (env_sysroot) {
688 string sysroot_command_path = env_sysroot + command_path;
689 if (utils::FileExists(sysroot_command_path.c_str()))
690 return sysroot_command_path;
691 }
692 return command_path;
693}
694
Alex Deymo032e7722014-03-25 17:53:56 -0700695// Tries to parse the header of an ELF file to obtain a human-readable
696// description of it on the |output| string.
697static bool GetFileFormatELF(const char* buffer, size_t size, string* output) {
698 // 0x00: EI_MAG - ELF magic header, 4 bytes.
699 if (size < 4 || memcmp(buffer, "\x7F""ELF", 4) != 0)
700 return false;
701 *output = "ELF";
702
703 // 0x04: EI_CLASS, 1 byte.
704 if (size < 0x04 + 1)
705 return true;
706 switch (buffer[4]) {
707 case 1:
708 *output += " 32-bit";
709 break;
710 case 2:
711 *output += " 64-bit";
712 break;
713 default:
714 *output += " ?-bit";
715 }
716
717 // 0x05: EI_DATA, endianness, 1 byte.
718 if (size < 0x05 + 1)
719 return true;
720 char ei_data = buffer[5];
721 switch (ei_data) {
722 case 1:
723 *output += " little-endian";
724 break;
725 case 2:
726 *output += " big-endian";
727 break;
728 default:
729 *output += " ?-endian";
730 // Don't parse anything after the 0x10 offset if endianness is unknown.
731 return true;
732 }
733
734 // 0x12: e_machine, 2 byte endianness based on ei_data
735 if (size < 0x12 + 2)
736 return true;
Ben Chan9abb7632014-08-07 00:10:53 -0700737 uint16_t e_machine = *reinterpret_cast<const uint16_t*>(buffer+0x12);
Alex Deymo032e7722014-03-25 17:53:56 -0700738 // Fix endianess regardless of the host endianess.
739 if (ei_data == 1)
740 e_machine = le16toh(e_machine);
741 else
742 e_machine = be16toh(e_machine);
743
744 switch (e_machine) {
745 case 0x03:
746 *output += " x86";
747 break;
748 case 0x28:
749 *output += " arm";
750 break;
751 case 0x3E:
752 *output += " x86-64";
753 break;
754 default:
755 *output += " unknown-arch";
756 }
757 return true;
758}
759
760string GetFileFormat(const string& path) {
761 vector<char> buffer;
762 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
763 return "File not found.";
764
765 string result;
766 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
767 return result;
768
769 return "data";
770}
771
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700772bool GetBootloader(BootLoader* out_bootloader) {
773 // For now, hardcode to syslinux.
774 *out_bootloader = BootLoader_SYSLINUX;
775 return true;
776}
777
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800778namespace {
779// Do the actual trigger. We do it as a main-loop callback to (try to) get a
780// consistent stack trace.
781gboolean TriggerCrashReporterUpload(void* unused) {
782 pid_t pid = fork();
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700783 CHECK_GE(pid, 0) << "fork failed"; // fork() failed. Something is very wrong.
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800784 if (pid == 0) {
785 // We are the child. Crash.
786 abort(); // never returns
787 }
788 // We are the parent. Wait for child to terminate.
789 pid_t result = waitpid(pid, NULL, 0);
790 LOG_IF(ERROR, result < 0) << "waitpid() failed";
791 return FALSE; // Don't call this callback again
792}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700793} // namespace
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800794
795void ScheduleCrashReporterUpload() {
796 g_idle_add(&TriggerCrashReporterUpload, NULL);
797}
798
Chris Sosa4f8ee272012-11-30 13:01:54 -0800799bool SetCpuShares(CpuShares shares) {
800 string string_shares = base::IntToString(static_cast<int>(shares));
801 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
802 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700803 if (utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
804 string_shares.size())) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800805 return true;
806 } else {
807 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
808 << " using " << cpu_shares_file;
809 return false;
810 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700811}
812
Chris Sosa4f8ee272012-11-30 13:01:54 -0800813int CompareCpuShares(CpuShares shares_lhs,
814 CpuShares shares_rhs) {
815 return static_cast<int>(shares_lhs) - static_cast<int>(shares_rhs);
Darin Petkovc6c135c2010-08-11 13:36:18 -0700816}
817
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700818int FuzzInt(int value, unsigned int range) {
819 int min = value - range / 2;
820 int max = value + range - range / 2;
821 return base::RandInt(min, max);
822}
823
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800824gboolean GlibRunClosure(gpointer data) {
825 google::protobuf::Closure* callback =
826 reinterpret_cast<google::protobuf::Closure*>(data);
827 callback->Run();
828 return FALSE;
829}
830
Alex Deymoc4acdf42014-05-28 21:07:10 -0700831void GlibDestroyClosure(gpointer data) {
832 delete reinterpret_cast<google::protobuf::Closure*>(data);
833}
834
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700835string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800836 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700837}
838
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800839string FormatTimeDelta(TimeDelta delta) {
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700840 // Canonicalize into days, hours, minutes, seconds and microseconds.
841 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800842 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700843 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800844 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700845 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800846 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700847 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800848 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700849 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800850
851 // Construct and return string.
852 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700853 if (days)
854 base::StringAppendF(&str, "%ud", days);
855 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800856 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700857 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800858 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700859 base::StringAppendF(&str, "%u", secs);
860 if (usecs) {
861 int width = 6;
862 while ((usecs / 10) * 10 == usecs) {
863 usecs /= 10;
864 width--;
865 }
866 base::StringAppendF(&str, ".%0*u", width, usecs);
867 }
868 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800869 return str;
870}
871
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700872string ToString(const Time utc_time) {
873 Time::Exploded exp_time;
874 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700875 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700876 exp_time.month,
877 exp_time.day_of_month,
878 exp_time.year,
879 exp_time.hour,
880 exp_time.minute,
881 exp_time.second);
882}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000883
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700884string ToString(bool b) {
885 return (b ? "true" : "false");
886}
887
Alex Deymo1c656c42013-06-28 11:02:14 -0700888string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700889 switch (source) {
890 case kDownloadSourceHttpsServer: return "HttpsServer";
891 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700892 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700893 case kNumDownloadSources: return "Unknown";
894 // Don't add a default case to let the compiler warn about newly added
895 // download sources which should be added here.
896 }
897
898 return "Unknown";
899}
900
Alex Deymo1c656c42013-06-28 11:02:14 -0700901string ToString(PayloadType payload_type) {
902 switch (payload_type) {
903 case kPayloadTypeDelta: return "Delta";
904 case kPayloadTypeFull: return "Full";
905 case kPayloadTypeForcedFull: return "ForcedFull";
906 case kNumPayloadTypes: return "Unknown";
907 // Don't add a default case to let the compiler warn about newly added
908 // payload types which should be added here.
909 }
910
911 return "Unknown";
912}
913
David Zeuthena99981f2013-04-29 13:42:47 -0700914ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700915 // Ignore the higher order bits in the code by applying the mask as
916 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700917 // with values less than ErrorCode::kUmaReportedMax.
918 ErrorCode base_code = static_cast<ErrorCode>(
919 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700920
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800921 // Make additional adjustments required for UMA and error classification.
922 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
923 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700924 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700925 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800926 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800927 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700928 << " to ErrorCode::kOmahaErrorInHTTPResponse";
929 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700930 }
931
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800932 return base_code;
933}
934
David Zeuthen33bae492014-02-25 16:16:18 -0800935metrics::AttemptResult GetAttemptResult(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700936 ErrorCode base_code = static_cast<ErrorCode>(
937 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -0800938
939 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700940 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -0800941 return metrics::AttemptResult::kUpdateSucceeded;
942
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700943 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -0800944 return metrics::AttemptResult::kPayloadDownloadError;
945
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700946 case ErrorCode::kDownloadInvalidMetadataSize:
947 case ErrorCode::kDownloadInvalidMetadataMagicString:
948 case ErrorCode::kDownloadMetadataSignatureError:
949 case ErrorCode::kDownloadMetadataSignatureVerificationError:
950 case ErrorCode::kPayloadMismatchedType:
951 case ErrorCode::kUnsupportedMajorPayloadVersion:
952 case ErrorCode::kUnsupportedMinorPayloadVersion:
953 case ErrorCode::kDownloadNewPartitionInfoError:
954 case ErrorCode::kDownloadSignatureMissingInManifest:
955 case ErrorCode::kDownloadManifestParseError:
956 case ErrorCode::kDownloadOperationHashMissingError:
David Zeuthen33bae492014-02-25 16:16:18 -0800957 return metrics::AttemptResult::kMetadataMalformed;
958
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700959 case ErrorCode::kDownloadOperationHashMismatch:
960 case ErrorCode::kDownloadOperationHashVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -0800961 return metrics::AttemptResult::kOperationMalformed;
962
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700963 case ErrorCode::kDownloadOperationExecutionError:
964 case ErrorCode::kInstallDeviceOpenError:
965 case ErrorCode::kKernelDeviceOpenError:
966 case ErrorCode::kDownloadWriteError:
967 case ErrorCode::kFilesystemCopierError:
David Zeuthen33bae492014-02-25 16:16:18 -0800968 return metrics::AttemptResult::kOperationExecutionError;
969
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700970 case ErrorCode::kDownloadMetadataSignatureMismatch:
David Zeuthen33bae492014-02-25 16:16:18 -0800971 return metrics::AttemptResult::kMetadataVerificationFailed;
972
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700973 case ErrorCode::kPayloadSizeMismatchError:
974 case ErrorCode::kPayloadHashMismatchError:
975 case ErrorCode::kDownloadPayloadVerificationError:
976 case ErrorCode::kSignedDeltaPayloadExpectedError:
977 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -0800978 return metrics::AttemptResult::kPayloadVerificationFailed;
979
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700980 case ErrorCode::kNewRootfsVerificationError:
981 case ErrorCode::kNewKernelVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -0800982 return metrics::AttemptResult::kVerificationFailed;
983
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700984 case ErrorCode::kPostinstallRunnerError:
985 case ErrorCode::kPostinstallBootedFromFirmwareB:
986 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
David Zeuthen33bae492014-02-25 16:16:18 -0800987 return metrics::AttemptResult::kPostInstallFailed;
988
989 // We should never get these errors in the update-attempt stage so
990 // return internal error if this happens.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700991 case ErrorCode::kError:
992 case ErrorCode::kOmahaRequestXMLParseError:
993 case ErrorCode::kOmahaRequestError:
994 case ErrorCode::kOmahaResponseHandlerError:
995 case ErrorCode::kDownloadStateInitializationError:
996 case ErrorCode::kOmahaRequestEmptyResponseError:
997 case ErrorCode::kDownloadInvalidMetadataSignature:
998 case ErrorCode::kOmahaResponseInvalid:
999 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1000 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1001 case ErrorCode::kOmahaErrorInHTTPResponse:
1002 case ErrorCode::kDownloadMetadataSignatureMissingError:
1003 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1004 case ErrorCode::kPostinstallPowerwashError:
1005 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthen33bae492014-02-25 16:16:18 -08001006 return metrics::AttemptResult::kInternalError;
1007
1008 // Special flags. These can't happen (we mask them out above) but
1009 // the compiler doesn't know that. Just break out so we can warn and
1010 // return |kInternalError|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001011 case ErrorCode::kUmaReportedMax:
1012 case ErrorCode::kOmahaRequestHTTPResponseBase:
1013 case ErrorCode::kDevModeFlag:
1014 case ErrorCode::kResumedFlag:
1015 case ErrorCode::kTestImageFlag:
1016 case ErrorCode::kTestOmahaUrlFlag:
1017 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001018 break;
1019 }
1020
1021 LOG(ERROR) << "Unexpected error code " << base_code;
1022 return metrics::AttemptResult::kInternalError;
1023}
1024
1025
1026metrics::DownloadErrorCode GetDownloadErrorCode(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001027 ErrorCode base_code = static_cast<ErrorCode>(
1028 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001029
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001030 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
1031 int http_status =
1032 static_cast<int>(base_code) -
1033 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase);
David Zeuthen33bae492014-02-25 16:16:18 -08001034 if (http_status >= 200 && http_status <= 599) {
1035 return static_cast<metrics::DownloadErrorCode>(
1036 static_cast<int>(metrics::DownloadErrorCode::kHttpStatus200) +
1037 http_status - 200);
1038 } else if (http_status == 0) {
1039 // The code is using HTTP Status 0 for "Unable to get http
1040 // response code."
1041 return metrics::DownloadErrorCode::kDownloadError;
1042 }
1043 LOG(WARNING) << "Unexpected HTTP status code " << http_status;
1044 return metrics::DownloadErrorCode::kHttpStatusOther;
1045 }
1046
1047 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001048 // Unfortunately, ErrorCode::kDownloadTransferError is returned for a wide
David Zeuthen33bae492014-02-25 16:16:18 -08001049 // variety of errors (proxy errors, host not reachable, timeouts etc.).
1050 //
1051 // For now just map that to kDownloading. See http://crbug.com/355745
1052 // for how we plan to add more detail in the future.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001053 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001054 return metrics::DownloadErrorCode::kDownloadError;
1055
1056 // All of these error codes are not related to downloading so break
1057 // out so we can warn and return InputMalformed.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001058 case ErrorCode::kSuccess:
1059 case ErrorCode::kError:
1060 case ErrorCode::kOmahaRequestError:
1061 case ErrorCode::kOmahaResponseHandlerError:
1062 case ErrorCode::kFilesystemCopierError:
1063 case ErrorCode::kPostinstallRunnerError:
1064 case ErrorCode::kPayloadMismatchedType:
1065 case ErrorCode::kInstallDeviceOpenError:
1066 case ErrorCode::kKernelDeviceOpenError:
1067 case ErrorCode::kPayloadHashMismatchError:
1068 case ErrorCode::kPayloadSizeMismatchError:
1069 case ErrorCode::kDownloadPayloadVerificationError:
1070 case ErrorCode::kDownloadNewPartitionInfoError:
1071 case ErrorCode::kDownloadWriteError:
1072 case ErrorCode::kNewRootfsVerificationError:
1073 case ErrorCode::kNewKernelVerificationError:
1074 case ErrorCode::kSignedDeltaPayloadExpectedError:
1075 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1076 case ErrorCode::kPostinstallBootedFromFirmwareB:
1077 case ErrorCode::kDownloadStateInitializationError:
1078 case ErrorCode::kDownloadInvalidMetadataMagicString:
1079 case ErrorCode::kDownloadSignatureMissingInManifest:
1080 case ErrorCode::kDownloadManifestParseError:
1081 case ErrorCode::kDownloadMetadataSignatureError:
1082 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1083 case ErrorCode::kDownloadMetadataSignatureMismatch:
1084 case ErrorCode::kDownloadOperationHashVerificationError:
1085 case ErrorCode::kDownloadOperationExecutionError:
1086 case ErrorCode::kDownloadOperationHashMismatch:
1087 case ErrorCode::kOmahaRequestEmptyResponseError:
1088 case ErrorCode::kOmahaRequestXMLParseError:
1089 case ErrorCode::kDownloadInvalidMetadataSize:
1090 case ErrorCode::kDownloadInvalidMetadataSignature:
1091 case ErrorCode::kOmahaResponseInvalid:
1092 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1093 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1094 case ErrorCode::kOmahaErrorInHTTPResponse:
1095 case ErrorCode::kDownloadOperationHashMissingError:
1096 case ErrorCode::kDownloadMetadataSignatureMissingError:
1097 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1098 case ErrorCode::kPostinstallPowerwashError:
1099 case ErrorCode::kUpdateCanceledByChannelChange:
1100 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1101 case ErrorCode::kUnsupportedMajorPayloadVersion:
1102 case ErrorCode::kUnsupportedMinorPayloadVersion:
David Zeuthen33bae492014-02-25 16:16:18 -08001103 break;
1104
1105 // Special flags. These can't happen (we mask them out above) but
1106 // the compiler doesn't know that. Just break out so we can warn and
1107 // return |kInputMalformed|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001108 case ErrorCode::kUmaReportedMax:
1109 case ErrorCode::kOmahaRequestHTTPResponseBase:
1110 case ErrorCode::kDevModeFlag:
1111 case ErrorCode::kResumedFlag:
1112 case ErrorCode::kTestImageFlag:
1113 case ErrorCode::kTestOmahaUrlFlag:
1114 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001115 LOG(ERROR) << "Unexpected error code " << base_code;
1116 break;
1117 }
1118
1119 return metrics::DownloadErrorCode::kInputMalformed;
1120}
1121
David Zeuthenb281f072014-04-02 10:20:19 -07001122metrics::ConnectionType GetConnectionType(
1123 NetworkConnectionType type,
1124 NetworkTethering tethering) {
1125 switch (type) {
1126 case kNetUnknown:
1127 return metrics::ConnectionType::kUnknown;
1128
1129 case kNetEthernet:
1130 if (tethering == NetworkTethering::kConfirmed)
1131 return metrics::ConnectionType::kTetheredEthernet;
1132 else
1133 return metrics::ConnectionType::kEthernet;
1134
1135 case kNetWifi:
1136 if (tethering == NetworkTethering::kConfirmed)
1137 return metrics::ConnectionType::kTetheredWifi;
1138 else
1139 return metrics::ConnectionType::kWifi;
1140
1141 case kNetWimax:
1142 return metrics::ConnectionType::kWimax;
1143
1144 case kNetBluetooth:
1145 return metrics::ConnectionType::kBluetooth;
1146
1147 case kNetCellular:
1148 return metrics::ConnectionType::kCellular;
1149 }
1150
1151 LOG(ERROR) << "Unexpected network connection type: type=" << type
1152 << ", tethering=" << static_cast<int>(tethering);
1153
1154 return metrics::ConnectionType::kUnknown;
1155}
1156
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001157// Returns a printable version of the various flags denoted in the higher order
1158// bits of the given code. Returns an empty string if none of those bits are
1159// set.
1160string GetFlagNames(uint32_t code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001161 uint32_t flags = (static_cast<uint32_t>(code) &
1162 static_cast<uint32_t>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001163 string flag_names;
1164 string separator = "";
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001165 for (size_t i = 0; i < sizeof(flags) * 8; i++) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001166 uint32_t flag = flags & (1 << i);
1167 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -07001168 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001169 separator = ", ";
1170 }
1171 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001172
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001173 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001174}
1175
David Zeuthena99981f2013-04-29 13:42:47 -07001176void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001177 if (!system_state)
1178 return;
1179
David Zeuthena99981f2013-04-29 13:42:47 -07001180 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001181
1182 // If the code doesn't have flags computed already, compute them now based on
1183 // the state of the current update attempt.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001184 uint32_t flags =
1185 static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001186 if (!flags)
1187 flags = system_state->update_attempter()->GetErrorCodeFlags();
1188
1189 // Determine the UMA bucket depending on the flags. But, ignore the resumed
1190 // flag, as it's perfectly normal for production devices to resume their
1191 // downloads and so we want to record those cases also in NormalErrorCodes
1192 // bucket.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001193 string metric =
1194 flags & ~static_cast<uint32_t>(ErrorCode::kResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001195 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
1196
1197 LOG(INFO) << "Sending error code " << uma_error_code
1198 << " (" << CodeToString(uma_error_code) << ")"
1199 << " to UMA metric: " << metric
1200 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
1201
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001202 system_state->metrics_lib()->SendEnumToUMA(
1203 metric, static_cast<int>(uma_error_code),
1204 static_cast<int>(ErrorCode::kUmaReportedMax));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001205}
1206
David Zeuthena99981f2013-04-29 13:42:47 -07001207string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001208 // If the given code has both parts (i.e. the error code part and the flags
1209 // part) then strip off the flags part since the switch statement below
1210 // has case statements only for the base error code or a single flag but
1211 // doesn't support any combinations of those.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001212 if ((static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags)) &&
1213 (static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags)))
1214 code = static_cast<ErrorCode>(
1215 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001216 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001217 case ErrorCode::kSuccess: return "ErrorCode::kSuccess";
1218 case ErrorCode::kError: return "ErrorCode::kError";
1219 case ErrorCode::kOmahaRequestError: return "ErrorCode::kOmahaRequestError";
1220 case ErrorCode::kOmahaResponseHandlerError:
1221 return "ErrorCode::kOmahaResponseHandlerError";
1222 case ErrorCode::kFilesystemCopierError:
1223 return "ErrorCode::kFilesystemCopierError";
1224 case ErrorCode::kPostinstallRunnerError:
1225 return "ErrorCode::kPostinstallRunnerError";
1226 case ErrorCode::kPayloadMismatchedType:
1227 return "ErrorCode::kPayloadMismatchedType";
1228 case ErrorCode::kInstallDeviceOpenError:
1229 return "ErrorCode::kInstallDeviceOpenError";
1230 case ErrorCode::kKernelDeviceOpenError:
1231 return "ErrorCode::kKernelDeviceOpenError";
1232 case ErrorCode::kDownloadTransferError:
1233 return "ErrorCode::kDownloadTransferError";
1234 case ErrorCode::kPayloadHashMismatchError:
1235 return "ErrorCode::kPayloadHashMismatchError";
1236 case ErrorCode::kPayloadSizeMismatchError:
1237 return "ErrorCode::kPayloadSizeMismatchError";
1238 case ErrorCode::kDownloadPayloadVerificationError:
1239 return "ErrorCode::kDownloadPayloadVerificationError";
1240 case ErrorCode::kDownloadNewPartitionInfoError:
1241 return "ErrorCode::kDownloadNewPartitionInfoError";
1242 case ErrorCode::kDownloadWriteError:
1243 return "ErrorCode::kDownloadWriteError";
1244 case ErrorCode::kNewRootfsVerificationError:
1245 return "ErrorCode::kNewRootfsVerificationError";
1246 case ErrorCode::kNewKernelVerificationError:
1247 return "ErrorCode::kNewKernelVerificationError";
1248 case ErrorCode::kSignedDeltaPayloadExpectedError:
1249 return "ErrorCode::kSignedDeltaPayloadExpectedError";
1250 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1251 return "ErrorCode::kDownloadPayloadPubKeyVerificationError";
1252 case ErrorCode::kPostinstallBootedFromFirmwareB:
1253 return "ErrorCode::kPostinstallBootedFromFirmwareB";
1254 case ErrorCode::kDownloadStateInitializationError:
1255 return "ErrorCode::kDownloadStateInitializationError";
1256 case ErrorCode::kDownloadInvalidMetadataMagicString:
1257 return "ErrorCode::kDownloadInvalidMetadataMagicString";
1258 case ErrorCode::kDownloadSignatureMissingInManifest:
1259 return "ErrorCode::kDownloadSignatureMissingInManifest";
1260 case ErrorCode::kDownloadManifestParseError:
1261 return "ErrorCode::kDownloadManifestParseError";
1262 case ErrorCode::kDownloadMetadataSignatureError:
1263 return "ErrorCode::kDownloadMetadataSignatureError";
1264 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1265 return "ErrorCode::kDownloadMetadataSignatureVerificationError";
1266 case ErrorCode::kDownloadMetadataSignatureMismatch:
1267 return "ErrorCode::kDownloadMetadataSignatureMismatch";
1268 case ErrorCode::kDownloadOperationHashVerificationError:
1269 return "ErrorCode::kDownloadOperationHashVerificationError";
1270 case ErrorCode::kDownloadOperationExecutionError:
1271 return "ErrorCode::kDownloadOperationExecutionError";
1272 case ErrorCode::kDownloadOperationHashMismatch:
1273 return "ErrorCode::kDownloadOperationHashMismatch";
1274 case ErrorCode::kOmahaRequestEmptyResponseError:
1275 return "ErrorCode::kOmahaRequestEmptyResponseError";
1276 case ErrorCode::kOmahaRequestXMLParseError:
1277 return "ErrorCode::kOmahaRequestXMLParseError";
1278 case ErrorCode::kDownloadInvalidMetadataSize:
1279 return "ErrorCode::kDownloadInvalidMetadataSize";
1280 case ErrorCode::kDownloadInvalidMetadataSignature:
1281 return "ErrorCode::kDownloadInvalidMetadataSignature";
1282 case ErrorCode::kOmahaResponseInvalid:
1283 return "ErrorCode::kOmahaResponseInvalid";
1284 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1285 return "ErrorCode::kOmahaUpdateIgnoredPerPolicy";
1286 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1287 return "ErrorCode::kOmahaUpdateDeferredPerPolicy";
1288 case ErrorCode::kOmahaErrorInHTTPResponse:
1289 return "ErrorCode::kOmahaErrorInHTTPResponse";
1290 case ErrorCode::kDownloadOperationHashMissingError:
1291 return "ErrorCode::kDownloadOperationHashMissingError";
1292 case ErrorCode::kDownloadMetadataSignatureMissingError:
1293 return "ErrorCode::kDownloadMetadataSignatureMissingError";
1294 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1295 return "ErrorCode::kOmahaUpdateDeferredForBackoff";
1296 case ErrorCode::kPostinstallPowerwashError:
1297 return "ErrorCode::kPostinstallPowerwashError";
1298 case ErrorCode::kUpdateCanceledByChannelChange:
1299 return "ErrorCode::kUpdateCanceledByChannelChange";
1300 case ErrorCode::kUmaReportedMax:
1301 return "ErrorCode::kUmaReportedMax";
1302 case ErrorCode::kOmahaRequestHTTPResponseBase:
1303 return "ErrorCode::kOmahaRequestHTTPResponseBase";
1304 case ErrorCode::kResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001305 return "Resumed";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001306 case ErrorCode::kDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001307 return "DevMode";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001308 case ErrorCode::kTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001309 return "TestImage";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001310 case ErrorCode::kTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001311 return "TestOmahaUrl";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001312 case ErrorCode::kSpecialFlags:
1313 return "ErrorCode::kSpecialFlags";
1314 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1315 return "ErrorCode::kPostinstallFirmwareRONotUpdatable";
1316 case ErrorCode::kUnsupportedMajorPayloadVersion:
1317 return "ErrorCode::kUnsupportedMajorPayloadVersion";
1318 case ErrorCode::kUnsupportedMinorPayloadVersion:
1319 return "ErrorCode::kUnsupportedMinorPayloadVersion";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001320 // Don't add a default case to let the compiler warn about newly added
1321 // error codes which should be added here.
1322 }
1323
1324 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1325}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001326
Gilad Arnold30dedd82013-07-03 06:19:09 -07001327bool CreatePowerwashMarkerFile(const char* file_path) {
1328 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1329 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001330 kPowerwashCommand,
1331 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001332 if (result) {
1333 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1334 } else {
1335 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1336 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001337
1338 return result;
1339}
1340
Gilad Arnold30dedd82013-07-03 06:19:09 -07001341bool DeletePowerwashMarkerFile(const char* file_path) {
1342 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001343 const base::FilePath kPowerwashMarkerPath(marker_file);
1344 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001345
1346 if (result)
1347 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001348 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001349 else
1350 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001351 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001352
1353 return result;
1354}
1355
Chris Sosad317e402013-06-12 13:47:09 -07001356bool GetInstallDev(const std::string& boot_dev, std::string* install_dev) {
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001357 std::string disk_name;
1358 int partition_num;
1359 if (!SplitPartitionName(boot_dev, &disk_name, &partition_num))
1360 return false;
Liam McLoughlin049d1652013-07-31 18:47:46 -07001361
Chris Sosad317e402013-06-12 13:47:09 -07001362 // Right now, we just switch '3' and '5' partition numbers.
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001363 if (partition_num == 3) {
1364 partition_num = 5;
1365 } else if (partition_num == 5) {
1366 partition_num = 3;
1367 } else {
1368 return false;
1369 }
1370
1371 if (install_dev)
1372 *install_dev = MakePartitionName(disk_name, partition_num);
Liam McLoughlin049d1652013-07-31 18:47:46 -07001373
Chris Sosad317e402013-06-12 13:47:09 -07001374 return true;
1375}
1376
David Zeuthen27a48bc2013-08-06 12:06:29 -07001377Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -07001378 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1379 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -07001380 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1381}
1382
1383gchar** StringVectorToGStrv(const vector<string> &vector) {
1384 GPtrArray *p = g_ptr_array_new();
1385 for (std::vector<string>::const_iterator i = vector.begin();
1386 i != vector.end(); ++i) {
1387 g_ptr_array_add(p, g_strdup(i->c_str()));
1388 }
1389 g_ptr_array_add(p, NULL);
1390 return reinterpret_cast<gchar**>(g_ptr_array_free(p, FALSE));
1391}
1392
1393string StringVectorToString(const vector<string> &vector) {
1394 string str = "[";
1395 for (std::vector<string>::const_iterator i = vector.begin();
1396 i != vector.end(); ++i) {
1397 if (i != vector.begin())
1398 str += ", ";
1399 str += '"';
1400 str += *i;
1401 str += '"';
1402 }
1403 str += "]";
1404 return str;
1405}
1406
David Zeuthen8f191b22013-08-06 12:27:50 -07001407string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
1408 string encoded_hash;
1409 OmahaHashCalculator::Base64Encode(payload_hash.c_str(),
1410 payload_hash.size(),
1411 &encoded_hash);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001412 return base::StringPrintf("cros_update_size_%zu_hash_%s",
David Zeuthen8f191b22013-08-06 12:27:50 -07001413 payload_size,
1414 encoded_hash.c_str());
1415}
1416
David Zeuthen910ec5b2013-09-26 12:10:58 -07001417bool IsXAttrSupported(const base::FilePath& dir_path) {
1418 char *path = strdup(dir_path.Append("xattr_test_XXXXXX").value().c_str());
1419
1420 int fd = mkstemp(path);
1421 if (fd == -1) {
1422 PLOG(ERROR) << "Error creating temporary file in " << dir_path.value();
1423 free(path);
1424 return false;
1425 }
1426
1427 if (unlink(path) != 0) {
1428 PLOG(ERROR) << "Error unlinking temporary file " << path;
1429 close(fd);
1430 free(path);
1431 return false;
1432 }
1433
1434 int xattr_res = fsetxattr(fd, "user.xattr-test", "value", strlen("value"), 0);
1435 if (xattr_res != 0) {
1436 if (errno == ENOTSUP) {
1437 // Leave it to call-sites to warn about non-support.
1438 } else {
1439 PLOG(ERROR) << "Error setting xattr on " << path;
1440 }
1441 }
1442 close(fd);
1443 free(path);
1444 return xattr_res == 0;
1445}
1446
David Zeuthene7f89172013-10-31 10:21:04 -07001447bool DecodeAndStoreBase64String(const std::string& base64_encoded,
1448 base::FilePath *out_path) {
1449 vector<char> contents;
1450
1451 out_path->clear();
1452
1453 if (base64_encoded.size() == 0) {
1454 LOG(ERROR) << "Can't decode empty string.";
1455 return false;
1456 }
1457
1458 if (!OmahaHashCalculator::Base64Decode(base64_encoded, &contents) ||
1459 contents.size() == 0) {
1460 LOG(ERROR) << "Error decoding base64.";
1461 return false;
1462 }
1463
Alex Vakulenko75039d72014-03-25 12:36:28 -07001464 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
David Zeuthene7f89172013-10-31 10:21:04 -07001465 if (file == NULL) {
1466 LOG(ERROR) << "Error creating temporary file.";
1467 return false;
1468 }
1469
1470 if (fwrite(&contents[0], 1, contents.size(), file) != contents.size()) {
1471 PLOG(ERROR) << "Error writing to temporary file.";
1472 if (fclose(file) != 0)
1473 PLOG(ERROR) << "Error closing temporary file.";
1474 if (unlink(out_path->value().c_str()) != 0)
1475 PLOG(ERROR) << "Error unlinking temporary file.";
1476 out_path->clear();
1477 return false;
1478 }
1479
1480 if (fclose(file) != 0) {
1481 PLOG(ERROR) << "Error closing temporary file.";
1482 out_path->clear();
1483 return false;
1484 }
1485
1486 return true;
1487}
1488
David Zeuthen639aa362014-02-03 16:23:44 -08001489bool ConvertToOmahaInstallDate(base::Time time, int *out_num_days) {
1490 time_t unix_time = time.ToTimeT();
1491 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1492 const time_t kOmahaEpoch = 1167638400;
1493 const int64_t kNumSecondsPerWeek = 7*24*3600;
1494 const int64_t kNumDaysPerWeek = 7;
1495
1496 time_t omaha_time = unix_time - kOmahaEpoch;
1497
1498 if (omaha_time < 0)
1499 return false;
1500
1501 // Note, as per the comment in utils.h we are deliberately not
1502 // handling DST correctly.
1503
1504 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1505 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1506
1507 return true;
1508}
1509
David Zeuthen33bae492014-02-25 16:16:18 -08001510bool WallclockDurationHelper(SystemState* system_state,
1511 const std::string& state_variable_key,
1512 base::TimeDelta* out_duration) {
1513 bool ret = false;
1514
1515 base::Time now = system_state->clock()->GetWallclockTime();
1516 int64_t stored_value;
1517 if (system_state->prefs()->GetInt64(state_variable_key, &stored_value)) {
1518 base::Time stored_time = base::Time::FromInternalValue(stored_value);
1519 if (stored_time > now) {
1520 LOG(ERROR) << "Stored time-stamp used for " << state_variable_key
1521 << " is in the future.";
1522 } else {
1523 *out_duration = now - stored_time;
1524 ret = true;
1525 }
1526 }
1527
1528 if (!system_state->prefs()->SetInt64(state_variable_key,
1529 now.ToInternalValue())) {
1530 LOG(ERROR) << "Error storing time-stamp in " << state_variable_key;
1531 }
1532
1533 return ret;
1534}
1535
1536bool MonotonicDurationHelper(SystemState* system_state,
1537 int64_t* storage,
1538 base::TimeDelta* out_duration) {
1539 bool ret = false;
1540
1541 base::Time now = system_state->clock()->GetMonotonicTime();
1542 if (*storage != 0) {
1543 base::Time stored_time = base::Time::FromInternalValue(*storage);
1544 *out_duration = now - stored_time;
1545 ret = true;
1546 }
1547 *storage = now.ToInternalValue();
1548
1549 return ret;
1550}
1551
adlr@google.com3defe6a2009-12-04 20:57:17 +00001552} // namespace utils
1553
1554} // namespace chromeos_update_engine