blob: 9a596a7140223c390a8c839a425ab4616b2eb16f [file] [log] [blame]
Mike Frysinger8155d082012-04-06 15:23:18 -04001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
adlr@google.com3defe6a2009-12-04 20:57:17 +00002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/utils.h"
Darin Petkovf74eb652010-08-04 12:08:38 -07006
Ben Chan9abb7632014-08-07 00:10:53 -07007#include <stdint.h>
8
adlr@google.com3defe6a2009-12-04 20:57:17 +00009#include <dirent.h>
Alex Deymoc1711e22014-08-08 13:16:23 -070010#include <elf.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000011#include <errno.h>
Alex Deymo192393b2014-11-10 15:58:38 -080012#include <ext2fs/ext2fs.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080013#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000014#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
Alex Deymoc4acdf42014-05-28 21:07:10 -070017#include <sys/mount.h>
18#include <sys/resource.h>
19#include <sys/stat.h>
20#include <sys/types.h>
21#include <sys/wait.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000022#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070023
adlr@google.com3defe6a2009-12-04 20:57:17 +000024#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070025#include <utility>
Chris Sosac1972482013-04-30 22:31:10 -070026#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070027
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070028#include <base/callback.h>
Ben Chan736fcb52014-05-21 18:28:22 -070029#include <base/files/file_path.h>
Alex Deymo192393b2014-11-10 15:58:38 -080030#include <base/files/file_util.h>
Ben Chan736fcb52014-05-21 18:28:22 -070031#include <base/files/scoped_file.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040032#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080033#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050034#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070035#include <base/strings/string_number_conversions.h>
36#include <base/strings/string_split.h>
37#include <base/strings/string_util.h>
38#include <base/strings/stringprintf.h>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080039#include <glib.h>
Will Drewry8f71da82010-08-30 14:07:11 -050040
David Zeuthen33bae492014-02-25 16:16:18 -080041#include "update_engine/clock_interface.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070042#include "update_engine/constants.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080043#include "update_engine/file_descriptor.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080044#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070045#include "update_engine/omaha_request_params.h"
David Zeuthen33bae492014-02-25 16:16:18 -080046#include "update_engine/prefs_interface.h"
Darin Petkov296889c2010-07-23 16:20:54 -070047#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080048#include "update_engine/system_state.h"
49#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000050
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070051using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080052using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000053using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070054using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000055using std::string;
56using std::vector;
57
58namespace chromeos_update_engine {
59
Ben Chan77a1eba2012-10-07 22:54:55 -070060namespace {
61
62// The following constants control how UnmountFilesystem should retry if
63// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
64// one second.
65const int kUnmountMaxNumOfRetries = 5;
66const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070067
68// Number of bytes to read from a file to attempt to detect its contents. Used
69// in GetFileFormat.
70const int kGetFileFormatMaxHeaderSize = 32;
71
Ben Chan77a1eba2012-10-07 22:54:55 -070072} // namespace
73
adlr@google.com3defe6a2009-12-04 20:57:17 +000074namespace utils {
75
Chris Sosa4f8ee272012-11-30 13:01:54 -080076// Cgroup container is created in update-engine's upstart script located at
77// /etc/init/update-engine.conf.
78static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
79
J. Richard Barnette63137e52013-10-28 10:57:29 -070080string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -070081 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -070082
Alex Vakulenko75039d72014-03-25 12:36:28 -070083 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -070084 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -070085 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -070086 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -080087 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -070088 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -080089 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -070090 string output;
91 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -080092 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -070093 return output;
94 }
95 }
96 }
97 LOG(ERROR) << "Unable to parse fwid from ec info.";
98 return "";
99}
100
101
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700102const string KernelDeviceOfBootDevice(const string& boot_device) {
103 string kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700104
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700105 string disk_name;
106 int partition_num;
107 if (SplitPartitionName(boot_device, &disk_name, &partition_num)) {
108 if (disk_name == "/dev/ubiblock") {
109 // Special case for NAND devices.
110 // eg: /dev/ubiblock3_0 becomes /dev/mtdblock2
111 disk_name = "/dev/mtdblock";
112 }
113 // Currently this assumes the partition number of the boot device is
114 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
115 // get the kernel device.
116 if (partition_num == 3 || partition_num == 5 || partition_num == 7) {
117 kernel_partition_name = MakePartitionName(disk_name, partition_num - 1);
118 }
J. Richard Barnette30842932013-10-28 15:04:23 -0700119 }
120
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700121 return kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700122}
123
124
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800125bool WriteFile(const char* path, const char* data, int data_len) {
126 DirectFileWriter writer;
127 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
128 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700129 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800130 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800131 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800132 return true;
133}
134
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700135bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700136 const char* c_buf = static_cast<const char*>(buf);
137 ssize_t bytes_written = 0;
138 while (bytes_written < static_cast<ssize_t>(count)) {
139 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
140 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
141 bytes_written += rc;
142 }
143 return true;
144}
145
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700146bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
147 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700148 size_t bytes_written = 0;
149 int num_attempts = 0;
150 while (bytes_written < count) {
151 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700152 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
153 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700154 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
155 if (rc < 0) {
156 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
157 << " bytes_written=" << bytes_written
158 << " count=" << count << " offset=" << offset;
159 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700160 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
161 bytes_written += rc;
162 }
163 return true;
164}
165
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800166bool WriteAll(FileDescriptorPtr fd, const void* buf, size_t count) {
167 const char* c_buf = static_cast<const char*>(buf);
168 ssize_t bytes_written = 0;
169 while (bytes_written < static_cast<ssize_t>(count)) {
170 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
171 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
172 bytes_written += rc;
173 }
174 return true;
175}
176
177bool PWriteAll(FileDescriptorPtr fd,
178 const void* buf,
179 size_t count,
180 off_t offset) {
181 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET));
182 return WriteAll(fd, buf, count);
183}
184
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700185bool PReadAll(int fd, void* buf, size_t count, off_t offset,
186 ssize_t* out_bytes_read) {
187 char* c_buf = static_cast<char*>(buf);
188 ssize_t bytes_read = 0;
189 while (bytes_read < static_cast<ssize_t>(count)) {
190 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
191 offset + bytes_read);
192 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
193 if (rc == 0) {
194 break;
195 }
196 bytes_read += rc;
197 }
198 *out_bytes_read = bytes_read;
199 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700200}
201
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800202bool PReadAll(FileDescriptorPtr fd, void* buf, size_t count, off_t offset,
203 ssize_t* out_bytes_read) {
204 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET));
205 char* c_buf = static_cast<char*>(buf);
206 ssize_t bytes_read = 0;
207 while (bytes_read < static_cast<ssize_t>(count)) {
208 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
209 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
210 if (rc == 0) {
211 break;
212 }
213 bytes_read += rc;
214 }
215 *out_bytes_read = bytes_read;
216 return true;
217}
218
Gilad Arnold19a45f02012-07-19 12:36:10 -0700219// Append |nbytes| of content from |buf| to the vector pointed to by either
220// |vec_p| or |str_p|.
221static void AppendBytes(const char* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700222 vector<char>* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700223 CHECK(buf);
224 CHECK(vec_p);
225 vec_p->insert(vec_p->end(), buf, buf + nbytes);
226}
227static void AppendBytes(const char* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700228 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700229 CHECK(buf);
230 CHECK(str_p);
231 str_p->append(buf, nbytes);
232}
233
234// Reads from an open file |fp|, appending the read content to the container
235// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200236// file's content, false otherwise. If |size| is not -1, reads up to |size|
237// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700238template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200239static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700240 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200241 CHECK(size == -1 || size >= 0);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700242 char buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200243 while (size == -1 || size > 0) {
244 off_t bytes_to_read = sizeof(buf);
245 if (size > 0 && bytes_to_read > size) {
246 bytes_to_read = size;
247 }
248 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
249 if (!nbytes) {
250 break;
251 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700252 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200253 if (size != -1) {
254 CHECK(size >= static_cast<off_t>(nbytes));
255 size -= nbytes;
256 }
257 }
258 if (ferror(fp)) {
259 return false;
260 }
261 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700262}
263
Darin Petkov8e447e02013-04-16 16:23:50 +0200264// Opens a file |path| for reading and appends its the contents to a container
265// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
266// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700267template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700268static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200269 off_t offset,
270 off_t size,
271 T* out_p) {
272 CHECK_GE(offset, 0);
273 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700274 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200275 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000276 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200277 if (offset) {
278 // Return success without appending any data if a chunk beyond the end of
279 // the file is requested.
280 if (offset >= FileSize(path)) {
281 return true;
282 }
283 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
284 }
285 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000286}
287
Alex Deymo10875d92014-11-10 21:52:57 -0800288// TODO(deymo): This is only used in unittest, but requires the private
289// Read<string>() defined here. Expose Read<string>() or move to base/ version.
290bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700291 FILE* fp = popen(cmd.c_str(), "r");
292 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000293 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200294 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700295 return (success && pclose(fp) >= 0);
296}
297
Darin Petkov8e447e02013-04-16 16:23:50 +0200298bool ReadFile(const string& path, vector<char>* out_p) {
299 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700300}
301
Darin Petkov8e447e02013-04-16 16:23:50 +0200302bool ReadFile(const string& path, string* out_p) {
303 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700304}
305
Darin Petkov8e447e02013-04-16 16:23:50 +0200306bool ReadFileChunk(const string& path, off_t offset, off_t size,
307 vector<char>* out_p) {
308 return ReadFileChunkAndAppend(path, offset, size, out_p);
309}
310
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700311off_t BlockDevSize(int fd) {
312 uint64_t dev_size;
313 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
314 if (rc == -1) {
315 dev_size = -1;
316 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
317 }
318 return dev_size;
319}
320
321off_t BlockDevSize(const string& path) {
322 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
323 if (fd == -1) {
324 PLOG(ERROR) << "Error opening " << path;
325 return fd;
326 }
327
328 off_t dev_size = BlockDevSize(fd);
329 if (dev_size == -1)
330 PLOG(ERROR) << "Error getting block device size on " << path;
331
332 close(fd);
333 return dev_size;
334}
335
336off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700337 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700338 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700339 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700340 if (rc < 0) {
341 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700342 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700343 }
344 if (S_ISREG(stbuf.st_mode))
345 return stbuf.st_size;
346 if (S_ISBLK(stbuf.st_mode))
347 return BlockDevSize(fd);
348 LOG(ERROR) << "Couldn't determine the type of " << fd;
349 return -1;
350}
351
352off_t FileSize(const string& path) {
353 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
354 if (fd == -1) {
355 PLOG(ERROR) << "Error opening " << path;
356 return fd;
357 }
358 off_t size = FileSize(fd);
359 if (size == -1)
360 PLOG(ERROR) << "Error getting file size of " << path;
361 close(fd);
362 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700363}
364
adlr@google.com3defe6a2009-12-04 20:57:17 +0000365void HexDumpArray(const unsigned char* const arr, const size_t length) {
366 const unsigned char* const char_arr =
367 reinterpret_cast<const unsigned char* const>(arr);
368 LOG(INFO) << "Logging array of length: " << length;
369 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700370 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000371 const unsigned int bytes_remaining = length - i;
372 const unsigned int bytes_per_this_line = min(bytes_per_line,
373 bytes_remaining);
374 char header[100];
375 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
376 TEST_AND_RETURN(r == 13);
377 string line = header;
378 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
379 char buf[20];
380 unsigned char c = char_arr[i + j];
381 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
382 TEST_AND_RETURN(r == 3);
383 line += buf;
384 }
385 LOG(INFO) << line;
386 }
387}
388
Alex Deymof329b932014-10-30 01:37:48 -0700389string GetDiskName(const string& partition_name) {
390 string disk_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800391 return SplitPartitionName(partition_name, &disk_name, nullptr) ?
Alex Deymof329b932014-10-30 01:37:48 -0700392 disk_name : string();
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700393}
394
Alex Deymof329b932014-10-30 01:37:48 -0700395int GetPartitionNumber(const string& partition_name) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800396 int partition_num = 0;
397 return SplitPartitionName(partition_name, nullptr, &partition_num) ?
398 partition_num : 0;
399}
400
Alex Deymof329b932014-10-30 01:37:48 -0700401bool SplitPartitionName(const string& partition_name,
402 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800403 int* out_partition_num) {
Alex Deymo10875d92014-11-10 21:52:57 -0800404 if (!StartsWithASCII(partition_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800405 LOG(ERROR) << "Invalid partition device name: " << partition_name;
406 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700407 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800408
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700409 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
410 if (last_nondigit_pos == string::npos ||
411 (last_nondigit_pos + 1) == partition_name.size()) {
412 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800413 return false;
414 }
415
Alex Deymof329b932014-10-30 01:37:48 -0700416 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700417 if (partition_name[last_nondigit_pos] == '_') {
418 // NAND block devices have weird naming which could be something
419 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
420 size_t prev_nondigit_pos =
421 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
422 if (prev_nondigit_pos == string::npos ||
423 (prev_nondigit_pos + 1) == last_nondigit_pos) {
424 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
425 return false;
426 }
427
428 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
429 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800430 }
431
432 if (out_disk_name) {
433 // Special case for MMC devices which have the following naming scheme:
434 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700435 size_t disk_name_len = last_nondigit_pos;
436 if (partition_name[last_nondigit_pos] != 'p' ||
437 last_nondigit_pos == 0 ||
438 !isdigit(partition_name[last_nondigit_pos - 1])) {
439 disk_name_len++;
440 }
441 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800442 }
443
444 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700445 string partition_str = partition_name.substr(last_nondigit_pos + 1,
446 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800447 *out_partition_num = atoi(partition_str.c_str());
448 }
449 return true;
450}
451
Alex Deymof329b932014-10-30 01:37:48 -0700452string MakePartitionName(const string& disk_name, int partition_num) {
Alex Deymo10875d92014-11-10 21:52:57 -0800453 if (!StartsWithASCII(disk_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800454 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700455 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800456 }
457
458 if (partition_num < 1) {
459 LOG(ERROR) << "Invalid partition number: " << partition_num;
Alex Deymof329b932014-10-30 01:37:48 -0700460 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800461 }
462
Alex Deymof329b932014-10-30 01:37:48 -0700463 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700464 if (isdigit(partition_name.back())) {
465 // Special case for devices with names ending with a digit.
466 // Add "p" to separate the disk name from partition number,
467 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800468 partition_name += 'p';
469 }
470
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700471 partition_name += std::to_string(partition_num);
472
Alex Deymo10875d92014-11-10 21:52:57 -0800473 if (StartsWithASCII(partition_name, "/dev/ubiblock", true)) {
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700474 // Special case for UBI block devieces that have "_0" suffix.
475 partition_name += "_0";
476 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800477 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700478}
479
Darin Petkovf74eb652010-08-04 12:08:38 -0700480string SysfsBlockDevice(const string& device) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700481 base::FilePath device_path(device);
Darin Petkovf74eb652010-08-04 12:08:38 -0700482 if (device_path.DirName().value() != "/dev") {
483 return "";
484 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700485 return base::FilePath("/sys/block").Append(device_path.BaseName()).value();
Darin Petkovf74eb652010-08-04 12:08:38 -0700486}
487
Alex Deymof329b932014-10-30 01:37:48 -0700488bool IsRemovableDevice(const string& device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700489 string sysfs_block = SysfsBlockDevice(device);
490 string removable;
491 if (sysfs_block.empty() ||
Alex Vakulenko75039d72014-03-25 12:36:28 -0700492 !base::ReadFileToString(base::FilePath(sysfs_block).Append("removable"),
Ben Chan736fcb52014-05-21 18:28:22 -0700493 &removable)) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700494 return false;
495 }
Ben Chan736fcb52014-05-21 18:28:22 -0700496 base::TrimWhitespaceASCII(removable, base::TRIM_ALL, &removable);
Darin Petkovf74eb652010-08-04 12:08:38 -0700497 return removable == "1";
498}
499
Alex Deymof329b932014-10-30 01:37:48 -0700500string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000501 char buf[100];
502 buf[0] = '\0';
503 return strerror_r(err, buf, sizeof(buf));
504}
505
Alex Deymof329b932014-10-30 01:37:48 -0700506string NormalizePath(const string& path, bool strip_trailing_slash) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000507 string ret;
Alex Deymo020600d2014-11-05 21:05:55 -0800508 std::unique_copy(path.begin(), path.end(), std::back_inserter(ret),
509 [](char c1, char c2) { return c1 == c2 && c1 == '/'; });
510 // The above code ensures no "//" is present in the string, so at most one
511 // '/' is present at the end of the line.
512 if (strip_trailing_slash && !ret.empty() && ret.back() == '/')
513 ret.pop_back();
adlr@google.com3defe6a2009-12-04 20:57:17 +0000514 return ret;
515}
516
517bool FileExists(const char* path) {
518 struct stat stbuf;
519 return 0 == lstat(path, &stbuf);
520}
521
Darin Petkov30291ed2010-11-12 10:23:06 -0800522bool IsSymlink(const char* path) {
523 struct stat stbuf;
524 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
525}
526
Alex Deymo7dc4c502014-05-20 20:09:58 -0700527bool IsDir(const char* path) {
528 struct stat stbuf;
529 TEST_AND_RETURN_FALSE_ERRNO(lstat(path, &stbuf) == 0);
530 return S_ISDIR(stbuf.st_mode);
531}
532
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800533// If |path| is absolute, or explicit relative to the current working directory,
534// leaves it as is. Otherwise, if TMPDIR is defined in the environment and is
535// non-empty, prepends it to |path|. Otherwise, prepends /tmp. Returns the
536// resulting path.
537static const string PrependTmpdir(const string& path) {
538 if (path[0] == '/' || StartsWithASCII(path, "./", true) ||
539 StartsWithASCII(path, "../", true))
540 return path;
541
542 const char *tmpdir = getenv("TMPDIR");
543 const string prefix = (tmpdir && *tmpdir ? tmpdir : "/tmp");
544 return prefix + "/" + path;
545}
546
Alex Deymof329b932014-10-30 01:37:48 -0700547bool MakeTempFile(const string& base_filename_template,
548 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700549 int* fd) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800550 const string filename_template = PrependTmpdir(base_filename_template);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700551 DCHECK(filename || fd);
552 vector<char> buf(filename_template.size() + 1);
553 memcpy(&buf[0], filename_template.data(), filename_template.size());
554 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700555
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700556 int mkstemp_fd = mkstemp(&buf[0]);
557 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
558 if (filename) {
559 *filename = &buf[0];
560 }
561 if (fd) {
562 *fd = mkstemp_fd;
563 } else {
564 close(mkstemp_fd);
565 }
566 return true;
567}
568
Alex Deymof329b932014-10-30 01:37:48 -0700569bool MakeTempDirectory(const string& base_dirname_template,
570 string* dirname) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800571 const string dirname_template = PrependTmpdir(base_dirname_template);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700572 DCHECK(dirname);
573 vector<char> buf(dirname_template.size() + 1);
574 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
575 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700576
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700577 char* return_code = mkdtemp(&buf[0]);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700578 TEST_AND_RETURN_FALSE_ERRNO(return_code != nullptr);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700579 *dirname = &buf[0];
580 return true;
581}
582
adlr@google.com3defe6a2009-12-04 20:57:17 +0000583bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700584 const string& mountpoint,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700585 unsigned long mountflags) { // NOLINT(runtime/int)
Alex Deymo4c82df32014-11-10 22:25:57 -0800586 // TODO(sosa): Remove "ext3" once crbug.com/208022 is resolved.
587 const vector<const char*> fstypes{"ext2", "ext3", "squashfs"};
588 for (const char* fstype : fstypes) {
589 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
590 nullptr);
591 if (rc == 0)
592 return true;
593
594 PLOG(WARNING) << "Unable to mount destination device " << device
595 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000596 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800597 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
598 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000599}
600
601bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700602 for (int num_retries = 0; ; ++num_retries) {
603 if (umount(mountpoint.c_str()) == 0)
604 break;
605
606 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
607 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800608 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700609 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000610 return true;
611}
612
Alex Deymof329b932014-10-30 01:37:48 -0700613bool GetFilesystemSize(const string& device,
Darin Petkovd3f8c892010-10-12 21:38:45 -0700614 int* out_block_count,
615 int* out_block_size) {
616 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
Alex Deymoe7141c62014-10-17 14:03:01 -0700617 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700618 ScopedFdCloser fd_closer(&fd);
619 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
620}
621
622bool GetFilesystemSizeFromFD(int fd,
623 int* out_block_count,
624 int* out_block_size) {
625 TEST_AND_RETURN_FALSE(fd >= 0);
626
Alex Deymo192393b2014-11-10 15:58:38 -0800627 // Determine the filesystem size by directly reading the block count and
628 // block size information from the superblock. Supported FS are ext3 and
629 // squashfs.
630
631 // Read from the fd only once and detect in memory. The first 2 KiB is enough
632 // to read the ext2 superblock (located at offset 1024) and the squashfs
633 // superblock (located at offset 0).
634 const ssize_t kBufferSize = 2048;
635
636 uint8_t buffer[kBufferSize];
637 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, 0)) != kBufferSize) {
638 PLOG(ERROR) << "Unable to read the file system header:";
Darin Petkovd3f8c892010-10-12 21:38:45 -0700639 return false;
640 }
Alex Deymo192393b2014-11-10 15:58:38 -0800641
642 if (GetSquashfs4Size(buffer, kBufferSize, out_block_count, out_block_size))
643 return true;
644 if (GetExt3Size(buffer, kBufferSize, out_block_count, out_block_size))
645 return true;
646
647 LOG(ERROR) << "Unable to determine file system type.";
648 return false;
649}
650
651bool GetExt3Size(const uint8_t* buffer, size_t buffer_size,
652 int* out_block_count,
653 int* out_block_size) {
654 // See include/linux/ext2_fs.h for more details on the structure. We obtain
655 // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
656 // library.
657 if (buffer_size < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
658 return false;
659
660 const uint8_t* superblock = buffer + SUPERBLOCK_OFFSET;
661
662 // ext3_fs.h: ext3_super_block.s_blocks_count
663 uint32_t block_count =
664 *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
665
666 // ext3_fs.h: ext3_super_block.s_log_block_size
667 uint32_t log_block_size =
668 *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
669
670 // ext3_fs.h: ext3_super_block.s_magic
671 uint16_t magic =
672 *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
673
Darin Petkovd3f8c892010-10-12 21:38:45 -0700674 block_count = le32toh(block_count);
Alex Deymo192393b2014-11-10 15:58:38 -0800675 log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700676 magic = le16toh(magic);
677
678 // Sanity check the parameters.
Alex Deymo192393b2014-11-10 15:58:38 -0800679 TEST_AND_RETURN_FALSE(magic == EXT2_SUPER_MAGIC);
680 TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
681 log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700682 TEST_AND_RETURN_FALSE(block_count > 0);
683
Alex Deymo192393b2014-11-10 15:58:38 -0800684 if (out_block_count)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700685 *out_block_count = block_count;
Alex Deymo192393b2014-11-10 15:58:38 -0800686 if (out_block_size)
687 *out_block_size = 1 << log_block_size;
688 return true;
689}
690
691bool GetSquashfs4Size(const unsigned char* buffer, size_t buffer_size,
692 int* out_block_count,
693 int* out_block_size) {
694 // See fs/squashfs/squashfs_fs.h for format details. We only support
695 // Squashfs 4.x little endian.
696
697 // sizeof(struct squashfs_super_block)
698 const size_t kSquashfsSuperBlockSize = 96;
699 if (buffer_size < kSquashfsSuperBlockSize)
700 return false;
701
702 // Check magic, squashfs_fs.h: SQUASHFS_MAGIC
703 if (memcmp(buffer, "hsqs", 4) != 0)
704 return false; // Only little endian is supported.
705
706 // squashfs_fs.h: struct squashfs_super_block.s_major
707 uint16_t s_major = *reinterpret_cast<const uint16_t*>(
708 buffer + 5 * sizeof(uint32_t) + 4 * sizeof(uint16_t));
709
710 if (s_major != 4) {
711 LOG(ERROR) << "Found unsupported squashfs major version " << s_major;
712 return false;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700713 }
Alex Deymo192393b2014-11-10 15:58:38 -0800714
715 // squashfs_fs.h: struct squashfs_super_block.bytes_used
716 uint64_t bytes_used = *reinterpret_cast<const int64_t*>(
717 buffer + 5 * sizeof(uint32_t) + 6 * sizeof(uint16_t) + sizeof(uint64_t));
718
719 const int block_size = 4096;
720
721 // The squashfs' bytes_used doesn't need to be aligned with the block boundary
722 // so we round up to the nearest blocksize.
723 if (out_block_count)
724 *out_block_count = (bytes_used + block_size - 1) / block_size;
725 if (out_block_size)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700726 *out_block_size = block_size;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700727 return true;
728}
729
Alex Deymo719bfff2014-07-11 12:12:32 -0700730string GetPathOnBoard(const string& command) {
731 int return_code = 0;
732 string command_path;
733 // TODO(deymo): prepend SYSROOT to each PATH instead of the result.
734 if (!Subprocess::SynchronousExec(
735 {"which", command}, &return_code, &command_path)) {
736 return command;
737 }
738 if (return_code != 0)
739 return command;
740
741 base::TrimWhitespaceASCII(command_path, base::TRIM_ALL, &command_path);
742 const char* env_sysroot = getenv("SYSROOT");
743 if (env_sysroot) {
744 string sysroot_command_path = env_sysroot + command_path;
745 if (utils::FileExists(sysroot_command_path.c_str()))
746 return sysroot_command_path;
747 }
748 return command_path;
749}
750
Alex Deymo032e7722014-03-25 17:53:56 -0700751// Tries to parse the header of an ELF file to obtain a human-readable
752// description of it on the |output| string.
753static bool GetFileFormatELF(const char* buffer, size_t size, string* output) {
754 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700755 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700756 return false;
757 *output = "ELF";
758
759 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700760 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700761 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700762 switch (buffer[EI_CLASS]) {
763 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700764 *output += " 32-bit";
765 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700766 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700767 *output += " 64-bit";
768 break;
769 default:
770 *output += " ?-bit";
771 }
772
773 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700774 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700775 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700776 char ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700777 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700778 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700779 *output += " little-endian";
780 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700781 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700782 *output += " big-endian";
783 break;
784 default:
785 *output += " ?-endian";
786 // Don't parse anything after the 0x10 offset if endianness is unknown.
787 return true;
788 }
789
Alex Deymoc1711e22014-08-08 13:16:23 -0700790 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
791 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
792 // and size is the same for both 32 and 64 bits.
793 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700794 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700795 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700796 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700797 if (ei_data == ELFDATA2LSB)
798 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700799 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700800 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700801
802 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700803 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700804 *output += " x86";
805 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700806 case EM_MIPS:
807 *output += " mips";
808 break;
809 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700810 *output += " arm";
811 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700812 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700813 *output += " x86-64";
814 break;
815 default:
816 *output += " unknown-arch";
817 }
818 return true;
819}
820
821string GetFileFormat(const string& path) {
822 vector<char> buffer;
823 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
824 return "File not found.";
825
826 string result;
827 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
828 return result;
829
830 return "data";
831}
832
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800833namespace {
834// Do the actual trigger. We do it as a main-loop callback to (try to) get a
835// consistent stack trace.
836gboolean TriggerCrashReporterUpload(void* unused) {
837 pid_t pid = fork();
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700838 CHECK_GE(pid, 0) << "fork failed"; // fork() failed. Something is very wrong.
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800839 if (pid == 0) {
840 // We are the child. Crash.
841 abort(); // never returns
842 }
843 // We are the parent. Wait for child to terminate.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700844 pid_t result = waitpid(pid, nullptr, 0);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800845 LOG_IF(ERROR, result < 0) << "waitpid() failed";
846 return FALSE; // Don't call this callback again
847}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700848} // namespace
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800849
850void ScheduleCrashReporterUpload() {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700851 g_idle_add(&TriggerCrashReporterUpload, nullptr);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800852}
853
Chris Sosa4f8ee272012-11-30 13:01:54 -0800854bool SetCpuShares(CpuShares shares) {
855 string string_shares = base::IntToString(static_cast<int>(shares));
856 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
857 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700858 if (utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
859 string_shares.size())) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800860 return true;
861 } else {
862 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
863 << " using " << cpu_shares_file;
864 return false;
865 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700866}
867
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700868int FuzzInt(int value, unsigned int range) {
869 int min = value - range / 2;
870 int max = value + range - range / 2;
871 return base::RandInt(min, max);
872}
873
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800874gboolean GlibRunClosure(gpointer data) {
Alex Vakulenko4906c1c2014-08-21 13:17:44 -0700875 base::Closure* callback = reinterpret_cast<base::Closure*>(data);
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800876 callback->Run();
877 return FALSE;
878}
879
Alex Deymoc4acdf42014-05-28 21:07:10 -0700880void GlibDestroyClosure(gpointer data) {
Alex Vakulenko4906c1c2014-08-21 13:17:44 -0700881 delete reinterpret_cast<base::Closure*>(data);
Alex Deymoc4acdf42014-05-28 21:07:10 -0700882}
883
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700884string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800885 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700886}
887
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800888string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400889 string str;
890
891 // Handle negative durations by prefixing with a minus.
892 if (delta.ToInternalValue() < 0) {
893 delta *= -1;
894 str = "-";
895 }
896
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700897 // Canonicalize into days, hours, minutes, seconds and microseconds.
898 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800899 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700900 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800901 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700902 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800903 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700904 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800905 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700906 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800907
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700908 if (days)
909 base::StringAppendF(&str, "%ud", days);
910 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800911 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700912 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800913 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700914 base::StringAppendF(&str, "%u", secs);
915 if (usecs) {
916 int width = 6;
917 while ((usecs / 10) * 10 == usecs) {
918 usecs /= 10;
919 width--;
920 }
921 base::StringAppendF(&str, ".%0*u", width, usecs);
922 }
923 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800924 return str;
925}
926
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700927string ToString(const Time utc_time) {
928 Time::Exploded exp_time;
929 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700930 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700931 exp_time.month,
932 exp_time.day_of_month,
933 exp_time.year,
934 exp_time.hour,
935 exp_time.minute,
936 exp_time.second);
937}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000938
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700939string ToString(bool b) {
940 return (b ? "true" : "false");
941}
942
Alex Deymo1c656c42013-06-28 11:02:14 -0700943string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700944 switch (source) {
945 case kDownloadSourceHttpsServer: return "HttpsServer";
946 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700947 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700948 case kNumDownloadSources: return "Unknown";
949 // Don't add a default case to let the compiler warn about newly added
950 // download sources which should be added here.
951 }
952
953 return "Unknown";
954}
955
Alex Deymo1c656c42013-06-28 11:02:14 -0700956string ToString(PayloadType payload_type) {
957 switch (payload_type) {
958 case kPayloadTypeDelta: return "Delta";
959 case kPayloadTypeFull: return "Full";
960 case kPayloadTypeForcedFull: return "ForcedFull";
961 case kNumPayloadTypes: return "Unknown";
962 // Don't add a default case to let the compiler warn about newly added
963 // payload types which should be added here.
964 }
965
966 return "Unknown";
967}
968
David Zeuthena99981f2013-04-29 13:42:47 -0700969ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700970 // Ignore the higher order bits in the code by applying the mask as
971 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700972 // with values less than ErrorCode::kUmaReportedMax.
973 ErrorCode base_code = static_cast<ErrorCode>(
974 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700975
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800976 // Make additional adjustments required for UMA and error classification.
977 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
978 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700979 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700980 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800981 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800982 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700983 << " to ErrorCode::kOmahaErrorInHTTPResponse";
984 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700985 }
986
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800987 return base_code;
988}
989
David Zeuthen33bae492014-02-25 16:16:18 -0800990metrics::AttemptResult GetAttemptResult(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700991 ErrorCode base_code = static_cast<ErrorCode>(
992 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -0800993
994 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700995 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -0800996 return metrics::AttemptResult::kUpdateSucceeded;
997
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700998 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -0800999 return metrics::AttemptResult::kPayloadDownloadError;
1000
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001001 case ErrorCode::kDownloadInvalidMetadataSize:
1002 case ErrorCode::kDownloadInvalidMetadataMagicString:
1003 case ErrorCode::kDownloadMetadataSignatureError:
1004 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1005 case ErrorCode::kPayloadMismatchedType:
1006 case ErrorCode::kUnsupportedMajorPayloadVersion:
1007 case ErrorCode::kUnsupportedMinorPayloadVersion:
1008 case ErrorCode::kDownloadNewPartitionInfoError:
1009 case ErrorCode::kDownloadSignatureMissingInManifest:
1010 case ErrorCode::kDownloadManifestParseError:
1011 case ErrorCode::kDownloadOperationHashMissingError:
David Zeuthen33bae492014-02-25 16:16:18 -08001012 return metrics::AttemptResult::kMetadataMalformed;
1013
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001014 case ErrorCode::kDownloadOperationHashMismatch:
1015 case ErrorCode::kDownloadOperationHashVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001016 return metrics::AttemptResult::kOperationMalformed;
1017
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001018 case ErrorCode::kDownloadOperationExecutionError:
1019 case ErrorCode::kInstallDeviceOpenError:
1020 case ErrorCode::kKernelDeviceOpenError:
1021 case ErrorCode::kDownloadWriteError:
1022 case ErrorCode::kFilesystemCopierError:
David Zeuthen33bae492014-02-25 16:16:18 -08001023 return metrics::AttemptResult::kOperationExecutionError;
1024
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001025 case ErrorCode::kDownloadMetadataSignatureMismatch:
David Zeuthen33bae492014-02-25 16:16:18 -08001026 return metrics::AttemptResult::kMetadataVerificationFailed;
1027
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001028 case ErrorCode::kPayloadSizeMismatchError:
1029 case ErrorCode::kPayloadHashMismatchError:
1030 case ErrorCode::kDownloadPayloadVerificationError:
1031 case ErrorCode::kSignedDeltaPayloadExpectedError:
1032 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001033 return metrics::AttemptResult::kPayloadVerificationFailed;
1034
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001035 case ErrorCode::kNewRootfsVerificationError:
1036 case ErrorCode::kNewKernelVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001037 return metrics::AttemptResult::kVerificationFailed;
1038
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001039 case ErrorCode::kPostinstallRunnerError:
1040 case ErrorCode::kPostinstallBootedFromFirmwareB:
1041 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
David Zeuthen33bae492014-02-25 16:16:18 -08001042 return metrics::AttemptResult::kPostInstallFailed;
1043
1044 // We should never get these errors in the update-attempt stage so
1045 // return internal error if this happens.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001046 case ErrorCode::kError:
1047 case ErrorCode::kOmahaRequestXMLParseError:
1048 case ErrorCode::kOmahaRequestError:
1049 case ErrorCode::kOmahaResponseHandlerError:
1050 case ErrorCode::kDownloadStateInitializationError:
1051 case ErrorCode::kOmahaRequestEmptyResponseError:
1052 case ErrorCode::kDownloadInvalidMetadataSignature:
1053 case ErrorCode::kOmahaResponseInvalid:
1054 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1055 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1056 case ErrorCode::kOmahaErrorInHTTPResponse:
1057 case ErrorCode::kDownloadMetadataSignatureMissingError:
1058 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1059 case ErrorCode::kPostinstallPowerwashError:
1060 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -04001061 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
David Zeuthen33bae492014-02-25 16:16:18 -08001062 return metrics::AttemptResult::kInternalError;
1063
1064 // Special flags. These can't happen (we mask them out above) but
1065 // the compiler doesn't know that. Just break out so we can warn and
1066 // return |kInternalError|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001067 case ErrorCode::kUmaReportedMax:
1068 case ErrorCode::kOmahaRequestHTTPResponseBase:
1069 case ErrorCode::kDevModeFlag:
1070 case ErrorCode::kResumedFlag:
1071 case ErrorCode::kTestImageFlag:
1072 case ErrorCode::kTestOmahaUrlFlag:
1073 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001074 break;
1075 }
1076
1077 LOG(ERROR) << "Unexpected error code " << base_code;
1078 return metrics::AttemptResult::kInternalError;
1079}
1080
1081
1082metrics::DownloadErrorCode GetDownloadErrorCode(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001083 ErrorCode base_code = static_cast<ErrorCode>(
1084 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001085
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001086 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
1087 int http_status =
1088 static_cast<int>(base_code) -
1089 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase);
David Zeuthen33bae492014-02-25 16:16:18 -08001090 if (http_status >= 200 && http_status <= 599) {
1091 return static_cast<metrics::DownloadErrorCode>(
1092 static_cast<int>(metrics::DownloadErrorCode::kHttpStatus200) +
1093 http_status - 200);
1094 } else if (http_status == 0) {
1095 // The code is using HTTP Status 0 for "Unable to get http
1096 // response code."
1097 return metrics::DownloadErrorCode::kDownloadError;
1098 }
1099 LOG(WARNING) << "Unexpected HTTP status code " << http_status;
1100 return metrics::DownloadErrorCode::kHttpStatusOther;
1101 }
1102
1103 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001104 // Unfortunately, ErrorCode::kDownloadTransferError is returned for a wide
David Zeuthen33bae492014-02-25 16:16:18 -08001105 // variety of errors (proxy errors, host not reachable, timeouts etc.).
1106 //
1107 // For now just map that to kDownloading. See http://crbug.com/355745
1108 // for how we plan to add more detail in the future.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001109 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001110 return metrics::DownloadErrorCode::kDownloadError;
1111
1112 // All of these error codes are not related to downloading so break
1113 // out so we can warn and return InputMalformed.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001114 case ErrorCode::kSuccess:
1115 case ErrorCode::kError:
1116 case ErrorCode::kOmahaRequestError:
1117 case ErrorCode::kOmahaResponseHandlerError:
1118 case ErrorCode::kFilesystemCopierError:
1119 case ErrorCode::kPostinstallRunnerError:
1120 case ErrorCode::kPayloadMismatchedType:
1121 case ErrorCode::kInstallDeviceOpenError:
1122 case ErrorCode::kKernelDeviceOpenError:
1123 case ErrorCode::kPayloadHashMismatchError:
1124 case ErrorCode::kPayloadSizeMismatchError:
1125 case ErrorCode::kDownloadPayloadVerificationError:
1126 case ErrorCode::kDownloadNewPartitionInfoError:
1127 case ErrorCode::kDownloadWriteError:
1128 case ErrorCode::kNewRootfsVerificationError:
1129 case ErrorCode::kNewKernelVerificationError:
1130 case ErrorCode::kSignedDeltaPayloadExpectedError:
1131 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1132 case ErrorCode::kPostinstallBootedFromFirmwareB:
1133 case ErrorCode::kDownloadStateInitializationError:
1134 case ErrorCode::kDownloadInvalidMetadataMagicString:
1135 case ErrorCode::kDownloadSignatureMissingInManifest:
1136 case ErrorCode::kDownloadManifestParseError:
1137 case ErrorCode::kDownloadMetadataSignatureError:
1138 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1139 case ErrorCode::kDownloadMetadataSignatureMismatch:
1140 case ErrorCode::kDownloadOperationHashVerificationError:
1141 case ErrorCode::kDownloadOperationExecutionError:
1142 case ErrorCode::kDownloadOperationHashMismatch:
1143 case ErrorCode::kOmahaRequestEmptyResponseError:
1144 case ErrorCode::kOmahaRequestXMLParseError:
1145 case ErrorCode::kDownloadInvalidMetadataSize:
1146 case ErrorCode::kDownloadInvalidMetadataSignature:
1147 case ErrorCode::kOmahaResponseInvalid:
1148 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1149 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1150 case ErrorCode::kOmahaErrorInHTTPResponse:
1151 case ErrorCode::kDownloadOperationHashMissingError:
1152 case ErrorCode::kDownloadMetadataSignatureMissingError:
1153 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1154 case ErrorCode::kPostinstallPowerwashError:
1155 case ErrorCode::kUpdateCanceledByChannelChange:
1156 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1157 case ErrorCode::kUnsupportedMajorPayloadVersion:
1158 case ErrorCode::kUnsupportedMinorPayloadVersion:
David Zeuthenf3e28012014-08-26 18:23:52 -04001159 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
David Zeuthen33bae492014-02-25 16:16:18 -08001160 break;
1161
1162 // Special flags. These can't happen (we mask them out above) but
1163 // the compiler doesn't know that. Just break out so we can warn and
1164 // return |kInputMalformed|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001165 case ErrorCode::kUmaReportedMax:
1166 case ErrorCode::kOmahaRequestHTTPResponseBase:
1167 case ErrorCode::kDevModeFlag:
1168 case ErrorCode::kResumedFlag:
1169 case ErrorCode::kTestImageFlag:
1170 case ErrorCode::kTestOmahaUrlFlag:
1171 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001172 LOG(ERROR) << "Unexpected error code " << base_code;
1173 break;
1174 }
1175
1176 return metrics::DownloadErrorCode::kInputMalformed;
1177}
1178
David Zeuthenb281f072014-04-02 10:20:19 -07001179metrics::ConnectionType GetConnectionType(
1180 NetworkConnectionType type,
1181 NetworkTethering tethering) {
1182 switch (type) {
1183 case kNetUnknown:
1184 return metrics::ConnectionType::kUnknown;
1185
1186 case kNetEthernet:
1187 if (tethering == NetworkTethering::kConfirmed)
1188 return metrics::ConnectionType::kTetheredEthernet;
1189 else
1190 return metrics::ConnectionType::kEthernet;
1191
1192 case kNetWifi:
1193 if (tethering == NetworkTethering::kConfirmed)
1194 return metrics::ConnectionType::kTetheredWifi;
1195 else
1196 return metrics::ConnectionType::kWifi;
1197
1198 case kNetWimax:
1199 return metrics::ConnectionType::kWimax;
1200
1201 case kNetBluetooth:
1202 return metrics::ConnectionType::kBluetooth;
1203
1204 case kNetCellular:
1205 return metrics::ConnectionType::kCellular;
1206 }
1207
1208 LOG(ERROR) << "Unexpected network connection type: type=" << type
1209 << ", tethering=" << static_cast<int>(tethering);
1210
1211 return metrics::ConnectionType::kUnknown;
1212}
1213
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001214// Returns a printable version of the various flags denoted in the higher order
1215// bits of the given code. Returns an empty string if none of those bits are
1216// set.
1217string GetFlagNames(uint32_t code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001218 uint32_t flags = (static_cast<uint32_t>(code) &
1219 static_cast<uint32_t>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001220 string flag_names;
1221 string separator = "";
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001222 for (size_t i = 0; i < sizeof(flags) * 8; i++) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001223 uint32_t flag = flags & (1 << i);
1224 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -07001225 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001226 separator = ", ";
1227 }
1228 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001229
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001230 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001231}
1232
David Zeuthena99981f2013-04-29 13:42:47 -07001233void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001234 if (!system_state)
1235 return;
1236
David Zeuthena99981f2013-04-29 13:42:47 -07001237 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001238
1239 // If the code doesn't have flags computed already, compute them now based on
1240 // the state of the current update attempt.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001241 uint32_t flags =
1242 static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001243 if (!flags)
1244 flags = system_state->update_attempter()->GetErrorCodeFlags();
1245
1246 // Determine the UMA bucket depending on the flags. But, ignore the resumed
1247 // flag, as it's perfectly normal for production devices to resume their
1248 // downloads and so we want to record those cases also in NormalErrorCodes
1249 // bucket.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001250 string metric =
1251 flags & ~static_cast<uint32_t>(ErrorCode::kResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001252 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
1253
1254 LOG(INFO) << "Sending error code " << uma_error_code
1255 << " (" << CodeToString(uma_error_code) << ")"
1256 << " to UMA metric: " << metric
1257 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
1258
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001259 system_state->metrics_lib()->SendEnumToUMA(
1260 metric, static_cast<int>(uma_error_code),
1261 static_cast<int>(ErrorCode::kUmaReportedMax));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001262}
1263
David Zeuthena99981f2013-04-29 13:42:47 -07001264string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001265 // If the given code has both parts (i.e. the error code part and the flags
1266 // part) then strip off the flags part since the switch statement below
1267 // has case statements only for the base error code or a single flag but
1268 // doesn't support any combinations of those.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001269 if ((static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags)) &&
1270 (static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags)))
1271 code = static_cast<ErrorCode>(
1272 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001273 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001274 case ErrorCode::kSuccess: return "ErrorCode::kSuccess";
1275 case ErrorCode::kError: return "ErrorCode::kError";
1276 case ErrorCode::kOmahaRequestError: return "ErrorCode::kOmahaRequestError";
1277 case ErrorCode::kOmahaResponseHandlerError:
1278 return "ErrorCode::kOmahaResponseHandlerError";
1279 case ErrorCode::kFilesystemCopierError:
1280 return "ErrorCode::kFilesystemCopierError";
1281 case ErrorCode::kPostinstallRunnerError:
1282 return "ErrorCode::kPostinstallRunnerError";
1283 case ErrorCode::kPayloadMismatchedType:
1284 return "ErrorCode::kPayloadMismatchedType";
1285 case ErrorCode::kInstallDeviceOpenError:
1286 return "ErrorCode::kInstallDeviceOpenError";
1287 case ErrorCode::kKernelDeviceOpenError:
1288 return "ErrorCode::kKernelDeviceOpenError";
1289 case ErrorCode::kDownloadTransferError:
1290 return "ErrorCode::kDownloadTransferError";
1291 case ErrorCode::kPayloadHashMismatchError:
1292 return "ErrorCode::kPayloadHashMismatchError";
1293 case ErrorCode::kPayloadSizeMismatchError:
1294 return "ErrorCode::kPayloadSizeMismatchError";
1295 case ErrorCode::kDownloadPayloadVerificationError:
1296 return "ErrorCode::kDownloadPayloadVerificationError";
1297 case ErrorCode::kDownloadNewPartitionInfoError:
1298 return "ErrorCode::kDownloadNewPartitionInfoError";
1299 case ErrorCode::kDownloadWriteError:
1300 return "ErrorCode::kDownloadWriteError";
1301 case ErrorCode::kNewRootfsVerificationError:
1302 return "ErrorCode::kNewRootfsVerificationError";
1303 case ErrorCode::kNewKernelVerificationError:
1304 return "ErrorCode::kNewKernelVerificationError";
1305 case ErrorCode::kSignedDeltaPayloadExpectedError:
1306 return "ErrorCode::kSignedDeltaPayloadExpectedError";
1307 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1308 return "ErrorCode::kDownloadPayloadPubKeyVerificationError";
1309 case ErrorCode::kPostinstallBootedFromFirmwareB:
1310 return "ErrorCode::kPostinstallBootedFromFirmwareB";
1311 case ErrorCode::kDownloadStateInitializationError:
1312 return "ErrorCode::kDownloadStateInitializationError";
1313 case ErrorCode::kDownloadInvalidMetadataMagicString:
1314 return "ErrorCode::kDownloadInvalidMetadataMagicString";
1315 case ErrorCode::kDownloadSignatureMissingInManifest:
1316 return "ErrorCode::kDownloadSignatureMissingInManifest";
1317 case ErrorCode::kDownloadManifestParseError:
1318 return "ErrorCode::kDownloadManifestParseError";
1319 case ErrorCode::kDownloadMetadataSignatureError:
1320 return "ErrorCode::kDownloadMetadataSignatureError";
1321 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1322 return "ErrorCode::kDownloadMetadataSignatureVerificationError";
1323 case ErrorCode::kDownloadMetadataSignatureMismatch:
1324 return "ErrorCode::kDownloadMetadataSignatureMismatch";
1325 case ErrorCode::kDownloadOperationHashVerificationError:
1326 return "ErrorCode::kDownloadOperationHashVerificationError";
1327 case ErrorCode::kDownloadOperationExecutionError:
1328 return "ErrorCode::kDownloadOperationExecutionError";
1329 case ErrorCode::kDownloadOperationHashMismatch:
1330 return "ErrorCode::kDownloadOperationHashMismatch";
1331 case ErrorCode::kOmahaRequestEmptyResponseError:
1332 return "ErrorCode::kOmahaRequestEmptyResponseError";
1333 case ErrorCode::kOmahaRequestXMLParseError:
1334 return "ErrorCode::kOmahaRequestXMLParseError";
1335 case ErrorCode::kDownloadInvalidMetadataSize:
1336 return "ErrorCode::kDownloadInvalidMetadataSize";
1337 case ErrorCode::kDownloadInvalidMetadataSignature:
1338 return "ErrorCode::kDownloadInvalidMetadataSignature";
1339 case ErrorCode::kOmahaResponseInvalid:
1340 return "ErrorCode::kOmahaResponseInvalid";
1341 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1342 return "ErrorCode::kOmahaUpdateIgnoredPerPolicy";
1343 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1344 return "ErrorCode::kOmahaUpdateDeferredPerPolicy";
1345 case ErrorCode::kOmahaErrorInHTTPResponse:
1346 return "ErrorCode::kOmahaErrorInHTTPResponse";
1347 case ErrorCode::kDownloadOperationHashMissingError:
1348 return "ErrorCode::kDownloadOperationHashMissingError";
1349 case ErrorCode::kDownloadMetadataSignatureMissingError:
1350 return "ErrorCode::kDownloadMetadataSignatureMissingError";
1351 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1352 return "ErrorCode::kOmahaUpdateDeferredForBackoff";
1353 case ErrorCode::kPostinstallPowerwashError:
1354 return "ErrorCode::kPostinstallPowerwashError";
1355 case ErrorCode::kUpdateCanceledByChannelChange:
1356 return "ErrorCode::kUpdateCanceledByChannelChange";
1357 case ErrorCode::kUmaReportedMax:
1358 return "ErrorCode::kUmaReportedMax";
1359 case ErrorCode::kOmahaRequestHTTPResponseBase:
1360 return "ErrorCode::kOmahaRequestHTTPResponseBase";
1361 case ErrorCode::kResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001362 return "Resumed";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001363 case ErrorCode::kDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001364 return "DevMode";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001365 case ErrorCode::kTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001366 return "TestImage";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001367 case ErrorCode::kTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001368 return "TestOmahaUrl";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001369 case ErrorCode::kSpecialFlags:
1370 return "ErrorCode::kSpecialFlags";
1371 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1372 return "ErrorCode::kPostinstallFirmwareRONotUpdatable";
1373 case ErrorCode::kUnsupportedMajorPayloadVersion:
1374 return "ErrorCode::kUnsupportedMajorPayloadVersion";
1375 case ErrorCode::kUnsupportedMinorPayloadVersion:
1376 return "ErrorCode::kUnsupportedMinorPayloadVersion";
David Zeuthenf3e28012014-08-26 18:23:52 -04001377 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
1378 return "ErrorCode::kOmahaRequestXMLHasEntityDecl";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001379 // Don't add a default case to let the compiler warn about newly added
1380 // error codes which should be added here.
1381 }
1382
1383 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1384}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001385
Gilad Arnold30dedd82013-07-03 06:19:09 -07001386bool CreatePowerwashMarkerFile(const char* file_path) {
1387 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1388 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001389 kPowerwashCommand,
1390 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001391 if (result) {
1392 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1393 } else {
1394 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1395 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001396
1397 return result;
1398}
1399
Gilad Arnold30dedd82013-07-03 06:19:09 -07001400bool DeletePowerwashMarkerFile(const char* file_path) {
1401 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001402 const base::FilePath kPowerwashMarkerPath(marker_file);
1403 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001404
1405 if (result)
1406 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001407 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001408 else
1409 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001410 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001411
1412 return result;
1413}
1414
Alex Deymof329b932014-10-30 01:37:48 -07001415bool GetInstallDev(const string& boot_dev, string* install_dev) {
1416 string disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001417 int partition_num;
1418 if (!SplitPartitionName(boot_dev, &disk_name, &partition_num))
1419 return false;
Liam McLoughlin049d1652013-07-31 18:47:46 -07001420
Chris Sosad317e402013-06-12 13:47:09 -07001421 // Right now, we just switch '3' and '5' partition numbers.
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001422 if (partition_num == 3) {
1423 partition_num = 5;
1424 } else if (partition_num == 5) {
1425 partition_num = 3;
1426 } else {
1427 return false;
1428 }
1429
1430 if (install_dev)
1431 *install_dev = MakePartitionName(disk_name, partition_num);
Liam McLoughlin049d1652013-07-31 18:47:46 -07001432
Chris Sosad317e402013-06-12 13:47:09 -07001433 return true;
1434}
1435
David Zeuthen27a48bc2013-08-06 12:06:29 -07001436Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -07001437 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1438 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -07001439 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1440}
1441
Alex Deymof329b932014-10-30 01:37:48 -07001442gchar** StringVectorToGStrv(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001443 GPtrArray *p = g_ptr_array_new();
Alex Deymo020600d2014-11-05 21:05:55 -08001444 for (const string& str : vec_str) {
1445 g_ptr_array_add(p, g_strdup(str.c_str()));
David Zeuthen27a48bc2013-08-06 12:06:29 -07001446 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001447 g_ptr_array_add(p, nullptr);
David Zeuthen27a48bc2013-08-06 12:06:29 -07001448 return reinterpret_cast<gchar**>(g_ptr_array_free(p, FALSE));
1449}
1450
Alex Deymof329b932014-10-30 01:37:48 -07001451string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001452 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -07001453 for (vector<string>::const_iterator i = vec_str.begin();
1454 i != vec_str.end(); ++i) {
1455 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -07001456 str += ", ";
1457 str += '"';
1458 str += *i;
1459 str += '"';
1460 }
1461 str += "]";
1462 return str;
1463}
1464
David Zeuthen8f191b22013-08-06 12:27:50 -07001465string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
1466 string encoded_hash;
1467 OmahaHashCalculator::Base64Encode(payload_hash.c_str(),
1468 payload_hash.size(),
1469 &encoded_hash);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001470 return base::StringPrintf("cros_update_size_%zu_hash_%s",
David Zeuthen8f191b22013-08-06 12:27:50 -07001471 payload_size,
1472 encoded_hash.c_str());
1473}
1474
Alex Deymof329b932014-10-30 01:37:48 -07001475bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -07001476 base::FilePath *out_path) {
1477 vector<char> contents;
1478
1479 out_path->clear();
1480
1481 if (base64_encoded.size() == 0) {
1482 LOG(ERROR) << "Can't decode empty string.";
1483 return false;
1484 }
1485
1486 if (!OmahaHashCalculator::Base64Decode(base64_encoded, &contents) ||
1487 contents.size() == 0) {
1488 LOG(ERROR) << "Error decoding base64.";
1489 return false;
1490 }
1491
Alex Vakulenko75039d72014-03-25 12:36:28 -07001492 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001493 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -07001494 LOG(ERROR) << "Error creating temporary file.";
1495 return false;
1496 }
1497
1498 if (fwrite(&contents[0], 1, contents.size(), file) != contents.size()) {
1499 PLOG(ERROR) << "Error writing to temporary file.";
1500 if (fclose(file) != 0)
1501 PLOG(ERROR) << "Error closing temporary file.";
1502 if (unlink(out_path->value().c_str()) != 0)
1503 PLOG(ERROR) << "Error unlinking temporary file.";
1504 out_path->clear();
1505 return false;
1506 }
1507
1508 if (fclose(file) != 0) {
1509 PLOG(ERROR) << "Error closing temporary file.";
1510 out_path->clear();
1511 return false;
1512 }
1513
1514 return true;
1515}
1516
Alex Deymof329b932014-10-30 01:37:48 -07001517bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -08001518 time_t unix_time = time.ToTimeT();
1519 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1520 const time_t kOmahaEpoch = 1167638400;
1521 const int64_t kNumSecondsPerWeek = 7*24*3600;
1522 const int64_t kNumDaysPerWeek = 7;
1523
1524 time_t omaha_time = unix_time - kOmahaEpoch;
1525
1526 if (omaha_time < 0)
1527 return false;
1528
1529 // Note, as per the comment in utils.h we are deliberately not
1530 // handling DST correctly.
1531
1532 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1533 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1534
1535 return true;
1536}
1537
David Zeuthen33bae492014-02-25 16:16:18 -08001538bool WallclockDurationHelper(SystemState* system_state,
Alex Deymof329b932014-10-30 01:37:48 -07001539 const string& state_variable_key,
1540 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001541 bool ret = false;
1542
Alex Deymof329b932014-10-30 01:37:48 -07001543 Time now = system_state->clock()->GetWallclockTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001544 int64_t stored_value;
1545 if (system_state->prefs()->GetInt64(state_variable_key, &stored_value)) {
Alex Deymof329b932014-10-30 01:37:48 -07001546 Time stored_time = Time::FromInternalValue(stored_value);
David Zeuthen33bae492014-02-25 16:16:18 -08001547 if (stored_time > now) {
1548 LOG(ERROR) << "Stored time-stamp used for " << state_variable_key
1549 << " is in the future.";
1550 } else {
1551 *out_duration = now - stored_time;
1552 ret = true;
1553 }
1554 }
1555
1556 if (!system_state->prefs()->SetInt64(state_variable_key,
1557 now.ToInternalValue())) {
1558 LOG(ERROR) << "Error storing time-stamp in " << state_variable_key;
1559 }
1560
1561 return ret;
1562}
1563
1564bool MonotonicDurationHelper(SystemState* system_state,
1565 int64_t* storage,
Alex Deymof329b932014-10-30 01:37:48 -07001566 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001567 bool ret = false;
1568
Alex Deymof329b932014-10-30 01:37:48 -07001569 Time now = system_state->clock()->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001570 if (*storage != 0) {
Alex Deymof329b932014-10-30 01:37:48 -07001571 Time stored_time = Time::FromInternalValue(*storage);
David Zeuthen33bae492014-02-25 16:16:18 -08001572 *out_duration = now - stored_time;
1573 ret = true;
1574 }
1575 *storage = now.ToInternalValue();
1576
1577 return ret;
1578}
1579
adlr@google.com3defe6a2009-12-04 20:57:17 +00001580} // namespace utils
1581
1582} // namespace chromeos_update_engine