blob: 77e5a356283020302222c4712822b80f221a0a99 [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
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800126bool WriteFile(const char* path, const void* data, int data_len) {
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800127 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|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800222static void AppendBytes(const uint8_t* buf, size_t nbytes,
223 chromeos::Blob* 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}
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800228static void AppendBytes(const uint8_t* 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);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800232 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700233}
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);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800243 uint8_t 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
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800299bool ReadFile(const string& path, chromeos::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200300 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,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800308 chromeos::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200309 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
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800366void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000367 LOG(INFO) << "Logging array of length: " << length;
368 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700369 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000370 const unsigned int bytes_remaining = length - i;
371 const unsigned int bytes_per_this_line = min(bytes_per_line,
372 bytes_remaining);
373 char header[100];
374 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
375 TEST_AND_RETURN(r == 13);
376 string line = header;
377 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
378 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800379 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000380 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
381 TEST_AND_RETURN(r == 3);
382 line += buf;
383 }
384 LOG(INFO) << line;
385 }
386}
387
Alex Deymof329b932014-10-30 01:37:48 -0700388string GetDiskName(const string& partition_name) {
389 string disk_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800390 return SplitPartitionName(partition_name, &disk_name, nullptr) ?
Alex Deymof329b932014-10-30 01:37:48 -0700391 disk_name : string();
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700392}
393
Alex Deymof329b932014-10-30 01:37:48 -0700394int GetPartitionNumber(const string& partition_name) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800395 int partition_num = 0;
396 return SplitPartitionName(partition_name, nullptr, &partition_num) ?
397 partition_num : 0;
398}
399
Alex Deymof329b932014-10-30 01:37:48 -0700400bool SplitPartitionName(const string& partition_name,
401 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800402 int* out_partition_num) {
Alex Deymo10875d92014-11-10 21:52:57 -0800403 if (!StartsWithASCII(partition_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800404 LOG(ERROR) << "Invalid partition device name: " << partition_name;
405 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700406 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800407
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700408 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
409 if (last_nondigit_pos == string::npos ||
410 (last_nondigit_pos + 1) == partition_name.size()) {
411 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800412 return false;
413 }
414
Alex Deymof329b932014-10-30 01:37:48 -0700415 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700416 if (partition_name[last_nondigit_pos] == '_') {
417 // NAND block devices have weird naming which could be something
418 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
419 size_t prev_nondigit_pos =
420 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
421 if (prev_nondigit_pos == string::npos ||
422 (prev_nondigit_pos + 1) == last_nondigit_pos) {
423 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
424 return false;
425 }
426
427 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
428 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800429 }
430
431 if (out_disk_name) {
432 // Special case for MMC devices which have the following naming scheme:
433 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700434 size_t disk_name_len = last_nondigit_pos;
435 if (partition_name[last_nondigit_pos] != 'p' ||
436 last_nondigit_pos == 0 ||
437 !isdigit(partition_name[last_nondigit_pos - 1])) {
438 disk_name_len++;
439 }
440 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800441 }
442
443 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700444 string partition_str = partition_name.substr(last_nondigit_pos + 1,
445 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800446 *out_partition_num = atoi(partition_str.c_str());
447 }
448 return true;
449}
450
Alex Deymof329b932014-10-30 01:37:48 -0700451string MakePartitionName(const string& disk_name, int partition_num) {
Alex Deymo10875d92014-11-10 21:52:57 -0800452 if (!StartsWithASCII(disk_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800453 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700454 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800455 }
456
457 if (partition_num < 1) {
458 LOG(ERROR) << "Invalid partition number: " << partition_num;
Alex Deymof329b932014-10-30 01:37:48 -0700459 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800460 }
461
Alex Deymof329b932014-10-30 01:37:48 -0700462 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700463 if (isdigit(partition_name.back())) {
464 // Special case for devices with names ending with a digit.
465 // Add "p" to separate the disk name from partition number,
466 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800467 partition_name += 'p';
468 }
469
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700470 partition_name += std::to_string(partition_num);
471
Alex Deymo10875d92014-11-10 21:52:57 -0800472 if (StartsWithASCII(partition_name, "/dev/ubiblock", true)) {
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700473 // Special case for UBI block devieces that have "_0" suffix.
474 partition_name += "_0";
475 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800476 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700477}
478
Darin Petkovf74eb652010-08-04 12:08:38 -0700479string SysfsBlockDevice(const string& device) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700480 base::FilePath device_path(device);
Darin Petkovf74eb652010-08-04 12:08:38 -0700481 if (device_path.DirName().value() != "/dev") {
482 return "";
483 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700484 return base::FilePath("/sys/block").Append(device_path.BaseName()).value();
Darin Petkovf74eb652010-08-04 12:08:38 -0700485}
486
Alex Deymof329b932014-10-30 01:37:48 -0700487bool IsRemovableDevice(const string& device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700488 string sysfs_block = SysfsBlockDevice(device);
489 string removable;
490 if (sysfs_block.empty() ||
Alex Vakulenko75039d72014-03-25 12:36:28 -0700491 !base::ReadFileToString(base::FilePath(sysfs_block).Append("removable"),
Ben Chan736fcb52014-05-21 18:28:22 -0700492 &removable)) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700493 return false;
494 }
Ben Chan736fcb52014-05-21 18:28:22 -0700495 base::TrimWhitespaceASCII(removable, base::TRIM_ALL, &removable);
Darin Petkovf74eb652010-08-04 12:08:38 -0700496 return removable == "1";
497}
498
Alex Deymof329b932014-10-30 01:37:48 -0700499string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000500 char buf[100];
501 buf[0] = '\0';
502 return strerror_r(err, buf, sizeof(buf));
503}
504
Alex Deymof329b932014-10-30 01:37:48 -0700505string NormalizePath(const string& path, bool strip_trailing_slash) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000506 string ret;
Alex Deymo020600d2014-11-05 21:05:55 -0800507 std::unique_copy(path.begin(), path.end(), std::back_inserter(ret),
508 [](char c1, char c2) { return c1 == c2 && c1 == '/'; });
509 // The above code ensures no "//" is present in the string, so at most one
510 // '/' is present at the end of the line.
511 if (strip_trailing_slash && !ret.empty() && ret.back() == '/')
512 ret.pop_back();
adlr@google.com3defe6a2009-12-04 20:57:17 +0000513 return ret;
514}
515
516bool FileExists(const char* path) {
517 struct stat stbuf;
518 return 0 == lstat(path, &stbuf);
519}
520
Darin Petkov30291ed2010-11-12 10:23:06 -0800521bool IsSymlink(const char* path) {
522 struct stat stbuf;
523 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
524}
525
Alex Deymo7dc4c502014-05-20 20:09:58 -0700526bool IsDir(const char* path) {
527 struct stat stbuf;
528 TEST_AND_RETURN_FALSE_ERRNO(lstat(path, &stbuf) == 0);
529 return S_ISDIR(stbuf.st_mode);
530}
531
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800532// If |path| is absolute, or explicit relative to the current working directory,
533// leaves it as is. Otherwise, if TMPDIR is defined in the environment and is
534// non-empty, prepends it to |path|. Otherwise, prepends /tmp. Returns the
535// resulting path.
536static const string PrependTmpdir(const string& path) {
537 if (path[0] == '/' || StartsWithASCII(path, "./", true) ||
538 StartsWithASCII(path, "../", true))
539 return path;
540
541 const char *tmpdir = getenv("TMPDIR");
542 const string prefix = (tmpdir && *tmpdir ? tmpdir : "/tmp");
543 return prefix + "/" + path;
544}
545
Alex Deymof329b932014-10-30 01:37:48 -0700546bool MakeTempFile(const string& base_filename_template,
547 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700548 int* fd) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800549 const string filename_template = PrependTmpdir(base_filename_template);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700550 DCHECK(filename || fd);
551 vector<char> buf(filename_template.size() + 1);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800552 memcpy(buf.data(), filename_template.data(), filename_template.size());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700553 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700554
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800555 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700556 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
557 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800558 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700559 }
560 if (fd) {
561 *fd = mkstemp_fd;
562 } else {
563 close(mkstemp_fd);
564 }
565 return true;
566}
567
Alex Deymof329b932014-10-30 01:37:48 -0700568bool MakeTempDirectory(const string& base_dirname_template,
569 string* dirname) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800570 const string dirname_template = PrependTmpdir(base_dirname_template);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700571 DCHECK(dirname);
572 vector<char> buf(dirname_template.size() + 1);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800573 memcpy(buf.data(), dirname_template.data(), dirname_template.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700574 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700575
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800576 char* return_code = mkdtemp(buf.data());
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700577 TEST_AND_RETURN_FALSE_ERRNO(return_code != nullptr);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800578 *dirname = buf.data();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700579 return true;
580}
581
adlr@google.com3defe6a2009-12-04 20:57:17 +0000582bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700583 const string& mountpoint,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700584 unsigned long mountflags) { // NOLINT(runtime/int)
Alex Deymo4c82df32014-11-10 22:25:57 -0800585 // TODO(sosa): Remove "ext3" once crbug.com/208022 is resolved.
586 const vector<const char*> fstypes{"ext2", "ext3", "squashfs"};
587 for (const char* fstype : fstypes) {
588 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
589 nullptr);
590 if (rc == 0)
591 return true;
592
593 PLOG(WARNING) << "Unable to mount destination device " << device
594 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000595 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800596 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
597 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000598}
599
600bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700601 for (int num_retries = 0; ; ++num_retries) {
602 if (umount(mountpoint.c_str()) == 0)
603 break;
604
605 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
606 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800607 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700608 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000609 return true;
610}
611
Alex Deymof329b932014-10-30 01:37:48 -0700612bool GetFilesystemSize(const string& device,
Darin Petkovd3f8c892010-10-12 21:38:45 -0700613 int* out_block_count,
614 int* out_block_size) {
615 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
Alex Deymoe7141c62014-10-17 14:03:01 -0700616 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700617 ScopedFdCloser fd_closer(&fd);
618 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
619}
620
621bool GetFilesystemSizeFromFD(int fd,
622 int* out_block_count,
623 int* out_block_size) {
624 TEST_AND_RETURN_FALSE(fd >= 0);
625
Alex Deymo192393b2014-11-10 15:58:38 -0800626 // Determine the filesystem size by directly reading the block count and
627 // block size information from the superblock. Supported FS are ext3 and
628 // squashfs.
629
630 // Read from the fd only once and detect in memory. The first 2 KiB is enough
631 // to read the ext2 superblock (located at offset 1024) and the squashfs
632 // superblock (located at offset 0).
633 const ssize_t kBufferSize = 2048;
634
635 uint8_t buffer[kBufferSize];
636 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, 0)) != kBufferSize) {
637 PLOG(ERROR) << "Unable to read the file system header:";
Darin Petkovd3f8c892010-10-12 21:38:45 -0700638 return false;
639 }
Alex Deymo192393b2014-11-10 15:58:38 -0800640
641 if (GetSquashfs4Size(buffer, kBufferSize, out_block_count, out_block_size))
642 return true;
643 if (GetExt3Size(buffer, kBufferSize, out_block_count, out_block_size))
644 return true;
645
646 LOG(ERROR) << "Unable to determine file system type.";
647 return false;
648}
649
650bool GetExt3Size(const uint8_t* buffer, size_t buffer_size,
651 int* out_block_count,
652 int* out_block_size) {
653 // See include/linux/ext2_fs.h for more details on the structure. We obtain
654 // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
655 // library.
656 if (buffer_size < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
657 return false;
658
659 const uint8_t* superblock = buffer + SUPERBLOCK_OFFSET;
660
661 // ext3_fs.h: ext3_super_block.s_blocks_count
662 uint32_t block_count =
663 *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
664
665 // ext3_fs.h: ext3_super_block.s_log_block_size
666 uint32_t log_block_size =
667 *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
668
669 // ext3_fs.h: ext3_super_block.s_magic
670 uint16_t magic =
671 *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
672
Darin Petkovd3f8c892010-10-12 21:38:45 -0700673 block_count = le32toh(block_count);
Alex Deymo192393b2014-11-10 15:58:38 -0800674 log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700675 magic = le16toh(magic);
676
677 // Sanity check the parameters.
Alex Deymo192393b2014-11-10 15:58:38 -0800678 TEST_AND_RETURN_FALSE(magic == EXT2_SUPER_MAGIC);
679 TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
680 log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700681 TEST_AND_RETURN_FALSE(block_count > 0);
682
Alex Deymo192393b2014-11-10 15:58:38 -0800683 if (out_block_count)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700684 *out_block_count = block_count;
Alex Deymo192393b2014-11-10 15:58:38 -0800685 if (out_block_size)
686 *out_block_size = 1 << log_block_size;
687 return true;
688}
689
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800690bool GetSquashfs4Size(const uint8_t* buffer, size_t buffer_size,
Alex Deymo192393b2014-11-10 15:58:38 -0800691 int* out_block_count,
692 int* out_block_size) {
693 // See fs/squashfs/squashfs_fs.h for format details. We only support
694 // Squashfs 4.x little endian.
695
696 // sizeof(struct squashfs_super_block)
697 const size_t kSquashfsSuperBlockSize = 96;
698 if (buffer_size < kSquashfsSuperBlockSize)
699 return false;
700
701 // Check magic, squashfs_fs.h: SQUASHFS_MAGIC
702 if (memcmp(buffer, "hsqs", 4) != 0)
703 return false; // Only little endian is supported.
704
705 // squashfs_fs.h: struct squashfs_super_block.s_major
706 uint16_t s_major = *reinterpret_cast<const uint16_t*>(
707 buffer + 5 * sizeof(uint32_t) + 4 * sizeof(uint16_t));
708
709 if (s_major != 4) {
710 LOG(ERROR) << "Found unsupported squashfs major version " << s_major;
711 return false;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700712 }
Alex Deymo192393b2014-11-10 15:58:38 -0800713
714 // squashfs_fs.h: struct squashfs_super_block.bytes_used
715 uint64_t bytes_used = *reinterpret_cast<const int64_t*>(
716 buffer + 5 * sizeof(uint32_t) + 6 * sizeof(uint16_t) + sizeof(uint64_t));
717
718 const int block_size = 4096;
719
720 // The squashfs' bytes_used doesn't need to be aligned with the block boundary
721 // so we round up to the nearest blocksize.
722 if (out_block_count)
723 *out_block_count = (bytes_used + block_size - 1) / block_size;
724 if (out_block_size)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700725 *out_block_size = block_size;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700726 return true;
727}
728
Alex Deymo719bfff2014-07-11 12:12:32 -0700729string GetPathOnBoard(const string& command) {
730 int return_code = 0;
731 string command_path;
732 // TODO(deymo): prepend SYSROOT to each PATH instead of the result.
733 if (!Subprocess::SynchronousExec(
734 {"which", command}, &return_code, &command_path)) {
735 return command;
736 }
737 if (return_code != 0)
738 return command;
739
740 base::TrimWhitespaceASCII(command_path, base::TRIM_ALL, &command_path);
741 const char* env_sysroot = getenv("SYSROOT");
742 if (env_sysroot) {
743 string sysroot_command_path = env_sysroot + command_path;
744 if (utils::FileExists(sysroot_command_path.c_str()))
745 return sysroot_command_path;
746 }
747 return command_path;
748}
749
Alex Deymo032e7722014-03-25 17:53:56 -0700750// Tries to parse the header of an ELF file to obtain a human-readable
751// description of it on the |output| string.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800752static bool GetFileFormatELF(const uint8_t* buffer, size_t size,
753 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700754 // 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 Vakulenkof68bbbc2015-02-09 12:53:18 -0800776 uint8_t 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) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800822 chromeos::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700823 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) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001466 string encoded_hash = chromeos::data_encoding::Base64Encode(payload_hash);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001467 return base::StringPrintf("cros_update_size_%zu_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001468 payload_size,
1469 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -07001470}
1471
Alex Deymof329b932014-10-30 01:37:48 -07001472bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -07001473 base::FilePath *out_path) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001474 chromeos::Blob contents;
David Zeuthene7f89172013-10-31 10:21:04 -07001475
1476 out_path->clear();
1477
1478 if (base64_encoded.size() == 0) {
1479 LOG(ERROR) << "Can't decode empty string.";
1480 return false;
1481 }
1482
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001483 if (!chromeos::data_encoding::Base64Decode(base64_encoded, &contents) ||
David Zeuthene7f89172013-10-31 10:21:04 -07001484 contents.size() == 0) {
1485 LOG(ERROR) << "Error decoding base64.";
1486 return false;
1487 }
1488
Alex Vakulenko75039d72014-03-25 12:36:28 -07001489 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001490 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -07001491 LOG(ERROR) << "Error creating temporary file.";
1492 return false;
1493 }
1494
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001495 if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
David Zeuthene7f89172013-10-31 10:21:04 -07001496 PLOG(ERROR) << "Error writing to temporary file.";
1497 if (fclose(file) != 0)
1498 PLOG(ERROR) << "Error closing temporary file.";
1499 if (unlink(out_path->value().c_str()) != 0)
1500 PLOG(ERROR) << "Error unlinking temporary file.";
1501 out_path->clear();
1502 return false;
1503 }
1504
1505 if (fclose(file) != 0) {
1506 PLOG(ERROR) << "Error closing temporary file.";
1507 out_path->clear();
1508 return false;
1509 }
1510
1511 return true;
1512}
1513
Alex Deymof329b932014-10-30 01:37:48 -07001514bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -08001515 time_t unix_time = time.ToTimeT();
1516 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1517 const time_t kOmahaEpoch = 1167638400;
1518 const int64_t kNumSecondsPerWeek = 7*24*3600;
1519 const int64_t kNumDaysPerWeek = 7;
1520
1521 time_t omaha_time = unix_time - kOmahaEpoch;
1522
1523 if (omaha_time < 0)
1524 return false;
1525
1526 // Note, as per the comment in utils.h we are deliberately not
1527 // handling DST correctly.
1528
1529 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1530 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1531
1532 return true;
1533}
1534
David Zeuthen33bae492014-02-25 16:16:18 -08001535bool WallclockDurationHelper(SystemState* system_state,
Alex Deymof329b932014-10-30 01:37:48 -07001536 const string& state_variable_key,
1537 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001538 bool ret = false;
1539
Alex Deymof329b932014-10-30 01:37:48 -07001540 Time now = system_state->clock()->GetWallclockTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001541 int64_t stored_value;
1542 if (system_state->prefs()->GetInt64(state_variable_key, &stored_value)) {
Alex Deymof329b932014-10-30 01:37:48 -07001543 Time stored_time = Time::FromInternalValue(stored_value);
David Zeuthen33bae492014-02-25 16:16:18 -08001544 if (stored_time > now) {
1545 LOG(ERROR) << "Stored time-stamp used for " << state_variable_key
1546 << " is in the future.";
1547 } else {
1548 *out_duration = now - stored_time;
1549 ret = true;
1550 }
1551 }
1552
1553 if (!system_state->prefs()->SetInt64(state_variable_key,
1554 now.ToInternalValue())) {
1555 LOG(ERROR) << "Error storing time-stamp in " << state_variable_key;
1556 }
1557
1558 return ret;
1559}
1560
1561bool MonotonicDurationHelper(SystemState* system_state,
1562 int64_t* storage,
Alex Deymof329b932014-10-30 01:37:48 -07001563 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001564 bool ret = false;
1565
Alex Deymof329b932014-10-30 01:37:48 -07001566 Time now = system_state->clock()->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001567 if (*storage != 0) {
Alex Deymof329b932014-10-30 01:37:48 -07001568 Time stored_time = Time::FromInternalValue(*storage);
David Zeuthen33bae492014-02-25 16:16:18 -08001569 *out_duration = now - stored_time;
1570 ret = true;
1571 }
1572 *storage = now.ToInternalValue();
1573
1574 return ret;
1575}
1576
adlr@google.com3defe6a2009-12-04 20:57:17 +00001577} // namespace utils
1578
1579} // namespace chromeos_update_engine