blob: 2007e9b976c282dcff5fdc5aaeb0149aa9d67f32 [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>
Alex Vakulenko981a9fb2015-02-09 12:51:24 -080039#include <chromeos/data_encoding.h>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080040#include <glib.h>
Will Drewry8f71da82010-08-30 14:07:11 -050041
David Zeuthen33bae492014-02-25 16:16:18 -080042#include "update_engine/clock_interface.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070043#include "update_engine/constants.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080044#include "update_engine/file_descriptor.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080045#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070046#include "update_engine/omaha_request_params.h"
David Zeuthen33bae492014-02-25 16:16:18 -080047#include "update_engine/prefs_interface.h"
Darin Petkov296889c2010-07-23 16:20:54 -070048#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080049#include "update_engine/system_state.h"
50#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000051
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070052using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080053using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000054using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070055using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000056using std::string;
57using std::vector;
58
59namespace chromeos_update_engine {
60
Ben Chan77a1eba2012-10-07 22:54:55 -070061namespace {
62
63// The following constants control how UnmountFilesystem should retry if
64// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
65// one second.
66const int kUnmountMaxNumOfRetries = 5;
67const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070068
69// Number of bytes to read from a file to attempt to detect its contents. Used
70// in GetFileFormat.
71const int kGetFileFormatMaxHeaderSize = 32;
72
Ben Chan77a1eba2012-10-07 22:54:55 -070073} // namespace
74
adlr@google.com3defe6a2009-12-04 20:57:17 +000075namespace utils {
76
Chris Sosa4f8ee272012-11-30 13:01:54 -080077// Cgroup container is created in update-engine's upstart script located at
78// /etc/init/update-engine.conf.
79static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
80
J. Richard Barnette63137e52013-10-28 10:57:29 -070081string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -070082 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -070083
Alex Vakulenko75039d72014-03-25 12:36:28 -070084 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -070085 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -070086 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -070087 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -080088 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -070089 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -080090 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -070091 string output;
92 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -080093 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -070094 return output;
95 }
96 }
97 }
98 LOG(ERROR) << "Unable to parse fwid from ec info.";
99 return "";
100}
101
102
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700103const string KernelDeviceOfBootDevice(const string& boot_device) {
104 string kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700105
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700106 string disk_name;
107 int partition_num;
108 if (SplitPartitionName(boot_device, &disk_name, &partition_num)) {
109 if (disk_name == "/dev/ubiblock") {
110 // Special case for NAND devices.
111 // eg: /dev/ubiblock3_0 becomes /dev/mtdblock2
112 disk_name = "/dev/mtdblock";
113 }
114 // Currently this assumes the partition number of the boot device is
115 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
116 // get the kernel device.
117 if (partition_num == 3 || partition_num == 5 || partition_num == 7) {
118 kernel_partition_name = MakePartitionName(disk_name, partition_num - 1);
119 }
J. Richard Barnette30842932013-10-28 15:04:23 -0700120 }
121
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700122 return kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700123}
124
125
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800126bool WriteFile(const char* path, const char* data, int data_len) {
127 DirectFileWriter writer;
128 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
129 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700130 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800131 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800132 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800133 return true;
134}
135
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700136bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700137 const char* c_buf = static_cast<const char*>(buf);
138 ssize_t bytes_written = 0;
139 while (bytes_written < static_cast<ssize_t>(count)) {
140 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
141 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
142 bytes_written += rc;
143 }
144 return true;
145}
146
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700147bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
148 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700149 size_t bytes_written = 0;
150 int num_attempts = 0;
151 while (bytes_written < count) {
152 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700153 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
154 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700155 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
156 if (rc < 0) {
157 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
158 << " bytes_written=" << bytes_written
159 << " count=" << count << " offset=" << offset;
160 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700161 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
162 bytes_written += rc;
163 }
164 return true;
165}
166
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800167bool WriteAll(FileDescriptorPtr fd, const void* buf, size_t count) {
168 const char* c_buf = static_cast<const char*>(buf);
169 ssize_t bytes_written = 0;
170 while (bytes_written < static_cast<ssize_t>(count)) {
171 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
172 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
173 bytes_written += rc;
174 }
175 return true;
176}
177
178bool PWriteAll(FileDescriptorPtr fd,
179 const void* buf,
180 size_t count,
181 off_t offset) {
182 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET));
183 return WriteAll(fd, buf, count);
184}
185
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700186bool PReadAll(int fd, void* buf, size_t count, off_t offset,
187 ssize_t* out_bytes_read) {
188 char* c_buf = static_cast<char*>(buf);
189 ssize_t bytes_read = 0;
190 while (bytes_read < static_cast<ssize_t>(count)) {
191 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
192 offset + bytes_read);
193 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
194 if (rc == 0) {
195 break;
196 }
197 bytes_read += rc;
198 }
199 *out_bytes_read = bytes_read;
200 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700201}
202
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800203bool PReadAll(FileDescriptorPtr fd, void* buf, size_t count, off_t offset,
204 ssize_t* out_bytes_read) {
205 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET));
206 char* c_buf = static_cast<char*>(buf);
207 ssize_t bytes_read = 0;
208 while (bytes_read < static_cast<ssize_t>(count)) {
209 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
210 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
211 if (rc == 0) {
212 break;
213 }
214 bytes_read += rc;
215 }
216 *out_bytes_read = bytes_read;
217 return true;
218}
219
Gilad Arnold19a45f02012-07-19 12:36:10 -0700220// Append |nbytes| of content from |buf| to the vector pointed to by either
221// |vec_p| or |str_p|.
222static void AppendBytes(const char* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700223 vector<char>* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700224 CHECK(buf);
225 CHECK(vec_p);
226 vec_p->insert(vec_p->end(), buf, buf + nbytes);
227}
228static void AppendBytes(const char* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700229 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700230 CHECK(buf);
231 CHECK(str_p);
232 str_p->append(buf, nbytes);
233}
234
235// Reads from an open file |fp|, appending the read content to the container
236// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200237// file's content, false otherwise. If |size| is not -1, reads up to |size|
238// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700239template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200240static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700241 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200242 CHECK(size == -1 || size >= 0);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700243 char buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200244 while (size == -1 || size > 0) {
245 off_t bytes_to_read = sizeof(buf);
246 if (size > 0 && bytes_to_read > size) {
247 bytes_to_read = size;
248 }
249 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
250 if (!nbytes) {
251 break;
252 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700253 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200254 if (size != -1) {
255 CHECK(size >= static_cast<off_t>(nbytes));
256 size -= nbytes;
257 }
258 }
259 if (ferror(fp)) {
260 return false;
261 }
262 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700263}
264
Darin Petkov8e447e02013-04-16 16:23:50 +0200265// Opens a file |path| for reading and appends its the contents to a container
266// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
267// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700268template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700269static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200270 off_t offset,
271 off_t size,
272 T* out_p) {
273 CHECK_GE(offset, 0);
274 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700275 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200276 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000277 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200278 if (offset) {
279 // Return success without appending any data if a chunk beyond the end of
280 // the file is requested.
281 if (offset >= FileSize(path)) {
282 return true;
283 }
284 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
285 }
286 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000287}
288
Alex Deymo10875d92014-11-10 21:52:57 -0800289// TODO(deymo): This is only used in unittest, but requires the private
290// Read<string>() defined here. Expose Read<string>() or move to base/ version.
291bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700292 FILE* fp = popen(cmd.c_str(), "r");
293 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000294 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200295 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700296 return (success && pclose(fp) >= 0);
297}
298
Darin Petkov8e447e02013-04-16 16:23:50 +0200299bool ReadFile(const string& path, vector<char>* out_p) {
300 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700301}
302
Darin Petkov8e447e02013-04-16 16:23:50 +0200303bool ReadFile(const string& path, string* out_p) {
304 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700305}
306
Darin Petkov8e447e02013-04-16 16:23:50 +0200307bool ReadFileChunk(const string& path, off_t offset, off_t size,
308 vector<char>* out_p) {
309 return ReadFileChunkAndAppend(path, offset, size, out_p);
310}
311
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700312off_t BlockDevSize(int fd) {
313 uint64_t dev_size;
314 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
315 if (rc == -1) {
316 dev_size = -1;
317 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
318 }
319 return dev_size;
320}
321
322off_t BlockDevSize(const string& path) {
323 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
324 if (fd == -1) {
325 PLOG(ERROR) << "Error opening " << path;
326 return fd;
327 }
328
329 off_t dev_size = BlockDevSize(fd);
330 if (dev_size == -1)
331 PLOG(ERROR) << "Error getting block device size on " << path;
332
333 close(fd);
334 return dev_size;
335}
336
337off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700338 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700339 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700340 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700341 if (rc < 0) {
342 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700343 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700344 }
345 if (S_ISREG(stbuf.st_mode))
346 return stbuf.st_size;
347 if (S_ISBLK(stbuf.st_mode))
348 return BlockDevSize(fd);
349 LOG(ERROR) << "Couldn't determine the type of " << fd;
350 return -1;
351}
352
353off_t FileSize(const string& path) {
354 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
355 if (fd == -1) {
356 PLOG(ERROR) << "Error opening " << path;
357 return fd;
358 }
359 off_t size = FileSize(fd);
360 if (size == -1)
361 PLOG(ERROR) << "Error getting file size of " << path;
362 close(fd);
363 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700364}
365
adlr@google.com3defe6a2009-12-04 20:57:17 +0000366void HexDumpArray(const unsigned char* const arr, const size_t length) {
367 const unsigned char* const char_arr =
368 reinterpret_cast<const unsigned char* const>(arr);
369 LOG(INFO) << "Logging array of length: " << length;
370 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700371 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000372 const unsigned int bytes_remaining = length - i;
373 const unsigned int bytes_per_this_line = min(bytes_per_line,
374 bytes_remaining);
375 char header[100];
376 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
377 TEST_AND_RETURN(r == 13);
378 string line = header;
379 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
380 char buf[20];
381 unsigned char c = char_arr[i + j];
382 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
383 TEST_AND_RETURN(r == 3);
384 line += buf;
385 }
386 LOG(INFO) << line;
387 }
388}
389
Alex Deymof329b932014-10-30 01:37:48 -0700390string GetDiskName(const string& partition_name) {
391 string disk_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800392 return SplitPartitionName(partition_name, &disk_name, nullptr) ?
Alex Deymof329b932014-10-30 01:37:48 -0700393 disk_name : string();
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700394}
395
Alex Deymof329b932014-10-30 01:37:48 -0700396int GetPartitionNumber(const string& partition_name) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800397 int partition_num = 0;
398 return SplitPartitionName(partition_name, nullptr, &partition_num) ?
399 partition_num : 0;
400}
401
Alex Deymof329b932014-10-30 01:37:48 -0700402bool SplitPartitionName(const string& partition_name,
403 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800404 int* out_partition_num) {
Alex Deymo10875d92014-11-10 21:52:57 -0800405 if (!StartsWithASCII(partition_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800406 LOG(ERROR) << "Invalid partition device name: " << partition_name;
407 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700408 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800409
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700410 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
411 if (last_nondigit_pos == string::npos ||
412 (last_nondigit_pos + 1) == partition_name.size()) {
413 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800414 return false;
415 }
416
Alex Deymof329b932014-10-30 01:37:48 -0700417 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700418 if (partition_name[last_nondigit_pos] == '_') {
419 // NAND block devices have weird naming which could be something
420 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
421 size_t prev_nondigit_pos =
422 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
423 if (prev_nondigit_pos == string::npos ||
424 (prev_nondigit_pos + 1) == last_nondigit_pos) {
425 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
426 return false;
427 }
428
429 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
430 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800431 }
432
433 if (out_disk_name) {
434 // Special case for MMC devices which have the following naming scheme:
435 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700436 size_t disk_name_len = last_nondigit_pos;
437 if (partition_name[last_nondigit_pos] != 'p' ||
438 last_nondigit_pos == 0 ||
439 !isdigit(partition_name[last_nondigit_pos - 1])) {
440 disk_name_len++;
441 }
442 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800443 }
444
445 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700446 string partition_str = partition_name.substr(last_nondigit_pos + 1,
447 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800448 *out_partition_num = atoi(partition_str.c_str());
449 }
450 return true;
451}
452
Alex Deymof329b932014-10-30 01:37:48 -0700453string MakePartitionName(const string& disk_name, int partition_num) {
Alex Deymo10875d92014-11-10 21:52:57 -0800454 if (!StartsWithASCII(disk_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800455 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700456 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800457 }
458
459 if (partition_num < 1) {
460 LOG(ERROR) << "Invalid partition number: " << partition_num;
Alex Deymof329b932014-10-30 01:37:48 -0700461 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800462 }
463
Alex Deymof329b932014-10-30 01:37:48 -0700464 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700465 if (isdigit(partition_name.back())) {
466 // Special case for devices with names ending with a digit.
467 // Add "p" to separate the disk name from partition number,
468 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800469 partition_name += 'p';
470 }
471
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700472 partition_name += std::to_string(partition_num);
473
Alex Deymo10875d92014-11-10 21:52:57 -0800474 if (StartsWithASCII(partition_name, "/dev/ubiblock", true)) {
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700475 // Special case for UBI block devieces that have "_0" suffix.
476 partition_name += "_0";
477 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800478 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700479}
480
Darin Petkovf74eb652010-08-04 12:08:38 -0700481string SysfsBlockDevice(const string& device) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700482 base::FilePath device_path(device);
Darin Petkovf74eb652010-08-04 12:08:38 -0700483 if (device_path.DirName().value() != "/dev") {
484 return "";
485 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700486 return base::FilePath("/sys/block").Append(device_path.BaseName()).value();
Darin Petkovf74eb652010-08-04 12:08:38 -0700487}
488
Alex Deymof329b932014-10-30 01:37:48 -0700489bool IsRemovableDevice(const string& device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700490 string sysfs_block = SysfsBlockDevice(device);
491 string removable;
492 if (sysfs_block.empty() ||
Alex Vakulenko75039d72014-03-25 12:36:28 -0700493 !base::ReadFileToString(base::FilePath(sysfs_block).Append("removable"),
Ben Chan736fcb52014-05-21 18:28:22 -0700494 &removable)) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700495 return false;
496 }
Ben Chan736fcb52014-05-21 18:28:22 -0700497 base::TrimWhitespaceASCII(removable, base::TRIM_ALL, &removable);
Darin Petkovf74eb652010-08-04 12:08:38 -0700498 return removable == "1";
499}
500
Alex Deymof329b932014-10-30 01:37:48 -0700501string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000502 char buf[100];
503 buf[0] = '\0';
504 return strerror_r(err, buf, sizeof(buf));
505}
506
Alex Deymof329b932014-10-30 01:37:48 -0700507string NormalizePath(const string& path, bool strip_trailing_slash) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000508 string ret;
Alex Deymo020600d2014-11-05 21:05:55 -0800509 std::unique_copy(path.begin(), path.end(), std::back_inserter(ret),
510 [](char c1, char c2) { return c1 == c2 && c1 == '/'; });
511 // The above code ensures no "//" is present in the string, so at most one
512 // '/' is present at the end of the line.
513 if (strip_trailing_slash && !ret.empty() && ret.back() == '/')
514 ret.pop_back();
adlr@google.com3defe6a2009-12-04 20:57:17 +0000515 return ret;
516}
517
518bool FileExists(const char* path) {
519 struct stat stbuf;
520 return 0 == lstat(path, &stbuf);
521}
522
Darin Petkov30291ed2010-11-12 10:23:06 -0800523bool IsSymlink(const char* path) {
524 struct stat stbuf;
525 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
526}
527
Alex Deymo7dc4c502014-05-20 20:09:58 -0700528bool IsDir(const char* path) {
529 struct stat stbuf;
530 TEST_AND_RETURN_FALSE_ERRNO(lstat(path, &stbuf) == 0);
531 return S_ISDIR(stbuf.st_mode);
532}
533
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800534// If |path| is absolute, or explicit relative to the current working directory,
535// leaves it as is. Otherwise, if TMPDIR is defined in the environment and is
536// non-empty, prepends it to |path|. Otherwise, prepends /tmp. Returns the
537// resulting path.
538static const string PrependTmpdir(const string& path) {
539 if (path[0] == '/' || StartsWithASCII(path, "./", true) ||
540 StartsWithASCII(path, "../", true))
541 return path;
542
543 const char *tmpdir = getenv("TMPDIR");
544 const string prefix = (tmpdir && *tmpdir ? tmpdir : "/tmp");
545 return prefix + "/" + path;
546}
547
Alex Deymof329b932014-10-30 01:37:48 -0700548bool MakeTempFile(const string& base_filename_template,
549 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700550 int* fd) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800551 const string filename_template = PrependTmpdir(base_filename_template);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700552 DCHECK(filename || fd);
553 vector<char> buf(filename_template.size() + 1);
554 memcpy(&buf[0], filename_template.data(), filename_template.size());
555 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700556
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700557 int mkstemp_fd = mkstemp(&buf[0]);
558 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
559 if (filename) {
560 *filename = &buf[0];
561 }
562 if (fd) {
563 *fd = mkstemp_fd;
564 } else {
565 close(mkstemp_fd);
566 }
567 return true;
568}
569
Alex Deymof329b932014-10-30 01:37:48 -0700570bool MakeTempDirectory(const string& base_dirname_template,
571 string* dirname) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800572 const string dirname_template = PrependTmpdir(base_dirname_template);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700573 DCHECK(dirname);
574 vector<char> buf(dirname_template.size() + 1);
575 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
576 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700577
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700578 char* return_code = mkdtemp(&buf[0]);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700579 TEST_AND_RETURN_FALSE_ERRNO(return_code != nullptr);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700580 *dirname = &buf[0];
581 return true;
582}
583
adlr@google.com3defe6a2009-12-04 20:57:17 +0000584bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700585 const string& mountpoint,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700586 unsigned long mountflags) { // NOLINT(runtime/int)
Alex Deymo4c82df32014-11-10 22:25:57 -0800587 // TODO(sosa): Remove "ext3" once crbug.com/208022 is resolved.
588 const vector<const char*> fstypes{"ext2", "ext3", "squashfs"};
589 for (const char* fstype : fstypes) {
590 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
591 nullptr);
592 if (rc == 0)
593 return true;
594
595 PLOG(WARNING) << "Unable to mount destination device " << device
596 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000597 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800598 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
599 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000600}
601
602bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700603 for (int num_retries = 0; ; ++num_retries) {
604 if (umount(mountpoint.c_str()) == 0)
605 break;
606
607 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
608 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800609 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700610 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000611 return true;
612}
613
Alex Deymof329b932014-10-30 01:37:48 -0700614bool GetFilesystemSize(const string& device,
Darin Petkovd3f8c892010-10-12 21:38:45 -0700615 int* out_block_count,
616 int* out_block_size) {
617 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
Alex Deymoe7141c62014-10-17 14:03:01 -0700618 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700619 ScopedFdCloser fd_closer(&fd);
620 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
621}
622
623bool GetFilesystemSizeFromFD(int fd,
624 int* out_block_count,
625 int* out_block_size) {
626 TEST_AND_RETURN_FALSE(fd >= 0);
627
Alex Deymo192393b2014-11-10 15:58:38 -0800628 // Determine the filesystem size by directly reading the block count and
629 // block size information from the superblock. Supported FS are ext3 and
630 // squashfs.
631
632 // Read from the fd only once and detect in memory. The first 2 KiB is enough
633 // to read the ext2 superblock (located at offset 1024) and the squashfs
634 // superblock (located at offset 0).
635 const ssize_t kBufferSize = 2048;
636
637 uint8_t buffer[kBufferSize];
638 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, 0)) != kBufferSize) {
639 PLOG(ERROR) << "Unable to read the file system header:";
Darin Petkovd3f8c892010-10-12 21:38:45 -0700640 return false;
641 }
Alex Deymo192393b2014-11-10 15:58:38 -0800642
643 if (GetSquashfs4Size(buffer, kBufferSize, out_block_count, out_block_size))
644 return true;
645 if (GetExt3Size(buffer, kBufferSize, out_block_count, out_block_size))
646 return true;
647
648 LOG(ERROR) << "Unable to determine file system type.";
649 return false;
650}
651
652bool GetExt3Size(const uint8_t* buffer, size_t buffer_size,
653 int* out_block_count,
654 int* out_block_size) {
655 // See include/linux/ext2_fs.h for more details on the structure. We obtain
656 // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
657 // library.
658 if (buffer_size < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
659 return false;
660
661 const uint8_t* superblock = buffer + SUPERBLOCK_OFFSET;
662
663 // ext3_fs.h: ext3_super_block.s_blocks_count
664 uint32_t block_count =
665 *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
666
667 // ext3_fs.h: ext3_super_block.s_log_block_size
668 uint32_t log_block_size =
669 *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
670
671 // ext3_fs.h: ext3_super_block.s_magic
672 uint16_t magic =
673 *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
674
Darin Petkovd3f8c892010-10-12 21:38:45 -0700675 block_count = le32toh(block_count);
Alex Deymo192393b2014-11-10 15:58:38 -0800676 log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700677 magic = le16toh(magic);
678
679 // Sanity check the parameters.
Alex Deymo192393b2014-11-10 15:58:38 -0800680 TEST_AND_RETURN_FALSE(magic == EXT2_SUPER_MAGIC);
681 TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
682 log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700683 TEST_AND_RETURN_FALSE(block_count > 0);
684
Alex Deymo192393b2014-11-10 15:58:38 -0800685 if (out_block_count)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700686 *out_block_count = block_count;
Alex Deymo192393b2014-11-10 15:58:38 -0800687 if (out_block_size)
688 *out_block_size = 1 << log_block_size;
689 return true;
690}
691
692bool GetSquashfs4Size(const unsigned char* buffer, size_t buffer_size,
693 int* out_block_count,
694 int* out_block_size) {
695 // See fs/squashfs/squashfs_fs.h for format details. We only support
696 // Squashfs 4.x little endian.
697
698 // sizeof(struct squashfs_super_block)
699 const size_t kSquashfsSuperBlockSize = 96;
700 if (buffer_size < kSquashfsSuperBlockSize)
701 return false;
702
703 // Check magic, squashfs_fs.h: SQUASHFS_MAGIC
704 if (memcmp(buffer, "hsqs", 4) != 0)
705 return false; // Only little endian is supported.
706
707 // squashfs_fs.h: struct squashfs_super_block.s_major
708 uint16_t s_major = *reinterpret_cast<const uint16_t*>(
709 buffer + 5 * sizeof(uint32_t) + 4 * sizeof(uint16_t));
710
711 if (s_major != 4) {
712 LOG(ERROR) << "Found unsupported squashfs major version " << s_major;
713 return false;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700714 }
Alex Deymo192393b2014-11-10 15:58:38 -0800715
716 // squashfs_fs.h: struct squashfs_super_block.bytes_used
717 uint64_t bytes_used = *reinterpret_cast<const int64_t*>(
718 buffer + 5 * sizeof(uint32_t) + 6 * sizeof(uint16_t) + sizeof(uint64_t));
719
720 const int block_size = 4096;
721
722 // The squashfs' bytes_used doesn't need to be aligned with the block boundary
723 // so we round up to the nearest blocksize.
724 if (out_block_count)
725 *out_block_count = (bytes_used + block_size - 1) / block_size;
726 if (out_block_size)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700727 *out_block_size = block_size;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700728 return true;
729}
730
Alex Deymo719bfff2014-07-11 12:12:32 -0700731string GetPathOnBoard(const string& command) {
732 int return_code = 0;
733 string command_path;
734 // TODO(deymo): prepend SYSROOT to each PATH instead of the result.
735 if (!Subprocess::SynchronousExec(
736 {"which", command}, &return_code, &command_path)) {
737 return command;
738 }
739 if (return_code != 0)
740 return command;
741
742 base::TrimWhitespaceASCII(command_path, base::TRIM_ALL, &command_path);
743 const char* env_sysroot = getenv("SYSROOT");
744 if (env_sysroot) {
745 string sysroot_command_path = env_sysroot + command_path;
746 if (utils::FileExists(sysroot_command_path.c_str()))
747 return sysroot_command_path;
748 }
749 return command_path;
750}
751
Alex Deymo032e7722014-03-25 17:53:56 -0700752// Tries to parse the header of an ELF file to obtain a human-readable
753// description of it on the |output| string.
754static bool GetFileFormatELF(const char* buffer, size_t size, string* output) {
755 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700756 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700757 return false;
758 *output = "ELF";
759
760 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700761 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700762 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700763 switch (buffer[EI_CLASS]) {
764 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700765 *output += " 32-bit";
766 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700767 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700768 *output += " 64-bit";
769 break;
770 default:
771 *output += " ?-bit";
772 }
773
774 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700775 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700776 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700777 char ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700778 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700779 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700780 *output += " little-endian";
781 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700782 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700783 *output += " big-endian";
784 break;
785 default:
786 *output += " ?-endian";
787 // Don't parse anything after the 0x10 offset if endianness is unknown.
788 return true;
789 }
790
Alex Deymoc1711e22014-08-08 13:16:23 -0700791 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
792 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
793 // and size is the same for both 32 and 64 bits.
794 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700795 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700796 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700797 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700798 if (ei_data == ELFDATA2LSB)
799 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700800 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700801 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700802
803 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700804 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700805 *output += " x86";
806 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700807 case EM_MIPS:
808 *output += " mips";
809 break;
810 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700811 *output += " arm";
812 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700813 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700814 *output += " x86-64";
815 break;
816 default:
817 *output += " unknown-arch";
818 }
819 return true;
820}
821
822string GetFileFormat(const string& path) {
823 vector<char> buffer;
824 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
825 return "File not found.";
826
827 string result;
828 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
829 return result;
830
831 return "data";
832}
833
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800834namespace {
835// Do the actual trigger. We do it as a main-loop callback to (try to) get a
836// consistent stack trace.
837gboolean TriggerCrashReporterUpload(void* unused) {
838 pid_t pid = fork();
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700839 CHECK_GE(pid, 0) << "fork failed"; // fork() failed. Something is very wrong.
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800840 if (pid == 0) {
841 // We are the child. Crash.
842 abort(); // never returns
843 }
844 // We are the parent. Wait for child to terminate.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700845 pid_t result = waitpid(pid, nullptr, 0);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800846 LOG_IF(ERROR, result < 0) << "waitpid() failed";
847 return FALSE; // Don't call this callback again
848}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700849} // namespace
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800850
851void ScheduleCrashReporterUpload() {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700852 g_idle_add(&TriggerCrashReporterUpload, nullptr);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800853}
854
Chris Sosa4f8ee272012-11-30 13:01:54 -0800855bool SetCpuShares(CpuShares shares) {
856 string string_shares = base::IntToString(static_cast<int>(shares));
857 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
858 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700859 if (utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
860 string_shares.size())) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800861 return true;
862 } else {
863 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
864 << " using " << cpu_shares_file;
865 return false;
866 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700867}
868
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700869int FuzzInt(int value, unsigned int range) {
870 int min = value - range / 2;
871 int max = value + range - range / 2;
872 return base::RandInt(min, max);
873}
874
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800875gboolean GlibRunClosure(gpointer data) {
Alex Vakulenko4906c1c2014-08-21 13:17:44 -0700876 base::Closure* callback = reinterpret_cast<base::Closure*>(data);
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800877 callback->Run();
878 return FALSE;
879}
880
Alex Deymoc4acdf42014-05-28 21:07:10 -0700881void GlibDestroyClosure(gpointer data) {
Alex Vakulenko4906c1c2014-08-21 13:17:44 -0700882 delete reinterpret_cast<base::Closure*>(data);
Alex Deymoc4acdf42014-05-28 21:07:10 -0700883}
884
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700885string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800886 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700887}
888
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800889string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400890 string str;
891
892 // Handle negative durations by prefixing with a minus.
893 if (delta.ToInternalValue() < 0) {
894 delta *= -1;
895 str = "-";
896 }
897
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700898 // Canonicalize into days, hours, minutes, seconds and microseconds.
899 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800900 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700901 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800902 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700903 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800904 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700905 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800906 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700907 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800908
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700909 if (days)
910 base::StringAppendF(&str, "%ud", days);
911 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800912 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700913 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800914 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700915 base::StringAppendF(&str, "%u", secs);
916 if (usecs) {
917 int width = 6;
918 while ((usecs / 10) * 10 == usecs) {
919 usecs /= 10;
920 width--;
921 }
922 base::StringAppendF(&str, ".%0*u", width, usecs);
923 }
924 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800925 return str;
926}
927
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700928string ToString(const Time utc_time) {
929 Time::Exploded exp_time;
930 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700931 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700932 exp_time.month,
933 exp_time.day_of_month,
934 exp_time.year,
935 exp_time.hour,
936 exp_time.minute,
937 exp_time.second);
938}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000939
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700940string ToString(bool b) {
941 return (b ? "true" : "false");
942}
943
Alex Deymo1c656c42013-06-28 11:02:14 -0700944string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700945 switch (source) {
946 case kDownloadSourceHttpsServer: return "HttpsServer";
947 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700948 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700949 case kNumDownloadSources: return "Unknown";
950 // Don't add a default case to let the compiler warn about newly added
951 // download sources which should be added here.
952 }
953
954 return "Unknown";
955}
956
Alex Deymo1c656c42013-06-28 11:02:14 -0700957string ToString(PayloadType payload_type) {
958 switch (payload_type) {
959 case kPayloadTypeDelta: return "Delta";
960 case kPayloadTypeFull: return "Full";
961 case kPayloadTypeForcedFull: return "ForcedFull";
962 case kNumPayloadTypes: return "Unknown";
963 // Don't add a default case to let the compiler warn about newly added
964 // payload types which should be added here.
965 }
966
967 return "Unknown";
968}
969
David Zeuthena99981f2013-04-29 13:42:47 -0700970ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700971 // Ignore the higher order bits in the code by applying the mask as
972 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700973 // with values less than ErrorCode::kUmaReportedMax.
974 ErrorCode base_code = static_cast<ErrorCode>(
975 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700976
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800977 // Make additional adjustments required for UMA and error classification.
978 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
979 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700980 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700981 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800982 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800983 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700984 << " to ErrorCode::kOmahaErrorInHTTPResponse";
985 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700986 }
987
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800988 return base_code;
989}
990
David Zeuthen33bae492014-02-25 16:16:18 -0800991metrics::AttemptResult GetAttemptResult(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700992 ErrorCode base_code = static_cast<ErrorCode>(
993 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -0800994
995 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700996 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -0800997 return metrics::AttemptResult::kUpdateSucceeded;
998
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700999 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001000 return metrics::AttemptResult::kPayloadDownloadError;
1001
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001002 case ErrorCode::kDownloadInvalidMetadataSize:
1003 case ErrorCode::kDownloadInvalidMetadataMagicString:
1004 case ErrorCode::kDownloadMetadataSignatureError:
1005 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1006 case ErrorCode::kPayloadMismatchedType:
1007 case ErrorCode::kUnsupportedMajorPayloadVersion:
1008 case ErrorCode::kUnsupportedMinorPayloadVersion:
1009 case ErrorCode::kDownloadNewPartitionInfoError:
1010 case ErrorCode::kDownloadSignatureMissingInManifest:
1011 case ErrorCode::kDownloadManifestParseError:
1012 case ErrorCode::kDownloadOperationHashMissingError:
David Zeuthen33bae492014-02-25 16:16:18 -08001013 return metrics::AttemptResult::kMetadataMalformed;
1014
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001015 case ErrorCode::kDownloadOperationHashMismatch:
1016 case ErrorCode::kDownloadOperationHashVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001017 return metrics::AttemptResult::kOperationMalformed;
1018
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001019 case ErrorCode::kDownloadOperationExecutionError:
1020 case ErrorCode::kInstallDeviceOpenError:
1021 case ErrorCode::kKernelDeviceOpenError:
1022 case ErrorCode::kDownloadWriteError:
1023 case ErrorCode::kFilesystemCopierError:
David Zeuthen33bae492014-02-25 16:16:18 -08001024 return metrics::AttemptResult::kOperationExecutionError;
1025
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001026 case ErrorCode::kDownloadMetadataSignatureMismatch:
David Zeuthen33bae492014-02-25 16:16:18 -08001027 return metrics::AttemptResult::kMetadataVerificationFailed;
1028
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001029 case ErrorCode::kPayloadSizeMismatchError:
1030 case ErrorCode::kPayloadHashMismatchError:
1031 case ErrorCode::kDownloadPayloadVerificationError:
1032 case ErrorCode::kSignedDeltaPayloadExpectedError:
1033 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001034 return metrics::AttemptResult::kPayloadVerificationFailed;
1035
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001036 case ErrorCode::kNewRootfsVerificationError:
1037 case ErrorCode::kNewKernelVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001038 return metrics::AttemptResult::kVerificationFailed;
1039
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001040 case ErrorCode::kPostinstallRunnerError:
1041 case ErrorCode::kPostinstallBootedFromFirmwareB:
1042 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
David Zeuthen33bae492014-02-25 16:16:18 -08001043 return metrics::AttemptResult::kPostInstallFailed;
1044
1045 // We should never get these errors in the update-attempt stage so
1046 // return internal error if this happens.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001047 case ErrorCode::kError:
1048 case ErrorCode::kOmahaRequestXMLParseError:
1049 case ErrorCode::kOmahaRequestError:
1050 case ErrorCode::kOmahaResponseHandlerError:
1051 case ErrorCode::kDownloadStateInitializationError:
1052 case ErrorCode::kOmahaRequestEmptyResponseError:
1053 case ErrorCode::kDownloadInvalidMetadataSignature:
1054 case ErrorCode::kOmahaResponseInvalid:
1055 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1056 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1057 case ErrorCode::kOmahaErrorInHTTPResponse:
1058 case ErrorCode::kDownloadMetadataSignatureMissingError:
1059 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1060 case ErrorCode::kPostinstallPowerwashError:
1061 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -04001062 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
David Zeuthen33bae492014-02-25 16:16:18 -08001063 return metrics::AttemptResult::kInternalError;
1064
1065 // Special flags. These can't happen (we mask them out above) but
1066 // the compiler doesn't know that. Just break out so we can warn and
1067 // return |kInternalError|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001068 case ErrorCode::kUmaReportedMax:
1069 case ErrorCode::kOmahaRequestHTTPResponseBase:
1070 case ErrorCode::kDevModeFlag:
1071 case ErrorCode::kResumedFlag:
1072 case ErrorCode::kTestImageFlag:
1073 case ErrorCode::kTestOmahaUrlFlag:
1074 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001075 break;
1076 }
1077
1078 LOG(ERROR) << "Unexpected error code " << base_code;
1079 return metrics::AttemptResult::kInternalError;
1080}
1081
1082
1083metrics::DownloadErrorCode GetDownloadErrorCode(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001084 ErrorCode base_code = static_cast<ErrorCode>(
1085 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001086
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001087 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
1088 int http_status =
1089 static_cast<int>(base_code) -
1090 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase);
David Zeuthen33bae492014-02-25 16:16:18 -08001091 if (http_status >= 200 && http_status <= 599) {
1092 return static_cast<metrics::DownloadErrorCode>(
1093 static_cast<int>(metrics::DownloadErrorCode::kHttpStatus200) +
1094 http_status - 200);
1095 } else if (http_status == 0) {
1096 // The code is using HTTP Status 0 for "Unable to get http
1097 // response code."
1098 return metrics::DownloadErrorCode::kDownloadError;
1099 }
1100 LOG(WARNING) << "Unexpected HTTP status code " << http_status;
1101 return metrics::DownloadErrorCode::kHttpStatusOther;
1102 }
1103
1104 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001105 // Unfortunately, ErrorCode::kDownloadTransferError is returned for a wide
David Zeuthen33bae492014-02-25 16:16:18 -08001106 // variety of errors (proxy errors, host not reachable, timeouts etc.).
1107 //
1108 // For now just map that to kDownloading. See http://crbug.com/355745
1109 // for how we plan to add more detail in the future.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001110 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001111 return metrics::DownloadErrorCode::kDownloadError;
1112
1113 // All of these error codes are not related to downloading so break
1114 // out so we can warn and return InputMalformed.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001115 case ErrorCode::kSuccess:
1116 case ErrorCode::kError:
1117 case ErrorCode::kOmahaRequestError:
1118 case ErrorCode::kOmahaResponseHandlerError:
1119 case ErrorCode::kFilesystemCopierError:
1120 case ErrorCode::kPostinstallRunnerError:
1121 case ErrorCode::kPayloadMismatchedType:
1122 case ErrorCode::kInstallDeviceOpenError:
1123 case ErrorCode::kKernelDeviceOpenError:
1124 case ErrorCode::kPayloadHashMismatchError:
1125 case ErrorCode::kPayloadSizeMismatchError:
1126 case ErrorCode::kDownloadPayloadVerificationError:
1127 case ErrorCode::kDownloadNewPartitionInfoError:
1128 case ErrorCode::kDownloadWriteError:
1129 case ErrorCode::kNewRootfsVerificationError:
1130 case ErrorCode::kNewKernelVerificationError:
1131 case ErrorCode::kSignedDeltaPayloadExpectedError:
1132 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1133 case ErrorCode::kPostinstallBootedFromFirmwareB:
1134 case ErrorCode::kDownloadStateInitializationError:
1135 case ErrorCode::kDownloadInvalidMetadataMagicString:
1136 case ErrorCode::kDownloadSignatureMissingInManifest:
1137 case ErrorCode::kDownloadManifestParseError:
1138 case ErrorCode::kDownloadMetadataSignatureError:
1139 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1140 case ErrorCode::kDownloadMetadataSignatureMismatch:
1141 case ErrorCode::kDownloadOperationHashVerificationError:
1142 case ErrorCode::kDownloadOperationExecutionError:
1143 case ErrorCode::kDownloadOperationHashMismatch:
1144 case ErrorCode::kOmahaRequestEmptyResponseError:
1145 case ErrorCode::kOmahaRequestXMLParseError:
1146 case ErrorCode::kDownloadInvalidMetadataSize:
1147 case ErrorCode::kDownloadInvalidMetadataSignature:
1148 case ErrorCode::kOmahaResponseInvalid:
1149 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1150 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1151 case ErrorCode::kOmahaErrorInHTTPResponse:
1152 case ErrorCode::kDownloadOperationHashMissingError:
1153 case ErrorCode::kDownloadMetadataSignatureMissingError:
1154 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1155 case ErrorCode::kPostinstallPowerwashError:
1156 case ErrorCode::kUpdateCanceledByChannelChange:
1157 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1158 case ErrorCode::kUnsupportedMajorPayloadVersion:
1159 case ErrorCode::kUnsupportedMinorPayloadVersion:
David Zeuthenf3e28012014-08-26 18:23:52 -04001160 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
David Zeuthen33bae492014-02-25 16:16:18 -08001161 break;
1162
1163 // Special flags. These can't happen (we mask them out above) but
1164 // the compiler doesn't know that. Just break out so we can warn and
1165 // return |kInputMalformed|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001166 case ErrorCode::kUmaReportedMax:
1167 case ErrorCode::kOmahaRequestHTTPResponseBase:
1168 case ErrorCode::kDevModeFlag:
1169 case ErrorCode::kResumedFlag:
1170 case ErrorCode::kTestImageFlag:
1171 case ErrorCode::kTestOmahaUrlFlag:
1172 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001173 LOG(ERROR) << "Unexpected error code " << base_code;
1174 break;
1175 }
1176
1177 return metrics::DownloadErrorCode::kInputMalformed;
1178}
1179
David Zeuthenb281f072014-04-02 10:20:19 -07001180metrics::ConnectionType GetConnectionType(
1181 NetworkConnectionType type,
1182 NetworkTethering tethering) {
1183 switch (type) {
1184 case kNetUnknown:
1185 return metrics::ConnectionType::kUnknown;
1186
1187 case kNetEthernet:
1188 if (tethering == NetworkTethering::kConfirmed)
1189 return metrics::ConnectionType::kTetheredEthernet;
1190 else
1191 return metrics::ConnectionType::kEthernet;
1192
1193 case kNetWifi:
1194 if (tethering == NetworkTethering::kConfirmed)
1195 return metrics::ConnectionType::kTetheredWifi;
1196 else
1197 return metrics::ConnectionType::kWifi;
1198
1199 case kNetWimax:
1200 return metrics::ConnectionType::kWimax;
1201
1202 case kNetBluetooth:
1203 return metrics::ConnectionType::kBluetooth;
1204
1205 case kNetCellular:
1206 return metrics::ConnectionType::kCellular;
1207 }
1208
1209 LOG(ERROR) << "Unexpected network connection type: type=" << type
1210 << ", tethering=" << static_cast<int>(tethering);
1211
1212 return metrics::ConnectionType::kUnknown;
1213}
1214
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001215// Returns a printable version of the various flags denoted in the higher order
1216// bits of the given code. Returns an empty string if none of those bits are
1217// set.
1218string GetFlagNames(uint32_t code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001219 uint32_t flags = (static_cast<uint32_t>(code) &
1220 static_cast<uint32_t>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001221 string flag_names;
1222 string separator = "";
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001223 for (size_t i = 0; i < sizeof(flags) * 8; i++) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001224 uint32_t flag = flags & (1 << i);
1225 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -07001226 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001227 separator = ", ";
1228 }
1229 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001230
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001231 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001232}
1233
David Zeuthena99981f2013-04-29 13:42:47 -07001234void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001235 if (!system_state)
1236 return;
1237
David Zeuthena99981f2013-04-29 13:42:47 -07001238 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001239
1240 // If the code doesn't have flags computed already, compute them now based on
1241 // the state of the current update attempt.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001242 uint32_t flags =
1243 static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001244 if (!flags)
1245 flags = system_state->update_attempter()->GetErrorCodeFlags();
1246
1247 // Determine the UMA bucket depending on the flags. But, ignore the resumed
1248 // flag, as it's perfectly normal for production devices to resume their
1249 // downloads and so we want to record those cases also in NormalErrorCodes
1250 // bucket.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001251 string metric =
1252 flags & ~static_cast<uint32_t>(ErrorCode::kResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001253 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
1254
1255 LOG(INFO) << "Sending error code " << uma_error_code
1256 << " (" << CodeToString(uma_error_code) << ")"
1257 << " to UMA metric: " << metric
1258 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
1259
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001260 system_state->metrics_lib()->SendEnumToUMA(
1261 metric, static_cast<int>(uma_error_code),
1262 static_cast<int>(ErrorCode::kUmaReportedMax));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001263}
1264
David Zeuthena99981f2013-04-29 13:42:47 -07001265string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001266 // If the given code has both parts (i.e. the error code part and the flags
1267 // part) then strip off the flags part since the switch statement below
1268 // has case statements only for the base error code or a single flag but
1269 // doesn't support any combinations of those.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001270 if ((static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags)) &&
1271 (static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags)))
1272 code = static_cast<ErrorCode>(
1273 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001274 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001275 case ErrorCode::kSuccess: return "ErrorCode::kSuccess";
1276 case ErrorCode::kError: return "ErrorCode::kError";
1277 case ErrorCode::kOmahaRequestError: return "ErrorCode::kOmahaRequestError";
1278 case ErrorCode::kOmahaResponseHandlerError:
1279 return "ErrorCode::kOmahaResponseHandlerError";
1280 case ErrorCode::kFilesystemCopierError:
1281 return "ErrorCode::kFilesystemCopierError";
1282 case ErrorCode::kPostinstallRunnerError:
1283 return "ErrorCode::kPostinstallRunnerError";
1284 case ErrorCode::kPayloadMismatchedType:
1285 return "ErrorCode::kPayloadMismatchedType";
1286 case ErrorCode::kInstallDeviceOpenError:
1287 return "ErrorCode::kInstallDeviceOpenError";
1288 case ErrorCode::kKernelDeviceOpenError:
1289 return "ErrorCode::kKernelDeviceOpenError";
1290 case ErrorCode::kDownloadTransferError:
1291 return "ErrorCode::kDownloadTransferError";
1292 case ErrorCode::kPayloadHashMismatchError:
1293 return "ErrorCode::kPayloadHashMismatchError";
1294 case ErrorCode::kPayloadSizeMismatchError:
1295 return "ErrorCode::kPayloadSizeMismatchError";
1296 case ErrorCode::kDownloadPayloadVerificationError:
1297 return "ErrorCode::kDownloadPayloadVerificationError";
1298 case ErrorCode::kDownloadNewPartitionInfoError:
1299 return "ErrorCode::kDownloadNewPartitionInfoError";
1300 case ErrorCode::kDownloadWriteError:
1301 return "ErrorCode::kDownloadWriteError";
1302 case ErrorCode::kNewRootfsVerificationError:
1303 return "ErrorCode::kNewRootfsVerificationError";
1304 case ErrorCode::kNewKernelVerificationError:
1305 return "ErrorCode::kNewKernelVerificationError";
1306 case ErrorCode::kSignedDeltaPayloadExpectedError:
1307 return "ErrorCode::kSignedDeltaPayloadExpectedError";
1308 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1309 return "ErrorCode::kDownloadPayloadPubKeyVerificationError";
1310 case ErrorCode::kPostinstallBootedFromFirmwareB:
1311 return "ErrorCode::kPostinstallBootedFromFirmwareB";
1312 case ErrorCode::kDownloadStateInitializationError:
1313 return "ErrorCode::kDownloadStateInitializationError";
1314 case ErrorCode::kDownloadInvalidMetadataMagicString:
1315 return "ErrorCode::kDownloadInvalidMetadataMagicString";
1316 case ErrorCode::kDownloadSignatureMissingInManifest:
1317 return "ErrorCode::kDownloadSignatureMissingInManifest";
1318 case ErrorCode::kDownloadManifestParseError:
1319 return "ErrorCode::kDownloadManifestParseError";
1320 case ErrorCode::kDownloadMetadataSignatureError:
1321 return "ErrorCode::kDownloadMetadataSignatureError";
1322 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1323 return "ErrorCode::kDownloadMetadataSignatureVerificationError";
1324 case ErrorCode::kDownloadMetadataSignatureMismatch:
1325 return "ErrorCode::kDownloadMetadataSignatureMismatch";
1326 case ErrorCode::kDownloadOperationHashVerificationError:
1327 return "ErrorCode::kDownloadOperationHashVerificationError";
1328 case ErrorCode::kDownloadOperationExecutionError:
1329 return "ErrorCode::kDownloadOperationExecutionError";
1330 case ErrorCode::kDownloadOperationHashMismatch:
1331 return "ErrorCode::kDownloadOperationHashMismatch";
1332 case ErrorCode::kOmahaRequestEmptyResponseError:
1333 return "ErrorCode::kOmahaRequestEmptyResponseError";
1334 case ErrorCode::kOmahaRequestXMLParseError:
1335 return "ErrorCode::kOmahaRequestXMLParseError";
1336 case ErrorCode::kDownloadInvalidMetadataSize:
1337 return "ErrorCode::kDownloadInvalidMetadataSize";
1338 case ErrorCode::kDownloadInvalidMetadataSignature:
1339 return "ErrorCode::kDownloadInvalidMetadataSignature";
1340 case ErrorCode::kOmahaResponseInvalid:
1341 return "ErrorCode::kOmahaResponseInvalid";
1342 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1343 return "ErrorCode::kOmahaUpdateIgnoredPerPolicy";
1344 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1345 return "ErrorCode::kOmahaUpdateDeferredPerPolicy";
1346 case ErrorCode::kOmahaErrorInHTTPResponse:
1347 return "ErrorCode::kOmahaErrorInHTTPResponse";
1348 case ErrorCode::kDownloadOperationHashMissingError:
1349 return "ErrorCode::kDownloadOperationHashMissingError";
1350 case ErrorCode::kDownloadMetadataSignatureMissingError:
1351 return "ErrorCode::kDownloadMetadataSignatureMissingError";
1352 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1353 return "ErrorCode::kOmahaUpdateDeferredForBackoff";
1354 case ErrorCode::kPostinstallPowerwashError:
1355 return "ErrorCode::kPostinstallPowerwashError";
1356 case ErrorCode::kUpdateCanceledByChannelChange:
1357 return "ErrorCode::kUpdateCanceledByChannelChange";
1358 case ErrorCode::kUmaReportedMax:
1359 return "ErrorCode::kUmaReportedMax";
1360 case ErrorCode::kOmahaRequestHTTPResponseBase:
1361 return "ErrorCode::kOmahaRequestHTTPResponseBase";
1362 case ErrorCode::kResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001363 return "Resumed";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001364 case ErrorCode::kDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001365 return "DevMode";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001366 case ErrorCode::kTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001367 return "TestImage";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001368 case ErrorCode::kTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001369 return "TestOmahaUrl";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001370 case ErrorCode::kSpecialFlags:
1371 return "ErrorCode::kSpecialFlags";
1372 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1373 return "ErrorCode::kPostinstallFirmwareRONotUpdatable";
1374 case ErrorCode::kUnsupportedMajorPayloadVersion:
1375 return "ErrorCode::kUnsupportedMajorPayloadVersion";
1376 case ErrorCode::kUnsupportedMinorPayloadVersion:
1377 return "ErrorCode::kUnsupportedMinorPayloadVersion";
David Zeuthenf3e28012014-08-26 18:23:52 -04001378 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
1379 return "ErrorCode::kOmahaRequestXMLHasEntityDecl";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001380 // Don't add a default case to let the compiler warn about newly added
1381 // error codes which should be added here.
1382 }
1383
1384 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1385}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001386
Gilad Arnold30dedd82013-07-03 06:19:09 -07001387bool CreatePowerwashMarkerFile(const char* file_path) {
1388 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1389 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001390 kPowerwashCommand,
1391 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001392 if (result) {
1393 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1394 } else {
1395 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1396 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001397
1398 return result;
1399}
1400
Gilad Arnold30dedd82013-07-03 06:19:09 -07001401bool DeletePowerwashMarkerFile(const char* file_path) {
1402 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001403 const base::FilePath kPowerwashMarkerPath(marker_file);
1404 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001405
1406 if (result)
1407 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001408 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001409 else
1410 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001411 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001412
1413 return result;
1414}
1415
Alex Deymof329b932014-10-30 01:37:48 -07001416bool GetInstallDev(const string& boot_dev, string* install_dev) {
1417 string disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001418 int partition_num;
1419 if (!SplitPartitionName(boot_dev, &disk_name, &partition_num))
1420 return false;
Liam McLoughlin049d1652013-07-31 18:47:46 -07001421
Chris Sosad317e402013-06-12 13:47:09 -07001422 // Right now, we just switch '3' and '5' partition numbers.
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001423 if (partition_num == 3) {
1424 partition_num = 5;
1425 } else if (partition_num == 5) {
1426 partition_num = 3;
1427 } else {
1428 return false;
1429 }
1430
1431 if (install_dev)
1432 *install_dev = MakePartitionName(disk_name, partition_num);
Liam McLoughlin049d1652013-07-31 18:47:46 -07001433
Chris Sosad317e402013-06-12 13:47:09 -07001434 return true;
1435}
1436
David Zeuthen27a48bc2013-08-06 12:06:29 -07001437Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -07001438 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1439 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -07001440 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1441}
1442
Alex Deymof329b932014-10-30 01:37:48 -07001443gchar** StringVectorToGStrv(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001444 GPtrArray *p = g_ptr_array_new();
Alex Deymo020600d2014-11-05 21:05:55 -08001445 for (const string& str : vec_str) {
1446 g_ptr_array_add(p, g_strdup(str.c_str()));
David Zeuthen27a48bc2013-08-06 12:06:29 -07001447 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001448 g_ptr_array_add(p, nullptr);
David Zeuthen27a48bc2013-08-06 12:06:29 -07001449 return reinterpret_cast<gchar**>(g_ptr_array_free(p, FALSE));
1450}
1451
Alex Deymof329b932014-10-30 01:37:48 -07001452string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001453 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -07001454 for (vector<string>::const_iterator i = vec_str.begin();
1455 i != vec_str.end(); ++i) {
1456 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -07001457 str += ", ";
1458 str += '"';
1459 str += *i;
1460 str += '"';
1461 }
1462 str += "]";
1463 return str;
1464}
1465
David Zeuthen8f191b22013-08-06 12:27:50 -07001466string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001467 string encoded_hash = chromeos::data_encoding::Base64Encode(payload_hash);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001468 return base::StringPrintf("cros_update_size_%zu_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001469 payload_size,
1470 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -07001471}
1472
Alex Deymof329b932014-10-30 01:37:48 -07001473bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -07001474 base::FilePath *out_path) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001475 chromeos::Blob contents;
David Zeuthene7f89172013-10-31 10:21:04 -07001476
1477 out_path->clear();
1478
1479 if (base64_encoded.size() == 0) {
1480 LOG(ERROR) << "Can't decode empty string.";
1481 return false;
1482 }
1483
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001484 if (!chromeos::data_encoding::Base64Decode(base64_encoded, &contents) ||
David Zeuthene7f89172013-10-31 10:21:04 -07001485 contents.size() == 0) {
1486 LOG(ERROR) << "Error decoding base64.";
1487 return false;
1488 }
1489
Alex Vakulenko75039d72014-03-25 12:36:28 -07001490 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001491 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -07001492 LOG(ERROR) << "Error creating temporary file.";
1493 return false;
1494 }
1495
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001496 if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
David Zeuthene7f89172013-10-31 10:21:04 -07001497 PLOG(ERROR) << "Error writing to temporary file.";
1498 if (fclose(file) != 0)
1499 PLOG(ERROR) << "Error closing temporary file.";
1500 if (unlink(out_path->value().c_str()) != 0)
1501 PLOG(ERROR) << "Error unlinking temporary file.";
1502 out_path->clear();
1503 return false;
1504 }
1505
1506 if (fclose(file) != 0) {
1507 PLOG(ERROR) << "Error closing temporary file.";
1508 out_path->clear();
1509 return false;
1510 }
1511
1512 return true;
1513}
1514
Alex Deymof329b932014-10-30 01:37:48 -07001515bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -08001516 time_t unix_time = time.ToTimeT();
1517 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1518 const time_t kOmahaEpoch = 1167638400;
1519 const int64_t kNumSecondsPerWeek = 7*24*3600;
1520 const int64_t kNumDaysPerWeek = 7;
1521
1522 time_t omaha_time = unix_time - kOmahaEpoch;
1523
1524 if (omaha_time < 0)
1525 return false;
1526
1527 // Note, as per the comment in utils.h we are deliberately not
1528 // handling DST correctly.
1529
1530 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1531 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1532
1533 return true;
1534}
1535
David Zeuthen33bae492014-02-25 16:16:18 -08001536bool WallclockDurationHelper(SystemState* system_state,
Alex Deymof329b932014-10-30 01:37:48 -07001537 const string& state_variable_key,
1538 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001539 bool ret = false;
1540
Alex Deymof329b932014-10-30 01:37:48 -07001541 Time now = system_state->clock()->GetWallclockTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001542 int64_t stored_value;
1543 if (system_state->prefs()->GetInt64(state_variable_key, &stored_value)) {
Alex Deymof329b932014-10-30 01:37:48 -07001544 Time stored_time = Time::FromInternalValue(stored_value);
David Zeuthen33bae492014-02-25 16:16:18 -08001545 if (stored_time > now) {
1546 LOG(ERROR) << "Stored time-stamp used for " << state_variable_key
1547 << " is in the future.";
1548 } else {
1549 *out_duration = now - stored_time;
1550 ret = true;
1551 }
1552 }
1553
1554 if (!system_state->prefs()->SetInt64(state_variable_key,
1555 now.ToInternalValue())) {
1556 LOG(ERROR) << "Error storing time-stamp in " << state_variable_key;
1557 }
1558
1559 return ret;
1560}
1561
1562bool MonotonicDurationHelper(SystemState* system_state,
1563 int64_t* storage,
Alex Deymof329b932014-10-30 01:37:48 -07001564 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001565 bool ret = false;
1566
Alex Deymof329b932014-10-30 01:37:48 -07001567 Time now = system_state->clock()->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001568 if (*storage != 0) {
Alex Deymof329b932014-10-30 01:37:48 -07001569 Time stored_time = Time::FromInternalValue(*storage);
David Zeuthen33bae492014-02-25 16:16:18 -08001570 *out_duration = now - stored_time;
1571 ret = true;
1572 }
1573 *storage = now.ToInternalValue();
1574
1575 return ret;
1576}
1577
adlr@google.com3defe6a2009-12-04 20:57:17 +00001578} // namespace utils
1579
1580} // namespace chromeos_update_engine